mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-22 18:57:42 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4f6f2e7db | ||
|
|
253671d882 | ||
|
|
94f3af3d09 | ||
|
|
f505c30b92 | ||
|
|
5bacb7c868 | ||
|
|
d2bceda3de | ||
|
|
56eea9e4b0 | ||
|
|
e14a2d3a63 | ||
|
|
1014775c8a | ||
|
|
0b51bb2fed | ||
|
|
8d60873dfb | ||
|
|
ad50351f50 | ||
|
|
42f6a58fd1 | ||
|
|
9c10c94e16 | ||
|
|
8cb0d98ccd | ||
|
|
e300919cc7 | ||
|
|
5d28d64bf2 | ||
|
|
1fb8a26960 | ||
|
|
8a97fa98ab | ||
|
|
225a5345bb | ||
|
|
b052049276 | ||
|
|
cbb1c1c50b | ||
|
|
afe77e18fa | ||
|
|
e6d624b9a4 | ||
|
|
19bc41dbb4 | ||
|
|
e50c254a22 | ||
|
|
660be5506b | ||
|
|
c622f623fc | ||
|
|
c661033349 | ||
|
|
44c20b1c0a | ||
|
|
80325823d4 | ||
|
|
a818a46f3d | ||
|
|
b019be0c86 | ||
|
|
362ac92974 |
@@ -72,7 +72,7 @@ jobs:
|
||||
|
||||
- name: Fetch emdawnwebgpu
|
||||
run: |
|
||||
DAWN_TAG="v20260908.214631"
|
||||
DAWN_TAG="v20261120.121236"
|
||||
EMDAWN_PKG="emdawnwebgpu_pkg-${DAWN_TAG}.zip"
|
||||
echo "Downloading ${EMDAWN_PKG}"
|
||||
curl -L -o emdawn.zip \
|
||||
|
||||
+5
-5
@@ -326,7 +326,7 @@ static bool parse_bool_value(const std::string & value) {
|
||||
// common_models_handler
|
||||
//
|
||||
|
||||
static std::string get_default_local_path(const std::string & url) {
|
||||
std::string common_get_default_local_path(const std::string & url) {
|
||||
auto f = string_split<std::string>(url, '#').front();
|
||||
f = string_split<std::string>(f, '?').front();
|
||||
return fs_get_cache_file(string_split<std::string>(f, '/').back()).string();
|
||||
@@ -436,7 +436,7 @@ static std::vector<common_download_task> build_url_tasks(const common_params_mod
|
||||
if (parts.size() == 1) {
|
||||
common_download_task task;
|
||||
task.url = parts[0];
|
||||
task.local_path = model.path.empty() ? get_default_local_path(parts[0]) : model.path;
|
||||
task.local_path = model.path.empty() ? common_get_default_local_path(parts[0]) : model.path;
|
||||
task.opts = opts;
|
||||
tasks.push_back(std::move(task));
|
||||
return tasks;
|
||||
@@ -454,7 +454,7 @@ static std::vector<common_download_task> build_url_tasks(const common_params_mod
|
||||
task.url = part;
|
||||
task.opts = opts;
|
||||
|
||||
std::string local = get_default_local_path(part);
|
||||
std::string local = common_get_default_local_path(part);
|
||||
if (!base_dir.empty()) {
|
||||
auto pos = local.rfind('/');
|
||||
std::string name = pos == std::string::npos ? local : local.substr(pos + 1);
|
||||
@@ -487,7 +487,7 @@ void common_models_handler_apply(common_models_handler & handler, common_params
|
||||
auto handle_url = [&](common_params_model & model) {
|
||||
if (!model.url.empty()) {
|
||||
if (model.path.empty()) {
|
||||
model.path = get_default_local_path(model.url);
|
||||
model.path = common_get_default_local_path(model.url);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -498,7 +498,7 @@ void common_models_handler_apply(common_models_handler & handler, common_params
|
||||
// optionally, if docker repo is set, resolve it
|
||||
if (!params.model.docker_repo.empty()) {
|
||||
params.model.url = common_docker_resolve_model(params.model.docker_repo);
|
||||
params.model.path = get_default_local_path(params.model.url);
|
||||
params.model.path = common_get_default_local_path(params.model.url);
|
||||
}
|
||||
|
||||
// handle plain "url" tasks (non-hf)
|
||||
|
||||
@@ -149,6 +149,9 @@ common_models_handler common_models_handler_init(const common_params & params, l
|
||||
// check if the model is a preset repo (i.e. has a preset file)
|
||||
bool common_models_handler_is_preset_repo(const common_models_handler & handler);
|
||||
|
||||
// the cache path a model downloaded from a plain url is stored at
|
||||
std::string common_get_default_local_path(const std::string & url);
|
||||
|
||||
// download and update params with the downloaded model path
|
||||
void common_models_handler_apply(common_models_handler & handler, common_params & params, common_download_callback * callback = nullptr);
|
||||
|
||||
|
||||
@@ -69,9 +69,21 @@ common_chat_params peg_generator::generate_parser(const common_chat_template &
|
||||
std::string trigger_marker = !autoparser.tools.format.section_start.empty() ? autoparser.tools.format.section_start :
|
||||
autoparser.tools.format.per_call_start;
|
||||
|
||||
// bare JSON calls without a start marker (e.g. Llama 3.x): trigger the lazy grammar on the call's opening instead
|
||||
std::string trigger_pattern;
|
||||
{
|
||||
const auto & fmt = autoparser.tools.format;
|
||||
bool top_level_name = (fmt.function_field.empty() || fmt.function_field == "function") &&
|
||||
fmt.name_field.find('.') == std::string::npos;
|
||||
if (trigger_marker.empty() && fmt.mode == tool_format::JSON_NATIVE && !fmt.fun_name_is_key &&
|
||||
!fmt.tools_array_wrapped && top_level_name) {
|
||||
trigger_pattern = "\\{\\s*\"" + regex_escape(fmt.name_field) + "\"\\s*:";
|
||||
}
|
||||
}
|
||||
|
||||
bool has_response_format = !inputs.json_schema.empty() && inputs.json_schema.is_object();
|
||||
bool include_grammar = has_response_format || (has_tools &&
|
||||
((inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && !trigger_marker.empty()) ||
|
||||
((inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && (!trigger_marker.empty() || !trigger_pattern.empty())) ||
|
||||
inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
|
||||
|
||||
if (include_grammar) {
|
||||
@@ -82,9 +94,11 @@ common_chat_params peg_generator::generate_parser(const common_chat_template &
|
||||
|
||||
// Set grammar triggers based on tool section markers (fall back to per-call markers)
|
||||
if (data.grammar_lazy) {
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, trigger_marker }
|
||||
};
|
||||
if (!trigger_marker.empty()) {
|
||||
data.grammar_triggers = { { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, trigger_marker } };
|
||||
} else {
|
||||
data.grammar_triggers = { { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, trigger_pattern } };
|
||||
}
|
||||
if (autoparser.tools.format.openai_wrapper_trigger) {
|
||||
// model emits the OpenAI function wrapper, trigger on it
|
||||
data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "{\"type\": \"function\"," });
|
||||
@@ -359,7 +373,9 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
auto & p = ctx.p;
|
||||
const auto & inputs = ctx.inputs;
|
||||
|
||||
auto until_suffix = p.rule("until-suffix", p.until(arguments.value_suffix));
|
||||
// A raw string value needs a suffix to end on, without one it is parsed as JSON
|
||||
bool raw_strings = !arguments.value_suffix.empty();
|
||||
auto until_suffix = raw_strings ? p.rule("until-suffix", p.until(arguments.value_suffix)) : p.eps();
|
||||
|
||||
common_peg_parser tool_choice = p.choice();
|
||||
|
||||
@@ -375,9 +391,9 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
p.tool_arg(p.tool_arg_open(arguments.name_prefix + p.tool_arg_name(p.literal(param.name)) +
|
||||
arguments.name_suffix) +
|
||||
arguments.value_prefix +
|
||||
(param.schema->may_be_string() ?
|
||||
p.ac(p.tool_arg_string_value(until_suffix) +
|
||||
p.tool_arg_close(p.literal(arguments.value_suffix)), arguments.value_suffix) :
|
||||
(raw_strings && param.schema->may_be_string() ?
|
||||
p.through(p.tool_arg_string_value(until_suffix),
|
||||
p.tool_arg_close(p.literal(arguments.value_suffix))) :
|
||||
(p.tool_arg_json_value(p.schema(
|
||||
p.json(), "tool-" + std::to_string(tool_index) + "-arg-" + std::to_string(param_index) + "-schema", doc, *param.schema)) +
|
||||
p.tool_arg_close(p.literal(arguments.value_suffix)))));
|
||||
|
||||
@@ -71,6 +71,7 @@ struct generation_params {
|
||||
bool is_inference = true;
|
||||
bool add_inference = false;
|
||||
bool mark_input = true; // whether to mark input strings in the jinja context
|
||||
common_peg_tokens specials;
|
||||
|
||||
bool has_continuation() const {
|
||||
return continue_final_message != COMMON_CHAT_CONTINUATION_NONE && !continue_msg.empty();
|
||||
|
||||
@@ -71,6 +71,9 @@ constexpr size_t COMMON_CHAT_MAX_PERMUTE = 6;
|
||||
|
||||
class common_chat_peg_builder : public common_peg_parser_builder {
|
||||
public:
|
||||
common_chat_peg_builder() = default;
|
||||
explicit common_chat_peg_builder(common_peg_tokens tokens) : common_peg_parser_builder(std::move(tokens)) {}
|
||||
|
||||
// Tag constants (from former common_chat_peg_base_builder)
|
||||
static constexpr const char * REASONING_BLOCK = "reasoning-block";
|
||||
static constexpr const char * REASONING = "reasoning";
|
||||
@@ -200,6 +203,14 @@ inline common_peg_arena build_chat_peg_parser(
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
inline common_peg_arena build_chat_peg_parser(
|
||||
const common_peg_tokens & specials,
|
||||
const std::function<common_peg_parser(common_chat_peg_builder & builder)> & fn) {
|
||||
common_chat_peg_builder builder(specials);
|
||||
builder.set_root(fn(builder));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
class tag_based_peg_mapper {
|
||||
public:
|
||||
std::map<std::string, std::string> tags;
|
||||
|
||||
+19
-3
@@ -315,6 +315,7 @@ struct common_chat_templates {
|
||||
bool add_bos;
|
||||
bool add_eos;
|
||||
bool has_explicit_template; // Model had builtin template or template overridden was specified.
|
||||
common_peg_tokens specials;
|
||||
std::unique_ptr<common_chat_template> template_default; // always set (defaults to chatml)
|
||||
std::unique_ptr<common_chat_template> template_tool_use;
|
||||
std::unique_ptr<common_chat_template> template_tts; // the prompt of a text to speak
|
||||
@@ -802,6 +803,10 @@ void common_chat_templates_free(struct common_chat_templates * tmpls) {
|
||||
delete tmpls;
|
||||
}
|
||||
|
||||
void common_chat_templates_set_specials(struct common_chat_templates * tmpls, common_peg_tokens specials) {
|
||||
tmpls->specials = std::move(specials);
|
||||
}
|
||||
|
||||
bool common_chat_templates_was_explicit(const struct common_chat_templates * tmpls) {
|
||||
return tmpls->has_explicit_template;
|
||||
}
|
||||
@@ -978,6 +983,7 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model *
|
||||
std::string token_eos = eos_token_override;
|
||||
bool add_bos = false;
|
||||
bool add_eos = false;
|
||||
common_peg_tokens specials;
|
||||
if (model) {
|
||||
const auto * vocab = llama_model_get_vocab(model);
|
||||
const auto get_token = [&](llama_token token, const char * name, const char * jinja_variable_name) {
|
||||
@@ -997,11 +1003,13 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model *
|
||||
token_eos = get_token(llama_vocab_eos(vocab), "EOS", "eos_token");
|
||||
add_bos = llama_vocab_get_add_bos(vocab);
|
||||
add_eos = llama_vocab_get_add_eos(vocab);
|
||||
specials = common_peg_tokens(vocab);
|
||||
}
|
||||
common_chat_templates_ptr tmpls(new common_chat_templates());
|
||||
tmpls->has_explicit_template = has_explicit_template;
|
||||
tmpls->add_bos = add_bos;
|
||||
tmpls->add_eos = add_eos;
|
||||
tmpls->specials = std::move(specials);
|
||||
try {
|
||||
tmpls->template_default = std::make_unique<common_chat_template>(default_template_src, token_bos, token_eos);
|
||||
} catch (const std::exception & e) {
|
||||
@@ -1398,7 +1406,7 @@ static common_chat_params_init_fn common_chat_template_detect_params_init(const
|
||||
}
|
||||
|
||||
// LFM2.5 format detection: template uses plain "List of tools: [...]" with no special tokens
|
||||
if (src.find("List of tools: [") != std::string::npos &&
|
||||
if (src.find("List of tools: ") != std::string::npos &&
|
||||
src.find("<|tool_list_start|>") == std::string::npos) {
|
||||
LOG_DBG("Using specialized template: LFM2.5\n");
|
||||
return common_chat_params_init_lfm2_5;
|
||||
@@ -1543,6 +1551,7 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
|
||||
params.add_generation_prompt = inputs.add_generation_prompt;
|
||||
params.add_bos = tmpls->add_bos;
|
||||
params.add_eos = tmpls->add_eos;
|
||||
params.specials = tmpls->specials;
|
||||
|
||||
params.continue_final_message = inputs.continue_final_message;
|
||||
if (params.continue_final_message != COMMON_CHAT_CONTINUATION_NONE) {
|
||||
@@ -1825,6 +1834,7 @@ common_chat_input common_chat_input_tokenize(const llama_vocab * vocab, const st
|
||||
}
|
||||
if (input.text != text) {
|
||||
// the pieces do not give back the same text, keep the text without tokens
|
||||
LOG_WRN("%s: token pieces do not match the text, parsing without token ids\n", __func__);
|
||||
return common_chat_input(text);
|
||||
}
|
||||
return input;
|
||||
@@ -1935,11 +1945,17 @@ common_chat_session::common_chat_session(const common_chat_templates * tm
|
||||
thinking_ends = std::move(applied.thinking_end_tags);
|
||||
|
||||
parser_params.format = applied.format;
|
||||
parser_params.generation_prompt = vocab ? common_chat_input_tokenize(vocab, applied.generation_prompt)
|
||||
: common_chat_input(applied.generation_prompt);
|
||||
parser_params.debug = params.debug;
|
||||
parser_params.parser = std::move(applied.parser);
|
||||
|
||||
if (vocab) {
|
||||
parser_params.generation_prompt = common_chat_input_tokenize(vocab, applied.generation_prompt);
|
||||
} else if (params.tokenize) {
|
||||
parser_params.generation_prompt = params.tokenize(applied.generation_prompt);
|
||||
} else {
|
||||
parser_params.generation_prompt = common_chat_input(applied.generation_prompt);
|
||||
}
|
||||
|
||||
delimiters = std::move(applied.message_delimiters);
|
||||
|
||||
if (vocab) {
|
||||
|
||||
@@ -372,6 +372,9 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model *
|
||||
const std::string & bos_token_override = "",
|
||||
const std::string & eos_token_override = "");
|
||||
|
||||
// override special tokens for testing
|
||||
void common_chat_templates_set_specials(struct common_chat_templates * tmpls, common_peg_tokens specials);
|
||||
|
||||
bool common_chat_templates_was_explicit(const struct common_chat_templates * tmpls);
|
||||
std::string common_chat_templates_source(const struct common_chat_templates * tmpls, const std::string & variant = "");
|
||||
|
||||
@@ -397,6 +400,9 @@ common_chat_msg common_chat_peg_parse(const common_peg_arena & src_parser, const
|
||||
struct common_chat_session_params {
|
||||
bool echo = false; // include the assistant prefill in the output when continuing a message
|
||||
bool debug = false; // enable debug output for the PEG parser
|
||||
|
||||
// tokenize the generation prompt when there is no vocab for testing
|
||||
std::function<common_chat_input(const std::string &)> tokenize;
|
||||
};
|
||||
|
||||
class common_chat_session {
|
||||
|
||||
+20
-6
@@ -98,6 +98,9 @@ class ProgressBar : public common_download_callback {
|
||||
std::string filename;
|
||||
size_t len = 0;
|
||||
|
||||
// the caller's callback, if any, still receives every event
|
||||
common_download_callback * next;
|
||||
|
||||
static void cleanup(const ProgressBar * line) {
|
||||
lines.erase(line);
|
||||
if (lines.empty()) {
|
||||
@@ -110,9 +113,12 @@ class ProgressBar : public common_download_callback {
|
||||
}
|
||||
|
||||
public:
|
||||
ProgressBar() = default;
|
||||
ProgressBar(common_download_callback * next) : next(next) {}
|
||||
|
||||
void on_start(const common_download_progress & p) override {
|
||||
if (next) {
|
||||
next->on_start(p);
|
||||
}
|
||||
filename = url_get_filename(p.url);
|
||||
|
||||
for (size_t i = 0; i < filename.size(); ++i) {
|
||||
@@ -126,12 +132,22 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
void on_done(const common_download_progress &, bool) override {
|
||||
void on_done(const common_download_progress & p, bool ok) override {
|
||||
if (next) {
|
||||
next->on_done(p, ok);
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
cleanup(this);
|
||||
}
|
||||
|
||||
bool is_cancelled() const override {
|
||||
return next && next->is_cancelled();
|
||||
}
|
||||
|
||||
void on_update(const common_download_progress & p) override {
|
||||
if (next) {
|
||||
next->on_update(p);
|
||||
}
|
||||
if (!p.total || !is_output_a_tty()) {
|
||||
return;
|
||||
}
|
||||
@@ -519,11 +535,9 @@ int common_download_file_single(const std::string & url,
|
||||
const std::string & lock_path,
|
||||
const std::string & alt_path) {
|
||||
if (!opts.offline) {
|
||||
ProgressBar tty_cb;
|
||||
ProgressBar tty_cb(opts.callback);
|
||||
common_download_opts online_opts = opts;
|
||||
if (!online_opts.callback) {
|
||||
online_opts.callback = &tty_cb;
|
||||
}
|
||||
online_opts.callback = &tty_cb;
|
||||
return common_download_file_single_online(url, path, online_opts, skip_etag, lock_path, alt_path);
|
||||
}
|
||||
|
||||
|
||||
@@ -593,7 +593,7 @@ caps caps_get(jinja::program & prog) {
|
||||
if (result.supports_reasoning_effort) {
|
||||
JJ_DEBUG("%s\n", ">>> Running capability check: reasoning effort levels");
|
||||
|
||||
static const std::vector<std::string> candidates = { "minimal", "low", "medium", "high", "xhigh", "max" };
|
||||
static const std::vector<std::string> candidates = { "none", "minimal", "low", "medium", "high", "xhigh", "max" };
|
||||
|
||||
// renders a single user turn with the given effort, nothing when the template raises
|
||||
const auto render = [&](const std::string & effort) {
|
||||
@@ -631,7 +631,10 @@ caps caps_get(jinja::program & prog) {
|
||||
for (const auto & level : candidates) {
|
||||
const auto rendered = render(level);
|
||||
if (!rendered) {
|
||||
rejected.push_back(level);
|
||||
// "none" also turns thinking off, so the server does not answer it with an error
|
||||
if (level != "none") {
|
||||
rejected.push_back(level);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (rendered == unknown) {
|
||||
|
||||
@@ -676,8 +676,8 @@ private:
|
||||
const auto & node = trie.nodes[idx];
|
||||
std::string rejects;
|
||||
auto first = true;
|
||||
for (const auto & [cpt, child] : node.children) {
|
||||
std::string c = common_unicode_cpt_to_utf8(cpt);
|
||||
for (const auto & [sym, child] : node.children) {
|
||||
std::string c = common_unicode_cpt_to_utf8(sym.value);
|
||||
rejects += c;
|
||||
if (first) {
|
||||
first = false;
|
||||
|
||||
+29
-26
@@ -24,7 +24,9 @@ struct depth_guard {
|
||||
// Gemma 4 value parsers
|
||||
void gemma4_value_rules(common_chat_peg_builder & p) {
|
||||
// The tags are what gemma4_to_json() in the mapper reads, the rules may wrap them freely.
|
||||
p.rule("gemma4-string", p.tag(gemma4::STRING, p.literal("<|\"|>") + p.tag(gemma4::STRING_CONTENT, p.until("<|\"|>")) + p.literal("<|\"|>")));
|
||||
auto string_delim = p.token("<|\"|>");
|
||||
|
||||
p.rule("gemma4-string", p.tag(gemma4::STRING, string_delim + p.tag(gemma4::STRING_CONTENT, p.until(string_delim)) + string_delim));
|
||||
|
||||
p.rule("gemma4-bool", p.tag(gemma4::BOOL, p.json_bool()));
|
||||
|
||||
@@ -34,7 +36,7 @@ void gemma4_value_rules(common_chat_peg_builder & p) {
|
||||
|
||||
// Keys are bare in the template, but Gemma 4 occasionally wraps them in quotes
|
||||
p.rule("gemma4-dict-key", p.tag(gemma4::DICT_KEY, p.choice({
|
||||
p.literal("<|\"|>") + p.tag(gemma4::DICT_KEY_NAME, p.until("<|\"|>")) + p.literal("<|\"|>"),
|
||||
string_delim + p.tag(gemma4::DICT_KEY_NAME, p.until(string_delim)) + string_delim,
|
||||
p.literal("\"") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^\"]", 1, -1)) + p.literal("\""),
|
||||
p.literal("'") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^']", 1, -1)) + p.literal("'"),
|
||||
p.tag(gemma4::DICT_KEY_NAME, p.chars("[^:}]", 1, -1)),
|
||||
@@ -144,7 +146,7 @@ class gemma4_schema_parser {
|
||||
alts |= name();
|
||||
}
|
||||
// Gemma 4 may emit keys in its string delimiters or quotes
|
||||
alts |= p_.literal("<|\"|>") + name() + p_.literal("<|\"|>");
|
||||
alts |= p_.token("<|\"|>") + name() + p_.token("<|\"|>");
|
||||
if (key.find('\'') == std::string::npos) {
|
||||
alts |= p_.literal("'") + name() + p_.literal("'");
|
||||
}
|
||||
@@ -331,18 +333,23 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template &
|
||||
auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE);
|
||||
auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
|
||||
|
||||
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
||||
auto start = p.rule("start", p.optional(p.literal("<|turn>model\n")));
|
||||
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto start = p.rule("start", p.optional(p.token("<|turn>") + p.literal("model\n")));
|
||||
auto channel_start = p.token("<|channel>");
|
||||
auto channel_end = p.token("<channel|>");
|
||||
auto think_start = channel_start + p.literal("thought");
|
||||
auto tool_call_start = p.token("<|tool_call>");
|
||||
// the model may start a tool call before closing the thought channel
|
||||
auto think_end = channel_end | p.peek(tool_call_start);
|
||||
|
||||
if (extract_reasoning) {
|
||||
// the model may start a tool call before closing the thought channel
|
||||
p.rule("thought", p.literal("<|channel>thought") + p.space() + p.reasoning(p.until_one_of({"<channel|>", "<|tool_call>"})) + (p.literal("<channel|>") | p.peek(p.literal("<|tool_call>"))));
|
||||
p.rule("thought", think_start + p.space() + p.reasoning(p.until(channel_end | tool_call_start)) + think_end);
|
||||
} else {
|
||||
p.rule("thought", p.content(p.literal("<|channel>thought") + p.space() + p.until_one_of({"<channel|>", "<|tool_call>"}) + (p.literal("<channel|>") | p.peek(p.literal("<|tool_call>")))));
|
||||
p.rule("thought", p.content(think_start + p.space() + p.until(channel_end | tool_call_start) + think_end));
|
||||
}
|
||||
|
||||
auto consume_empty_channels = p.gbnf(p.zero_or_more(p.literal("<|channel>") + p.negate(p.literal("thought"))), "");
|
||||
auto thought = (p.peek(p.literal("<|channel>")) + consume_empty_channels + p.ref("thought")) | p.negate(p.literal("<|channel>"));
|
||||
auto consume_empty_channels = p.gbnf(p.zero_or_more(channel_start + p.negate(p.literal("thought"))), "");
|
||||
auto thought = (p.peek(channel_start) + consume_empty_channels + p.ref("thought")) | p.negate(channel_start);
|
||||
|
||||
if (has_response_format) {
|
||||
auto response_format = p.literal("```json") <<
|
||||
@@ -378,39 +385,35 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template &
|
||||
})));
|
||||
});
|
||||
|
||||
auto tool_call = p.trigger_rule("tool-call", p.repeat(
|
||||
"<|tool_call>call:" + tool_choice + "<tool_call|>",
|
||||
/* min = */ inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0,
|
||||
/* max = */ inputs.parallel_tool_calls ? -1 : 1
|
||||
));
|
||||
auto tool_call_rest = p.literal("call:") + tool_choice + p.token("<tool_call|>");
|
||||
auto tool_call = p.rule("tool-call", tool_call_start + tool_call_rest);
|
||||
auto more = inputs.parallel_tool_calls ? p.zero_or_more(tool_call) : p.eps();
|
||||
|
||||
auto tool_calls = p.trigger_rule("tool-calls", tool_call_start, tool_call_rest + more);
|
||||
|
||||
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
return start + thought + tool_call;
|
||||
return start + thought + tool_calls;
|
||||
}
|
||||
|
||||
auto scan_to_toolcall = p.rule("scan-to-toolcall", p.until("<|tool_call>"));
|
||||
auto content = p.rule("content", p.content(p.until_one_of({"<|channel>", "<channel|>", "<|tool_call>"})));
|
||||
auto scan_to_toolcall = p.rule("scan-to-toolcall", p.until(tool_call_start));
|
||||
auto content = p.rule("content", p.content(p.until(channel_start | channel_end | tool_call_start)));
|
||||
auto message = p.rule("message", thought + content);
|
||||
return start + p.zero_or_more(message) + scan_to_toolcall + tool_call;
|
||||
return start + p.zero_or_more(message) + scan_to_toolcall + p.optional(tool_calls);
|
||||
}
|
||||
|
||||
// Gemma 4 may emit an extra <|channel>thought\n<channel|> at the end of the content. It may
|
||||
// also emit a single trailing <channel|> token. Consume all complete reasoning blocks and
|
||||
// then stop at the first unmatched <channel|> token.
|
||||
auto content = p.rule("content", p.content(p.until_one_of({"<|channel>", "<channel|>"})));
|
||||
auto content = p.rule("content", p.content(p.until(channel_start | channel_end)));
|
||||
auto message = p.rule("message", thought + content);
|
||||
return start + p.one_or_more(message);
|
||||
});
|
||||
|
||||
if (include_grammar) {
|
||||
data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
|
||||
data.grammar_lazy = false;
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
data.parser.build_grammar(builder, !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)));
|
||||
});
|
||||
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|tool_call>" },
|
||||
};
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
+31
-30
@@ -65,17 +65,18 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template &
|
||||
auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE);
|
||||
auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
|
||||
|
||||
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
||||
auto start = p.rule("start", p.literal("<|start|>assistant"));
|
||||
auto end = p.rule("end", p.literal("<|end|>"));
|
||||
auto content = p.rule("message-content", p.until("<|end|>"));
|
||||
auto channel = p.literal("<|channel|>") + (p.literal("commentary") | p.literal("analysis"));
|
||||
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto start_assistant = p.token("<|start|>") + p.literal("assistant");
|
||||
auto start = p.rule("start", start_assistant);
|
||||
auto end = p.rule("end", p.token("<|end|>"));
|
||||
auto content = p.rule("message-content", p.until(p.token("<|end|>")));
|
||||
auto channel = p.token("<|channel|>") + (p.literal("commentary") | p.literal("analysis"));
|
||||
auto constrain_type = p.chars("[A-Za-z0-9_-]", 1, -1);
|
||||
auto constraint = p.optional(p.space() + p.optional(p.literal("<|constrain|>")) + constrain_type);
|
||||
auto constraint = p.optional(p.chars("[ ]", 1, -1) + p.optional(p.token("<|constrain|>")) + constrain_type);
|
||||
|
||||
// Occasionally, gpt-oss-20b will prefix channels with this commentary
|
||||
auto stray_commentary = p.optional(p.literal("<|channel|>commentary") + p.optional(p.literal(" to=assistant")));
|
||||
auto start_analysis = stray_commentary + p.literal("<|channel|>analysis<|message|>");
|
||||
auto stray_commentary = p.optional(p.token("<|channel|>") + p.literal("commentary") + p.optional(p.literal(" to=assistant")));
|
||||
auto start_analysis = stray_commentary + p.token("<|channel|>") + p.literal("analysis") + p.token("<|message|>");
|
||||
|
||||
if (extract_reasoning) {
|
||||
p.rule("analysis", start_analysis + p.reasoning(content) + end);
|
||||
@@ -84,8 +85,8 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template &
|
||||
}
|
||||
|
||||
auto analysis = p.ref("analysis");
|
||||
auto preamble = p.rule("preamble", p.literal("<|channel|>commentary<|message|>") + p.content(content) + end);
|
||||
auto final_msg = p.rule("final", stray_commentary + p.literal("<|channel|>final") + constraint + p.literal("<|message|>") + p.content(content));
|
||||
auto preamble = p.rule("preamble", p.token("<|channel|>") + p.literal("commentary") + p.token("<|message|>") + p.content(content) + end);
|
||||
auto final_msg = p.rule("final", stray_commentary + p.token("<|channel|>") + p.literal("final") + constraint + p.token("<|message|>") + p.content(content));
|
||||
|
||||
// Consume any unsolicited tool calls, e.g. builtin functions
|
||||
auto unsolicited = p.rule("unsolicited", p.atomic(p.optional(channel) + p.literal(" to=") + content + end));
|
||||
@@ -94,58 +95,58 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template &
|
||||
|
||||
if (has_response_format) {
|
||||
auto response_format = p.rule("response-format",
|
||||
p.literal("<|channel|>final") + constraint + p.literal("<|message|>") +
|
||||
p.token("<|channel|>") + p.literal("final") + constraint + p.token("<|message|>") +
|
||||
p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)));
|
||||
|
||||
return p.zero_or_more(start + analysis) + start + response_format;
|
||||
}
|
||||
|
||||
if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
|
||||
auto tool_choice = p.choice();
|
||||
auto in_role = p.choice();
|
||||
auto in_channel = p.choice();
|
||||
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
const auto & function = tool.at("function");
|
||||
std::string name = function.at("name");
|
||||
const auto params = common_chat_tool_parameters(function);
|
||||
|
||||
auto func_name = p.literal(" to=functions.") + p.tool_name(p.literal(name));
|
||||
auto func_name = p.tool_name(p.literal(name));
|
||||
auto args = p.tool_args(p.schema(p.json(), "tool-" + std::to_string(tool_index) + "-schema", params));
|
||||
|
||||
// recipient in role header
|
||||
// <|start|>assistant to=functions.NAME<|channel|>(commentary|analysis)[constraint]<|message|>ARGS
|
||||
auto tool_in_role = p.tool(p.tool_open(func_name + channel + constraint + p.literal("<|message|>")) + args);
|
||||
in_role |= p.rule("tool-" + std::to_string(tool_index) + "-in-role",
|
||||
p.atomic(func_name + channel + constraint + p.token("<|message|>")) + args);
|
||||
|
||||
// recipient in channel header
|
||||
// <|channel|>(commentary|analysis) to=functions.NAME[constraint]<|message|>ARGS
|
||||
auto tool_in_channel = p.tool(p.tool_open(channel + func_name + constraint + p.literal("<|message|>")) + args);
|
||||
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), tool_in_role | tool_in_channel);
|
||||
// <|start|>assistant<|channel|>(commentary|analysis) to=functions.NAME[constraint]<|message|>ARGS
|
||||
in_channel |= p.rule("tool-" + std::to_string(tool_index) + "-in-channel",
|
||||
p.atomic(func_name + constraint + p.token("<|message|>")) + args);
|
||||
});
|
||||
|
||||
auto tool_call = p.trigger_rule("tool-call", tool_choice);
|
||||
// The recipient prefix is the trigger, so the grammar constrains the name that follows it
|
||||
auto to_functions = p.tool_open(p.literal(" to=functions."));
|
||||
auto tool_call = p.choice({
|
||||
p.trigger_rule("tool-call-in-role", start_assistant + to_functions, in_role),
|
||||
p.trigger_rule("tool-call-in-channel", start_assistant + channel + to_functions, in_channel)
|
||||
});
|
||||
|
||||
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
return p.zero_or_more(start + any) + start + tool_call;
|
||||
return p.zero_or_more(start + any) + tool_call;
|
||||
}
|
||||
|
||||
return p.zero_or_more(start + any) + start + (tool_call | final_msg);
|
||||
return p.zero_or_more(start + any) + (tool_call | (start + final_msg));
|
||||
}
|
||||
|
||||
return p.zero_or_more(start + any) + start + (final_msg | unsolicited);
|
||||
});
|
||||
|
||||
if (include_grammar) {
|
||||
data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
|
||||
// The grammar scans for the triggers itself, so the sampler runs it from the first token
|
||||
data.grammar_lazy = false;
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO);
|
||||
});
|
||||
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "^\\s+to$" },
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "^<\\|channel\\|>(?:commentary|analysis)\\s+to=functions$" },
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|start\\|>assistant(\\s+to)" },
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|start\\|>assistant(<\\|channel\\|>(?:commentary|analysis)\\s+to)" }
|
||||
};
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
@@ -99,8 +99,11 @@ common_chat_params common_chat_params_init_harmony_xml(const common_chat_templat
|
||||
auto arg_close = p.tool_arg_close(p.gbnf(
|
||||
p.literal(PARAM_CLOSE) | (p.literal("\n") + p.peek(p.optional(p.literal("\n")) + next_open)),
|
||||
gbnf_format_literal("\n") + " " + gbnf_format_literal(PARAM_CLOSE.substr(1)) + "?"));
|
||||
auto arg_string = p.rule("rfl-arg-string",
|
||||
p.ac(p.tool_arg_string_value(p.until_one_of(string_ends)) + arg_close, PARAM_CLOSE));
|
||||
auto string_value = p.tool_arg_string_value(p.until_one_of(string_ends));
|
||||
auto arg_string = p.rule("rfl-arg-string", p.through(string_value, p.tool_arg_close(p.literal(PARAM_CLOSE))));
|
||||
// the parser also accepts a value with no closing tag, the grammar still requires the closing tag
|
||||
auto missing_close = string_value + p.tool_arg_close(p.literal("\n") + p.peek(p.optional(p.literal("\n")) + next_open));
|
||||
arg_string = p.gbnf(arg_string | missing_close, "rfl-arg-string");
|
||||
auto arg_sep = p.optional(p.literal("\n"));
|
||||
|
||||
std::string call_close_gbnf = gbnf_format_literal("<|end|>");
|
||||
|
||||
@@ -91,7 +91,7 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template
|
||||
}
|
||||
auto think_body = p.until_one_of(data.thinking_end_tags);
|
||||
auto think_block = [&](const common_peg_parser & body) {
|
||||
return p.optional(THINK_START + p.space() + p.ac(body + think_end, data.thinking_end_tags));
|
||||
return p.optional(THINK_START + p.space() + p.through(body, think_end));
|
||||
};
|
||||
auto reasoning = extract_reasoning ? think_block(p.reasoning(think_body)) : p.eps();
|
||||
|
||||
@@ -110,7 +110,7 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template
|
||||
tool_choice = p.standard_json_tools(CALL_START, CALL_END, inputs.tools, false, true);
|
||||
} else {
|
||||
auto arg_close = p.tool_arg_close(p.literal(ARG_VAL_END));
|
||||
auto arg_string = p.rule("xml-arg-string", p.ac(p.tool_arg_string_value(p.until(ARG_VAL_END)) + arg_close, ARG_VAL_END));
|
||||
auto arg_string = p.rule("xml-arg-string", p.through(p.tool_arg_string_value(p.until(ARG_VAL_END)), arg_close));
|
||||
|
||||
// The models leave out <ifm|arg_type> even when asked for xml_typed
|
||||
auto arg_type = call_format == "xml_typed" ? p.optional(ARG_TYPE + p.until(ARG_TYPE_END) + ARG_TYPE_END + p.space()) : p.eps();
|
||||
|
||||
@@ -63,8 +63,8 @@ common_chat_params common_chat_params_init_minicpm5(const common_chat_template &
|
||||
// CDATA lets a value carry characters that would otherwise close the tag (e.g.
|
||||
// </param>); capture the inner text only, excluding the CDATA markers.
|
||||
auto string_value = p.choice({
|
||||
p.literal("<![CDATA[") + p.ac(p.tool_arg_string_value(p.until("]]>")) + p.literal("]]>"), "]]>") + p.tool_arg_close(p.literal("</param>")),
|
||||
p.negate(p.literal("<![CDATA[")) + p.ac(p.tool_arg_string_value(p.until("</param>")) + p.tool_arg_close(p.literal("</param>")), "</param>")
|
||||
p.literal("<![CDATA[") + p.through(p.tool_arg_string_value(p.until("]]>")), "]]>") + p.tool_arg_close(p.literal("</param>")),
|
||||
p.negate(p.literal("< {
|
||||
auto start = p.rule("start", p.literal("<|start|>assistant"));
|
||||
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto start_token = p.token("<|start|>");
|
||||
auto message = p.token("<|message|>");
|
||||
auto eom = p.token("<|eom|>");
|
||||
auto start = p.rule("start", start_token + p.literal("assistant"));
|
||||
|
||||
if (!extract_reasoning && !include_grammar) {
|
||||
return start + p.content(p.rest());
|
||||
}
|
||||
|
||||
if (extract_reasoning) {
|
||||
p.rule("analysis", p.literal(" to=self<|message|>") + p.reasoning(p.until("<|eom|>")) + p.literal("<|eom|>"));
|
||||
p.rule("analysis", p.literal(" to=self") + message + p.reasoning(p.until(eom)) + eom);
|
||||
} else {
|
||||
p.rule("analysis", p.literal(" to=self<|message|>") + p.content(p.until("<|eom|>")) + p.literal("<|eom|>"));
|
||||
p.rule("analysis", p.literal(" to=self") + message + p.content(p.until(eom)) + eom);
|
||||
}
|
||||
auto analysis = p.ref("analysis");
|
||||
|
||||
auto recipient = p.optional(p.literal(" to=user"));
|
||||
auto final_msg = p.rule("final", recipient + p.literal("<|message|>") +
|
||||
p.content(p.until_one_of({ "<|eot|>", "<|eom|>" })));
|
||||
auto final_msg = p.rule("final", recipient + message + p.content(p.until(eom)));
|
||||
|
||||
if (has_response_format) {
|
||||
auto response_json = p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema));
|
||||
auto response_format = p.rule("response-format",
|
||||
recipient + p.literal("<|message|>") +
|
||||
recipient + message +
|
||||
((p.literal("```json") + p.space() + response_json + p.space() + p.literal("```")) | response_json));
|
||||
|
||||
return p.zero_or_more(start + analysis) + start + response_format;
|
||||
}
|
||||
|
||||
if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
|
||||
auto string_value = p.ac(
|
||||
p.tool_arg_string_value(p.until("</atem:parameter>")) + p.tool_arg_close(p.literal("</atem:parameter>")),
|
||||
"</atem:parameter>");
|
||||
auto string_value = p.through(p.tool_arg_string_value(p.until("</atem:parameter>")),
|
||||
p.tool_arg_close(p.literal("</atem:parameter>")));
|
||||
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
@@ -106,40 +107,35 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa
|
||||
args = p.zero_or_more(p.choice(arg_rules) + p.space());
|
||||
}
|
||||
|
||||
auto tool_parser = p.tool(
|
||||
p.tool_open(p.literal(" to=") + p.until("<|message|>") +
|
||||
p.literal("<|message|><atem:function_calls>") + p.space() +
|
||||
p.literal("<atem:invoke name=\"") + p.tool_name(p.literal(name)) + p.literal("\">") + p.space())
|
||||
auto open = p.tool_open(start_token + p.literal("assistant to=") + p.tool_name(p.literal(name)) + message);
|
||||
auto body = p.rule("tool-" + std::to_string(tool_index),
|
||||
p.literal("<atem:function_calls>") + p.space() + p.literal("<atem:invoke name=\"" + name + "\">") + p.space()
|
||||
<< p.tool_args(args)
|
||||
<< p.tool_close(p.literal("</atem:invoke>") + p.space() + p.literal("</atem:function_calls>")));
|
||||
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), tool_parser);
|
||||
tool_choice |= open + body;
|
||||
});
|
||||
|
||||
auto tool_calls = inputs.parallel_tool_calls
|
||||
? p.trigger_rule("tool-call", tool_choice + p.zero_or_more(p.literal("<|eom|>") + start + tool_choice))
|
||||
: p.trigger_rule("tool-call", tool_choice);
|
||||
|
||||
auto more = inputs.parallel_tool_calls ? p.zero_or_more(eom + tool_choice) : p.eps();
|
||||
auto tool_calls = p.rule("tool-calls", tool_choice + more);
|
||||
|
||||
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
return p.zero_or_more(start + analysis) + start + tool_calls;
|
||||
return p.zero_or_more(start + analysis) + tool_calls;
|
||||
}
|
||||
auto trailing_calls = p.optional(p.literal("<|eom|>") + start + tool_calls);
|
||||
return p.zero_or_more(start + analysis) + start + (tool_calls | (final_msg + trailing_calls));
|
||||
auto trailing_calls = p.optional(eom + tool_calls);
|
||||
return p.zero_or_more(start + analysis) + (tool_calls | (start + final_msg + trailing_calls));
|
||||
}
|
||||
|
||||
return p.zero_or_more(start + analysis) + start + final_msg;
|
||||
});
|
||||
|
||||
if (include_grammar) {
|
||||
data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
|
||||
// Every message starts with a recipient header, so the grammar is not lazy.
|
||||
// The model cannot generate a recipient that is not self, user, or a tool.
|
||||
data.grammar_lazy = false;
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
data.parser.build_grammar(builder);
|
||||
});
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN,
|
||||
"(?:^|<\\|start\\|>assistant)( to=(?!self<\\|message\\|>)(?!user<\\|message\\|>)[^<]*?<\\|message\\|>)" },
|
||||
};
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
@@ -86,9 +86,8 @@ common_chat_params common_chat_params_init_muse_spark(const common_chat_template
|
||||
}
|
||||
|
||||
if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
|
||||
auto string_value = p.ac(
|
||||
p.tool_arg_string_value(p.until("</atem:parameter>")) + p.tool_arg_close(p.literal("</atem:parameter>")),
|
||||
"</atem:parameter>");
|
||||
auto string_value = p.through(p.tool_arg_string_value(p.until("</atem:parameter>")),
|
||||
p.tool_arg_close(p.literal("</atem:parameter>")));
|
||||
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
|
||||
@@ -59,27 +59,16 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
|
||||
data.prompt.append(data.generation_prompt);
|
||||
}
|
||||
|
||||
std::vector<std::string> tool_call_starts = { "<tool_call>" };
|
||||
|
||||
if (is_qwen3_coder) {
|
||||
// Match complete <function=name> opener for Qwen3-Coder models that occasionally omit the
|
||||
// starting <tool_call>. The model may hallucinate a tool name, but it is preferable over
|
||||
// constraining on <function which may occur in valid content generation, e.g. #include <functional>
|
||||
foreach_function(inputs.tools, [&](size_t, const json & tool) {
|
||||
const std::string name = tool.at("function").at("name");
|
||||
tool_call_starts.push_back("<function=" + name + ">");
|
||||
});
|
||||
}
|
||||
|
||||
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
||||
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto generation_prompt = p.literal(GEN_PREFIX);
|
||||
|
||||
// The template strips the newline before </think>, so leave it out of the reasoning
|
||||
auto think_body = p.until_one_of({ "\n</think>", "</think>", "<tool_call>" });
|
||||
auto think_close = p.literal("\n</think>") | p.literal("</think>") | p.peek(p.literal("<tool_call>"));
|
||||
auto think_end = (p.literal("\n") + p.token("</think>")) | p.token("</think>");
|
||||
auto think_body = p.until(think_end | p.token("<tool_call>"));
|
||||
auto think_close = think_end | p.peek(p.token("<tool_call>"));
|
||||
|
||||
auto reasoning_extracted = p.optional("<think>" + p.space() + p.reasoning(think_body) + think_close);
|
||||
auto reasoning_skipped = p.optional("<think>" + p.space() + think_body + think_close);
|
||||
auto reasoning_extracted = p.optional(p.token("<think>") + p.space() + p.reasoning(think_body) + think_close);
|
||||
auto reasoning_skipped = p.optional(p.token("<think>") + p.space() + think_body + think_close);
|
||||
|
||||
auto reasoning = p.eps();
|
||||
if (supports_reasoning && extract_reasoning) {
|
||||
@@ -99,7 +88,13 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
|
||||
if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
|
||||
auto arg_close = p.tool_arg_close(p.literal("\n</parameter>\n"));
|
||||
auto arg_string = p.rule("xml-arg-string",
|
||||
p.ac(p.tool_arg_string_value(p.until("\n</parameter>\n")) + arg_close, "\n</parameter>\n"));
|
||||
p.through(p.tool_arg_string_value(p.until("\n</parameter>\n")), arg_close));
|
||||
|
||||
auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0;
|
||||
|
||||
auto more = inputs.parallel_tool_calls ? p.zero_or_more(p.ref("tool-call")) : p.eps();
|
||||
auto starts = p.token("<tool_call>");
|
||||
auto tool_calls = p.choice();
|
||||
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
@@ -155,35 +150,29 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
|
||||
args = args + p.zero_or_more(p.choice(optional_args));
|
||||
}
|
||||
|
||||
auto func = p.tool(p.tool_open("<function=" + p.tool_name(p.literal(name)) + ">\n") +
|
||||
p.tool_args(args) +
|
||||
p.tool_close(p.literal("</function>\n")));
|
||||
auto opener = p.tool_open("<function=" + p.tool_name(p.literal(name)) + ">");
|
||||
auto body = p.literal("\n") + p.tool_args(args) + p.tool_close(p.literal("</function>\n"));
|
||||
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), func);
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(opener + body));
|
||||
|
||||
if (is_qwen3_coder) {
|
||||
// Qwen3-Coder models sometimes omit <tool_call>, so the full <function=name> opener is also a trigger.
|
||||
// Do not trigger on <function alone, it occurs in normal content, e.g. #include <functional>.
|
||||
tool_calls |= p.trigger_rule("tool-calls-" + std::to_string(tool_index), opener, body + p.token("</tool_call>") + p.space() + more);
|
||||
starts |= opener;
|
||||
}
|
||||
});
|
||||
|
||||
auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0;
|
||||
auto tool_call_body = tool_choice + p.token("</tool_call>") + p.space();
|
||||
p.rule("tool-call", p.token("<tool_call>") + p.literal("\n") + tool_call_body);
|
||||
|
||||
auto tool_call_body = tool_choice + "</tool_call>" + p.space();
|
||||
auto tool_call = p.rule("tool-call", "<tool_call>\n" + tool_call_body);
|
||||
|
||||
// Qwen3-Coder models may occasionally omit the <tool_call> token.
|
||||
auto tool_call_first = is_qwen3_coder ?
|
||||
p.rule("tool-call-first", p.optional(p.literal("<tool_call>\n")) + tool_call_body) :
|
||||
tool_call;
|
||||
|
||||
auto calls = inputs.parallel_tool_calls ? tool_call_first + p.zero_or_more(tool_call) : tool_call_first;
|
||||
auto tool_calls = p.trigger_rule("tool-call-root", p.repeat(calls, min_calls, 1));
|
||||
tool_calls |= p.trigger_rule("tool-calls", p.token("<tool_call>"), p.literal("\n") + tool_call_body + more);
|
||||
|
||||
// The templates separate content from the tool calls with one or two newlines,
|
||||
// stop the content before them
|
||||
std::vector<std::string> content_ends;
|
||||
for (const auto & start : tool_call_starts) {
|
||||
content_ends.insert(content_ends.end(), { "\n\n" + start, "\n" + start, start });
|
||||
}
|
||||
auto content_end = (p.literal("\n\n") + starts) | (p.literal("\n") + starts) | starts;
|
||||
|
||||
return generation_prompt +
|
||||
(reasoning << p.content(p.until_one_of(content_ends)) << tool_calls);
|
||||
return generation_prompt + (reasoning << p.content(p.until(content_end)) << p.repeat(tool_calls, min_calls, 1));
|
||||
}
|
||||
|
||||
// Content only parser
|
||||
@@ -191,17 +180,11 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
|
||||
});
|
||||
|
||||
if (include_grammar) {
|
||||
data.grammar_lazy = !has_response_format && has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO;
|
||||
|
||||
// The grammar scans for the triggers itself, so the sampler runs it from the first token
|
||||
data.grammar_lazy = false;
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO);
|
||||
});
|
||||
|
||||
if (data.grammar_lazy) {
|
||||
for (const auto & start : tool_call_starts) {
|
||||
data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, start });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
+544
-116
@@ -208,6 +208,89 @@ void common_peg_ast_arena::visit(const common_peg_parse_result & result, const c
|
||||
}
|
||||
}
|
||||
|
||||
common_peg_tokens::common_peg_tokens(const llama_vocab * vocab) {
|
||||
const llama_token n_tokens = llama_vocab_n_tokens(vocab);
|
||||
for (llama_token id = 0; id < n_tokens; ++id) {
|
||||
const auto attr = llama_vocab_get_attr(vocab, id);
|
||||
if (attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
|
||||
std::string text = llama_vocab_get_text(vocab, id);
|
||||
ids.emplace(text, id);
|
||||
tokens.emplace(id, common_peg_token{ std::move(text), attr });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
llama_token common_peg_tokens::token_id(const std::string & text) const {
|
||||
auto it = ids.find(text);
|
||||
return it != ids.end() ? it->second : LLAMA_TOKEN_NULL;
|
||||
}
|
||||
|
||||
// Insert every delimiter the parser matches into the trie, starting from each node in from. Returns the end nodes.
|
||||
// A choice adds the delimiters of each branch. A sequence joins every combination of its children.
|
||||
static std::set<size_t> insert_delimiter(common_trie & trie, const common_peg_arena & arena, common_peg_parser_id id,
|
||||
std::set<size_t> from = { 0 }) {
|
||||
return std::visit([&](const auto & p) -> std::set<size_t> {
|
||||
using T = std::decay_t<decltype(p)>;
|
||||
if constexpr (std::is_same_v<T, common_peg_tag_parser> || std::is_same_v<T, common_peg_atomic_parser>) {
|
||||
return insert_delimiter(trie, arena, p.child, std::move(from));
|
||||
} else if constexpr (std::is_same_v<T, common_peg_literal_parser>) {
|
||||
std::set<size_t> ends;
|
||||
for (size_t node : from) {
|
||||
size_t pos = 0;
|
||||
while (pos < p.literal.size()) {
|
||||
auto result = common_parse_utf8_codepoint(p.literal, pos);
|
||||
if (result.status != utf8_parse_result::SUCCESS) {
|
||||
break;
|
||||
}
|
||||
node = trie.extend(node, common_trie::symbol::codepoint(result.codepoint));
|
||||
pos += result.bytes_consumed;
|
||||
}
|
||||
ends.insert(node);
|
||||
}
|
||||
return ends;
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_parser>) {
|
||||
std::set<size_t> ends;
|
||||
for (size_t node : from) {
|
||||
ends.insert(trie.extend(node, common_trie::symbol::token(p.token)));
|
||||
}
|
||||
return ends;
|
||||
} else if constexpr (std::is_same_v<T, common_peg_choice_parser>) {
|
||||
std::set<size_t> ends;
|
||||
for (auto child : p.children) {
|
||||
ends.merge(insert_delimiter(trie, arena, child, from));
|
||||
}
|
||||
return ends;
|
||||
} else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
|
||||
for (auto child : p.children) {
|
||||
from = insert_delimiter(trie, arena, child, std::move(from));
|
||||
}
|
||||
return from;
|
||||
} else {
|
||||
throw std::invalid_argument("a delimiter may only be a sequence of literals, tokens, and choices of them, possibly wrapped in tags and atomics");
|
||||
}
|
||||
}, arena.get(id));
|
||||
}
|
||||
|
||||
// Build the matcher of an until parser, each pattern valued by the branch it belongs to
|
||||
static common_trie build_until_matcher(const common_peg_arena & arena,
|
||||
const std::vector<common_peg_until_branch> & branches,
|
||||
bool include) {
|
||||
common_trie matcher;
|
||||
for (size_t b = 0; b < branches.size(); b++) {
|
||||
for (size_t end : insert_delimiter(matcher, arena, branches[b].delimiter)) {
|
||||
if (end == 0) {
|
||||
throw std::invalid_argument("delimiter must not match the empty string");
|
||||
}
|
||||
// nothing follows a delimiter without include, so the first branch to claim it wins
|
||||
auto owner = matcher.mark(end, (int32_t) b);
|
||||
if (owner != (int32_t) b && include) {
|
||||
throw std::invalid_argument("until branches " + std::to_string(owner) + " and " + std::to_string(b) + " must not share a delimiter");
|
||||
}
|
||||
}
|
||||
}
|
||||
return matcher;
|
||||
}
|
||||
|
||||
struct parser_executor;
|
||||
|
||||
common_peg_parser_id common_peg_arena::add_parser(common_peg_parser_variant parser) {
|
||||
@@ -298,6 +381,49 @@ struct parser_executor {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_token_parser & p) {
|
||||
if (start_pos >= ctx.input.size()) {
|
||||
if (!ctx.is_lenient()) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
|
||||
}
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos);
|
||||
}
|
||||
|
||||
if (start_pos >= ctx.tokens.size() || ctx.tokens[start_pos] != p.token) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
|
||||
}
|
||||
|
||||
// Skip the rest of the piece, up to the next token or the end of the input
|
||||
auto pos = start_pos + 1;
|
||||
while (pos < ctx.input.size() && ctx.tokens[pos] == LLAMA_TOKEN_NULL) {
|
||||
++pos;
|
||||
}
|
||||
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_token_not_parser & p) {
|
||||
if (start_pos >= ctx.input.size()) {
|
||||
if (!ctx.is_lenient()) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
|
||||
}
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos);
|
||||
}
|
||||
|
||||
if (start_pos >= ctx.tokens.size() || ctx.tokens[start_pos] == LLAMA_TOKEN_NULL ||
|
||||
std::find(p.tokens.begin(), p.tokens.end(), ctx.tokens[start_pos]) != p.tokens.end()) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
|
||||
}
|
||||
|
||||
// Skip the rest of the piece, up to the next token or the end of the input
|
||||
auto pos = start_pos + 1;
|
||||
while (pos < ctx.input.size() && ctx.tokens[pos] == LLAMA_TOKEN_NULL) {
|
||||
++pos;
|
||||
}
|
||||
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_sequence_parser & p) {
|
||||
if (ctx.is_debug()) {
|
||||
LOG_DBG("%sSEQ start at %zu '%s' (%zu children)\n", debug_indent().c_str(), start_pos,
|
||||
@@ -689,7 +815,11 @@ struct parser_executor {
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_until_parser & p) const {
|
||||
common_trie matcher(p.delimiters);
|
||||
if (p.include) {
|
||||
return parse_through(p);
|
||||
}
|
||||
|
||||
const auto & matcher = p.matcher;
|
||||
|
||||
// Scan input and check for delimiters
|
||||
size_t pos = start_pos;
|
||||
@@ -697,24 +827,24 @@ struct parser_executor {
|
||||
std::vector<common_peg_invalid_utf8> invalid_utf8;
|
||||
|
||||
while (pos < ctx.input.size()) {
|
||||
auto utf8_result = common_parse_utf8_codepoint(ctx.input, pos);
|
||||
auto step = matcher.next(ctx.input, ctx.tokens, pos);
|
||||
|
||||
if (utf8_result.status == utf8_parse_result::INCOMPLETE && ctx.is_lenient()) {
|
||||
if (step.status == utf8_parse_result::INCOMPLETE && ctx.is_lenient()) {
|
||||
// The rest of the sequence may still arrive, return what we have so far
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, last_valid_pos, {}, std::move(invalid_utf8));
|
||||
}
|
||||
|
||||
if (utf8_result.status != utf8_parse_result::SUCCESS) {
|
||||
if (step.status != utf8_parse_result::SUCCESS) {
|
||||
// Malformed UTF-8, or a sequence truncated by the end of a complete input.
|
||||
// A delimiter cannot start inside bytes that fail to decode, so consume them and move on
|
||||
invalid_utf8.push_back({pos, utf8_result.bytes_consumed});
|
||||
pos += utf8_result.bytes_consumed;
|
||||
invalid_utf8.push_back({pos, step.bytes_consumed});
|
||||
pos += step.bytes_consumed;
|
||||
last_valid_pos = pos;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if a delimiter starts at this position
|
||||
auto match = matcher.check_at(ctx.input, pos);
|
||||
auto match = matcher.check_at(ctx.input, ctx.tokens, pos);
|
||||
|
||||
if (match == common_trie::COMPLETE_MATCH) {
|
||||
// Found a complete delimiter, return everything before it
|
||||
@@ -727,7 +857,7 @@ struct parser_executor {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos, {}, std::move(invalid_utf8));
|
||||
}
|
||||
|
||||
pos += utf8_result.bytes_consumed;
|
||||
pos += step.bytes_consumed;
|
||||
last_valid_pos = pos;
|
||||
}
|
||||
|
||||
@@ -738,6 +868,48 @@ struct parser_executor {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, last_valid_pos, {}, std::move(invalid_utf8));
|
||||
}
|
||||
|
||||
// Parse content, then the first branch whose delimiter and rest follow it, like C (D1 R1 | D2 R2 | ...)
|
||||
common_peg_parse_result parse_through(const common_peg_until_parser & p) const {
|
||||
auto content = arena.parse(p.content, ctx, start_pos);
|
||||
if (content.fail() || content.need_more_input()) {
|
||||
return content;
|
||||
}
|
||||
|
||||
auto pos = content.end;
|
||||
for (const auto & branch : p.branches) {
|
||||
auto nodes = content.nodes;
|
||||
auto invalid_utf8 = content.invalid_utf8;
|
||||
auto end = pos;
|
||||
bool matched = true;
|
||||
|
||||
for (auto id : { branch.delimiter, branch.rest }) {
|
||||
if (id == COMMON_PEG_INVALID_PARSER_ID) {
|
||||
continue;
|
||||
}
|
||||
auto result = arena.parse(id, ctx, end);
|
||||
if (result.fail()) {
|
||||
matched = false;
|
||||
break;
|
||||
}
|
||||
nodes.insert(nodes.end(), result.nodes.begin(), result.nodes.end());
|
||||
invalid_utf8.insert(invalid_utf8.end(), result.invalid_utf8.begin(), result.invalid_utf8.end());
|
||||
end = result.end;
|
||||
if (result.need_more_input()) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, end, std::move(nodes), std::move(invalid_utf8));
|
||||
}
|
||||
}
|
||||
if (matched) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, end, std::move(nodes), std::move(invalid_utf8));
|
||||
}
|
||||
}
|
||||
|
||||
if (p.optional && pos == ctx.input.size()) {
|
||||
auto type = ctx.is_lenient() ? COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT : COMMON_PEG_PARSE_RESULT_SUCCESS;
|
||||
return common_peg_parse_result(type, start_pos, pos, std::move(content.nodes), std::move(content.invalid_utf8));
|
||||
}
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos, pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_schema_parser & p) {
|
||||
return arena.parse(p.child, ctx, start_pos);
|
||||
}
|
||||
@@ -823,10 +995,6 @@ struct parser_executor {
|
||||
common_peg_parse_result operator()(const common_peg_gbnf_parser & p) {
|
||||
return arena.parse(p.child, ctx, start_pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_ac_parser & p) {
|
||||
return arena.parse(p.child, ctx, start_pos);
|
||||
}
|
||||
};
|
||||
|
||||
common_peg_parse_result common_peg_arena::parse(common_peg_parse_context & ctx, size_t start) const {
|
||||
@@ -899,19 +1067,33 @@ void common_peg_arena::resolve_refs() {
|
||||
std::is_same_v<T, common_peg_not_parser> ||
|
||||
std::is_same_v<T, common_peg_tag_parser> ||
|
||||
std::is_same_v<T, common_peg_atomic_parser> ||
|
||||
std::is_same_v<T, common_peg_gbnf_parser> ||
|
||||
std::is_same_v<T, common_peg_ac_parser>) {
|
||||
std::is_same_v<T, common_peg_gbnf_parser>) {
|
||||
p.child = resolve_ref(p.child);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
|
||||
if (p.content != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
p.content = resolve_ref(p.content);
|
||||
}
|
||||
for (auto & branch : p.branches) {
|
||||
branch.delimiter = resolve_ref(branch.delimiter);
|
||||
if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
branch.rest = resolve_ref(branch.rest);
|
||||
}
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
|
||||
p.child = resolve_ref(p.child);
|
||||
if (p.start != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
p.start = resolve_ref(p.start);
|
||||
p.rest = resolve_ref(p.rest);
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
|
||||
p.child = resolve_ref(p.child);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_epsilon_parser> ||
|
||||
std::is_same_v<T, common_peg_start_parser> ||
|
||||
std::is_same_v<T, common_peg_end_parser> ||
|
||||
std::is_same_v<T, common_peg_ref_parser> ||
|
||||
std::is_same_v<T, common_peg_until_parser> ||
|
||||
std::is_same_v<T, common_peg_literal_parser> ||
|
||||
std::is_same_v<T, common_peg_token_parser> ||
|
||||
std::is_same_v<T, common_peg_token_not_parser> ||
|
||||
std::is_same_v<T, common_peg_string_parser> ||
|
||||
std::is_same_v<T, common_peg_chars_parser> ||
|
||||
std::is_same_v<T, common_peg_any_parser> ||
|
||||
@@ -955,6 +1137,14 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id
|
||||
return "End";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_literal_parser>) {
|
||||
return "Literal(" + p.literal + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_parser>) {
|
||||
return "Token(" + p.piece + ", " + std::to_string(p.token) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_not_parser>) {
|
||||
std::vector<std::string> parts;
|
||||
for (auto token : p.tokens) {
|
||||
parts.push_back(std::to_string(token));
|
||||
}
|
||||
return "TokenNot(" + string_join(parts, ", ") + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
|
||||
std::vector<std::string> parts;
|
||||
for (const auto & child : p.children) {
|
||||
@@ -981,8 +1171,6 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id
|
||||
return "Atomic(" + dump_impl(p.child, visited) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_gbnf_parser>) {
|
||||
return "Gbnf(" + p.grammar + ", " + dump_impl(p.child, visited) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_ac_parser>) {
|
||||
return "Ac(" + string_join(p.delimiters, " | ") + ", " + dump_impl(p.child, visited) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_any_parser>) {
|
||||
return "Any";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_space_parser>) {
|
||||
@@ -995,7 +1183,18 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id
|
||||
} else if constexpr (std::is_same_v<T, common_peg_string_parser>) {
|
||||
return "String(" + std::string(1, p.delimiter) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
|
||||
return "Until(" + string_join(p.delimiters, " | ") + ")";
|
||||
std::vector<std::string> branches;
|
||||
for (const auto & branch : p.branches) {
|
||||
auto text = dump_impl(branch.delimiter, visited);
|
||||
if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
text += " " + dump_impl(branch.rest, visited);
|
||||
}
|
||||
branches.push_back(std::move(text));
|
||||
}
|
||||
if (p.include) {
|
||||
return "Until(" + dump_impl(p.content, visited) + ", " + string_join(branches, " | ") + (p.optional ? ", optional" : "") + ")";
|
||||
}
|
||||
return "Until(" + string_join(branches, " | ") + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
|
||||
return "Schema(" + dump_impl(p.child, visited) + ", " + (p.node ? common_chat_schema::kind_name(p.node->kind()) : "null") + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
|
||||
@@ -1089,6 +1288,67 @@ common_peg_parser operator|(const std::string & str, const common_peg_parser & p
|
||||
|
||||
common_peg_parser_builder::common_peg_parser_builder() {}
|
||||
|
||||
common_peg_parser_builder::common_peg_parser_builder(common_peg_tokens tokens) {
|
||||
arena_.tokens_ = std::move(tokens);
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::until_one_of(const std::vector<std::string> & delimiters) {
|
||||
common_peg_until_parser p;
|
||||
for (const auto & d : delimiters) {
|
||||
p.branches.push_back({ literal(d).id() });
|
||||
}
|
||||
p.matcher = build_until_matcher(arena_, p.branches, p.include);
|
||||
return add(std::move(p));
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::until(const common_peg_parser & delimiter) {
|
||||
common_peg_until_parser p;
|
||||
p.branches = { { delimiter.id() } };
|
||||
p.matcher = build_until_matcher(arena_, p.branches, p.include);
|
||||
return add(std::move(p));
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::through(const common_peg_parser & content, const std::vector<common_peg_until_branch> & branches, bool optional) {
|
||||
if (branches.empty()) {
|
||||
throw std::runtime_error("through requires at least one branch");
|
||||
}
|
||||
common_peg_until_parser p;
|
||||
p.branches = branches;
|
||||
p.include = true;
|
||||
p.optional = optional;
|
||||
p.content = content.id();
|
||||
p.matcher = build_until_matcher(arena_, p.branches, p.include);
|
||||
return add(std::move(p));
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::token(const std::string & piece) {
|
||||
auto token = arena_.tokens_.token_id(piece);
|
||||
if (token == LLAMA_TOKEN_NULL) {
|
||||
return literal(piece);
|
||||
}
|
||||
return add(common_peg_token_parser{token, piece});
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::token(const std::vector<std::string> & pieces, bool negate) {
|
||||
if (!negate) {
|
||||
std::vector<common_peg_parser> alts;
|
||||
for (const auto & piece : pieces) {
|
||||
alts.push_back(token(piece));
|
||||
}
|
||||
return choice(alts);
|
||||
}
|
||||
|
||||
common_peg_token_not_parser p;
|
||||
for (const auto & piece : pieces) {
|
||||
auto token = arena_.tokens_.token_id(piece);
|
||||
if (token == LLAMA_TOKEN_NULL) {
|
||||
throw std::invalid_argument("token is not registered with the builder: " + piece);
|
||||
}
|
||||
p.tokens.push_back(token);
|
||||
}
|
||||
return add(p);
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::sequence(const std::vector<common_peg_parser_id> & parsers) {
|
||||
// Flatten nested sequences
|
||||
std::vector<common_peg_parser_id> flattened;
|
||||
@@ -1195,6 +1455,17 @@ common_peg_parser common_peg_parser_builder::rule(const std::string & name, cons
|
||||
return ref(clean_name);
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::trigger_rule(const std::string & name, const common_peg_parser & start, const common_peg_parser & rest) {
|
||||
common_trie scratch;
|
||||
if (insert_delimiter(scratch, arena_, start.id()).count(0)) {
|
||||
throw std::invalid_argument("trigger start must not match the empty string");
|
||||
}
|
||||
auto clean_name = gbnf_format_rule_name(name);
|
||||
auto rule_id = arena_.add_parser(common_peg_rule_parser{clean_name, (start + rest).id(), true, start.id(), rest.id()});
|
||||
arena_.add_rule(clean_name, rule_id);
|
||||
return ref(clean_name);
|
||||
}
|
||||
|
||||
void common_peg_parser_builder::set_root(const common_peg_parser & p) {
|
||||
arena_.set_root(p.id());
|
||||
}
|
||||
@@ -1392,13 +1663,6 @@ common_peg_parser common_peg_parser_builder::json_member(const std::string & key
|
||||
});
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::ac(const common_peg_parser & p, const std::vector<std::string> & delimiters) {
|
||||
if (delimiters.empty()) {
|
||||
throw std::runtime_error("ac parser requires at least one delimiter");
|
||||
}
|
||||
return add(common_peg_ac_parser{p, delimiters});
|
||||
}
|
||||
|
||||
static std::string gbnf_escape_char_class(uint32_t c) {
|
||||
if (c == '-' || c == ']' || c == '[' || c == '\\') {
|
||||
return "\\" + std::string(1, (char) c);
|
||||
@@ -1457,15 +1721,63 @@ static std::string gbnf_char_class(const std::vector<uint32_t> & chars, bool neg
|
||||
return s + "]";
|
||||
}
|
||||
|
||||
// Token set such as <[1,5-9]>, with consecutive ids collapsed into ranges
|
||||
static std::string gbnf_token_set(const std::vector<uint32_t> & tokens, bool negate) {
|
||||
std::string s = negate ? "!<[" : "<[";
|
||||
for (size_t i = 0; i < tokens.size();) {
|
||||
size_t j = i;
|
||||
while (j + 1 < tokens.size() && tokens[j + 1] == tokens[j] + 1) {
|
||||
j++;
|
||||
}
|
||||
s += (i == 0 ? "" : ",") + std::to_string(tokens[i]);
|
||||
if (j > i) {
|
||||
s += "-" + std::to_string(tokens[j]);
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
return s + "]>";
|
||||
}
|
||||
|
||||
// Symbols on the transitions out of an automaton state, codepoints and tokens kept apart
|
||||
struct gbnf_ac_symbols {
|
||||
std::vector<uint32_t> chars;
|
||||
std::vector<uint32_t> tokens;
|
||||
|
||||
void add(const common_trie::symbol & sym) {
|
||||
(sym.is_token() ? tokens : chars).push_back(sym.value);
|
||||
}
|
||||
|
||||
// One alternative for the codepoints and one for the tokens, each followed by next if given
|
||||
std::vector<std::string> alternatives(const std::string & next = "") const {
|
||||
std::vector<std::string> alts;
|
||||
const std::string tail = next.empty() ? "" : " " + next;
|
||||
if (!chars.empty()) {
|
||||
alts.push_back(gbnf_char_class(chars, false) + tail);
|
||||
}
|
||||
if (!tokens.empty()) {
|
||||
alts.push_back(gbnf_token_set(tokens, false) + tail);
|
||||
}
|
||||
return alts;
|
||||
}
|
||||
};
|
||||
|
||||
static std::string gbnf_ac_grammar(
|
||||
const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const std::vector<std::string> & strings,
|
||||
const std::function<std::string(const std::vector<uint32_t> &,
|
||||
const std::map<size_t, std::vector<uint32_t>> &,
|
||||
const std::vector<uint32_t> &,
|
||||
const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const common_trie & trie,
|
||||
const std::set<uint32_t> & opaque,
|
||||
const std::function<std::string(const gbnf_ac_symbols &,
|
||||
const std::map<size_t, gbnf_ac_symbols> &,
|
||||
const std::map<size_t, gbnf_ac_symbols> &,
|
||||
const std::string &,
|
||||
const std::function<std::string(size_t)> &)> & build_rule) {
|
||||
common_aho_corasick ac(strings);
|
||||
common_aho_corasick ac(trie);
|
||||
|
||||
// With only tokens in the alphabet, the grammar can step a whole token at a time
|
||||
bool token_only = true;
|
||||
for (const auto & sym : ac.alphabet) {
|
||||
token_only = token_only && sym.is_token();
|
||||
}
|
||||
|
||||
auto state_name = [&](size_t s) -> std::string {
|
||||
if (s == 0) {
|
||||
@@ -1481,27 +1793,43 @@ static std::string gbnf_ac_grammar(
|
||||
continue; // match states
|
||||
}
|
||||
|
||||
std::map<size_t, std::vector<uint32_t>> buckets;
|
||||
std::vector<uint32_t> completing; // chars that complete a delimiter
|
||||
std::vector<uint32_t> specific; // chars with an explicit transition
|
||||
for (uint32_t c : ac.alphabet) {
|
||||
size_t d = ac.next(q, c);
|
||||
std::map<size_t, gbnf_ac_symbols> buckets;
|
||||
std::map<size_t, gbnf_ac_symbols> completing_to; // completing symbols by the match state they reach
|
||||
gbnf_ac_symbols completing; // symbols that complete a delimiter
|
||||
gbnf_ac_symbols specific; // symbols with an explicit transition
|
||||
for (const auto & sym : ac.alphabet) {
|
||||
size_t d = ac.next(q, sym);
|
||||
if (ac.is_terminal(d)) {
|
||||
completing.push_back(c);
|
||||
specific.push_back(c);
|
||||
completing.add(sym);
|
||||
completing_to[d].add(sym);
|
||||
specific.add(sym);
|
||||
} else if (d != 0) {
|
||||
buckets[d].push_back(c); // specific non-root destination
|
||||
specific.push_back(c);
|
||||
buckets[d].add(sym); // specific non-root destination
|
||||
specific.add(sym);
|
||||
}
|
||||
}
|
||||
|
||||
builder.add_rule(state_name(q), build_rule(completing, buckets, specific, state_name));
|
||||
}
|
||||
// every other symbol goes back to the start
|
||||
std::string fallback;
|
||||
if (token_only) {
|
||||
fallback = gbnf_token_set(specific.tokens, true);
|
||||
} else {
|
||||
fallback = specific.chars.empty() ? "." : gbnf_char_class(specific.chars, true);
|
||||
|
||||
// An empty delimiter makes the start state terminal. Emit an entry rule
|
||||
// that matches the empty string so the returned reference stays valid.
|
||||
if (ac.is_terminal(0)) {
|
||||
builder.add_rule(prefix, "|");
|
||||
// Char rules never match a token named by a token rule, so allow the other named tokens by name
|
||||
std::vector<uint32_t> others;
|
||||
for (auto token : opaque) {
|
||||
if (std::find(specific.tokens.begin(), specific.tokens.end(), token) == specific.tokens.end()) {
|
||||
others.push_back(token);
|
||||
}
|
||||
}
|
||||
if (!others.empty()) {
|
||||
fallback = "(" + fallback + " | " + gbnf_token_set(others, false) + ")";
|
||||
}
|
||||
}
|
||||
fallback += " " + state_name(0);
|
||||
|
||||
builder.add_rule(state_name(q), build_rule(completing, completing_to, buckets, fallback, state_name));
|
||||
}
|
||||
|
||||
return state_name(0);
|
||||
@@ -1514,52 +1842,104 @@ static std::string gbnf_ac_grammar(
|
||||
// ref: https://github.com/ggml-org/llama.cpp/pull/24839
|
||||
static std::string gbnf_excluding_grammar(const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const std::vector<std::string> & strings) {
|
||||
return gbnf_ac_grammar(builder, prefix, strings,
|
||||
[](const std::vector<uint32_t> & /*completing*/,
|
||||
const std::map<size_t, std::vector<uint32_t>> & buckets,
|
||||
const std::vector<uint32_t> & specific,
|
||||
const common_trie & trie,
|
||||
const std::set<uint32_t> & opaque) {
|
||||
return gbnf_ac_grammar(builder, prefix, trie, opaque,
|
||||
[](const gbnf_ac_symbols & /*completing*/,
|
||||
const std::map<size_t, gbnf_ac_symbols> & /*completing_to*/,
|
||||
const std::map<size_t, gbnf_ac_symbols> & buckets,
|
||||
const std::string & fallback,
|
||||
const std::function<std::string(size_t)> & state_name) {
|
||||
// every state is accepting and completing chars get no
|
||||
// alternative, so a forbidden string can never be matched
|
||||
// every state accepts and completing symbols get no alternative, so a forbidden string never matches
|
||||
std::string rhs = "|";
|
||||
for (const auto & [d, chars] : buckets) {
|
||||
rhs += " " + gbnf_char_class(chars, false) + " " + state_name(d) + " |";
|
||||
for (const auto & [d, symbols] : buckets) {
|
||||
for (const auto & alt : symbols.alternatives(state_name(d))) {
|
||||
rhs += " " + alt + " |";
|
||||
}
|
||||
}
|
||||
rhs += " " + gbnf_char_class(specific, true) + " " + state_name(0);
|
||||
rhs += " " + fallback;
|
||||
return rhs;
|
||||
});
|
||||
}
|
||||
|
||||
// GBNF grammar matching everything up to and including the first occurrence of
|
||||
// any string in `strings`. Emits the Aho-Corasick automaton DFA and returns
|
||||
// the start state rule name.
|
||||
static std::string gbnf_including_grammar(const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const std::vector<std::string> & strings) {
|
||||
return gbnf_ac_grammar(builder, prefix, strings,
|
||||
[](const std::vector<uint32_t> & completing,
|
||||
const std::map<size_t, std::vector<uint32_t>> & buckets,
|
||||
const std::vector<uint32_t> & specific,
|
||||
const std::function<std::string(size_t)> & state_name) {
|
||||
// GBNF grammar matching up to the first pattern in the trie, then the rest rule of that pattern's value.
|
||||
// For the pattern "ab" with rest "x":
|
||||
//
|
||||
// prefix ::= [a] prefix-01 | [^a] prefix
|
||||
// prefix-01 ::= [b] rest | [a] prefix-01 | [^ab] prefix
|
||||
// rest ::= "x"
|
||||
static std::string gbnf_including_grammar(const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const common_trie & trie,
|
||||
const std::set<uint32_t> & opaque,
|
||||
const std::vector<std::string> & rests,
|
||||
bool optional) {
|
||||
common_aho_corasick ac(trie);
|
||||
|
||||
// every pattern ending at a match state, the longest and the ones reached by suffix links
|
||||
auto rests_at = [&](size_t s, bool & terminal) {
|
||||
std::vector<std::string> alts;
|
||||
terminal = false;
|
||||
for (; s != 0; s = ac.fail[s]) {
|
||||
auto pattern = ac.t.nodes[s].pattern;
|
||||
if (pattern < 0) {
|
||||
continue;
|
||||
}
|
||||
if (rests[pattern].empty()) {
|
||||
terminal = true;
|
||||
} else if (std::find(alts.begin(), alts.end(), rests[pattern]) == alts.end()) {
|
||||
alts.push_back(rests[pattern]);
|
||||
}
|
||||
}
|
||||
return alts;
|
||||
};
|
||||
|
||||
return gbnf_ac_grammar(builder, prefix, trie, opaque,
|
||||
[&](const gbnf_ac_symbols & /*completing*/,
|
||||
const std::map<size_t, gbnf_ac_symbols> & completing_to,
|
||||
const std::map<size_t, gbnf_ac_symbols> & buckets,
|
||||
const std::string & fallback,
|
||||
const std::function<std::string(size_t)> & state_name) {
|
||||
std::vector<std::string> alts;
|
||||
if (!completing.empty()) {
|
||||
alts.push_back(gbnf_char_class(completing, false)); // terminate on match
|
||||
gbnf_ac_symbols terminating; // symbols that complete a pattern with no rest
|
||||
for (const auto & [d, symbols] : completing_to) {
|
||||
bool terminal = false;
|
||||
auto rest = rests_at(d, terminal);
|
||||
if (!rest.empty()) {
|
||||
for (auto & alt : symbols.alternatives(rest.size() == 1 ? rest[0] : "(" + string_join(rest, " | ") + ")")) {
|
||||
alts.push_back(std::move(alt));
|
||||
}
|
||||
}
|
||||
if (terminal) {
|
||||
terminating.chars.insert(terminating.chars.end(), symbols.chars.begin(), symbols.chars.end());
|
||||
terminating.tokens.insert(terminating.tokens.end(), symbols.tokens.begin(), symbols.tokens.end());
|
||||
}
|
||||
}
|
||||
for (const auto & [d, chars] : buckets) {
|
||||
alts.push_back(gbnf_char_class(chars, false) + " " + state_name(d));
|
||||
for (auto & alt : terminating.alternatives()) {
|
||||
alts.push_back(std::move(alt));
|
||||
}
|
||||
// every other character keeps scanning from the start state
|
||||
alts.push_back(gbnf_char_class(specific, true) + " " + state_name(0));
|
||||
return string_join(alts, " | ");
|
||||
for (const auto & [d, symbols] : buckets) {
|
||||
for (auto & alt : symbols.alternatives(state_name(d))) {
|
||||
alts.push_back(std::move(alt));
|
||||
}
|
||||
}
|
||||
// every other symbol keeps scanning from the start state
|
||||
alts.push_back(fallback);
|
||||
return (optional ? "| " : "") + string_join(alts, " | ");
|
||||
});
|
||||
}
|
||||
|
||||
static std::set<std::string> collect_reachable_rules(
|
||||
// The rules and the tokens named by token rules that the grammar of a parser reaches
|
||||
struct common_peg_reachable {
|
||||
std::set<std::string> rules;
|
||||
std::set<uint32_t> tokens;
|
||||
};
|
||||
|
||||
static void collect_reachable(
|
||||
const common_peg_arena & arena,
|
||||
const common_peg_parser_id & rule
|
||||
const common_peg_parser_id & root,
|
||||
common_peg_reachable & reachable
|
||||
) {
|
||||
std::set<std::string> reachable;
|
||||
std::set<std::string> visited;
|
||||
|
||||
std::function<void(common_peg_parser_id)> visit = [&](common_peg_parser_id id) {
|
||||
@@ -1571,13 +1951,27 @@ static std::set<std::string> collect_reachable_rules(
|
||||
if constexpr (std::is_same_v<T, common_peg_epsilon_parser> ||
|
||||
std::is_same_v<T, common_peg_start_parser> ||
|
||||
std::is_same_v<T, common_peg_end_parser> ||
|
||||
std::is_same_v<T, common_peg_until_parser> ||
|
||||
std::is_same_v<T, common_peg_literal_parser> ||
|
||||
std::is_same_v<T, common_peg_chars_parser> ||
|
||||
std::is_same_v<T, common_peg_space_parser> ||
|
||||
std::is_same_v<T, common_peg_any_parser> ||
|
||||
std::is_same_v<T, common_peg_string_parser>) {
|
||||
// These parsers do not have any children
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_parser>) {
|
||||
reachable.tokens.insert(p.token);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_not_parser>) {
|
||||
reachable.tokens.insert(p.tokens.begin(), p.tokens.end());
|
||||
} else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
|
||||
// The delimiters name their tokens in the grammar
|
||||
if (p.content != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
visit(p.content);
|
||||
}
|
||||
for (const auto & branch : p.branches) {
|
||||
visit(branch.delimiter);
|
||||
if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
visit(branch.rest);
|
||||
}
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
|
||||
for (auto child : p.children) {
|
||||
visit(child);
|
||||
@@ -1592,13 +1986,12 @@ static std::set<std::string> collect_reachable_rules(
|
||||
std::is_same_v<T, common_peg_tag_parser> ||
|
||||
std::is_same_v<T, common_peg_atomic_parser> ||
|
||||
std::is_same_v<T, common_peg_gbnf_parser> ||
|
||||
std::is_same_v<T, common_peg_ac_parser> ||
|
||||
std::is_same_v<T, common_peg_schema_parser>) {
|
||||
visit(p.child);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
|
||||
if (visited.find(p.name) == visited.end()) {
|
||||
visited.insert(p.name);
|
||||
reachable.insert(p.name);
|
||||
reachable.rules.insert(p.name);
|
||||
visit(p.child);
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, common_peg_ref_parser>) {
|
||||
@@ -1611,12 +2004,13 @@ static std::set<std::string> collect_reachable_rules(
|
||||
}, parser);
|
||||
};
|
||||
|
||||
visit(rule);
|
||||
return reachable;
|
||||
visit(root);
|
||||
}
|
||||
|
||||
// GBNF generation implementation
|
||||
void common_peg_arena::build_grammar(const common_grammar_builder & builder, bool lazy) const {
|
||||
common_peg_reachable reachable;
|
||||
|
||||
// A raw string value is parsed by the child rather than constrained by the schema
|
||||
auto schema_delegates = [](const common_peg_schema_parser & s) -> bool {
|
||||
return !s.node || (s.raw && s.node->may_be_string());
|
||||
@@ -1655,6 +2049,10 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
|
||||
return "";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_literal_parser>) {
|
||||
return gbnf_format_literal(p.literal);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_parser>) {
|
||||
return "<[" + std::to_string(p.token) + "]>";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_not_parser>) {
|
||||
return gbnf_token_set(std::vector<uint32_t>(p.tokens.begin(), p.tokens.end()), true);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
|
||||
std::string s;
|
||||
for (const auto & child : p.children) {
|
||||
@@ -1746,10 +2144,19 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
|
||||
const std::string delim(1, p.delimiter);
|
||||
return R"(( [^)" + delim + R"(\\] | "\\" ( [)" + delim + R"(\\/ bfnrt] | "u" [0-9a-fA-F]{4} ) )*)";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
|
||||
if (p.delimiters.empty()) {
|
||||
return ".*";
|
||||
auto prefix = "until-" + std::to_string(id);
|
||||
if (!p.include) {
|
||||
if (p.branches.empty()) {
|
||||
return ".*";
|
||||
}
|
||||
return gbnf_excluding_grammar(builder, prefix, p.matcher, reachable.tokens);
|
||||
}
|
||||
return gbnf_excluding_grammar(builder, "until-" + std::to_string(id), p.delimiters);
|
||||
std::vector<std::string> branch_rests;
|
||||
for (size_t b = 0; b < p.branches.size(); b++) {
|
||||
auto rest = p.branches[b].rest;
|
||||
branch_rests.push_back(rest == COMMON_PEG_INVALID_PARSER_ID ? "" : builder.add_rule(prefix + "-rest-" + std::to_string(b), to_gbnf(rest)));
|
||||
}
|
||||
return gbnf_including_grammar(builder, prefix, p.matcher, reachable.tokens, branch_rests, p.optional);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
|
||||
if (schema_delegates(p)) {
|
||||
return to_gbnf(p.child);
|
||||
@@ -1766,38 +2173,52 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
|
||||
return to_gbnf(p.child);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_gbnf_parser>) {
|
||||
return p.grammar;
|
||||
} else if constexpr (std::is_same_v<T, common_peg_ac_parser>) {
|
||||
return gbnf_including_grammar(builder, "ac-" + std::to_string(id), p.delimiters);
|
||||
} else {
|
||||
static_assert(is_always_false_v<T>);
|
||||
}
|
||||
}, parser);
|
||||
};
|
||||
|
||||
// Collect reachable rules
|
||||
std::set<std::string> reachable_rules;
|
||||
|
||||
if (lazy) {
|
||||
// Collect rules reachable from trigger rules
|
||||
for (const auto & [name, id] : rules_) {
|
||||
const auto & parser = parsers_.at(id);
|
||||
if (auto rule = std::get_if<common_peg_rule_parser>(&parser)) {
|
||||
if (rule->trigger) {
|
||||
// Mark trigger as reachable and visit it
|
||||
reachable_rules.insert(name);
|
||||
auto add_rules = collect_reachable_rules(*this, id);
|
||||
reachable_rules.insert(add_rules.begin(), add_rules.end());
|
||||
}
|
||||
// Trigger rules, sorted for a predictable order
|
||||
std::vector<const common_peg_rule_parser *> trigger_rules;
|
||||
for (const auto & [name, id] : rules_) {
|
||||
if (auto rule = std::get_if<common_peg_rule_parser>(&parsers_.at(id))) {
|
||||
if (rule->trigger) {
|
||||
trigger_rules.push_back(rule);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::sort(trigger_rules.begin(), trigger_rules.end(), [](const auto * a, const auto * b) { return a->name < b->name; });
|
||||
|
||||
// A lazy grammar scans for the starts when the trigger rules were built from a start and rest
|
||||
bool scans = false;
|
||||
for (const auto * rule : trigger_rules) {
|
||||
scans = scans || rule->start != COMMON_PEG_INVALID_PARSER_ID;
|
||||
}
|
||||
if (scans) {
|
||||
for (const auto * rule : trigger_rules) {
|
||||
if (rule->start == COMMON_PEG_INVALID_PARSER_ID) {
|
||||
throw std::runtime_error("trigger rule without a start in a scanning grammar: " + rule->name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (lazy && scans) {
|
||||
for (const auto * rule : trigger_rules) {
|
||||
collect_reachable(*this, rule->start, reachable);
|
||||
collect_reachable(*this, rule->rest, reachable);
|
||||
}
|
||||
} else if (lazy) {
|
||||
for (const auto * rule : trigger_rules) {
|
||||
collect_reachable(*this, rules_.at(rule->name), reachable);
|
||||
}
|
||||
} else {
|
||||
// Collect rules reachable from root
|
||||
reachable_rules = collect_reachable_rules(*this, root_);
|
||||
collect_reachable(*this, root_, reachable);
|
||||
}
|
||||
|
||||
// Create GBNF rules for all reachable rules
|
||||
for (const auto & [name, rule_id] : rules_) {
|
||||
if (reachable_rules.find(name) == reachable_rules.end()) {
|
||||
if (reachable.rules.find(name) == reachable.rules.end()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1807,20 +2228,27 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
|
||||
}
|
||||
}
|
||||
|
||||
if (lazy) {
|
||||
// Generate root rule from trigger rules only
|
||||
std::vector<std::string> trigger_names;
|
||||
for (const auto & [name, rule_id] : rules_) {
|
||||
const auto & parser = parsers_.at(rule_id);
|
||||
if (auto rule = std::get_if<common_peg_rule_parser>(&parser)) {
|
||||
if (rule->trigger) {
|
||||
trigger_names.push_back(rule->name);
|
||||
if (lazy && scans) {
|
||||
// The root scans for a trigger start and then constrains its rest
|
||||
common_trie starts;
|
||||
std::vector<std::string> rests;
|
||||
for (const auto * rule : trigger_rules) {
|
||||
auto value = (int32_t) rests.size();
|
||||
rests.push_back(builder.add_rule(rule->name + "-rest", to_gbnf(rule->rest)));
|
||||
for (size_t end : insert_delimiter(starts, *this, rule->start)) {
|
||||
auto owner = starts.mark(end, value);
|
||||
if (owner != value) {
|
||||
throw std::runtime_error("trigger rules " + trigger_rules[owner]->name + " and " + rule->name + " must not share a start");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort for predictable order
|
||||
std::sort(trigger_names.begin(), trigger_names.end());
|
||||
builder.add_rule("root", gbnf_including_grammar(builder, "trigger", starts, reachable.tokens, rests, /* optional = */ true));
|
||||
} else if (lazy) {
|
||||
// Generate root rule from trigger rules only
|
||||
std::vector<std::string> trigger_names;
|
||||
for (const auto * rule : trigger_rules) {
|
||||
trigger_names.push_back(rule->name);
|
||||
}
|
||||
builder.add_rule("root", string_join(trigger_names, " | "));
|
||||
} else if (root_ != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
builder.add_rule("root", to_gbnf(root_));
|
||||
|
||||
+77
-17
@@ -3,6 +3,7 @@
|
||||
#include "json-schema.h"
|
||||
#include "json.h"
|
||||
#include "llama.h"
|
||||
#include "trie.h"
|
||||
|
||||
#include <memory>
|
||||
#include <set>
|
||||
@@ -188,6 +189,22 @@ struct common_peg_recursion_error : std::invalid_argument {
|
||||
using std::invalid_argument::invalid_argument;
|
||||
};
|
||||
|
||||
struct common_peg_token {
|
||||
std::string text;
|
||||
llama_token_attr attr;
|
||||
};
|
||||
|
||||
struct common_peg_tokens {
|
||||
std::unordered_map<llama_token, common_peg_token> tokens;
|
||||
std::unordered_map<std::string, llama_token> ids;
|
||||
|
||||
common_peg_tokens() = default;
|
||||
explicit common_peg_tokens(const llama_vocab * vocab);
|
||||
|
||||
// LLAMA_TOKEN_NULL if text is not a special token
|
||||
llama_token token_id(const std::string & text) const;
|
||||
};
|
||||
|
||||
struct common_peg_parse_context {
|
||||
std::string input; // [h, e, l, l, o, _, w, o, r, l, d]
|
||||
std::vector<llama_token> tokens; // [id, -1, -1, -1, -1, id, -1, -1, -1, -1, -1]
|
||||
@@ -226,6 +243,16 @@ struct common_peg_literal_parser {
|
||||
std::string literal;
|
||||
};
|
||||
|
||||
struct common_peg_token_parser {
|
||||
llama_token token;
|
||||
std::string piece;
|
||||
};
|
||||
|
||||
// Matches one token that is not one of the tokens
|
||||
struct common_peg_token_not_parser {
|
||||
std::vector<llama_token> tokens;
|
||||
};
|
||||
|
||||
struct common_peg_sequence_parser {
|
||||
std::vector<common_peg_parser_id> children;
|
||||
};
|
||||
@@ -270,8 +297,18 @@ struct common_peg_string_parser {
|
||||
char delimiter;
|
||||
};
|
||||
|
||||
// A delimiter an until parser stops at, and the parser that follows it when the delimiter is consumed
|
||||
struct common_peg_until_branch {
|
||||
common_peg_parser_id delimiter;
|
||||
common_peg_parser_id rest = COMMON_PEG_INVALID_PARSER_ID;
|
||||
};
|
||||
|
||||
struct common_peg_until_parser {
|
||||
std::vector<std::string> delimiters;
|
||||
std::vector<common_peg_until_branch> branches;
|
||||
bool include = false; // consume the first delimiter and parse the rest of its branch
|
||||
bool optional = false; // with include, the input may end before any delimiter
|
||||
common_peg_parser_id content = COMMON_PEG_INVALID_PARSER_ID; // with include, parsed up to the delimiter
|
||||
common_trie matcher; // each pattern valued by its branch
|
||||
};
|
||||
|
||||
struct common_peg_schema_parser {
|
||||
@@ -288,6 +325,9 @@ struct common_peg_rule_parser {
|
||||
std::string name;
|
||||
common_peg_parser_id child;
|
||||
bool trigger;
|
||||
// set when the rule has a start and rest, the lazy grammar scans for the start
|
||||
common_peg_parser_id start = COMMON_PEG_INVALID_PARSER_ID;
|
||||
common_peg_parser_id rest = COMMON_PEG_INVALID_PARSER_ID;
|
||||
};
|
||||
|
||||
struct common_peg_ref_parser {
|
||||
@@ -308,17 +348,14 @@ struct common_peg_gbnf_parser {
|
||||
std::string grammar;
|
||||
};
|
||||
|
||||
struct common_peg_ac_parser {
|
||||
common_peg_parser_id child;
|
||||
std::vector<std::string> delimiters;
|
||||
};
|
||||
|
||||
// Variant holding all parser types
|
||||
using common_peg_parser_variant = std::variant<
|
||||
common_peg_epsilon_parser,
|
||||
common_peg_start_parser,
|
||||
common_peg_end_parser,
|
||||
common_peg_literal_parser,
|
||||
common_peg_token_parser,
|
||||
common_peg_token_not_parser,
|
||||
common_peg_sequence_parser,
|
||||
common_peg_choice_parser,
|
||||
common_peg_repetition_parser,
|
||||
@@ -334,14 +371,14 @@ using common_peg_parser_variant = std::variant<
|
||||
common_peg_ref_parser,
|
||||
common_peg_atomic_parser,
|
||||
common_peg_tag_parser,
|
||||
common_peg_gbnf_parser,
|
||||
common_peg_ac_parser
|
||||
common_peg_gbnf_parser
|
||||
>;
|
||||
|
||||
class common_peg_arena {
|
||||
std::vector<common_peg_parser_variant> parsers_;
|
||||
std::unordered_map<std::string, common_peg_parser_id> rules_;
|
||||
common_peg_parser_id root_ = COMMON_PEG_INVALID_PARSER_ID;
|
||||
common_peg_tokens tokens_;
|
||||
|
||||
public:
|
||||
const common_peg_parser_variant & get(common_peg_parser_id id) const { return parsers_.at(id); }
|
||||
@@ -356,6 +393,8 @@ class common_peg_arena {
|
||||
common_peg_parser_id root() const { return root_; }
|
||||
void set_root(common_peg_parser_id id) { root_ = id; }
|
||||
|
||||
const common_peg_tokens & tokens() const { return tokens_; }
|
||||
|
||||
common_peg_parse_result parse(common_peg_parse_context & ctx, size_t start = 0) const;
|
||||
common_peg_parse_result parse(common_peg_parser_id id, common_peg_parse_context & ctx, size_t start) const;
|
||||
|
||||
@@ -384,6 +423,7 @@ class common_peg_parser_builder {
|
||||
|
||||
public:
|
||||
common_peg_parser_builder();
|
||||
explicit common_peg_parser_builder(common_peg_tokens tokens);
|
||||
|
||||
// Match nothing, always succeed.
|
||||
// S -> ε
|
||||
@@ -401,6 +441,16 @@ class common_peg_parser_builder {
|
||||
// S -> "hello"
|
||||
common_peg_parser literal(const std::string & literal) { return add(common_peg_literal_parser{literal}); }
|
||||
|
||||
// Matches a token. Falls back to a literal if the token is not registered with the builder.
|
||||
// S -> <[token-id]>
|
||||
common_peg_parser token(const std::string & piece);
|
||||
|
||||
// Matches one of the tokens. With negate, matches one token that is not in the set.
|
||||
// A negated set may only name tokens registered with the builder.
|
||||
// S -> <[id1]> | <[id2]> | ... or !<[id1,id2,...]>
|
||||
common_peg_parser token(const std::vector<std::string> & pieces, bool negate = false);
|
||||
common_peg_parser token(std::initializer_list<std::string> pieces, bool negate = false) { return token(std::vector<std::string>(pieces), negate); }
|
||||
|
||||
// Matches a sequence of parsers in order, all must succeed.
|
||||
// S -> A B C
|
||||
common_peg_parser sequence() { return add(common_peg_sequence_parser{}); }
|
||||
@@ -457,16 +507,29 @@ class common_peg_parser_builder {
|
||||
// Matches all characters until a delimiter is found (delimiter not consumed).
|
||||
// Invalid UTF-8 is consumed and recorded on the AST nodes.
|
||||
// S -> (!delim .)*
|
||||
common_peg_parser until(const std::string & delimiter) { return add(common_peg_until_parser{{delimiter}}); }
|
||||
common_peg_parser until(const std::string & delimiter) { return until_one_of({delimiter}); }
|
||||
|
||||
// Matches all characters until one of the delimiters in the list is found (delimiter not consumed).
|
||||
// S -> (!delim .)*
|
||||
common_peg_parser until_one_of(const std::vector<std::string> & delimiters) { return add(common_peg_until_parser{delimiters}); }
|
||||
common_peg_parser until_one_of(const std::vector<std::string> & delimiters);
|
||||
|
||||
// Matches all characters until the delimiter is found (delimiter not consumed).
|
||||
// The delimiter may only be a sequence of literals, tokens, and choices of them. Tags and atomics may wrap them.
|
||||
// S -> (!delim .)*
|
||||
common_peg_parser until(const common_peg_parser & delimiter);
|
||||
|
||||
// Matches everything
|
||||
// S -> .*
|
||||
common_peg_parser rest() { return until_one_of({}); }
|
||||
|
||||
// Matches content, then the first delimiter, then the rest of the branch of that delimiter.
|
||||
// Branches must not share a delimiter. With optional, the input may end before any delimiter.
|
||||
// S -> C (D1 R1 | D2 R2 | ...)
|
||||
common_peg_parser through(const common_peg_parser & content, const std::vector<common_peg_until_branch> & branches, bool optional = false);
|
||||
common_peg_parser through(const common_peg_parser & content, std::initializer_list<common_peg_until_branch> branches, bool optional = false) { return through(content, std::vector<common_peg_until_branch>(branches), optional); }
|
||||
common_peg_parser through(const common_peg_parser & content, const common_peg_parser & delimiter) { return through(content, { { delimiter } }); }
|
||||
common_peg_parser through(const common_peg_parser & content, const std::string & delimiter) { return through(content, literal(delimiter)); }
|
||||
|
||||
// Matches between min and max repetitions of a parser (inclusive).
|
||||
// S -> A{m,n}
|
||||
// Use -1 for max to represent unbounded repetition (equivalent to {m,})
|
||||
@@ -537,6 +600,10 @@ class common_peg_parser_builder {
|
||||
common_peg_parser trigger_rule(const std::string & name, const common_peg_parser & p) { return rule(name, p, true); }
|
||||
common_peg_parser trigger_rule(const std::string & name, const std::function<common_peg_parser()> & builder) { return rule(name, builder, true); }
|
||||
|
||||
// Creates a trigger rule that matches start followed by rest. A lazy grammar scans for the start of any such rule, then only allows its rest.
|
||||
// The start has the same limits as an until() delimiter.
|
||||
common_peg_parser trigger_rule(const std::string & name, const common_peg_parser & start, const common_peg_parser & rest);
|
||||
|
||||
// Creates an atomic parser. Atomic parsers do not create an AST node if
|
||||
// the child results in a partial parse, i.e. NEEDS_MORE_INPUT. This is
|
||||
// intended for situations where partial output is undesirable.
|
||||
@@ -550,13 +617,6 @@ class common_peg_parser_builder {
|
||||
// the child's grammar. Parsing delegates entirely to the child.
|
||||
common_peg_parser gbnf(const common_peg_parser & p, const std::string & grammar) { return add(common_peg_gbnf_parser{p, grammar}); }
|
||||
|
||||
// Wraps a child parser but emits a GBNF grammar built from the Aho-Corasick
|
||||
// automaton of `delimiters`, matching everything up to and including the
|
||||
// first delimiter. Parsing delegates entirely to the child, which is
|
||||
// responsible for consuming the delimiter (e.g. until(D) + literal(D)).
|
||||
common_peg_parser ac(const common_peg_parser & p, const std::vector<std::string> & delimiters);
|
||||
common_peg_parser ac(const common_peg_parser & p, const std::string & delimiter) { return ac(p, std::vector<std::string>{delimiter}); }
|
||||
|
||||
void set_root(const common_peg_parser & p);
|
||||
|
||||
common_peg_arena build();
|
||||
|
||||
@@ -31,14 +31,18 @@ struct token_matcher {
|
||||
static common_trie build_trie(const std::vector<llama_tokens> & seqs) {
|
||||
common_trie t;
|
||||
for (const auto & seq : seqs) {
|
||||
t.insert(std::vector<uint32_t>(seq.begin(), seq.end()));
|
||||
std::vector<common_trie::symbol> symbols;
|
||||
for (llama_token token : seq) {
|
||||
symbols.push_back(common_trie::symbol::token(token));
|
||||
}
|
||||
t.insert(symbols);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
// returns the index into seqs of the longest sequence ending at this token, or -1
|
||||
int32_t advance(llama_token token) {
|
||||
state = ac.next(state, (uint32_t) token);
|
||||
state = ac.next(state, common_trie::symbol::token(token));
|
||||
const int32_t p = ac.match_pattern(state);
|
||||
if (p >= 0) {
|
||||
state = 0;
|
||||
|
||||
+54
-20
@@ -4,26 +4,46 @@
|
||||
|
||||
#include <deque>
|
||||
|
||||
common_trie::step common_trie::next(std::string_view sv, const std::vector<int32_t> & token_map, size_t pos) const {
|
||||
if (!tokens.empty() && pos < token_map.size()) {
|
||||
const int32_t id = token_map[pos];
|
||||
if (id >= 0 && tokens.find(id) != tokens.end()) {
|
||||
size_t end = pos + 1;
|
||||
while (end < token_map.size() && token_map[end] < 0) {
|
||||
++end;
|
||||
}
|
||||
return { utf8_parse_result::SUCCESS, symbol::token(id), end - pos };
|
||||
}
|
||||
}
|
||||
|
||||
auto result = common_parse_utf8_codepoint(sv, pos);
|
||||
return { result.status, symbol::codepoint(result.codepoint), result.bytes_consumed };
|
||||
}
|
||||
|
||||
common_trie::match_result common_trie::check_at(std::string_view sv, size_t start_pos) const {
|
||||
return check_at(sv, {}, start_pos);
|
||||
}
|
||||
|
||||
common_trie::match_result common_trie::check_at(std::string_view sv, const std::vector<int32_t> & token_map, size_t start_pos) const {
|
||||
size_t current = 0; // Start at root
|
||||
size_t pos = start_pos;
|
||||
|
||||
// LOG_DBG("%s: checking at pos %zu, sv='%s'\n", __func__, start_pos, std::string(sv).c_str());
|
||||
|
||||
while (pos < sv.size()) {
|
||||
auto result = common_parse_utf8_codepoint(sv, pos);
|
||||
if (result.status != utf8_parse_result::SUCCESS) {
|
||||
auto step = next(sv, token_map, pos);
|
||||
if (step.status != utf8_parse_result::SUCCESS) {
|
||||
break;
|
||||
}
|
||||
|
||||
auto it = nodes[current].children.find(result.codepoint);
|
||||
auto it = nodes[current].children.find(step.symbol);
|
||||
if (it == nodes[current].children.end()) {
|
||||
// Can't continue matching
|
||||
return match_result{match_result::NO_MATCH};
|
||||
}
|
||||
|
||||
current = it->second;
|
||||
pos += result.bytes_consumed;
|
||||
pos += step.bytes_consumed;
|
||||
|
||||
// Check if we've matched a complete word
|
||||
if (nodes[current].pattern >= 0) {
|
||||
@@ -42,7 +62,7 @@ common_trie::match_result common_trie::check_at(std::string_view sv, size_t star
|
||||
}
|
||||
|
||||
int32_t common_trie::insert(const std::string & word) {
|
||||
std::vector<uint32_t> symbols;
|
||||
std::vector<symbol> symbols;
|
||||
size_t pos = 0;
|
||||
while (pos < word.length()) {
|
||||
auto result = common_parse_utf8_codepoint(word, pos);
|
||||
@@ -50,28 +70,42 @@ int32_t common_trie::insert(const std::string & word) {
|
||||
break;
|
||||
}
|
||||
|
||||
symbols.push_back(result.codepoint);
|
||||
symbols.push_back(symbol::codepoint(result.codepoint));
|
||||
pos += result.bytes_consumed;
|
||||
}
|
||||
return insert(symbols);
|
||||
}
|
||||
|
||||
int32_t common_trie::insert(const std::vector<uint32_t> & symbols) {
|
||||
int32_t common_trie::insert(const std::vector<symbol> & symbols) {
|
||||
size_t current = 0;
|
||||
for (uint32_t ch : symbols) {
|
||||
auto it = nodes[current].children.find(ch);
|
||||
if (it == nodes[current].children.end()) {
|
||||
size_t child = create_node();
|
||||
nodes[current].children[ch] = child;
|
||||
current = child;
|
||||
} else {
|
||||
current = it->second;
|
||||
}
|
||||
for (symbol ch : symbols) {
|
||||
current = extend(current, ch);
|
||||
}
|
||||
if (nodes[current].pattern < 0) {
|
||||
nodes[current].pattern = n_patterns++;
|
||||
int32_t pattern = mark(current, n_patterns);
|
||||
if (pattern == n_patterns) {
|
||||
n_patterns++;
|
||||
}
|
||||
return nodes[current].pattern;
|
||||
return pattern;
|
||||
}
|
||||
|
||||
size_t common_trie::extend(size_t node, symbol ch) {
|
||||
if (ch.is_token()) {
|
||||
tokens.insert((int32_t) ch.value);
|
||||
}
|
||||
auto it = nodes[node].children.find(ch);
|
||||
if (it != nodes[node].children.end()) {
|
||||
return it->second;
|
||||
}
|
||||
size_t child = create_node();
|
||||
nodes[node].children[ch] = child;
|
||||
return child;
|
||||
}
|
||||
|
||||
int32_t common_trie::mark(size_t node, int32_t value) {
|
||||
if (nodes[node].pattern < 0) {
|
||||
nodes[node].pattern = value;
|
||||
}
|
||||
return nodes[node].pattern;
|
||||
}
|
||||
|
||||
common_aho_corasick::common_aho_corasick(common_trie trie) : t(std::move(trie)) {
|
||||
@@ -113,7 +147,7 @@ common_aho_corasick::common_aho_corasick(common_trie trie) : t(std::move(trie))
|
||||
}
|
||||
}
|
||||
|
||||
size_t common_aho_corasick::next(size_t state, uint32_t ch) const {
|
||||
size_t common_aho_corasick::next(size_t state, common_trie::symbol ch) const {
|
||||
const auto & nodes = t.nodes;
|
||||
while (state && nodes[state].children.find(ch) == nodes[state].children.end()) {
|
||||
state = fail[state];
|
||||
|
||||
+51
-10
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "unicode.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <set>
|
||||
@@ -10,13 +12,42 @@
|
||||
// Trie for matching multiple literals.
|
||||
// This is used in common_peg_until_parser and to build a GBNF exclusion grammar
|
||||
struct common_trie {
|
||||
// A symbol is either a UTF-8 codepoint or a token
|
||||
struct symbol {
|
||||
enum kind_type : uint8_t { CODEPOINT, TOKEN };
|
||||
|
||||
kind_type kind = CODEPOINT;
|
||||
uint32_t value = 0;
|
||||
|
||||
static symbol codepoint(uint32_t cpt) { return { CODEPOINT, cpt }; }
|
||||
static symbol token(int32_t id) { return { TOKEN, (uint32_t) id }; }
|
||||
|
||||
bool is_token() const { return kind == TOKEN; }
|
||||
|
||||
bool operator<(const symbol & other) const {
|
||||
return kind != other.kind ? kind < other.kind : value < other.value;
|
||||
}
|
||||
bool operator==(const symbol & other) const {
|
||||
return kind == other.kind && value == other.value;
|
||||
}
|
||||
};
|
||||
|
||||
struct step {
|
||||
enum utf8_parse_result::status status;
|
||||
common_trie::symbol symbol;
|
||||
size_t bytes_consumed;
|
||||
};
|
||||
|
||||
struct node {
|
||||
std::map<uint32_t, size_t> children; // Use uint32_t to store Unicode codepoints
|
||||
std::map<symbol, size_t> children;
|
||||
int32_t pattern = -1; // index of the pattern ending at this node, -1 if none
|
||||
};
|
||||
|
||||
std::vector<node> nodes;
|
||||
|
||||
// every token id used by a pattern, the input is split so these match as single symbols
|
||||
std::set<int32_t> tokens;
|
||||
|
||||
common_trie() {
|
||||
create_node(); // root node
|
||||
}
|
||||
@@ -29,15 +60,25 @@ struct common_trie {
|
||||
|
||||
enum match_result { NO_MATCH, PARTIAL_MATCH, COMPLETE_MATCH };
|
||||
|
||||
// Read the symbol at pos. It is a token if a pattern uses the token at pos, else a UTF-8 codepoint.
|
||||
step next(std::string_view sv, const std::vector<int32_t> & token_map, size_t pos) const;
|
||||
|
||||
// Check if a delimiter starts at the given position
|
||||
match_result check_at(std::string_view sv, size_t start_pos) const;
|
||||
match_result check_at(std::string_view sv, const std::vector<int32_t> & token_map, size_t start_pos) const;
|
||||
|
||||
// Insert a word as a sequence of Unicode codepoints, returns its pattern index
|
||||
int32_t insert(const std::string & word);
|
||||
|
||||
// Insert a raw symbol sequence, returns its pattern index (insertion order,
|
||||
// duplicates keep the first index)
|
||||
int32_t insert(const std::vector<uint32_t> & symbols);
|
||||
// Insert a symbol sequence, returns its pattern index (insertion order, duplicates keep the first index)
|
||||
int32_t insert(const std::vector<symbol> & symbols);
|
||||
|
||||
// Child of node on a symbol, created if missing
|
||||
size_t extend(size_t node, symbol ch);
|
||||
|
||||
// Mark node as the end of a pattern with a value from the caller. Returns the value already there, or value if the node had none.
|
||||
// A trie must take its values from mark or from insert, not both.
|
||||
int32_t mark(size_t node, int32_t value);
|
||||
|
||||
private:
|
||||
int32_t n_patterns = 0;
|
||||
@@ -51,11 +92,11 @@ struct common_trie {
|
||||
|
||||
// Aho-Corasick automaton
|
||||
struct common_aho_corasick {
|
||||
common_trie t;
|
||||
std::vector<size_t> fail; // failure links
|
||||
std::vector<size_t> order; // states in BFS order
|
||||
std::vector<int32_t> match; // longest pattern ending at each state (directly or via a suffix link), -1 if none
|
||||
std::set<uint32_t> alphabet; // every character with a transition
|
||||
common_trie t;
|
||||
std::vector<size_t> fail; // failure links
|
||||
std::vector<size_t> order; // states in BFS order
|
||||
std::vector<int32_t> match; // longest pattern ending at each state (directly or via a suffix link), -1 if none
|
||||
std::set<common_trie::symbol> alphabet; // every symbol with a transition
|
||||
|
||||
common_aho_corasick(common_trie trie);
|
||||
|
||||
@@ -69,5 +110,5 @@ struct common_aho_corasick {
|
||||
int32_t match_pattern(size_t s) const { return match[s]; }
|
||||
|
||||
// follow failure links until a transition on `ch` exists.
|
||||
size_t next(size_t state, uint32_t ch) const;
|
||||
size_t next(size_t state, common_trie::symbol ch) const;
|
||||
};
|
||||
|
||||
@@ -286,6 +286,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"Qwen3NextForCausalLM": "qwen",
|
||||
"Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
|
||||
"PocketTTSModel": "pockettts",
|
||||
"MoshiModel": "moshi",
|
||||
"KokoroModel": "kokoro",
|
||||
"TinyVocaModel": "tiny_voca",
|
||||
"Zonos3Model": "zonos3",
|
||||
@@ -432,6 +433,7 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
|
||||
"Qwen3ASRForConditionalGeneration": "qwen3vl",
|
||||
"Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
|
||||
"PocketTTSModel": "pockettts",
|
||||
"MoshiModel": "moshi",
|
||||
"KokoroModel": "kokoro",
|
||||
"TinyVocaModel": "tiny_voca",
|
||||
"SopranoModel": "soprano",
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable, TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from torch import Tensor
|
||||
|
||||
from .base import ModelBase, MmprojModel, SentencePieceTokenTypes, TextModel, gguf, logger
|
||||
from .pockettts import mimi_seanet_tensors, mimi_tfm_tensors
|
||||
|
||||
# Moshi family (Kyutai): a backbone over parallel streams (text + generated audio codes + input audio codes),
|
||||
# one position per 80 ms frame. Only Hibiki (simultaneous speech translation) is supported for now.
|
||||
# The checkpoint is not in the HF layout: a moshi-style config.json and two safetensors (LM + mimi).
|
||||
#
|
||||
# pipeline stage mapping:
|
||||
# transformer + text_emb/text_linear --> normal libllama text model (arch moshi)
|
||||
# mimi encoder + RVQ + emb[dep_q:] --> mtmd audio stream (projector moshi), rows of the input audio
|
||||
# depformer + emb[:dep_q] --> MTMD_GEN_PROCESS_TYPE_GEN_CODE, codes of a frame + their backbone embedding
|
||||
# RVQ decode + mimi decoder --> MTMD_GEN_PROCESS_TYPE_GEN_WAV
|
||||
#
|
||||
# Tricks:
|
||||
# - the initial text token (text_card) is appended to the vocab as <|text_start|>, the head has no logit for it;
|
||||
# it only opens the stream, the embeddings of the initial codes of the generated audio are folded into it
|
||||
# - the condition of Hibiki ("very_good" description, added to every row) is folded into the text embeddings,
|
||||
# every row has exactly one text embedding
|
||||
# - Hibiki ignores an early EOS: the reference gives it the embedding of PAD, done here too
|
||||
# - low-rank depformer embeddings are folded into full tables
|
||||
|
||||
_MIMI_PREFIX = "mimi."
|
||||
_COND_VALUE = "very_good"
|
||||
|
||||
|
||||
def _read_config(dir_model: Path) -> dict[str, Any] | None:
|
||||
path = dir_model / "config.json"
|
||||
if not path.is_file():
|
||||
return None
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
return config if isinstance(config, dict) and "moshi_name" in config else None
|
||||
|
||||
|
||||
def _tensor_shape(path: Path, name: str) -> tuple[int, ...]:
|
||||
with gguf.utility.SafetensorsLocal(path) as part:
|
||||
return tuple(part[name].shape)
|
||||
|
||||
|
||||
@ModelBase.register_hparams_loader(lambda dir_model: _read_config(dir_model) is not None)
|
||||
def _load_hparams(dir_model: Path) -> dict[str, Any]:
|
||||
config = _read_config(dir_model)
|
||||
assert config is not None
|
||||
model_type = config.get("model_type", "moshi")
|
||||
if model_type != "hibiki":
|
||||
raise NotImplementedError(f"moshi checkpoint of type {model_type!r} is not supported yet")
|
||||
logger.info(f"gguf: detected a moshi checkpoint ({model_type})")
|
||||
|
||||
# mtmd has the layout of Hibiki: the acoustic codes lag by 2 frames, the depformer has no positional embedding,
|
||||
# its steps past the last weight set reuse it, and the initial code is the extra entry after the mimi codebook
|
||||
n_q = config["dep_q"]
|
||||
schedule = config.get("depformer_weights_per_step_schedule") or list(range(n_q))
|
||||
# text, then the generated and the input codes
|
||||
if config["delays"] != [0] + ([0] + [2] * (n_q - 1)) * 2:
|
||||
raise NotImplementedError(f"unsupported delays {config['delays']}")
|
||||
if schedule != [min(i, max(schedule)) for i in range(n_q)] or config.get("depformer_pos_emb", "none") != "none":
|
||||
raise NotImplementedError("unsupported depformer layout")
|
||||
if config["card"] != 2048 or config["n_q"] != 2 * n_q:
|
||||
raise NotImplementedError("unsupported audio codebooks")
|
||||
|
||||
lm_path = dir_model / config["moshi_name"]
|
||||
# the gating hidden size is derived from dim_feedforward, read it back from the tensors
|
||||
n_ff = _tensor_shape(lm_path, "transformer.layers.0.gating.linear_out.weight")[1]
|
||||
n_ff_dep = _tensor_shape(lm_path, "depformer.layers.0.gating.0.linear_out.weight")[1]
|
||||
return {
|
||||
"architectures": ["MoshiModel"],
|
||||
"model_type": "moshi",
|
||||
"moshi_config": config,
|
||||
"num_hidden_layers": config["num_layers"],
|
||||
"hidden_size": config["dim"],
|
||||
"intermediate_size": n_ff,
|
||||
"num_attention_heads": config["num_heads"],
|
||||
"num_key_value_heads": config["num_heads"],
|
||||
"max_position_embeddings": config["context"],
|
||||
"sliding_window": config["context"],
|
||||
"rope_theta": config["max_period"],
|
||||
"rms_norm_eps": 1e-8, # rms_norm_f32
|
||||
"vocab_size": config["text_card"] + 1,
|
||||
"audio_config": {
|
||||
# mimi encoder transformer, constant across the family
|
||||
"num_hidden_layers": 8,
|
||||
"hidden_size": 512,
|
||||
"intermediate_size": 2048,
|
||||
"num_attention_heads": 8,
|
||||
},
|
||||
"depformer_config": {
|
||||
"num_hidden_layers": config["depformer_num_layers"],
|
||||
"hidden_size": config["depformer_dim"],
|
||||
"intermediate_size": n_ff_dep,
|
||||
"num_attention_heads": config["depformer_num_heads"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# the LM and mimi weights are in two files named by the config, mimi tensors get the "mimi." prefix
|
||||
def _moshi_config(model: ModelBase) -> dict[str, Any]:
|
||||
config = model.hparams.get("moshi_config")
|
||||
if config is None and isinstance(model, MmprojModel):
|
||||
config = model.global_config["moshi_config"] # the mmproj moves the hparams aside
|
||||
assert config is not None
|
||||
return config
|
||||
|
||||
|
||||
def _index_moshi_tensors(model: ModelBase) -> dict[str, Callable[[], Tensor]]:
|
||||
config = _moshi_config(model)
|
||||
tensors = model.index_local_tensors(Path(config["moshi_name"]).stem)
|
||||
for name, gen in model.index_local_tensors(Path(config["mimi_name"]).stem).items():
|
||||
tensors[_MIMI_PREFIX + name] = gen
|
||||
return tensors
|
||||
|
||||
|
||||
def _low_rank_embd(model: ModelBase, prefix: str) -> Tensor:
|
||||
embd = model.model_tensors[prefix + ".weight"]().float()
|
||||
proj = model.model_tensors.get(prefix + ".low_rank.weight")
|
||||
return embd @ proj().float().T if proj is not None else embd
|
||||
|
||||
|
||||
def _condition(model: ModelBase, value: str) -> Tensor:
|
||||
# LUT conditioner: output_proj(embed[index of value])
|
||||
lut = _moshi_config(model)["conditioners"]["description"]["lut"]
|
||||
prefix = "condition_provider.conditioners.description."
|
||||
embed = model.model_tensors[prefix + "embed.weight"]().float()
|
||||
proj = model.model_tensors[prefix + "output_proj.weight"]().float()
|
||||
return embed[lut["possible_values"].index(value)] @ proj.T
|
||||
|
||||
|
||||
@ModelBase.register("MoshiModel")
|
||||
@ModelBase.example("kyutai/hibiki-1b-pytorch-bf16", "kyutai/hibiki-2b-pytorch-bf16")
|
||||
class MoshiModel(TextModel):
|
||||
model_arch = gguf.MODEL_ARCH.MOSHI
|
||||
|
||||
def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]:
|
||||
assert remote_hf_model_id is None
|
||||
return _index_moshi_tensors(self)
|
||||
|
||||
def set_vocab(self):
|
||||
from sentencepiece import SentencePieceProcessor
|
||||
|
||||
config = _moshi_config(self)
|
||||
sp = SentencePieceProcessor()
|
||||
sp.LoadFromFile(str(self.dir_model / config["tokenizer_name"]))
|
||||
assert sp.vocab_size() == config["text_card"]
|
||||
|
||||
tokens: list[bytes] = []
|
||||
scores: list[float] = []
|
||||
toktypes: list[int] = []
|
||||
for i in range(sp.vocab_size()):
|
||||
toktype = SentencePieceTokenTypes.NORMAL
|
||||
if sp.IsControl(i) or sp.IsUnknown(i):
|
||||
# <unk> (0) is the end-of-padding marker of the text stream, it has no text
|
||||
toktype = SentencePieceTokenTypes.CONTROL
|
||||
elif sp.IsUnused(i):
|
||||
toktype = SentencePieceTokenTypes.UNUSED
|
||||
elif sp.IsByte(i):
|
||||
toktype = SentencePieceTokenTypes.BYTE
|
||||
tokens.append(sp.IdToPiece(i).encode("utf-8"))
|
||||
scores.append(sp.GetScore(i))
|
||||
toktypes.append(toktype)
|
||||
|
||||
# the initial token of the text stream
|
||||
tokens.append(b"<|text_start|>")
|
||||
scores.append(-1000.0)
|
||||
toktypes.append(SentencePieceTokenTypes.CONTROL)
|
||||
|
||||
self.gguf_writer.add_tokenizer_model("llama")
|
||||
self.gguf_writer.add_tokenizer_pre("default")
|
||||
self.gguf_writer.add_token_list(tokens)
|
||||
self.gguf_writer.add_token_scores(scores)
|
||||
self.gguf_writer.add_token_types(toktypes)
|
||||
self.gguf_writer.add_unk_token_id(sp.unk_id())
|
||||
self.gguf_writer.add_bos_token_id(sp.bos_id())
|
||||
self.gguf_writer.add_eos_token_id(sp.eos_id())
|
||||
self.gguf_writer.add_pad_token_id(sp.pad_id())
|
||||
self.gguf_writer.add_add_bos_token(False)
|
||||
self.gguf_writer.add_add_eos_token(False)
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
super().set_gguf_parameters()
|
||||
self.gguf_writer.add_sliding_window(self.hparams["sliding_window"])
|
||||
|
||||
# sampling of the text tokens, the audio codes are sampled by mtmd
|
||||
gen = _moshi_config(self).get("lm_gen_config", {})
|
||||
self.gguf_writer.add_sampling_temp(gen.get("temp_text", 0.7))
|
||||
self.gguf_writer.add_sampling_top_k(gen.get("top_k_text", 25))
|
||||
self.gguf_writer.add_sampling_top_p(1.0)
|
||||
self.gguf_writer.add_sampling_min_p(0.0)
|
||||
|
||||
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
|
||||
T = gguf.MODEL_TENSOR
|
||||
|
||||
if name == "text_emb.weight":
|
||||
config = _moshi_config(self)
|
||||
embd = data_torch.float().clone()
|
||||
embd[2] = embd[3] # EOS -> PAD, see get_moshi() of the reference
|
||||
embd += _condition(self, _COND_VALUE)
|
||||
assert embd.shape[0] == config["text_card"] + 1
|
||||
# <|text_start|> only opens the stream, with the initial codes of the generated audio
|
||||
for k in range(config["dep_q"]):
|
||||
embd[-1] += self.model_tensors[f"emb.{k}.weight"]()[config["card"]].float()
|
||||
yield (self.format_tensor_name(T.TOKEN_EMBD), embd)
|
||||
return
|
||||
if name == "text_linear.weight":
|
||||
yield (self.format_tensor_name(T.OUTPUT), data_torch)
|
||||
return
|
||||
if name == "out_norm.alpha":
|
||||
yield (self.format_tensor_name(T.OUTPUT_NORM), data_torch.reshape(-1))
|
||||
return
|
||||
|
||||
if not name.startswith("transformer.layers."):
|
||||
return # mimi, depformer and the audio embeddings go to the mmproj
|
||||
assert bid is not None
|
||||
key = name.split(f"layers.{bid}.", 1)[1]
|
||||
|
||||
if key == "self_attn.in_proj_weight":
|
||||
q, k, v = data_torch.chunk(3, dim=0)
|
||||
yield (self.format_tensor_name(T.ATTN_Q, bid), q)
|
||||
yield (self.format_tensor_name(T.ATTN_K, bid), k)
|
||||
yield (self.format_tensor_name(T.ATTN_V, bid), v)
|
||||
elif key == "self_attn.out_proj.weight":
|
||||
yield (self.format_tensor_name(T.ATTN_OUT, bid), data_torch)
|
||||
elif key == "norm1.alpha":
|
||||
yield (self.format_tensor_name(T.ATTN_NORM, bid), data_torch.reshape(-1))
|
||||
elif key == "norm2.alpha":
|
||||
yield (self.format_tensor_name(T.FFN_NORM, bid), data_torch.reshape(-1))
|
||||
elif key == "gating.linear_in.weight":
|
||||
# silu(first half) * second half
|
||||
gate, up = data_torch.chunk(2, dim=0)
|
||||
yield (self.format_tensor_name(T.FFN_GATE, bid), gate)
|
||||
yield (self.format_tensor_name(T.FFN_UP, bid), up)
|
||||
elif key == "gating.linear_out.weight":
|
||||
yield (self.format_tensor_name(T.FFN_DOWN, bid), data_torch)
|
||||
else:
|
||||
raise ValueError(f"unexpected tensor {name}")
|
||||
|
||||
|
||||
@ModelBase.register("MoshiModel")
|
||||
@ModelBase.example("kyutai/hibiki-1b-pytorch-bf16", "kyutai/hibiki-2b-pytorch-bf16")
|
||||
class MoshiMmprojModel(MmprojModel):
|
||||
has_audio_encoder = True
|
||||
has_vision_encoder = False
|
||||
|
||||
def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]:
|
||||
assert remote_hf_model_id is None
|
||||
return _index_moshi_tensors(self)
|
||||
|
||||
def _n_codebooks(self) -> int:
|
||||
return _moshi_config(self)["dep_q"]
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
self.gguf_writer.add_file_type(self.ftype)
|
||||
assert self.hparams_audio is not None
|
||||
dep = self.global_config["depformer_config"]
|
||||
|
||||
# input audio: mimi encoder + RVQ + embeddings of the input codes
|
||||
self.gguf_writer.add_clip_has_audio_encoder(True)
|
||||
self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.MOSHI)
|
||||
self.gguf_writer.add_audio_projection_dim(self.n_embd_text)
|
||||
self.gguf_writer.add_audio_block_count(self.hparams_audio["num_hidden_layers"])
|
||||
self.gguf_writer.add_audio_embedding_length(self.hparams_audio["hidden_size"])
|
||||
self.gguf_writer.add_audio_feed_forward_length(self.hparams_audio["intermediate_size"])
|
||||
self.gguf_writer.add_audio_head_count(self.hparams_audio["num_attention_heads"])
|
||||
self.gguf_writer.add_audio_attention_layernorm_eps(1e-5)
|
||||
# mimi convolves the waveform directly, it is passed around as a 1-row "mel"
|
||||
self.gguf_writer.add_audio_num_mel_bins(1)
|
||||
|
||||
# generation: depformer + mimi decoder, the mimi hparams are constant and held by mtmd
|
||||
self.gguf_writer.add_clip_has_gen_audio_encoder(True)
|
||||
self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.MOSHI_GEN)
|
||||
self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text)
|
||||
self.gguf_writer.add_gen_audio_embedding_length(dep["hidden_size"])
|
||||
self.gguf_writer.add_gen_audio_feed_forward_length(dep["intermediate_size"])
|
||||
self.gguf_writer.add_gen_audio_block_count(dep["num_hidden_layers"])
|
||||
self.gguf_writer.add_gen_audio_head_count(dep["num_attention_heads"])
|
||||
self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-8)
|
||||
self.gguf_writer.add_gen_audio_model_variant(_moshi_config(self)["model_type"])
|
||||
|
||||
def tensor_force_quant(self, name, new_name, bid, n_dims):
|
||||
del name, bid, n_dims
|
||||
# conv1d/conv1d_dw kernels must be F16, ggml_conv_1d(_dw) has no BF16 path
|
||||
if ".seanet." in new_name or new_name in ("a.downsample.conv.weight", "a.gen.wav.upsample.weight"):
|
||||
return gguf.GGMLQuantizationType.F16
|
||||
# nearest-code search and RVQ decode stay exact
|
||||
if ".codebook" in new_name or new_name.startswith("a.codec.vq."):
|
||||
return gguf.GGMLQuantizationType.F32
|
||||
return False
|
||||
|
||||
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
|
||||
del bid
|
||||
T = gguf.MODEL_TENSOR
|
||||
if name.startswith(("a.", "mm.a.")):
|
||||
yield (name, data_torch) # already named by generate_extra_tensors()
|
||||
return
|
||||
if not name.startswith(_MIMI_PREFIX):
|
||||
return # the LM tensors are stacked in generate_extra_tensors()
|
||||
if name == "mimi.downsample.conv.conv.conv.weight":
|
||||
yield (self.format_tensor_name(T.A_ENC_DOWNSAMPLE_CONV), data_torch)
|
||||
elif name == "mimi.upsample.convtr.convtr.convtr.weight":
|
||||
yield (self.format_tensor_name(T.A_GEN_WAV_UPSAMPLE), data_torch)
|
||||
elif "_transformer.transformer.layers." in name:
|
||||
# pocket-tts names it in_proj.weight
|
||||
yield from mimi_tfm_tensors(self, name.replace(".in_proj_weight", ".in_proj.weight"), data_torch)
|
||||
elif name.startswith(("mimi.encoder.model.", "mimi.decoder.model.")):
|
||||
yield from mimi_seanet_tensors(self, name, data_torch, 4)
|
||||
|
||||
def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
|
||||
T = gguf.MODEL_TENSOR
|
||||
config = _moshi_config(self)
|
||||
n_q = self._n_codebooks()
|
||||
|
||||
def get(name: str) -> Tensor:
|
||||
return self.model_tensors[name]()
|
||||
|
||||
def stack(names: Iterable[str]) -> Tensor:
|
||||
return torch.stack([get(n) for n in names], dim=0)
|
||||
|
||||
# mimi RVQ: one semantic codebook, then n_q - 1 acoustic ones
|
||||
def codebooks(prefix: str, n: int) -> Tensor:
|
||||
books = []
|
||||
for i in range(n):
|
||||
embedding_sum = get(f"{prefix}.vq.layers.{i}._codebook.embedding_sum").float()
|
||||
cluster_usage = get(f"{prefix}.vq.layers.{i}._codebook.cluster_usage").float()
|
||||
books.append(embedding_sum / cluster_usage.clamp_min(1e-5).unsqueeze(-1))
|
||||
return torch.stack(books, dim=0) if n > 1 else books[0]
|
||||
|
||||
q = "mimi.quantizer."
|
||||
cb_first = codebooks(q + "rvq_first", 1)
|
||||
cb_rest = codebooks(q + "rvq_rest", n_q - 1)
|
||||
yield (self.format_tensor_name(T.A_CODEC_VQ_FIRST_IN), get(q + "rvq_first.input_proj.weight").squeeze(-1))
|
||||
yield (self.format_tensor_name(T.A_CODEC_VQ_FIRST_CB), cb_first)
|
||||
yield (self.format_tensor_name(T.A_CODEC_VQ_REST_IN), get(q + "rvq_rest.input_proj.weight").squeeze(-1))
|
||||
yield (self.format_tensor_name(T.A_CODEC_VQ_REST_CB), cb_rest)
|
||||
yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_FIRST_OUT), get(q + "rvq_first.output_proj.weight").squeeze(-1))
|
||||
yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_FIRST_CB), cb_first)
|
||||
yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_REST_OUT), get(q + "rvq_rest.output_proj.weight").squeeze(-1))
|
||||
yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_REST_CB), cb_rest)
|
||||
|
||||
# backbone embeddings of the audio codes: the generated stream first, then the input stream
|
||||
assert config["n_q"] == 2 * n_q
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_OUT_EMBD), stack(f"emb.{k}.weight" for k in range(n_q)))
|
||||
yield (self.format_tensor_name(T.A_MM_CODE_EMBD), stack(f"emb.{k}.weight" for k in range(n_q, 2 * n_q)))
|
||||
|
||||
# depformer: per-step weights are stacked on the last ggml dim, steps past the last weight set reuse it
|
||||
dep = self.global_config["depformer_config"]
|
||||
n_dim = dep["hidden_size"]
|
||||
n_in = sum(1 for name in self.model_tensors if name.startswith("depformer_in."))
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_PROJ_IN), stack(f"depformer_in.{i}.weight" for i in range(n_in)))
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_TOK_EMBD), _low_rank_embd(self, "depformer_text_emb"))
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_EMBD),
|
||||
torch.stack([_low_rank_embd(self, f"depformer_emb.{i}") for i in range(n_q - 1)], dim=0))
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_HEAD), stack(f"linears.{k}.weight" for k in range(n_q)))
|
||||
|
||||
for il in range(dep["num_hidden_layers"]):
|
||||
p = f"depformer.layers.{il}."
|
||||
n_w = sum(1 for name in self.model_tensors if name.startswith(p + "gating.") and name.endswith(".linear_in.weight"))
|
||||
assert n_w == n_in, "depformer_in and the per-step weights use the same schedule"
|
||||
qkv = get(p + "self_attn.in_proj_weight").reshape(n_w, 3, n_dim, n_dim)
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_Q, il), qkv[:, 0])
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_K, il), qkv[:, 1])
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_V, il), qkv[:, 2])
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_OUT, il), get(p + "self_attn.out_proj.weight").reshape(n_w, n_dim, n_dim))
|
||||
gate_up = stack(f"{p}gating.{i}.linear_in.weight" for i in range(n_w))
|
||||
gate, up = gate_up.chunk(2, dim=1)
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_FFN_GATE, il), gate)
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_FFN_UP, il), up)
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_FFN_DOWN, il), stack(f"{p}gating.{i}.linear_out.weight" for i in range(n_w)))
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_NORM, il), get(p + "norm1.alpha").reshape(-1))
|
||||
yield (self.format_tensor_name(T.A_GEN_CODE_FFN_NORM, il), get(p + "norm2.alpha").reshape(-1))
|
||||
+74
-70
@@ -271,26 +271,84 @@ class PocketTTSModel(TextModel):
|
||||
return torch.cat(rows, dim=0)
|
||||
|
||||
|
||||
# mimi tensors (shared with moshi): the transformers of the encoder and the decoder, and the SEANet stacks
|
||||
MIMI_TFM_MAP = {
|
||||
"norm1": (gguf.MODEL_TENSOR.A_ENC_INPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_NORM),
|
||||
"norm2": (gguf.MODEL_TENSOR.A_ENC_OUTPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_NORM),
|
||||
"self_attn.out_proj": (gguf.MODEL_TENSOR.A_ENC_OUTPUT, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_OUT),
|
||||
"linear1": (gguf.MODEL_TENSOR.A_ENC_FFN_UP, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_UP),
|
||||
"linear2": (gguf.MODEL_TENSOR.A_ENC_FFN_DOWN, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_DOWN),
|
||||
"layer_scale_1.scale": (gguf.MODEL_TENSOR.A_ENC_ATTN_SCALE, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_SCALE),
|
||||
"layer_scale_2.scale": (gguf.MODEL_TENSOR.A_ENC_FFN_SCALE_LS, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_SCALE),
|
||||
}
|
||||
MIMI_TFM_QKV = (
|
||||
(gguf.MODEL_TENSOR.A_ENC_ATTN_Q, gguf.MODEL_TENSOR.A_ENC_ATTN_K, gguf.MODEL_TENSOR.A_ENC_ATTN_V),
|
||||
(gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_Q, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_K, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_V),
|
||||
)
|
||||
|
||||
|
||||
def mimi_tfm_tensors(model: MmprojModel, name: str, data_torch: Tensor) -> Iterable[tuple[str, Tensor]]:
|
||||
is_decoder = name.startswith("mimi.decoder_transformer.")
|
||||
bid = int(name.split("_transformer.transformer.layers.", 1)[1].split(".")[0])
|
||||
key_with_suffix = name.split(f".layers.{bid}.", 1)[1]
|
||||
|
||||
if key_with_suffix == "self_attn.in_proj.weight":
|
||||
q, k, v = data_torch.chunk(3, dim=0)
|
||||
names = MIMI_TFM_QKV[1 if is_decoder else 0]
|
||||
for tensor, part in zip(names, (q, k, v)):
|
||||
yield (model.format_tensor_name(tensor, bid), part)
|
||||
return
|
||||
|
||||
key, suffix = key_with_suffix.rsplit(".", 1)
|
||||
entry = MIMI_TFM_MAP.get(key) or MIMI_TFM_MAP.get(key_with_suffix)
|
||||
if entry is None:
|
||||
return
|
||||
tensor = entry[1 if is_decoder else 0]
|
||||
suffix = ".weight" if key_with_suffix.endswith(".scale") else "." + suffix
|
||||
yield (model.format_tensor_name(tensor, bid, suffix=suffix), data_torch)
|
||||
|
||||
|
||||
def mimi_seanet_tensors(model: MmprojModel, name: str, data_torch: Tensor, n_stages: int) -> Iterable[tuple[str, Tensor]]:
|
||||
T = gguf.MODEL_TENSOR
|
||||
is_decoder = name.startswith("mimi.decoder.")
|
||||
idx = int(name.split(".model.", 1)[1].split(".")[0])
|
||||
suffix = "." + name.rsplit(".", 1)[1]
|
||||
|
||||
conv_in, conv_out, res1, res2, scale = (
|
||||
(T.A_GEN_WAV_SEANET_CONV_IN, T.A_GEN_WAV_SEANET_CONV_OUT, T.A_GEN_WAV_SEANET_RES_CONV1,
|
||||
T.A_GEN_WAV_SEANET_RES_CONV2, T.A_GEN_WAV_SEANET_SCALE_CONV)
|
||||
if is_decoder else
|
||||
(T.A_ENC_SEANET_CONV_IN, T.A_ENC_SEANET_CONV_OUT, T.A_ENC_SEANET_RES_CONV1,
|
||||
T.A_ENC_SEANET_RES_CONV2, T.A_ENC_SEANET_SCALE_CONV)
|
||||
)
|
||||
|
||||
if idx == 0:
|
||||
yield (model.format_tensor_name(conv_in, suffix=suffix), data_torch)
|
||||
return
|
||||
if idx == 3 * n_stages + 2:
|
||||
yield (model.format_tensor_name(conv_out, suffix=suffix), data_torch)
|
||||
return
|
||||
|
||||
for stage in range(n_stages):
|
||||
res_idx = _DEC_RES_IDX(stage) if is_decoder else _ENC_RES_IDX(stage)
|
||||
scale_idx = _DEC_SCALE_IDX(stage) if is_decoder else _ENC_SCALE_IDX(stage)
|
||||
if idx == scale_idx:
|
||||
yield (model.format_tensor_name(scale, stage, suffix=suffix), data_torch)
|
||||
return
|
||||
if idx == res_idx:
|
||||
# block.1 is the dilated conv, block.3 the pointwise one (0 and 2 are ELU)
|
||||
inner = int(name.split(".block.", 1)[1].split(".")[0])
|
||||
tensor = res1 if inner == 1 else res2
|
||||
yield (model.format_tensor_name(tensor, stage, suffix=suffix), data_torch)
|
||||
return
|
||||
|
||||
|
||||
@ModelBase.register("PocketTTSModel")
|
||||
# [TAG_HF_EXAMPLE_MISSING] model is gated, and the checkpoint requires cd to subdir, not supported here
|
||||
class PocketTTSMmprojModel(MmprojModel):
|
||||
has_audio_encoder = True
|
||||
has_vision_encoder = False
|
||||
|
||||
_MIMI_TFM_MAP = {
|
||||
"norm1": (gguf.MODEL_TENSOR.A_ENC_INPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_NORM),
|
||||
"norm2": (gguf.MODEL_TENSOR.A_ENC_OUTPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_NORM),
|
||||
"self_attn.out_proj": (gguf.MODEL_TENSOR.A_ENC_OUTPUT, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_OUT),
|
||||
"linear1": (gguf.MODEL_TENSOR.A_ENC_FFN_UP, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_UP),
|
||||
"linear2": (gguf.MODEL_TENSOR.A_ENC_FFN_DOWN, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_DOWN),
|
||||
"layer_scale_1.scale": (gguf.MODEL_TENSOR.A_ENC_ATTN_SCALE, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_SCALE),
|
||||
"layer_scale_2.scale": (gguf.MODEL_TENSOR.A_ENC_FFN_SCALE_LS, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_SCALE),
|
||||
}
|
||||
_MIMI_TFM_QKV = (
|
||||
(gguf.MODEL_TENSOR.A_ENC_ATTN_Q, gguf.MODEL_TENSOR.A_ENC_ATTN_K, gguf.MODEL_TENSOR.A_ENC_ATTN_V),
|
||||
(gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_Q, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_K, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_V),
|
||||
)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.has_audio_encoder = _has_voice_encoder(self.dir_model)
|
||||
@@ -419,11 +477,11 @@ class PocketTTSMmprojModel(MmprojModel):
|
||||
return
|
||||
|
||||
if "_transformer.transformer.layers." in name:
|
||||
yield from self._mimi_tfm_tensor(name, data_torch)
|
||||
yield from mimi_tfm_tensors(self, name, data_torch)
|
||||
return
|
||||
|
||||
if name.startswith("mimi.encoder.model.") or name.startswith("mimi.decoder.model."):
|
||||
yield from self._seanet_tensor(name, data_torch)
|
||||
yield from mimi_seanet_tensors(self, name, data_torch, _N_SEANET_STAGES)
|
||||
return
|
||||
|
||||
return
|
||||
@@ -471,57 +529,3 @@ class PocketTTSMmprojModel(MmprojModel):
|
||||
if tensor is not None:
|
||||
yield (self.format_tensor_name(tensor, bid, suffix=suffix), data_torch)
|
||||
return
|
||||
|
||||
def _mimi_tfm_tensor(self, name: str, data_torch: Tensor) -> Iterable[tuple[str, Tensor]]:
|
||||
is_decoder = name.startswith("mimi.decoder_transformer.")
|
||||
bid = int(name.split("_transformer.transformer.layers.", 1)[1].split(".")[0])
|
||||
key_with_suffix = name.split(f".layers.{bid}.", 1)[1]
|
||||
|
||||
if key_with_suffix == "self_attn.in_proj.weight":
|
||||
q, k, v = data_torch.chunk(3, dim=0)
|
||||
names = self._MIMI_TFM_QKV[1 if is_decoder else 0]
|
||||
for tensor, part in zip(names, (q, k, v)):
|
||||
yield (self.format_tensor_name(tensor, bid), part)
|
||||
return
|
||||
|
||||
key, suffix = key_with_suffix.rsplit(".", 1)
|
||||
entry = self._MIMI_TFM_MAP.get(key) or self._MIMI_TFM_MAP.get(key_with_suffix)
|
||||
if entry is None:
|
||||
return
|
||||
tensor = entry[1 if is_decoder else 0]
|
||||
suffix = ".weight" if key_with_suffix.endswith(".scale") else "." + suffix
|
||||
yield (self.format_tensor_name(tensor, bid, suffix=suffix), data_torch)
|
||||
|
||||
def _seanet_tensor(self, name: str, data_torch: Tensor) -> Iterable[tuple[str, Tensor]]:
|
||||
T = gguf.MODEL_TENSOR
|
||||
is_decoder = name.startswith("mimi.decoder.")
|
||||
idx = int(name.split(".model.", 1)[1].split(".")[0])
|
||||
suffix = "." + name.rsplit(".", 1)[1]
|
||||
|
||||
conv_in, conv_out, res1, res2, scale = (
|
||||
(T.A_GEN_WAV_SEANET_CONV_IN, T.A_GEN_WAV_SEANET_CONV_OUT, T.A_GEN_WAV_SEANET_RES_CONV1,
|
||||
T.A_GEN_WAV_SEANET_RES_CONV2, T.A_GEN_WAV_SEANET_SCALE_CONV)
|
||||
if is_decoder else
|
||||
(T.A_ENC_SEANET_CONV_IN, T.A_ENC_SEANET_CONV_OUT, T.A_ENC_SEANET_RES_CONV1,
|
||||
T.A_ENC_SEANET_RES_CONV2, T.A_ENC_SEANET_SCALE_CONV)
|
||||
)
|
||||
|
||||
if idx == 0:
|
||||
yield (self.format_tensor_name(conv_in, suffix=suffix), data_torch)
|
||||
return
|
||||
if idx == 3 * _N_SEANET_STAGES + 2:
|
||||
yield (self.format_tensor_name(conv_out, suffix=suffix), data_torch)
|
||||
return
|
||||
|
||||
for stage in range(_N_SEANET_STAGES):
|
||||
res_idx = _DEC_RES_IDX(stage) if is_decoder else _ENC_RES_IDX(stage)
|
||||
scale_idx = _DEC_SCALE_IDX(stage) if is_decoder else _ENC_SCALE_IDX(stage)
|
||||
if idx == scale_idx:
|
||||
yield (self.format_tensor_name(scale, stage, suffix=suffix), data_torch)
|
||||
return
|
||||
if idx == res_idx:
|
||||
# block.1 is the dilated conv, block.3 the pointwise one (0 and 2 are ELU)
|
||||
inner = int(name.split(".block.", 1)[1].split(".")[0])
|
||||
tensor = res1 if inner == 1 else res2
|
||||
yield (self.format_tensor_name(tensor, stage, suffix=suffix), data_torch)
|
||||
return
|
||||
|
||||
@@ -67,6 +67,8 @@ For a more complete example, see `test_example_native()` in
|
||||
- **`end()`** - Matches the end of input (anchor `$`)
|
||||
- **`literal(string)`** - Matches an exact literal string
|
||||
- **`any()`** - Matches any single character (`.`)
|
||||
- **`token(piece)`** - Matches a special token, or the literal `piece` if it is not registered with the builder (see [Special Tokens](#special-tokens))
|
||||
- **`token(pieces, negate)`** - Matches one of the tokens, or with `negate` one token that is not one of them
|
||||
|
||||
### Combinators
|
||||
|
||||
@@ -89,6 +91,8 @@ For a more complete example, see `test_example_native()` in
|
||||
- **`space()`** - Matches zero or more whitespace characters (space, tab, newline)
|
||||
- **`until(delimiter)`** - Matches characters until delimiter is found (delimiter not consumed)
|
||||
- **`until_one_of(delimiters)`** - Matches characters until any delimiter in the list is found
|
||||
- **`until(parser)`** - Matches characters until a delimiter built from literals and tokens is found (delimiter not consumed, see [until(parser)](#untilparser))
|
||||
- **`through(content, branches, optional)`** - Matches content, then the first delimiter found and the rest of its branch (delimiter consumed). The grammar scans for the delimiters instead of following content
|
||||
- **`rest()`** - Matches everything remaining (`.*`)
|
||||
|
||||
### JSON Parsers
|
||||
@@ -108,6 +112,7 @@ For a more complete example, see `test_example_native()` in
|
||||
- **`ref(name)`** - Creates a lightweight reference to a named rule (for recursive grammars)
|
||||
- **`rule(name, p, trigger)`** - Creates a named rule and returns a reference
|
||||
- **`trigger_rule(name, p)`** - Creates a trigger rule (entry point for lazy grammar generation)
|
||||
- **`trigger_rule(name, start, rest)`** - Creates a trigger rule matching `start` then `rest`, gating the lazy grammar on the start
|
||||
- **`schema(p, name, schema, raw)`** - Wraps parser with JSON schema metadata for grammar generation
|
||||
- **`schema(p, name, doc, node, raw)`** - Same, for a node of a `common_chat_schema_document` built earlier, e.g. one tool parameter
|
||||
|
||||
@@ -116,6 +121,110 @@ For a more complete example, see `test_example_native()` in
|
||||
- **`atomic(p)`** - Prevents AST node creation for partial parses
|
||||
- **`tag(tag, p)`** - Creates AST nodes with semantic tags (multiple nodes can share tags)
|
||||
|
||||
## Special Tokens
|
||||
|
||||
Matching a special token by its text alone is ambiguous: a model may emit
|
||||
`<|end|>` as a single control token, or spell it out as plain text, such as
|
||||
when quoting a chat template. The parser can tell them apart when the builder
|
||||
knows the special tokens of the vocabulary, and the input carries the ids of
|
||||
the tokens that produced it.
|
||||
|
||||
A `common_peg_tokens` table constructed from a `llama_vocab` registers every
|
||||
control and user-defined token. Pass it to the builder:
|
||||
|
||||
```cpp
|
||||
common_peg_tokens specials(vocab);
|
||||
|
||||
auto parser = build_chat_peg_parser(specials, [&](common_chat_peg_builder & p) {
|
||||
return p.content(p.until(p.token("<|end|>"))) + p.token("<|end|>");
|
||||
});
|
||||
```
|
||||
|
||||
Chat templates initialized with a model build this table from its vocabulary,
|
||||
and format handlers receive it as `inputs.specials`.
|
||||
|
||||
### token()
|
||||
|
||||
`token(piece)` matches only where the input holds the id of that token, and
|
||||
consumes the whole piece. The same characters without the id do not match.
|
||||
If `piece` is not registered with the builder, it falls back to
|
||||
`literal(piece)`.
|
||||
|
||||
`token(pieces)` matches any of the tokens, and `token(pieces, true)` matches one
|
||||
token that is not in the set. Every piece of a negated set must be registered,
|
||||
otherwise it throws `std::invalid_argument`.
|
||||
|
||||
In the grammar, a token emits `<[id]>` and a negated set emits `!<[...]>`:
|
||||
|
||||
```cpp
|
||||
p.token({ "<a>", "<b>" }) + p.token({ "<a>", "<b>" }, true)
|
||||
```
|
||||
|
||||
```
|
||||
root ::= (<[1]> | <[2]>) !<[1-2]>
|
||||
```
|
||||
|
||||
### until(parser)
|
||||
|
||||
`until(delimiter)` with a parser instead of a string stops at a delimiter that
|
||||
may contain tokens, or several literals joined in a sequence:
|
||||
|
||||
```cpp
|
||||
auto end = p.token("<|end|>");
|
||||
auto final = p.token("<|channel|>") + p.literal("final");
|
||||
|
||||
p.reasoning(p.until(end | final))
|
||||
```
|
||||
|
||||
The delimiter may only be built from:
|
||||
|
||||
- `literal()` and `token()`
|
||||
- `sequence()` and `choice()` of the above
|
||||
- `tag()` and `atomic()` wrapping any of the above
|
||||
|
||||
Any other parser throws `std::invalid_argument`. A choice inside a sequence
|
||||
expands to every combination, so `"a" + ("b" | "d")` stops at both `ab` and
|
||||
`ad`.
|
||||
|
||||
The grammar scans for the delimiters the same way as `until_one_of()`:
|
||||
|
||||
```cpp
|
||||
p.until((p.literal("a") + p.literal("b")) | p.literal("cd"))
|
||||
```
|
||||
|
||||
```
|
||||
root ::= until-5
|
||||
until-5 ::= | [a] until-5-01 | [c] until-5-03 | [^ac] until-5
|
||||
until-5-01 ::= | [a] until-5-01 | [c] until-5-03 | [^abc] until-5
|
||||
until-5-03 ::= | [a] until-5-01 | [c] until-5-03 | [^acd] until-5
|
||||
```
|
||||
|
||||
A token never matches a character rule such as `.` or `[^a]`, so the scan lets
|
||||
the other tokens named elsewhere in the grammar through by name. Here `<b>` is
|
||||
token 2:
|
||||
|
||||
```cpp
|
||||
p.until(p.token("<a>") + p.literal("x")) + p.token("<a>") + p.literal("x") + p.token("<b>")
|
||||
```
|
||||
|
||||
```
|
||||
root ::= until-3 <[1]> "x" <[2]>
|
||||
until-3 ::= | <[1]> until-3-01 | (. | <[2]>) until-3
|
||||
until-3-01 ::= | <[1]> until-3-01 | ([^x] | <[2]>) until-3
|
||||
```
|
||||
|
||||
When the delimiters are made of tokens alone, the scan consumes whole tokens
|
||||
with a negated token set instead:
|
||||
|
||||
```cpp
|
||||
p.until(p.token("<a>")) + p.token("<a>")
|
||||
```
|
||||
|
||||
```
|
||||
root ::= until-1 <[1]>
|
||||
until-1 ::= | !<[1]> until-1
|
||||
```
|
||||
|
||||
## GBNF Grammar Generation
|
||||
|
||||
The PEG parser also acts as a convenient DSL for generating GBNF grammars, with
|
||||
@@ -143,6 +252,28 @@ are emitted in the grammar. All trigger rules are added as alternations in the
|
||||
root rule. It is still necessary to define trigger patterns, as the parser has
|
||||
no interaction with the grammar sampling.
|
||||
|
||||
With `trigger_rule(name, start, rest)`, the grammar instead scans for a start and
|
||||
then constrains the rest. It runs from the first token, so `grammar_lazy` is false
|
||||
and no trigger patterns are needed. For example:
|
||||
|
||||
```cpp
|
||||
auto ab = p.literal("ab");
|
||||
auto cd = p.literal("cd");
|
||||
return p.until(ab | cd) + (p.trigger_rule("one", ab, p.literal("x")) | p.trigger_rule("two", cd, p.literal("y")));
|
||||
```
|
||||
|
||||
```
|
||||
root ::= trigger
|
||||
trigger ::= | [a] trigger-01 | [c] trigger-03 | [^ac] trigger
|
||||
trigger-01 ::= | [b] one-rest | [a] trigger-01 | [c] trigger-03 | [^abc] trigger
|
||||
trigger-03 ::= | [d] two-rest | [a] trigger-01 | [c] trigger-03 | [^acd] trigger
|
||||
one-rest ::= "x"
|
||||
two-rest ::= "y"
|
||||
```
|
||||
|
||||
A start may only be a sequence of literals, tokens, and choices of them, possibly
|
||||
wrapped in tags and atomics.
|
||||
|
||||
### JSON Schema
|
||||
|
||||
The `schema(p, name, schema, raw)` parser will use the `json-schema-to-grammar`
|
||||
|
||||
@@ -15,6 +15,7 @@ Supported models:
|
||||
- [Fish Audio S2 Pro](#fish-audio-s2-pro)
|
||||
- [YuE2](#yue2) (songs)
|
||||
- [MiniMax Music 3](#minimax-music-3) (songs)
|
||||
- [Hibiki](#hibiki) (speech translation, `llama-server` realtime endpoint only)
|
||||
- [Kokoro](#kokoro)
|
||||
- [tiny-voca](#tiny-voca)
|
||||
- [VoxCPM2](#voxcpm2)
|
||||
@@ -367,6 +368,22 @@ python convert_hf_to_gguf.py MiniMax-Music3 --mmproj --outfile mmproj-minimax-mu
|
||||
|
||||
The mmproj holds the depth decoder and the DiT layers (in the `--outtype` type), and the condition encoder, the small DiT projections and the DAC decoder, always in F32.
|
||||
|
||||
## Hibiki
|
||||
|
||||
Hibiki (Kyutai) translates French speech to English speech in real time. It is a full duplex model: it only runs through the [realtime endpoint](../../tools/server/README.md#full-duplex) of `llama-server`, the audio goes in and comes out every 80 ms.
|
||||
|
||||
The checkpoint is not in the HF layout, the converter reads its `config.json` and the LM and mimi files it names (Hibiki-1B `kyutai/hibiki-1b-pytorch-bf16`, Hibiki-2B `kyutai/hibiki-2b-pytorch-bf16`):
|
||||
|
||||
```sh
|
||||
python convert_hf_to_gguf.py path/to/hibiki-1b-pytorch-bf16 --outfile hibiki-1b.gguf
|
||||
python convert_hf_to_gguf.py path/to/hibiki-1b-pytorch-bf16 --mmproj --outfile mmproj-hibiki-1b.gguf
|
||||
|
||||
llama-server -m hibiki-1b.gguf --mmproj mmproj-hibiki-1b.gguf -c 1500
|
||||
```
|
||||
|
||||
- The voice of the output is conditioned like the reference (`very_good`), classifier-free guidance is not supported yet
|
||||
- The audio codes are sampled with the settings of the checkpoint (temperature 0.8, top-k 250), so is the text (temperature 0.8, top-k 50) unless the server sampling options override it
|
||||
|
||||
## Kokoro
|
||||
|
||||
Available params:
|
||||
|
||||
@@ -8,10 +8,10 @@ extern "C" {
|
||||
|
||||
#define RPC_PROTO_MAJOR_VERSION 10
|
||||
#define RPC_PROTO_MINOR_VERSION 0
|
||||
#define RPC_PROTO_PATCH_VERSION 1
|
||||
#define RPC_PROTO_PATCH_VERSION 2
|
||||
|
||||
#ifdef __cplusplus
|
||||
static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION");
|
||||
static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION");
|
||||
#endif
|
||||
|
||||
#define GGML_RPC_MAX_SERVERS 16
|
||||
|
||||
@@ -433,6 +433,8 @@ extern "C" {
|
||||
|
||||
GGML_OP_SLEEP,
|
||||
|
||||
GGML_OP_SIGMOID_BACK,
|
||||
|
||||
GGML_OP_COUNT,
|
||||
};
|
||||
|
||||
@@ -1038,6 +1040,13 @@ extern "C" {
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * b);
|
||||
|
||||
// a - dy
|
||||
// b - x
|
||||
GGML_API struct ggml_tensor * ggml_sigmoid_back(
|
||||
struct ggml_context * ctx,
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * b);
|
||||
|
||||
// hardswish(x) = x * relu6(x + 3) / 6
|
||||
GGML_API struct ggml_tensor * ggml_hardswish(
|
||||
struct ggml_context * ctx,
|
||||
|
||||
@@ -35,6 +35,7 @@ bool ggml_op_can_inplace(enum ggml_op op) {
|
||||
case GGML_OP_ROPE:
|
||||
case GGML_OP_ROPE_BACK:
|
||||
case GGML_OP_SILU_BACK:
|
||||
case GGML_OP_SIGMOID_BACK:
|
||||
case GGML_OP_RMS_NORM:
|
||||
case GGML_OP_RMS_NORM_BACK:
|
||||
case GGML_OP_CLAMP:
|
||||
|
||||
@@ -57,8 +57,9 @@ extern "C" {
|
||||
void * (*get_base) (ggml_backend_buffer_t buffer);
|
||||
// (optional) initialize a tensor in the buffer (eg. add tensor extras)
|
||||
enum ggml_status (*init_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor);
|
||||
// tensor data access
|
||||
// (optional) fill tensor data with a value, ggml_backend_tensor_memset falls back to set_tensor
|
||||
void (*memset_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size);
|
||||
// tensor data access
|
||||
void (*set_tensor) (ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size);
|
||||
void (*get_tensor) (ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size);
|
||||
// (optional) 2d data copies
|
||||
|
||||
@@ -971,7 +971,8 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
|
||||
case GGML_OP_CONCAT: {
|
||||
split_state = handle_concat(src_ss);
|
||||
} break;
|
||||
case GGML_OP_SILU_BACK: {
|
||||
case GGML_OP_SILU_BACK:
|
||||
case GGML_OP_SIGMOID_BACK: {
|
||||
split_state = handle_generic(src_ss, /*scalar_only =*/ false);
|
||||
} break;
|
||||
case GGML_OP_NORM:
|
||||
@@ -2154,8 +2155,28 @@ static enum ggml_status ggml_backend_meta_graph_compute(ggml_backend_t backend,
|
||||
}
|
||||
};
|
||||
|
||||
skip_unrelated();
|
||||
if (id + 1 >= cgraph->n_nodes) {
|
||||
// Chain of MULs with MIRRORED src[1], returns false at the end of the graph
|
||||
auto absorb_muls = [&]() -> bool {
|
||||
while (true) {
|
||||
skip_unrelated();
|
||||
if (id + 1 >= cgraph->n_nodes) {
|
||||
return false;
|
||||
}
|
||||
ggml_tensor * next = cgraph->nodes[id+1];
|
||||
if (next->op == GGML_OP_MUL && next->src[0] == node &&
|
||||
ggml_backend_meta_get_split_state(next->src[1], false).axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) {
|
||||
node = next;
|
||||
id++;
|
||||
idr = id;
|
||||
n_used = ggml_node_get_use_count(cgraph, id);
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// MULs before the PARTIAL bias (e.g. a per-expert weight scale): sum_j(s*p_j + b/n) == s*sum_j(p_j) + b
|
||||
if (!absorb_muls()) {
|
||||
return idr;
|
||||
}
|
||||
{
|
||||
@@ -2169,22 +2190,8 @@ static enum ggml_status ggml_backend_meta_graph_compute(ggml_backend_t backend,
|
||||
n_used = ggml_node_get_use_count(cgraph, id);
|
||||
}
|
||||
}
|
||||
// Chain of MULs with MIRRORED src[1]
|
||||
while (true) {
|
||||
skip_unrelated();
|
||||
if (id + 1 >= cgraph->n_nodes) {
|
||||
return idr;
|
||||
}
|
||||
ggml_tensor * next = cgraph->nodes[id+1];
|
||||
if (next->op == GGML_OP_MUL && next->src[0] == node &&
|
||||
ggml_backend_meta_get_split_state(next->src[1], false).axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) {
|
||||
node = next;
|
||||
id++;
|
||||
idr = id;
|
||||
n_used = ggml_node_get_use_count(cgraph, id);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
if (!absorb_muls()) {
|
||||
return idr;
|
||||
}
|
||||
|
||||
if (n_used != node->ne[1] || id + 2*n_used-1 >= cgraph->n_nodes) {
|
||||
|
||||
@@ -761,7 +761,17 @@ void ggml_backend_tensor_memset(struct ggml_tensor * tensor, uint8_t value, size
|
||||
GGML_ASSERT(buf != NULL && "tensor buffer not set");
|
||||
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
||||
GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
|
||||
GGML_ASSERT(buf->iface.memset_tensor != NULL && "memset not implemented by backend buffer");
|
||||
|
||||
if (buf->iface.memset_tensor == NULL) {
|
||||
GGML_ASSERT(buf->iface.set_tensor != NULL && "memset not implemented by backend buffer");
|
||||
|
||||
// fallback: write the value in chunks with set_tensor
|
||||
const std::vector<uint8_t> chunk(std::min(size, (size_t) 1024*1024), value);
|
||||
for (size_t chunk_offset = 0; chunk_offset < size; chunk_offset += chunk.size()) {
|
||||
ggml_backend_tensor_set(tensor, chunk.data(), offset + chunk_offset, std::min(size - chunk_offset, chunk.size()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
buf->iface.memset_tensor(buf, tensor, value, offset, size);
|
||||
}
|
||||
|
||||
@@ -1169,6 +1169,28 @@ void ggml_set_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2,
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
static inline void ggml_deinterleave_f32(
|
||||
float * GGML_RESTRICT dst0,
|
||||
float * GGML_RESTRICT dst1,
|
||||
const float * GGML_RESTRICT src,
|
||||
int64_t n,
|
||||
size_t bs,
|
||||
int nrc) {
|
||||
GGML_ASSERT(nrc >= 1 && nrc <= 2);
|
||||
|
||||
if (nrc == 1) {
|
||||
memcpy(dst0, src, n * sizeof(float));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
dst0[i ] = src[2*i + 0 ];
|
||||
dst1[i ] = src[2*i + 1 ];
|
||||
dst0[bs + i] = src[2*i + 0 + 16];
|
||||
dst1[bs + i] = src[2*i + 1 + 16];
|
||||
}
|
||||
}
|
||||
|
||||
// ggml_compute_forward_mul_mat
|
||||
|
||||
static void ggml_compute_forward_mul_mat_one_chunk(
|
||||
@@ -1218,8 +1240,12 @@ static void ggml_compute_forward_mul_mat_one_chunk(
|
||||
// 16 * 2, accounting for mmla kernels
|
||||
float tmp[32];
|
||||
|
||||
const int64_t nr0_split = (ir0_end - ir0_start) / num_rows_per_vec_dot; // rows per stream
|
||||
const int64_t ir0_end_split = ir0_start + nr0_split;
|
||||
const int64_t blck_0_split = blck_0 / num_rows_per_vec_dot;
|
||||
|
||||
for (int64_t iir1 = ir1_start; iir1 < ir1_end; iir1 += blck_1) {
|
||||
for (int64_t iir0 = ir0_start; iir0 < ir0_end; iir0 += blck_0) {
|
||||
for (int64_t iir0 = ir0_start; iir0 < ir0_end_split; iir0 += blck_0_split) {
|
||||
for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir1_end; ir1 += num_rows_per_vec_dot) {
|
||||
const int64_t i13 = (ir1 / (ne12 * ne1));
|
||||
const int64_t i12 = (ir1 - i13 * ne12 * ne1) / ne1;
|
||||
@@ -1249,13 +1275,13 @@ static void ggml_compute_forward_mul_mat_one_chunk(
|
||||
// vec_dot(ne00, &dst_col[ir0], src0_row + ir0*nb01, src1_col);
|
||||
//}
|
||||
|
||||
for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ir0 += num_rows_per_vec_dot) {
|
||||
vec_dot(ne00, &tmp[ir0 - iir0], (num_rows_per_vec_dot > 1 ? 16 : 0), src0_row + ir0 * nb01, (num_rows_per_vec_dot > 1 ? nb01 : 0), src1_col, (num_rows_per_vec_dot > 1 ? src1_col_stride : 0), num_rows_per_vec_dot);
|
||||
for (int64_t ir0 = iir0; ir0 < iir0 + blck_0_split && ir0 < ir0_end_split; ++ir0) {
|
||||
vec_dot(ne00, &tmp[(ir0 - iir0) * num_rows_per_vec_dot], (num_rows_per_vec_dot > 1 ? 16 : 0), src0_row + ir0 * nb01, (num_rows_per_vec_dot > 1 ? nb01 * nr0_split : 0), src1_col, (num_rows_per_vec_dot > 1 ? src1_col_stride : 0), num_rows_per_vec_dot);
|
||||
}
|
||||
|
||||
for (int cn = 0; cn < num_rows_per_vec_dot; ++cn) {
|
||||
memcpy(&dst_col[iir0 + cn * nb1 / nb0], tmp + (cn * 16), (MIN(iir0 + blck_0, ir0_end) - iir0) * sizeof(float));
|
||||
}
|
||||
const int64_t n = MIN(iir0 + blck_0_split, ir0_end_split) - iir0;
|
||||
float * dst0 = dst_col + iir0;
|
||||
ggml_deinterleave_f32(dst0, dst0 + nr0_split, tmp, n, nb1 / nb0, num_rows_per_vec_dot);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1858,6 +1884,10 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm
|
||||
{
|
||||
ggml_compute_forward_silu_back(params, tensor);
|
||||
} break;
|
||||
case GGML_OP_SIGMOID_BACK:
|
||||
{
|
||||
ggml_compute_forward_sigmoid_back(params, tensor);
|
||||
} break;
|
||||
case GGML_OP_NORM:
|
||||
{
|
||||
ggml_compute_forward_norm(params, tensor);
|
||||
@@ -2366,6 +2396,7 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) {
|
||||
}
|
||||
break;
|
||||
case GGML_OP_SILU_BACK:
|
||||
case GGML_OP_SIGMOID_BACK:
|
||||
case GGML_OP_MUL:
|
||||
case GGML_OP_DIV:
|
||||
case GGML_OP_NORM:
|
||||
|
||||
@@ -2898,6 +2898,118 @@ void ggml_compute_forward_silu_back(
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ggml_compute_forward_sigmoid_back
|
||||
|
||||
static void ggml_compute_forward_sigmoid_back_f32(
|
||||
const ggml_compute_params * params,
|
||||
ggml_tensor * dst) {
|
||||
|
||||
const ggml_tensor * grad = dst->src[0];
|
||||
const ggml_tensor * src1 = dst->src[1];
|
||||
|
||||
GGML_ASSERT(ggml_is_contiguous_1(grad));
|
||||
GGML_ASSERT(ggml_is_contiguous_1(src1));
|
||||
GGML_ASSERT(ggml_is_contiguous_1(dst));
|
||||
GGML_ASSERT(ggml_are_same_shape(src1, dst));
|
||||
GGML_ASSERT(ggml_are_same_shape(src1, grad));
|
||||
|
||||
const int ith = params->ith;
|
||||
const int nth = params->nth;
|
||||
|
||||
const int nc = src1->ne[0];
|
||||
const int nr = ggml_nrows(src1);
|
||||
|
||||
// rows per thread
|
||||
const int dr = (nr + nth - 1)/nth;
|
||||
|
||||
// row range for this thread
|
||||
const int ir0 = dr*ith;
|
||||
const int ir1 = MIN(ir0 + dr, nr);
|
||||
|
||||
for (int i1 = ir0; i1 < ir1; i1++) {
|
||||
ggml_vec_sigmoid_backward_f32(nc,
|
||||
(float *) ((char *) dst->data + i1*( dst->nb[1])),
|
||||
(float *) ((char *) src1->data + i1*(src1->nb[1])),
|
||||
(float *) ((char *) grad->data + i1*(grad->nb[1])));
|
||||
|
||||
#ifndef NDEBUG
|
||||
for (int k = 0; k < nc; k++) {
|
||||
const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
|
||||
GGML_UNUSED(x);
|
||||
assert(!isnan(x));
|
||||
assert(!isinf(x));
|
||||
}
|
||||
#endif // NDEBUG
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_compute_forward_sigmoid_back_f16(
|
||||
const ggml_compute_params * params,
|
||||
ggml_tensor * dst) {
|
||||
|
||||
const ggml_tensor * grad = dst->src[0];
|
||||
const ggml_tensor * src1 = dst->src[1];
|
||||
|
||||
GGML_ASSERT(ggml_is_contiguous_1(grad));
|
||||
GGML_ASSERT(ggml_is_contiguous_1(src1));
|
||||
GGML_ASSERT(ggml_is_contiguous_1(dst));
|
||||
GGML_ASSERT(ggml_are_same_shape(src1, dst));
|
||||
GGML_ASSERT(ggml_are_same_shape(src1, grad));
|
||||
|
||||
const int ith = params->ith;
|
||||
const int nth = params->nth;
|
||||
|
||||
const int nc = src1->ne[0];
|
||||
const int nr = ggml_nrows(src1);
|
||||
|
||||
// rows per thread
|
||||
const int dr = (nr + nth - 1)/nth;
|
||||
|
||||
// row range for this thread
|
||||
const int ir0 = dr*ith;
|
||||
const int ir1 = MIN(ir0 + dr, nr);
|
||||
|
||||
for (int i1 = ir0; i1 < ir1; i1++) {
|
||||
ggml_vec_sigmoid_backward_f16(nc,
|
||||
(ggml_fp16_t *) ((char *) dst->data + i1*( dst->nb[1])),
|
||||
(ggml_fp16_t *) ((char *) src1->data + i1*(src1->nb[1])),
|
||||
(ggml_fp16_t *) ((char *) grad->data + i1*(grad->nb[1])));
|
||||
|
||||
#ifndef NDEBUG
|
||||
for (int k = 0; k < nc; k++) {
|
||||
const float x = ((ggml_fp16_t *) ((char *) dst->data + i1*( dst->nb[1])))[k];
|
||||
const float v = GGML_CPU_FP16_TO_FP32(x);
|
||||
GGML_UNUSED(v);
|
||||
assert(!isnan(v));
|
||||
assert(!isinf(v));
|
||||
}
|
||||
#endif // NDEBUG
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_compute_forward_sigmoid_back(
|
||||
const ggml_compute_params * params,
|
||||
ggml_tensor * dst) {
|
||||
|
||||
const ggml_tensor * src0 = dst->src[0];
|
||||
|
||||
switch (src0->type) {
|
||||
case GGML_TYPE_F32:
|
||||
{
|
||||
ggml_compute_forward_sigmoid_back_f32(params, dst);
|
||||
} break;
|
||||
case GGML_TYPE_F16:
|
||||
{
|
||||
ggml_compute_forward_sigmoid_back_f16(params, dst);
|
||||
} break;
|
||||
default:
|
||||
{
|
||||
GGML_ABORT("fatal error");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ggml_compute_forward_reglu
|
||||
|
||||
// row loop shared by the BF16 GLU ops
|
||||
|
||||
@@ -41,6 +41,7 @@ void ggml_compute_forward_repeat(const struct ggml_compute_params * params, stru
|
||||
void ggml_compute_forward_repeat_back(const struct ggml_compute_params * params, struct ggml_tensor * dst);
|
||||
void ggml_compute_forward_concat(const struct ggml_compute_params * params, struct ggml_tensor * dst);
|
||||
void ggml_compute_forward_silu_back(const struct ggml_compute_params * params, struct ggml_tensor * dst);
|
||||
void ggml_compute_forward_sigmoid_back(const struct ggml_compute_params * params, struct ggml_tensor * dst);
|
||||
void ggml_compute_forward_norm(const struct ggml_compute_params * params, struct ggml_tensor * dst);
|
||||
void ggml_compute_forward_rms_norm(const struct ggml_compute_params * params, struct ggml_tensor * dst);
|
||||
void ggml_compute_forward_rms_norm_mul_fused(const struct ggml_compute_params * params, struct ggml_tensor * dst_rms_norm, struct ggml_tensor * dst_mul);
|
||||
|
||||
@@ -1536,6 +1536,29 @@ inline static void ggml_vec_silu_backward_f16(const int n, ggml_fp16_t * dx, con
|
||||
}
|
||||
}
|
||||
|
||||
inline static float ggml_sigmoid_backward_f32(float x, float dy) {
|
||||
const float s = 1.0f/(1.0f + expf(-x));
|
||||
return dy*s*(1.0f - s);
|
||||
}
|
||||
|
||||
inline static ggml_fp16_t ggml_sigmoid_backward_f16(ggml_fp16_t x, ggml_fp16_t dy) {
|
||||
const float v = GGML_CPU_FP16_TO_FP32(x);
|
||||
const float s = 1.0f/(1.0f + expf(-v));
|
||||
return GGML_CPU_FP32_TO_FP16(GGML_CPU_FP16_TO_FP32(dy)*s*(1.0f - s));
|
||||
}
|
||||
|
||||
inline static void ggml_vec_sigmoid_backward_f32(const int n, float * dx, const float * x, const float * dy) {
|
||||
for (int i = 0; i < n; ++i) {
|
||||
dx[i] = ggml_sigmoid_backward_f32(x[i], dy[i]);
|
||||
}
|
||||
}
|
||||
|
||||
inline static void ggml_vec_sigmoid_backward_f16(const int n, ggml_fp16_t * dx, const ggml_fp16_t * x, const ggml_fp16_t * dy) {
|
||||
for (int i = 0; i < n; ++i) {
|
||||
dx[i] = ggml_sigmoid_backward_f16(x[i], dy[i]);
|
||||
}
|
||||
}
|
||||
|
||||
inline static void ggml_vec_reglu_f32 (const int n, float * y, const float * x, const float * g) {
|
||||
for (int i = 0; i < n; ++i) {
|
||||
y[i] = (x[i] > 0.f) ? x[i] * g[i] : 0.f;
|
||||
|
||||
@@ -911,7 +911,7 @@ static __device__ __forceinline__ float ggml_cuda_ue4m3_to_fp32(uint8_t x) {
|
||||
// but CDNA3 supports only e4m3_fnuz (no inf).
|
||||
const uint32_t bits = x * (x != 0x7F && x != 0xFF); // Convert NaN to 0.0f to match CPU implementation.
|
||||
const __hip_fp8_e4m3_fnuz xf = *reinterpret_cast<const __hip_fp8_e4m3_fnuz *>(&bits);
|
||||
return static_cast<float>(xf) / 2;
|
||||
return static_cast<float>(xf);
|
||||
#else
|
||||
#if defined(FP8_AVAILABLE) && !defined(GGML_USE_HIP)
|
||||
const uint32_t bits = x * (x != 0x7F && x != 0xFF); // Convert NaN to 0.0f to match CPU implementation.
|
||||
@@ -1046,6 +1046,12 @@ static const uint3 init_fastdiv_values(uint64_t d_64) {
|
||||
uint32_t L = 0;
|
||||
while (L < 32 && (uint32_t{ 1 } << L) < d) {
|
||||
L++;
|
||||
if (L == 32) {
|
||||
// Shifting uint32_t by 32 to the right is undefined behavior.
|
||||
// On NVIDIA it will produce 0.
|
||||
// On AMD the value by which is shifted is masked with & 31 so it is shifting by 0 bits.
|
||||
GGML_ABORT("undefined behavior in fastdiv");
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t mp = (uint32_t) ((uint64_t{ 1 } << 32) * ((uint64_t{ 1 } << L) - d) / d + 1);
|
||||
|
||||
@@ -227,6 +227,13 @@ set(GGML_OPENCL_KERNELS
|
||||
gemm_coopk_q4_0_q8_1_dp4a
|
||||
gemm_coopk_q4_k_q8_1_dp4a
|
||||
gemm_coopk_q6_k_q8_1_dp4a
|
||||
pack_b_f16_coopmat
|
||||
gemm_noshuffle_q4_0_f32_coopmat
|
||||
gemm_noshuffle_q5_0_f32_coopmat
|
||||
gemm_noshuffle_q8_0_f32_coopmat
|
||||
gemm_noshuffle_q4_k_f32_coopmat
|
||||
gemm_noshuffle_q5_k_f32_coopmat
|
||||
gemm_noshuffle_q6_k_f32_coopmat
|
||||
quant_a_q8_1
|
||||
gemv_moe_q4_k_f32_ns
|
||||
gemm_moe_q5_k_f32_ns
|
||||
|
||||
@@ -1495,6 +1495,13 @@ struct ggml_backend_opencl_context {
|
||||
cl_kernel kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a = nullptr; // dp4a (int8) dense IQ4_NL prefill GEMM
|
||||
cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a = nullptr; // dp4a (int8) dense q4_0 prefill GEMM
|
||||
cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4 = nullptr;
|
||||
cl_kernel kernel_pack_b_f16_coopmat = nullptr;
|
||||
cl_kernel kernel_gemm_noshuffle_q4_0_f32_coopmat = nullptr;
|
||||
cl_kernel kernel_gemm_noshuffle_q5_0_f32_coopmat = nullptr;
|
||||
cl_kernel kernel_gemm_noshuffle_q8_0_f32_coopmat = nullptr;
|
||||
cl_kernel kernel_gemm_noshuffle_q4_k_f32_coopmat = nullptr;
|
||||
cl_kernel kernel_gemm_noshuffle_q5_k_f32_coopmat = nullptr;
|
||||
cl_kernel kernel_gemm_noshuffle_q6_k_f32_coopmat = nullptr;
|
||||
cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c4 = nullptr;
|
||||
cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c2 = nullptr;
|
||||
int nsg_coopk_dp4a_q4_0 = 8;
|
||||
@@ -1979,6 +1986,137 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx
|
||||
}
|
||||
}
|
||||
|
||||
static void load_cl_kernels_coopmat(ggml_backend_opencl_context * backend_ctx) {
|
||||
if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO || !strstr(backend_ctx->device_name.c_str(), "850")) {
|
||||
return;
|
||||
}
|
||||
|
||||
cl_int err;
|
||||
const std::string opts = "-cl-std=CL" + std::to_string(backend_ctx->opencl_c_version.major) + "." +
|
||||
std::to_string(backend_ctx->opencl_c_version.minor) +
|
||||
(backend_ctx->adreno_use_large_buffer ? " -qcom-enable-large-buffer" : "");
|
||||
|
||||
// pack_b_f16_coopmat
|
||||
{
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
const std::string kernel_src {
|
||||
#include "pack_b_f16_coopmat.cl.h"
|
||||
};
|
||||
#else
|
||||
const std::string kernel_src = read_file("pack_b_f16_coopmat.cl");
|
||||
#endif
|
||||
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false);
|
||||
if (!prog) {
|
||||
return;
|
||||
}
|
||||
CL_CHECK((backend_ctx->kernel_pack_b_f16_coopmat = clCreateKernel(prog, "kernel_pack_b_f16_coopmat", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
|
||||
// gemm_noshuffle_q4_0_f32_coopmat
|
||||
{
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
const std::string kernel_src {
|
||||
#include "gemm_noshuffle_q4_0_f32_coopmat.cl.h"
|
||||
};
|
||||
#else
|
||||
const std::string kernel_src = read_file("gemm_noshuffle_q4_0_f32_coopmat.cl");
|
||||
#endif
|
||||
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false);
|
||||
if (prog) {
|
||||
CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_f32_coopmat", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_noshuffle_q5_0_f32_coopmat
|
||||
{
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
const std::string kernel_src {
|
||||
#include "gemm_noshuffle_q5_0_f32_coopmat.cl.h"
|
||||
};
|
||||
#else
|
||||
const std::string kernel_src = read_file("gemm_noshuffle_q5_0_f32_coopmat.cl");
|
||||
#endif
|
||||
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false);
|
||||
if (prog) {
|
||||
CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_f32_coopmat", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_noshuffle_q8_0_f32_coopmat
|
||||
{
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
const std::string kernel_src {
|
||||
#include "gemm_noshuffle_q8_0_f32_coopmat.cl.h"
|
||||
};
|
||||
#else
|
||||
const std::string kernel_src = read_file("gemm_noshuffle_q8_0_f32_coopmat.cl");
|
||||
#endif
|
||||
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false);
|
||||
if (prog) {
|
||||
CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_f32_coopmat", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_noshuffle_q4_k_f32_coopmat
|
||||
{
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
const std::string kernel_src {
|
||||
#include "gemm_noshuffle_q4_k_f32_coopmat.cl.h"
|
||||
};
|
||||
#else
|
||||
const std::string kernel_src = read_file("gemm_noshuffle_q4_k_f32_coopmat.cl");
|
||||
#endif
|
||||
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false);
|
||||
if (prog) {
|
||||
CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_coopmat", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_noshuffle_q5_k_f32_coopmat
|
||||
{
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
const std::string kernel_src {
|
||||
#include "gemm_noshuffle_q5_k_f32_coopmat.cl.h"
|
||||
};
|
||||
#else
|
||||
const std::string kernel_src = read_file("gemm_noshuffle_q5_k_f32_coopmat.cl");
|
||||
#endif
|
||||
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false);
|
||||
if (prog) {
|
||||
CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_f32_coopmat", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_noshuffle_q6_k_f32_coopmat
|
||||
{
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
const std::string kernel_src {
|
||||
#include "gemm_noshuffle_q6_k_f32_coopmat.cl.h"
|
||||
};
|
||||
#else
|
||||
const std::string kernel_src = read_file("gemm_noshuffle_q6_k_f32_coopmat.cl");
|
||||
#endif
|
||||
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false);
|
||||
if (prog) {
|
||||
CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_k_f32_coopmat", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
static std::string ggml_opencl_make_compile_opts(const ggml_backend_opencl_context * backend_ctx) {
|
||||
@@ -7813,6 +7951,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
|
||||
}
|
||||
}
|
||||
load_cl_kernels_gemm_coopk(backend_ctx);
|
||||
load_cl_kernels_coopmat(backend_ctx);
|
||||
#endif // GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
GGML_LOG_CONT("\n");
|
||||
backend_ctx->kernels_loaded = true;
|
||||
@@ -11739,7 +11878,8 @@ inline bool use_q4_0_bin_kernels(const ggml_backend_opencl_context *backend_ctx,
|
||||
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
if (!backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32b_trans ||
|
||||
!(backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin ||
|
||||
backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin)) {
|
||||
backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin ||
|
||||
backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -11893,7 +12033,8 @@ inline bool use_q6_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx,
|
||||
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
if (!backend_ctx->kernel_gemv_noshuffle_q6_k_f32_32b_trans ||
|
||||
!(backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin ||
|
||||
backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin)) {
|
||||
backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin ||
|
||||
backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat)) {
|
||||
return false;
|
||||
}
|
||||
// bin kernels require ne2 == 1 and ne3 == 1 for weights
|
||||
@@ -11911,7 +12052,8 @@ inline bool use_q4_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx,
|
||||
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
if (!backend_ctx->kernel_gemv_noshuffle_q4_k_f32_32b_trans ||
|
||||
!(backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin ||
|
||||
backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin)) {
|
||||
backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin ||
|
||||
backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat)) {
|
||||
return false;
|
||||
}
|
||||
// bin kernels require ne2 == 1 and ne3 == 1 for weights
|
||||
@@ -11929,7 +12071,8 @@ inline bool use_q5_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx,
|
||||
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
if (!backend_ctx->kernel_gemv_noshuffle_q5_k_f32_32b_trans ||
|
||||
!(backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin ||
|
||||
backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin)) {
|
||||
backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin ||
|
||||
backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat)) {
|
||||
return false;
|
||||
}
|
||||
return (tensor->ne[0] % 256 == 0) && (tensor->ne[1] % 64 == 0);
|
||||
@@ -25619,6 +25762,48 @@ static void ggml_cl_mul_mat_q2_0_f32_adreno(ggml_backend_t backend, const ggml_t
|
||||
CL_CHECK(clReleaseMemObject(b_sub_buf));
|
||||
}
|
||||
|
||||
static bool ggml_cl_mul_mat_coopmat(ggml_backend_opencl_context * backend_ctx, cl_kernel kernel,
|
||||
std::initializer_list<cl_mem> weights,
|
||||
const ggml_tensor * src1, ggml_tensor * dst, int K, int M, int N) {
|
||||
if (kernel == nullptr || M % 64 != 0 || N < 2) {
|
||||
return false;
|
||||
}
|
||||
ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra;
|
||||
ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra;
|
||||
cl_ulong offset1 = extra1->offset + src1->view_offs;
|
||||
cl_ulong offsetd = extrad->offset + dst->view_offs;
|
||||
|
||||
const int n_tiles = CEIL_DIV(N, 64);
|
||||
|
||||
backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, (size_t)n_tiles * 64 * K * sizeof(cl_half));
|
||||
|
||||
cl_kernel pk = backend_ctx->kernel_pack_b_f16_coopmat;
|
||||
CL_CHECK(clSetKernelArg(pk, 0, sizeof(cl_mem), &extra1->data_device));
|
||||
CL_CHECK(clSetKernelArg(pk, 1, sizeof(cl_ulong), &offset1));
|
||||
CL_CHECK(clSetKernelArg(pk, 2, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer));
|
||||
CL_CHECK(clSetKernelArg(pk, 3, sizeof(int), &K));
|
||||
CL_CHECK(clSetKernelArg(pk, 4, sizeof(int), &N));
|
||||
size_t p_local[2] = { 64, 4 };
|
||||
size_t p_global[2] = { (size_t)n_tiles * 64, (size_t)CEIL_DIV(K, 64) * 4 };
|
||||
backend_ctx->enqueue_ndrange_kernel(pk, 2, p_global, p_local, dst);
|
||||
|
||||
cl_uint ka = 0;
|
||||
for (cl_mem w : weights) {
|
||||
CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &w));
|
||||
}
|
||||
CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer));
|
||||
CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &extrad->data_device));
|
||||
CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_ulong), &offsetd));
|
||||
CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &K));
|
||||
CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &M));
|
||||
CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &N));
|
||||
|
||||
size_t c_local[3] = { 64, 1, 4 };
|
||||
size_t c_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(n_tiles, 4) * 4 };
|
||||
backend_ctx->enqueue_ndrange_kernel(kernel, 3, c_global, c_local, dst);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void ggml_cl_mul_mat_q4_0_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
GGML_ASSERT(src0);
|
||||
@@ -25934,6 +26119,11 @@ static void ggml_cl_mul_mat_q4_0_f32_adreno(ggml_backend_t backend, const ggml_t
|
||||
|
||||
const bool use_bin = use_q4_0_bin_kernels(backend_ctx, src0);
|
||||
|
||||
if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat,
|
||||
{ extra0_q4_0->q, extra0_q4_0->d }, src1, dst, K, M, N)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_bin) {
|
||||
if (use_q40_mc3) {
|
||||
static bool warned = false;
|
||||
@@ -26498,6 +26688,11 @@ static void ggml_cl_mul_mat_q5_0_f32_adreno(ggml_backend_t backend, const ggml_t
|
||||
int N = ne1;
|
||||
int K = ne00;
|
||||
|
||||
if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q5_0_f32_coopmat,
|
||||
{ extra0_q5_0->qs, extra0_q5_0->qh, extra0_q5_0->d }, src1, dst, K, M, N)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ne1 == 1) {
|
||||
cl_mem qs_img = nullptr;
|
||||
cl_mem b_sub_buf = nullptr;
|
||||
@@ -27340,6 +27535,11 @@ static void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_t
|
||||
int N = ne1;
|
||||
int K = ne00;
|
||||
|
||||
if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q8_0_f32_coopmat,
|
||||
{ extra0_q8_0->q, extra0_q8_0->d }, src1, dst, K, M, N)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Multi-column verify GEMV for ne1 2..4, reuses the ne1 == 1 image setup.
|
||||
// Default on for X2E, GGML_OPENCL_Q8_0_MC=0/1 forces it.
|
||||
static const char * q8_mc_env = getenv("GGML_OPENCL_Q8_0_MC");
|
||||
@@ -28321,6 +28521,11 @@ static void ggml_cl_mul_mat_q4_k_f32_adreno(ggml_backend_t backend, const ggml_t
|
||||
|
||||
const bool use_bin = use_q4_k_bin_kernels(backend_ctx, src0);
|
||||
|
||||
if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat,
|
||||
{ extra0_q4_k->q, extra0_q4_k->s, extra0_q4_k->d, extra0_q4_k->dm }, src1, dst, K, M, N)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_bin) {
|
||||
if (use_mc3) {
|
||||
static bool warned = false;
|
||||
@@ -29231,6 +29436,11 @@ static void ggml_cl_mul_mat_q6_K_f32_adreno(ggml_backend_t backend, const ggml_t
|
||||
|
||||
const bool use_bin = use_q6_k_bin_kernels(backend_ctx, src0);
|
||||
|
||||
if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat,
|
||||
{ extra0_q6_K->ql, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, src1, dst, ne00, ne01, ne1)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_bin) {
|
||||
if (use_q6k_mc3 || use_q6k_tiled_mc) {
|
||||
static bool warned = false;
|
||||
@@ -29971,6 +30181,11 @@ static void ggml_cl_mul_mat_q5_K_f32_adreno(ggml_backend_t backend, const ggml_t
|
||||
|
||||
const bool use_bin = use_q5_k_bin_kernels(backend_ctx, src0);
|
||||
|
||||
if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat,
|
||||
{ extra0_q5_k->q, extra0_q5_k->qh, extra0_q5_k->s, extra0_q5_k->d, extra0_q5_k->dm }, src1, dst, K, M, N)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_bin) {
|
||||
if (use_q5k_mc3) {
|
||||
static bool warned = false;
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
|
||||
#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable
|
||||
|
||||
// Q4_0 x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave,
|
||||
// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat.
|
||||
|
||||
typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM)));
|
||||
typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM)));
|
||||
typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM)));
|
||||
|
||||
typedef half half1024 __attribute__((ext_vector_type(1024)));
|
||||
typedef half half4096 __attribute__((ext_vector_type(4096)));
|
||||
|
||||
typedef union {
|
||||
half1024 v;
|
||||
half16 h;
|
||||
} a_row_t;
|
||||
|
||||
typedef union {
|
||||
half4096 v;
|
||||
struct {
|
||||
half16 h0;
|
||||
half16 h1;
|
||||
half16 h2;
|
||||
half16 h3;
|
||||
} s;
|
||||
} c_row_t;
|
||||
|
||||
inline half8 dequant8(uint v, half d) {
|
||||
uint4 t;
|
||||
t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000);
|
||||
t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000);
|
||||
t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000);
|
||||
t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000);
|
||||
t |= (uint4)(0x64006400);
|
||||
|
||||
return (as_half8(t) - (half8)(1032.0h)) * d;
|
||||
}
|
||||
|
||||
inline void store_c16(global float * p, half16 h, int j0, int nv, int M) {
|
||||
float16 f = convert_float16(h);
|
||||
if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0;
|
||||
if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1;
|
||||
if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2;
|
||||
if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3;
|
||||
if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4;
|
||||
if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5;
|
||||
if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6;
|
||||
if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7;
|
||||
if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8;
|
||||
if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9;
|
||||
if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa;
|
||||
if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb;
|
||||
if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc;
|
||||
if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd;
|
||||
if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se;
|
||||
if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf;
|
||||
}
|
||||
|
||||
#define LOAD_Q(qv, dd, o) { \
|
||||
qv.s0 = qp[(4 * (o) + 0) * M]; \
|
||||
qv.s1 = qp[(4 * (o) + 1) * M]; \
|
||||
qv.s2 = qp[(4 * (o) + 2) * M]; \
|
||||
qv.s3 = qp[(4 * (o) + 3) * M]; \
|
||||
dd = dp[(o) * M]; }
|
||||
|
||||
#define MMA_K32(qv, dd, b) { \
|
||||
a_row_t ua0; \
|
||||
a_row_t ua1; \
|
||||
ua0.h = (half16)(dequant8(qv.s0, dd), dequant8(qv.s1, dd)); \
|
||||
ua1.h = (half16)(dequant8(qv.s2, dd), dequant8(qv.s3, dd)); \
|
||||
mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \
|
||||
mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \
|
||||
mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \
|
||||
acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); }
|
||||
|
||||
kernel void kernel_gemm_noshuffle_q4_0_f32_coopmat(
|
||||
global const uint * src0_q, // A: q4_0 quants, [K/8][M] u32
|
||||
global const half * src0_d, // A: q4_0 scales, [K/32][M] f16
|
||||
global const half * src1, // B: packed f16 tiles
|
||||
global char * dst, // C: [N][M] f32
|
||||
ulong offsetd,
|
||||
int K,
|
||||
int M,
|
||||
int N
|
||||
) {
|
||||
const int lane = get_local_id(0);
|
||||
const int row = get_global_id(1) * 64;
|
||||
const int tn = get_global_id(2);
|
||||
const int n_tiles = (N + 63) / 64;
|
||||
|
||||
if (tn >= n_tiles) {
|
||||
return;
|
||||
}
|
||||
|
||||
global const uint * qp = src0_q + row + lane;
|
||||
global const half * dp = src0_d + row + lane;
|
||||
global const half * bp = src1 + (ulong)tn * (K / 16) * 1024;
|
||||
|
||||
mat_c_t acc = qcom_coop_mat_init(0.0);
|
||||
|
||||
{
|
||||
const int odd = (K / 32) & 1;
|
||||
const int ob = odd ? 0 : 1;
|
||||
uint4 qa;
|
||||
uint4 qb;
|
||||
half da;
|
||||
half db;
|
||||
LOAD_Q(qa, da, 0)
|
||||
LOAD_Q(qb, db, ob)
|
||||
da = odd ? 0.0h : da;
|
||||
MMA_K32(qa, da, bp)
|
||||
MMA_K32(qb, db, bp + ob * 2048)
|
||||
qp += (ob + 1) * 4 * M;
|
||||
dp += (ob + 1) * M;
|
||||
bp += (ob + 1) * 2048;
|
||||
}
|
||||
|
||||
#pragma unroll 1
|
||||
for (int k0 = (K / 32) & 1 ? 32 : 64; k0 < K; k0 += 64) {
|
||||
uint4 qa;
|
||||
uint4 qb;
|
||||
half da;
|
||||
half db;
|
||||
LOAD_Q(qa, da, 0)
|
||||
LOAD_Q(qb, db, 1)
|
||||
MMA_K32(qa, da, bp)
|
||||
MMA_K32(qb, db, bp + 2048)
|
||||
qp += 8 * M;
|
||||
dp += 2 * M;
|
||||
bp += 4096;
|
||||
}
|
||||
|
||||
c_row_t uc;
|
||||
uc.v = __builtin_astype(acc, half4096);
|
||||
|
||||
global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane;
|
||||
const int nv = N - tn * 64;
|
||||
store_c16(p, uc.s.h0, 0, nv, M);
|
||||
store_c16(p, uc.s.h1, 16, nv, M);
|
||||
store_c16(p, uc.s.h2, 32, nv, M);
|
||||
store_c16(p, uc.s.h3, 48, nv, M);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
|
||||
#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable
|
||||
|
||||
// Q4_K x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave,
|
||||
// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat.
|
||||
|
||||
#define K_SCALE_SIZE 12
|
||||
|
||||
typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM)));
|
||||
typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM)));
|
||||
typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM)));
|
||||
|
||||
typedef half half1024 __attribute__((ext_vector_type(1024)));
|
||||
typedef half half4096 __attribute__((ext_vector_type(4096)));
|
||||
|
||||
typedef union {
|
||||
half1024 v;
|
||||
half16 h;
|
||||
} a_row_t;
|
||||
|
||||
typedef union {
|
||||
half4096 v;
|
||||
struct {
|
||||
half16 h0;
|
||||
half16 h1;
|
||||
half16 h2;
|
||||
half16 h3;
|
||||
} s;
|
||||
} c_row_t;
|
||||
|
||||
inline half8 dequant8(uint v, half scale, half nminv) {
|
||||
uint4 t;
|
||||
t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000);
|
||||
t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000);
|
||||
t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000);
|
||||
t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000);
|
||||
t |= (uint4)(0x64006400);
|
||||
|
||||
return (as_half8(t) - (half8)(1024.0h)) * scale + nminv;
|
||||
}
|
||||
|
||||
inline void store_c16(global float * p, half16 h, int j0, int nv, int M) {
|
||||
float16 f = convert_float16(h);
|
||||
if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0;
|
||||
if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1;
|
||||
if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2;
|
||||
if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3;
|
||||
if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4;
|
||||
if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5;
|
||||
if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6;
|
||||
if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7;
|
||||
if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8;
|
||||
if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9;
|
||||
if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa;
|
||||
if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb;
|
||||
if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc;
|
||||
if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd;
|
||||
if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se;
|
||||
if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf;
|
||||
}
|
||||
|
||||
#define MMA_K32(q0, q1, q2, q3, sc, nm, b) { \
|
||||
a_row_t ua0; \
|
||||
a_row_t ua1; \
|
||||
ua0.h = (half16)(dequant8(q0, sc, nm), dequant8(q1, sc, nm)); \
|
||||
ua1.h = (half16)(dequant8(q2, sc, nm), dequant8(q3, sc, nm)); \
|
||||
mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \
|
||||
mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \
|
||||
mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \
|
||||
acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); }
|
||||
|
||||
#define STEP64(sa, na, sb_, nb_) { \
|
||||
uint8 qv; \
|
||||
qv.s0 = qp[0]; \
|
||||
qv.s1 = qp[M]; \
|
||||
qv.s2 = qp[2 * M]; \
|
||||
qv.s3 = qp[3 * M]; \
|
||||
qv.s4 = qp[4 * M]; \
|
||||
qv.s5 = qp[5 * M]; \
|
||||
qv.s6 = qp[6 * M]; \
|
||||
qv.s7 = qp[7 * M]; \
|
||||
qp += 8 * M; \
|
||||
MMA_K32(qv.s0, qv.s1, qv.s2, qv.s3, sa, na, bp) \
|
||||
MMA_K32(qv.s4, qv.s5, qv.s6, qv.s7, sb_, nb_, bp + 2048) \
|
||||
bp += 4096; }
|
||||
|
||||
kernel void kernel_gemm_noshuffle_q4_k_f32_coopmat(
|
||||
global const uint * src0_q, // A: q4_K quants, [K/8][M] u32
|
||||
global const uchar * src0_s, // A: 6-bit scale/min codes, [K/256*12][M] u8
|
||||
global const half * src0_d, // A: per-superblock scale, [K/256][M] f16
|
||||
global const half * src0_dm, // A: per-superblock min, [K/256][M] f16
|
||||
global const half * src1, // B: packed f16 tiles
|
||||
global char * dst, // C: [N][M] f32
|
||||
ulong offsetd,
|
||||
int K,
|
||||
int M,
|
||||
int N
|
||||
) {
|
||||
const int lane = get_local_id(0);
|
||||
const int row = get_global_id(1) * 64;
|
||||
const int tn = get_global_id(2);
|
||||
const int n_tiles = (N + 63) / 64;
|
||||
|
||||
if (tn >= n_tiles) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int lrow = row + lane;
|
||||
|
||||
global const uint * qp = src0_q + lrow;
|
||||
global const half * bp = src1 + (ulong)tn * (K / 16) * 1024;
|
||||
|
||||
mat_c_t acc = qcom_coop_mat_init(0.0);
|
||||
|
||||
#pragma unroll 1
|
||||
for (int k0 = 0; k0 < K; k0 += 128) {
|
||||
const int sb = k0 >> 8;
|
||||
const half dd = src0_d [(ulong)sb * M + lrow];
|
||||
const half dmm = src0_dm[(ulong)sb * M + lrow];
|
||||
|
||||
global const uchar * sp = src0_s + (ulong)(sb * K_SCALE_SIZE) * M + lrow;
|
||||
const uchar4 c0 = (uchar4)(sp[0], sp[M], sp[2 * M], sp[3 * M]);
|
||||
const uchar4 c1 = (uchar4)(sp[4 * M], sp[5 * M], sp[6 * M], sp[7 * M]);
|
||||
const uchar4 c2 = (uchar4)(sp[8 * M], sp[9 * M], sp[10 * M], sp[11 * M]);
|
||||
const uchar4 sl = c0 & (uchar)0x3F;
|
||||
const uchar4 ml = c1 & (uchar)0x3F;
|
||||
const uchar4 sh = (c2 & (uchar)0x0F) | ((c0 >> (uchar)2) & (uchar)0x30);
|
||||
const uchar4 mh = (c2 >> (uchar)4) | ((c1 >> (uchar)2) & (uchar)0x30);
|
||||
const int hi = (k0 >> 7) & 1;
|
||||
const half4 S = dd * convert_half4(hi ? sh : sl);
|
||||
const half4 Nm = -(dmm * convert_half4(hi ? mh : ml));
|
||||
|
||||
STEP64(S.s0, Nm.s0, S.s1, Nm.s1)
|
||||
STEP64(S.s2, Nm.s2, S.s3, Nm.s3)
|
||||
}
|
||||
|
||||
c_row_t uc;
|
||||
uc.v = __builtin_astype(acc, half4096);
|
||||
|
||||
global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane;
|
||||
const int nv = N - tn * 64;
|
||||
store_c16(p, uc.s.h0, 0, nv, M);
|
||||
store_c16(p, uc.s.h1, 16, nv, M);
|
||||
store_c16(p, uc.s.h2, 32, nv, M);
|
||||
store_c16(p, uc.s.h3, 48, nv, M);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
|
||||
#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable
|
||||
|
||||
// Q5_0 x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave,
|
||||
// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat.
|
||||
|
||||
typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM)));
|
||||
typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM)));
|
||||
typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM)));
|
||||
|
||||
typedef half half1024 __attribute__((ext_vector_type(1024)));
|
||||
typedef half half4096 __attribute__((ext_vector_type(4096)));
|
||||
|
||||
typedef union {
|
||||
half1024 v;
|
||||
half16 h;
|
||||
} a_row_t;
|
||||
|
||||
typedef union {
|
||||
half4096 v;
|
||||
struct {
|
||||
half16 h0;
|
||||
half16 h1;
|
||||
half16 h2;
|
||||
half16 h3;
|
||||
} s;
|
||||
} c_row_t;
|
||||
|
||||
inline half8 dequant8(uint v, uint h, half d) {
|
||||
uint4 t;
|
||||
t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000) | ((h << 4) & 0x0010) | ((h << 19) & 0x00100000);
|
||||
t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000) | ((h << 2) & 0x0010) | ((h << 17) & 0x00100000);
|
||||
t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000) | ( h & 0x0010) | ((h << 15) & 0x00100000);
|
||||
t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000) | ((h >> 2) & 0x0010) | ((h << 13) & 0x00100000);
|
||||
t |= (uint4)(0x64006400);
|
||||
|
||||
return (as_half8(t) - (half8)(1040.0h)) * d;
|
||||
}
|
||||
|
||||
inline void store_c16(global float * p, half16 h, int j0, int nv, int M) {
|
||||
float16 f = convert_float16(h);
|
||||
if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0;
|
||||
if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1;
|
||||
if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2;
|
||||
if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3;
|
||||
if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4;
|
||||
if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5;
|
||||
if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6;
|
||||
if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7;
|
||||
if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8;
|
||||
if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9;
|
||||
if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa;
|
||||
if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb;
|
||||
if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc;
|
||||
if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd;
|
||||
if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se;
|
||||
if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf;
|
||||
}
|
||||
|
||||
#define LOAD_Q(qv, hv, dd, o) { \
|
||||
qv.s0 = (uint)qp[(8 * (o) + 0) * M] | ((uint)qp[(8 * (o) + 1) * M] << 16); \
|
||||
qv.s1 = (uint)qp[(8 * (o) + 2) * M] | ((uint)qp[(8 * (o) + 3) * M] << 16); \
|
||||
qv.s2 = (uint)qp[(8 * (o) + 4) * M] | ((uint)qp[(8 * (o) + 5) * M] << 16); \
|
||||
qv.s3 = (uint)qp[(8 * (o) + 6) * M] | ((uint)qp[(8 * (o) + 7) * M] << 16); \
|
||||
hv.s0 = hp[(4 * (o) + 0) * M]; \
|
||||
hv.s1 = hp[(4 * (o) + 1) * M]; \
|
||||
hv.s2 = hp[(4 * (o) + 2) * M]; \
|
||||
hv.s3 = hp[(4 * (o) + 3) * M]; \
|
||||
dd = dp[(o) * M]; }
|
||||
|
||||
#define MMA_K32(qv, hv, dd, b) { \
|
||||
a_row_t ua0; \
|
||||
a_row_t ua1; \
|
||||
ua0.h = (half16)(dequant8(qv.s0, hv.s0, dd), dequant8(qv.s1, hv.s1, dd)); \
|
||||
ua1.h = (half16)(dequant8(qv.s2, hv.s2, dd), dequant8(qv.s3, hv.s3, dd)); \
|
||||
mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \
|
||||
mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \
|
||||
mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \
|
||||
acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); }
|
||||
|
||||
kernel void kernel_gemm_noshuffle_q5_0_f32_coopmat(
|
||||
global const ushort * src0_q, // A: q5_0 quants, [K/4][M] u16
|
||||
global const uchar * src0_qh, // A: q5_0 high bits, [K/8][M] u8
|
||||
global const half * src0_d, // A: q5_0 scales, [K/32][M] f16
|
||||
global const half * src1, // B: packed f16 tiles
|
||||
global char * dst, // C: [N][M] f32
|
||||
ulong offsetd,
|
||||
int K,
|
||||
int M,
|
||||
int N
|
||||
) {
|
||||
const int lane = get_local_id(0);
|
||||
const int row = get_global_id(1) * 64;
|
||||
const int tn = get_global_id(2);
|
||||
const int n_tiles = (N + 63) / 64;
|
||||
|
||||
if (tn >= n_tiles) {
|
||||
return;
|
||||
}
|
||||
|
||||
global const ushort * qp = src0_q + row + lane;
|
||||
global const uchar * hp = src0_qh + row + lane;
|
||||
global const half * dp = src0_d + row + lane;
|
||||
global const half * bp = src1 + (ulong)tn * (K / 16) * 1024;
|
||||
|
||||
mat_c_t acc = qcom_coop_mat_init(0.0);
|
||||
|
||||
{
|
||||
const int odd = (K / 32) & 1;
|
||||
const int ob = odd ? 0 : 1;
|
||||
uint4 qa;
|
||||
uint4 qb;
|
||||
uint4 ha;
|
||||
uint4 hb;
|
||||
half da;
|
||||
half db;
|
||||
LOAD_Q(qa, ha, da, 0)
|
||||
LOAD_Q(qb, hb, db, ob)
|
||||
da = odd ? 0.0h : da;
|
||||
MMA_K32(qa, ha, da, bp)
|
||||
MMA_K32(qb, hb, db, bp + ob * 2048)
|
||||
qp += (ob + 1) * 8 * M;
|
||||
hp += (ob + 1) * 4 * M;
|
||||
dp += (ob + 1) * M;
|
||||
bp += (ob + 1) * 2048;
|
||||
}
|
||||
|
||||
#pragma unroll 1
|
||||
for (int k0 = (K / 32) & 1 ? 32 : 64; k0 < K; k0 += 64) {
|
||||
uint4 qa;
|
||||
uint4 qb;
|
||||
uint4 ha;
|
||||
uint4 hb;
|
||||
half da;
|
||||
half db;
|
||||
LOAD_Q(qa, ha, da, 0)
|
||||
LOAD_Q(qb, hb, db, 1)
|
||||
MMA_K32(qa, ha, da, bp)
|
||||
MMA_K32(qb, hb, db, bp + 2048)
|
||||
qp += 16 * M;
|
||||
hp += 8 * M;
|
||||
dp += 2 * M;
|
||||
bp += 4096;
|
||||
}
|
||||
|
||||
c_row_t uc;
|
||||
uc.v = __builtin_astype(acc, half4096);
|
||||
|
||||
global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane;
|
||||
const int nv = N - tn * 64;
|
||||
store_c16(p, uc.s.h0, 0, nv, M);
|
||||
store_c16(p, uc.s.h1, 16, nv, M);
|
||||
store_c16(p, uc.s.h2, 32, nv, M);
|
||||
store_c16(p, uc.s.h3, 48, nv, M);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
|
||||
#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable
|
||||
|
||||
// Q5_K x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave,
|
||||
// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat.
|
||||
|
||||
#define K_SCALE_SIZE 12
|
||||
|
||||
typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM)));
|
||||
typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM)));
|
||||
typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM)));
|
||||
|
||||
typedef half half1024 __attribute__((ext_vector_type(1024)));
|
||||
typedef half half4096 __attribute__((ext_vector_type(4096)));
|
||||
|
||||
typedef union {
|
||||
half1024 v;
|
||||
half16 h;
|
||||
} a_row_t;
|
||||
|
||||
typedef union {
|
||||
half4096 v;
|
||||
struct {
|
||||
half16 h0;
|
||||
half16 h1;
|
||||
half16 h2;
|
||||
half16 h3;
|
||||
} s;
|
||||
} c_row_t;
|
||||
|
||||
inline half8 dequant8(uint v, uint h, half scale, half nminv) {
|
||||
uint4 t;
|
||||
t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000);
|
||||
t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000);
|
||||
t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000);
|
||||
t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000);
|
||||
t.s0 |= ((h & 0x01u) << 4) | ((h & 0x02u) << 19);
|
||||
t.s1 |= ((h & 0x04u) << 2) | ((h & 0x08u) << 17);
|
||||
t.s2 |= ( h & 0x10u ) | ((h & 0x20u) << 15);
|
||||
t.s3 |= ((h & 0x40u) >> 2) | ((h & 0x80u) << 13);
|
||||
t |= (uint4)(0x64006400);
|
||||
|
||||
return (as_half8(t) - (half8)(1024.0h)) * scale + nminv;
|
||||
}
|
||||
|
||||
inline void store_c16(global float * p, half16 h, int j0, int nv, int M) {
|
||||
float16 f = convert_float16(h);
|
||||
if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0;
|
||||
if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1;
|
||||
if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2;
|
||||
if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3;
|
||||
if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4;
|
||||
if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5;
|
||||
if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6;
|
||||
if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7;
|
||||
if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8;
|
||||
if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9;
|
||||
if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa;
|
||||
if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb;
|
||||
if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc;
|
||||
if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd;
|
||||
if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se;
|
||||
if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf;
|
||||
}
|
||||
|
||||
#define MMA_K32(q0, q1, q2, q3, h0_, h1_, h2_, h3_, sc, nm, b) { \
|
||||
a_row_t ua0; \
|
||||
a_row_t ua1; \
|
||||
ua0.h = (half16)(dequant8(q0, h0_, sc, nm), dequant8(q1, h1_, sc, nm)); \
|
||||
ua1.h = (half16)(dequant8(q2, h2_, sc, nm), dequant8(q3, h3_, sc, nm)); \
|
||||
mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \
|
||||
mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \
|
||||
mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \
|
||||
acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); }
|
||||
|
||||
#define STEP64(sa, na, sb_, nb_) { \
|
||||
uint8 qv; \
|
||||
qv.s0 = qp[0]; \
|
||||
qv.s1 = qp[M]; \
|
||||
qv.s2 = qp[2 * M]; \
|
||||
qv.s3 = qp[3 * M]; \
|
||||
qv.s4 = qp[4 * M]; \
|
||||
qv.s5 = qp[5 * M]; \
|
||||
qv.s6 = qp[6 * M]; \
|
||||
qv.s7 = qp[7 * M]; \
|
||||
qp += 8 * M; \
|
||||
uint8 hv; \
|
||||
hv.s0 = qhp[0]; \
|
||||
hv.s1 = qhp[M]; \
|
||||
hv.s2 = qhp[2 * M]; \
|
||||
hv.s3 = qhp[3 * M]; \
|
||||
hv.s4 = qhp[4 * M]; \
|
||||
hv.s5 = qhp[5 * M]; \
|
||||
hv.s6 = qhp[6 * M]; \
|
||||
hv.s7 = qhp[7 * M]; \
|
||||
qhp += 8 * M; \
|
||||
MMA_K32(qv.s0, qv.s1, qv.s2, qv.s3, hv.s0, hv.s1, hv.s2, hv.s3, sa, na, bp) \
|
||||
MMA_K32(qv.s4, qv.s5, qv.s6, qv.s7, hv.s4, hv.s5, hv.s6, hv.s7, sb_, nb_, bp + 2048) \
|
||||
bp += 4096; }
|
||||
|
||||
kernel void kernel_gemm_noshuffle_q5_k_f32_coopmat(
|
||||
global const uint * src0_q, // A: q5_K low nibbles, [K/8][M] u32
|
||||
global const uchar * src0_qh, // A: q5_K high bits, [K/8][M] u8
|
||||
global const uchar * src0_s, // A: 6-bit scale/min codes, [K/256*12][M] u8
|
||||
global const half * src0_d, // A: per-superblock scale, [K/256][M] f16
|
||||
global const half * src0_dm, // A: per-superblock min, [K/256][M] f16
|
||||
global const half * src1, // B: packed f16 tiles
|
||||
global char * dst, // C: [N][M] f32
|
||||
ulong offsetd,
|
||||
int K,
|
||||
int M,
|
||||
int N
|
||||
) {
|
||||
const int lane = get_local_id(0);
|
||||
const int row = get_global_id(1) * 64;
|
||||
const int tn = get_global_id(2);
|
||||
const int n_tiles = (N + 63) / 64;
|
||||
|
||||
if (tn >= n_tiles) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int lrow = row + lane;
|
||||
|
||||
global const uint * qp = src0_q + lrow;
|
||||
global const uchar * qhp = src0_qh + lrow;
|
||||
global const half * bp = src1 + (ulong)tn * (K / 16) * 1024;
|
||||
|
||||
mat_c_t acc = qcom_coop_mat_init(0.0);
|
||||
|
||||
#pragma unroll 1
|
||||
for (int k0 = 0; k0 < K; k0 += 128) {
|
||||
const int sb = k0 >> 8;
|
||||
const half dd = src0_d [(ulong)sb * M + lrow];
|
||||
const half dmm = src0_dm[(ulong)sb * M + lrow];
|
||||
|
||||
global const uchar * sp = src0_s + (ulong)(sb * K_SCALE_SIZE) * M + lrow;
|
||||
const uchar4 c0 = (uchar4)(sp[0], sp[M], sp[2 * M], sp[3 * M]);
|
||||
const uchar4 c1 = (uchar4)(sp[4 * M], sp[5 * M], sp[6 * M], sp[7 * M]);
|
||||
const uchar4 c2 = (uchar4)(sp[8 * M], sp[9 * M], sp[10 * M], sp[11 * M]);
|
||||
const uchar4 sl = c0 & (uchar)0x3F;
|
||||
const uchar4 ml = c1 & (uchar)0x3F;
|
||||
const uchar4 sh = (c2 & (uchar)0x0F) | ((c0 >> (uchar)2) & (uchar)0x30);
|
||||
const uchar4 mh = (c2 >> (uchar)4) | ((c1 >> (uchar)2) & (uchar)0x30);
|
||||
const int hi = (k0 >> 7) & 1;
|
||||
const half4 S = dd * convert_half4(hi ? sh : sl);
|
||||
const half4 Nm = -(dmm * convert_half4(hi ? mh : ml));
|
||||
|
||||
STEP64(S.s0, Nm.s0, S.s1, Nm.s1)
|
||||
STEP64(S.s2, Nm.s2, S.s3, Nm.s3)
|
||||
}
|
||||
|
||||
c_row_t uc;
|
||||
uc.v = __builtin_astype(acc, half4096);
|
||||
|
||||
global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane;
|
||||
const int nv = N - tn * 64;
|
||||
store_c16(p, uc.s.h0, 0, nv, M);
|
||||
store_c16(p, uc.s.h1, 16, nv, M);
|
||||
store_c16(p, uc.s.h2, 32, nv, M);
|
||||
store_c16(p, uc.s.h3, 48, nv, M);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
|
||||
#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable
|
||||
|
||||
// Q6_K x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave,
|
||||
// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat.
|
||||
|
||||
typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM)));
|
||||
typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM)));
|
||||
typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM)));
|
||||
|
||||
typedef half half1024 __attribute__((ext_vector_type(1024)));
|
||||
typedef half half4096 __attribute__((ext_vector_type(4096)));
|
||||
|
||||
typedef union {
|
||||
half1024 v;
|
||||
half16 h;
|
||||
} a_row_t;
|
||||
|
||||
typedef union {
|
||||
half4096 v;
|
||||
struct {
|
||||
half16 h0;
|
||||
half16 h1;
|
||||
half16 h2;
|
||||
half16 h3;
|
||||
} s;
|
||||
} c_row_t;
|
||||
|
||||
inline half8 dequant8(uint v, uint hh, half scale) {
|
||||
uint4 t;
|
||||
t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000);
|
||||
t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000);
|
||||
t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000);
|
||||
t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000);
|
||||
t.s0 |= ((hh & 0x0003u) << 4) | ((hh & 0x000Cu) << 18);
|
||||
t.s1 |= ( hh & 0x0030u ) | ((hh & 0x00C0u) << 14);
|
||||
t.s2 |= ((hh & 0x0300u) >> 4) | ((hh & 0x0C00u) << 10);
|
||||
t.s3 |= ((hh & 0x3000u) >> 8) | ((hh & 0xC000u) << 6);
|
||||
t |= (uint4)(0x64006400);
|
||||
|
||||
return (as_half8(t) - (half8)(1056.0h)) * scale;
|
||||
}
|
||||
|
||||
inline void store_c16(global float * p, half16 h, int j0, int nv, int M) {
|
||||
float16 f = convert_float16(h);
|
||||
if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0;
|
||||
if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1;
|
||||
if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2;
|
||||
if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3;
|
||||
if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4;
|
||||
if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5;
|
||||
if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6;
|
||||
if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7;
|
||||
if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8;
|
||||
if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9;
|
||||
if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa;
|
||||
if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb;
|
||||
if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc;
|
||||
if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd;
|
||||
if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se;
|
||||
if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf;
|
||||
}
|
||||
|
||||
#define MMA_K32(q0, q1, q2, q3, hA, hB, sc0, sc1, b) { \
|
||||
a_row_t ua0; \
|
||||
a_row_t ua1; \
|
||||
ua0.h = (half16)(dequant8(q0, (hA), sc0), dequant8(q1, (hA) >> 16, sc0)); \
|
||||
ua1.h = (half16)(dequant8(q2, (hB), sc1), dequant8(q3, (hB) >> 16, sc1)); \
|
||||
mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \
|
||||
mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \
|
||||
mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \
|
||||
acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); }
|
||||
|
||||
kernel void kernel_gemm_noshuffle_q6_k_f32_coopmat(
|
||||
global const uint * src0_ql, // A: q6_K low nibbles, [K/8][M] u32
|
||||
global const uint * src0_qh, // A: q6_K high 2-bit, [K/16][M] u32
|
||||
global const uint * src0_s, // A: int8 sub-scales, [M][K/16] (4 per u32)
|
||||
global const half * src0_d, // A: per-superblock scale, [K/256][M] f16
|
||||
global const half * src1, // B: packed f16 tiles
|
||||
global char * dst, // C: [N][M] f32
|
||||
ulong offsetd,
|
||||
int K,
|
||||
int M,
|
||||
int N
|
||||
) {
|
||||
const int lane = get_local_id(0);
|
||||
const int row = get_global_id(1) * 64;
|
||||
const int tn = get_global_id(2);
|
||||
const int n_tiles = (N + 63) / 64;
|
||||
|
||||
if (tn >= n_tiles) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int lrow = row + lane;
|
||||
|
||||
global const uint * qp = src0_ql + lrow;
|
||||
global const uint * qhp = src0_qh + lrow;
|
||||
global const half * bp = src1 + (ulong)tn * (K / 16) * 1024;
|
||||
global const uint * sp = src0_s + (ulong)lrow * (K / 64);
|
||||
|
||||
mat_c_t acc = qcom_coop_mat_init(0.0);
|
||||
|
||||
#pragma unroll 1
|
||||
for (int k0 = 0; k0 < K; k0 += 64) {
|
||||
const half dd = src0_d[(ulong)(k0 >> 8) * M + lrow];
|
||||
|
||||
const half4 g = convert_half4(as_char4(sp[0])) * dd;
|
||||
sp += 1;
|
||||
|
||||
uint8 qv;
|
||||
qv.s0 = qp[0];
|
||||
qv.s1 = qp[M];
|
||||
qv.s2 = qp[2 * M];
|
||||
qv.s3 = qp[3 * M];
|
||||
qv.s4 = qp[4 * M];
|
||||
qv.s5 = qp[5 * M];
|
||||
qv.s6 = qp[6 * M];
|
||||
qv.s7 = qp[7 * M];
|
||||
qp += 8 * M;
|
||||
|
||||
uint4 hv;
|
||||
hv.s0 = qhp[0];
|
||||
hv.s1 = qhp[M];
|
||||
hv.s2 = qhp[2 * M];
|
||||
hv.s3 = qhp[3 * M];
|
||||
qhp += 4 * M;
|
||||
|
||||
MMA_K32(qv.s0, qv.s1, qv.s2, qv.s3, hv.s0, hv.s1, g.s0, g.s1, bp)
|
||||
MMA_K32(qv.s4, qv.s5, qv.s6, qv.s7, hv.s2, hv.s3, g.s2, g.s3, bp + 2048)
|
||||
bp += 4096;
|
||||
}
|
||||
|
||||
c_row_t uc;
|
||||
uc.v = __builtin_astype(acc, half4096);
|
||||
|
||||
global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane;
|
||||
const int nv = N - tn * 64;
|
||||
store_c16(p, uc.s.h0, 0, nv, M);
|
||||
store_c16(p, uc.s.h1, 16, nv, M);
|
||||
store_c16(p, uc.s.h2, 32, nv, M);
|
||||
store_c16(p, uc.s.h3, 48, nv, M);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
|
||||
#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable
|
||||
|
||||
// Q8_0 x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave,
|
||||
// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat.
|
||||
|
||||
typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM)));
|
||||
typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM)));
|
||||
typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM)));
|
||||
|
||||
typedef half half1024 __attribute__((ext_vector_type(1024)));
|
||||
typedef half half4096 __attribute__((ext_vector_type(4096)));
|
||||
|
||||
typedef union {
|
||||
half1024 v;
|
||||
half16 h;
|
||||
} a_row_t;
|
||||
|
||||
typedef union {
|
||||
half4096 v;
|
||||
struct {
|
||||
half16 h0;
|
||||
half16 h1;
|
||||
half16 h2;
|
||||
half16 h3;
|
||||
} s;
|
||||
} c_row_t;
|
||||
|
||||
inline half4 dequant4(uint v, half d) {
|
||||
return convert_half4(as_char4(v)) * d;
|
||||
}
|
||||
|
||||
inline void store_c16(global float * p, half16 h, int j0, int nv, int M) {
|
||||
float16 f = convert_float16(h);
|
||||
if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0;
|
||||
if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1;
|
||||
if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2;
|
||||
if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3;
|
||||
if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4;
|
||||
if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5;
|
||||
if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6;
|
||||
if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7;
|
||||
if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8;
|
||||
if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9;
|
||||
if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa;
|
||||
if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb;
|
||||
if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc;
|
||||
if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd;
|
||||
if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se;
|
||||
if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf;
|
||||
}
|
||||
|
||||
#define LOAD_Q(qv, dd) { \
|
||||
qv.s0 = qp[0]; \
|
||||
qv.s1 = qp[M]; \
|
||||
qv.s2 = qp[2 * M]; \
|
||||
qv.s3 = qp[3 * M]; \
|
||||
qv.s4 = qp[4 * M]; \
|
||||
qv.s5 = qp[5 * M]; \
|
||||
qv.s6 = qp[6 * M]; \
|
||||
qv.s7 = qp[7 * M]; \
|
||||
dd = dp[0]; \
|
||||
qp += 8 * M; \
|
||||
dp += M; }
|
||||
|
||||
#define MMA_K32(qv, dd, b) { \
|
||||
a_row_t ua0; \
|
||||
a_row_t ua1; \
|
||||
ua0.h = (half16)(dequant4(qv.s0, dd), dequant4(qv.s1, dd), dequant4(qv.s2, dd), dequant4(qv.s3, dd)); \
|
||||
ua1.h = (half16)(dequant4(qv.s4, dd), dequant4(qv.s5, dd), dequant4(qv.s6, dd), dequant4(qv.s7, dd)); \
|
||||
mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \
|
||||
mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \
|
||||
mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \
|
||||
acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \
|
||||
acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); }
|
||||
|
||||
kernel void kernel_gemm_noshuffle_q8_0_f32_coopmat(
|
||||
global const uint * src0_q, // A: q8_0 quants, [K/4][M] u32
|
||||
global const half * src0_d, // A: q8_0 scales, [K/32][M] f16
|
||||
global const half * src1, // B: packed f16 tiles
|
||||
global char * dst, // C: [N][M] f32
|
||||
ulong offsetd,
|
||||
int K,
|
||||
int M,
|
||||
int N
|
||||
) {
|
||||
const int lane = get_local_id(0);
|
||||
const int row = get_global_id(1) * 64;
|
||||
const int tn = get_global_id(2);
|
||||
const int n_tiles = (N + 63) / 64;
|
||||
|
||||
if (tn >= n_tiles) {
|
||||
return;
|
||||
}
|
||||
|
||||
global const uint * qp = src0_q + row + lane;
|
||||
global const half * dp = src0_d + row + lane;
|
||||
global const half * bp = src1 + (ulong)tn * (K / 16) * 1024;
|
||||
|
||||
mat_c_t acc = qcom_coop_mat_init(0.0);
|
||||
|
||||
{
|
||||
const int odd = (K / 32) & 1;
|
||||
const int kb = odd ? 0 : 32;
|
||||
uint8 qa;
|
||||
uint8 qb;
|
||||
half da;
|
||||
half db;
|
||||
qa.s0 = qp[0];
|
||||
qa.s1 = qp[M];
|
||||
qa.s2 = qp[2 * M];
|
||||
qa.s3 = qp[3 * M];
|
||||
qa.s4 = qp[4 * M];
|
||||
qa.s5 = qp[5 * M];
|
||||
qa.s6 = qp[6 * M];
|
||||
qa.s7 = qp[7 * M];
|
||||
da = odd ? 0.0h : dp[0];
|
||||
qb.s0 = qp[(kb / 4 + 0) * M];
|
||||
qb.s1 = qp[(kb / 4 + 1) * M];
|
||||
qb.s2 = qp[(kb / 4 + 2) * M];
|
||||
qb.s3 = qp[(kb / 4 + 3) * M];
|
||||
qb.s4 = qp[(kb / 4 + 4) * M];
|
||||
qb.s5 = qp[(kb / 4 + 5) * M];
|
||||
qb.s6 = qp[(kb / 4 + 6) * M];
|
||||
qb.s7 = qp[(kb / 4 + 7) * M];
|
||||
db = dp[(kb / 32) * M];
|
||||
MMA_K32(qa, da, bp)
|
||||
MMA_K32(qb, db, bp + (kb / 16) * 1024)
|
||||
qp += (kb / 4 + 8) * M;
|
||||
dp += (kb / 32 + 1) * M;
|
||||
bp += (kb / 16 + 2) * 1024;
|
||||
}
|
||||
|
||||
#pragma unroll 1
|
||||
for (int k0 = (K / 32) & 1 ? 32 : 64; k0 < K; k0 += 64) {
|
||||
uint8 qa;
|
||||
uint8 qb;
|
||||
half da;
|
||||
half db;
|
||||
LOAD_Q(qa, da)
|
||||
LOAD_Q(qb, db)
|
||||
MMA_K32(qa, da, bp)
|
||||
MMA_K32(qb, db, bp + 2048)
|
||||
bp += 4096;
|
||||
}
|
||||
|
||||
c_row_t uc;
|
||||
uc.v = __builtin_astype(acc, half4096);
|
||||
|
||||
global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane;
|
||||
const int nv = N - tn * 64;
|
||||
store_c16(p, uc.s.h0, 0, nv, M);
|
||||
store_c16(p, uc.s.h1, 16, nv, M);
|
||||
store_c16(p, uc.s.h2, 32, nv, M);
|
||||
store_c16(p, uc.s.h3, 48, nv, M);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
|
||||
|
||||
// Pack B f32 [N][K] into f16 64x16 tiles (column-major, ld 16) at (tn * (K/16) + ks) * 1024.
|
||||
// Columns >= N are zero. A workgroup (64, 4) packs 64 columns x 64 k.
|
||||
#define PACK_LDS (64 + 8)
|
||||
|
||||
kernel void kernel_pack_b_f16_coopmat(
|
||||
global const char * src1,
|
||||
ulong offset1,
|
||||
global half * dst,
|
||||
int K,
|
||||
int N
|
||||
) {
|
||||
local half tile[64 * PACK_LDS];
|
||||
|
||||
const int l = get_local_id(1) * 64 + get_local_id(0);
|
||||
const int tn = get_group_id(0);
|
||||
const int kt = get_group_id(1);
|
||||
const int k0 = kt * 64;
|
||||
|
||||
global const float * src = (global const float *)(src1 + offset1);
|
||||
|
||||
for (int j = 0; j < 4; j++) {
|
||||
const int f = j * 256 + l;
|
||||
const int r = f >> 4;
|
||||
const int c = (f & 15) * 4;
|
||||
const int n = tn * 64 + r;
|
||||
float4 v = (float4)(0.0f);
|
||||
if (n < N && k0 + c < K) {
|
||||
v = vload4(0, src + (ulong)n * K + k0 + c);
|
||||
}
|
||||
vstore_half4(v, 0, tile + r * PACK_LDS + c);
|
||||
}
|
||||
|
||||
barrier(CLK_LOCAL_MEM_FENCE);
|
||||
|
||||
global half * out = dst + ((ulong)tn * (K / 16) + kt * 4) * 1024;
|
||||
for (int j = 0; j < 2; j++) {
|
||||
const int q = j * 256 + l;
|
||||
const int ks = q >> 7;
|
||||
const int n = (q >> 1) & 63;
|
||||
const int h = q & 1;
|
||||
if (kt * 4 + ks < K / 16) {
|
||||
half8 v = vload8(0, tile + n * PACK_LDS + ks * 16 + h * 8);
|
||||
vstore8(v, 0, out + q * 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1683,10 +1683,6 @@ bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) {
|
||||
LOG_ERROR("[%s] tensor region out of buffer bounds\n", __func__);
|
||||
return false;
|
||||
}
|
||||
if (tensor->buffer->iface.memset_tensor == nullptr) {
|
||||
LOG_ERROR("[%s] memset not implemented by backend buffer\n", __func__);
|
||||
return false;
|
||||
}
|
||||
|
||||
LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, value: %u\n",
|
||||
__func__, rpc_log_format_tensor(tensor).c_str(), (void *) tensor->buffer, tensor->data, request.offset,
|
||||
|
||||
@@ -28,16 +28,17 @@ static void conv_transpose_1d_kernel(
|
||||
|
||||
float accumulator = 0;
|
||||
|
||||
for (int c = 0; c < src0_ne2; c++) {
|
||||
int idx = global_index % dst_ne0;
|
||||
const int idx = global_index % dst_ne0;
|
||||
|
||||
// only inputs with i*s0 <= idx < i*s0 + src0_ne0 contribute
|
||||
const int i_begin = idx >= src0_ne0 ? (idx - src0_ne0) / s0 + 1 : 0;
|
||||
const int i_end = sycl::min(src1_ne0, idx / s0 + 1);
|
||||
|
||||
for (int c = 0; c < src0_ne2; c++) {
|
||||
int kernel_offset = (src0_ne0 * src0_ne1 * c) + (out_index * src0_ne0);
|
||||
int input_offset = src1_ne0 * c;
|
||||
|
||||
for (int i = 0; i < src1_ne0; i++) {
|
||||
if (!(idx >= i*s0 && idx < i*s0 + src0_ne0)) {
|
||||
continue;
|
||||
}
|
||||
for (int i = i_begin; i < i_end; i++) {
|
||||
int weight_idx = idx - i*s0;
|
||||
|
||||
float kernel_weight = src0[kernel_offset + weight_idx];
|
||||
|
||||
@@ -516,6 +516,16 @@ static void dequantize_row_iq4_nl_sycl(const void *vx, dst_t *y, const int64_t k
|
||||
}
|
||||
}
|
||||
|
||||
template <ggml_type type, typename dst_t>
|
||||
static void dequantize_row_iq4_sycl_reorder(const void * vx, dst_t * y, const int64_t k, dpct::queue_ptr stream) {
|
||||
// flat range<1>, four qs bytes (8 outputs) per item
|
||||
GGML_ASSERT(k % ggml_sycl_reordered::block_q_t<type>::traits::qk == 0);
|
||||
stream->parallel_for(sycl::range<1>((size_t) (k / 8)),
|
||||
[=](sycl::id<1> idx) {
|
||||
dequantize_block_iq4_reorder_wide<type>(vx, y, k, idx);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename dst_t>
|
||||
static void dequantize_row_mxfp4_sycl(const void * vx, dst_t * y, const int64_t k, dpct::queue_ptr stream) {
|
||||
const int nb = (k + QK_K - 1) / QK_K;
|
||||
@@ -743,9 +753,17 @@ static to_t_sycl_t<dst_t> ggml_get_dequant_sycl(ggml_type type, ggml_tensor * ds
|
||||
return dequantize_row_iq3_s_sycl;
|
||||
}
|
||||
case GGML_TYPE_IQ4_XS:
|
||||
return dequantize_row_iq4_xs_sycl;
|
||||
if (is_reordered_src0(dst)) {
|
||||
return dequantize_row_iq4_sycl_reorder<GGML_TYPE_IQ4_XS>;
|
||||
} else {
|
||||
return dequantize_row_iq4_xs_sycl;
|
||||
}
|
||||
case GGML_TYPE_IQ4_NL:
|
||||
return dequantize_row_iq4_nl_sycl;
|
||||
if (is_reordered_src0(dst)) {
|
||||
return dequantize_row_iq4_sycl_reorder<GGML_TYPE_IQ4_NL>;
|
||||
} else {
|
||||
return dequantize_row_iq4_nl_sycl;
|
||||
}
|
||||
case GGML_TYPE_MXFP4:
|
||||
if (is_reordered_src0(dst)) {
|
||||
return dequantize_row_mxfp4_sycl_reorder;
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
#include "common.hpp"
|
||||
#include "convert.hpp"
|
||||
#include "quants.hpp"
|
||||
|
||||
typedef void (*dequantize_kernel_t)(const void * vx, const int64_t ib, const int iqs, dfloat2 & v);
|
||||
typedef void (*dequantize_kernel_t_reorder)(const void *d, const int64_t ib, const void *qs,
|
||||
@@ -674,6 +675,15 @@ static __dpct_inline__ void dequantize_iq4_nl(const void *vx, const int64_t ib,
|
||||
v.y() = dequantize_one(iqs + 1);
|
||||
}
|
||||
|
||||
static __dpct_inline__ void dequantize_iq4_nl_reorder(const void * d_ptr, const int64_t ib, const void * qs,
|
||||
const int iqs, dfloat2 & v) {
|
||||
const float d = (float) ((const sycl::half *) d_ptr)[ib];
|
||||
const uint8_t q = ((const uint8_t *) qs)[iqs];
|
||||
|
||||
v.x() = d * kvalues_iq4nl[q & 0xF];
|
||||
v.y() = d * kvalues_iq4nl[q >> 4];
|
||||
}
|
||||
|
||||
static __dpct_inline__ void dequantize_iq4_xs(const void *vx, const int64_t ib,
|
||||
const int iqs, dfloat2 &v) {
|
||||
#if QK_K == 256
|
||||
@@ -1758,6 +1768,60 @@ dequantize_block_iq4_xs(const void *__restrict__ vx, dst_t *__restrict__ yy,
|
||||
}
|
||||
}
|
||||
|
||||
// reordered IQ4_NL / IQ4_XS: qs bytes iq .. iq + 3 of 32-value group g to y[iq + j] and y[iq + 16 + j], with y the
|
||||
// group's first output, in two vec<dst_t, 4> stores as for MXFP4; tail is the first byte after all qs
|
||||
template <ggml_type type, typename dst_t>
|
||||
static __dpct_inline__ void dequantize_iq4_reorder_quad(const uint8_t * __restrict__ x,
|
||||
const uint8_t * __restrict__ tail, const int64_t g,
|
||||
const int iq, dst_t * __restrict__ y) {
|
||||
const uint8_t * qs = x + 16 * g + iq;
|
||||
const float d = ggml_sycl_reordered::iq4_group_scale<type>(tail, g);
|
||||
|
||||
sycl::vec<dst_t, 4> lo, hi;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
lo[j] = d * kvalues_iq4nl[qs[j] & 0xf];
|
||||
hi[j] = d * kvalues_iq4nl[qs[j] >> 4];
|
||||
}
|
||||
*reinterpret_cast<sycl::vec<dst_t, 4> *>(y + iq) = lo;
|
||||
*reinterpret_cast<sycl::vec<dst_t, 4> *>(y + iq + 16) = hi;
|
||||
}
|
||||
|
||||
// flat range over k / 8 items: item i takes group i / 4 from qs byte 4 * (i % 4)
|
||||
template <ggml_type type, typename dst_t>
|
||||
static void dequantize_block_iq4_reorder_wide(const void * __restrict__ vx, dst_t * __restrict__ yy, int64_t k,
|
||||
const sycl::id<1> idx) {
|
||||
const int64_t i = (int64_t) idx[0];
|
||||
const int64_t g = i / 4;
|
||||
const uint8_t * x = (const uint8_t *) vx;
|
||||
dequantize_iq4_reorder_quad<type>(x, x + k / 2, g, (int) (4 * (i % 4)), yy + 32 * g);
|
||||
}
|
||||
|
||||
// item t (0..31) of block ib dequantizes four qs bytes of sub-block t/4 into y, the output of block ib
|
||||
template <typename dst_t>
|
||||
static __dpct_inline__ void dequantize_block_iq4_xs_reorder(const void * __restrict__ vx, dst_t * __restrict__ y,
|
||||
const int64_t ib, const int t, const int64_t nb) {
|
||||
const int ib32 = t / 4;
|
||||
const int iq = 4 * (t % 4);
|
||||
|
||||
const uint8_t * qs = (const uint8_t *) vx + ib * (QK_K / 2) + 16 * ib32 + iq;
|
||||
const uint8_t * meta = (const uint8_t *) vx + nb * (QK_K / 2) + ib * offsetof(block_iq4_xs, qs);
|
||||
const uint16_t scales_h = *(const uint16_t *) (meta + offsetof(block_iq4_xs, scales_h));
|
||||
const uint8_t scales_l = meta[offsetof(block_iq4_xs, scales_l) + ib32 / 2];
|
||||
const float d = (float) *(const ggml_half *) (meta + offsetof(block_iq4_xs, d)) *
|
||||
((((scales_l >> (4 * (ib32 % 2))) & 0xf) | (((scales_h >> (2 * ib32)) & 3) << 4)) - 32);
|
||||
|
||||
sycl::vec<dst_t, 4> lo, hi;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
lo[j] = d * kvalues_iq4nl[qs[j] & 0xf];
|
||||
hi[j] = d * kvalues_iq4nl[qs[j] >> 4];
|
||||
}
|
||||
dst_t * yb = y + 32 * ib32 + iq;
|
||||
*reinterpret_cast<sycl::vec<dst_t, 4> *>(yb) = lo;
|
||||
*reinterpret_cast<sycl::vec<dst_t, 4> *>(yb + 16) = hi;
|
||||
}
|
||||
|
||||
template<typename dst_t>
|
||||
static void dequantize_block_mxfp4(const void * __restrict__ vx, dst_t * __restrict__ yy,
|
||||
const sycl::nd_item<3> &item_ct1) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "fused-gemm.hpp"
|
||||
#include "fused-gemm-esimd.hpp"
|
||||
#include "quants.hpp"
|
||||
|
||||
#include <sycl/ext/oneapi/matrix/matrix.hpp>
|
||||
|
||||
@@ -421,14 +422,10 @@ static __dpct_inline__ void fg_pack_quarter(const float * __restrict__ t, typena
|
||||
}
|
||||
}
|
||||
|
||||
// 32 values from 16 qs bytes, as in IQ4_NL blocks and IQ4_XS sub-blocks: the low nibbles fill the
|
||||
// first half of the step and the high nibbles the second, so the halves land at a[0..7] and a[8..15]
|
||||
template <typename E>
|
||||
static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, const int kb, typename E::pair * a) {
|
||||
FG_SUPERBLOCK(block_iq4_xs);
|
||||
// low nibbles fill the first half of the step, high nibbles the second, so the two halves
|
||||
// land at a[0..7] and a[8..15] and no quarter loop is needed
|
||||
const float d = (float) blk->d *
|
||||
((((blk->scales_l[ib / 2] >> (4 * (ib % 2))) & 0xf) | (((blk->scales_h >> (2 * ib)) & 3) << 4)) - 32);
|
||||
const uint8_t * q4 = blk->qs + 16 * ib;
|
||||
static __dpct_inline__ void fg_decode_iq4(const uint8_t * __restrict__ q4, const float d, typename E::pair * a) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
a[j] = E::make(d * kvalues_iq4nl[q4[2 * j] & 0xf], d * kvalues_iq4nl[q4[2 * j + 1] & 0xf]);
|
||||
@@ -436,6 +433,14 @@ static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, c
|
||||
}
|
||||
}
|
||||
|
||||
template <typename E>
|
||||
static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, const int kb, typename E::pair * a) {
|
||||
FG_SUPERBLOCK(block_iq4_xs);
|
||||
const float d = (float) blk->d *
|
||||
((((blk->scales_l[ib / 2] >> (4 * (ib % 2))) & 0xf) | (((blk->scales_h >> (2 * ib)) & 3) << 4)) - 32);
|
||||
fg_decode_iq4<E>(blk->qs + 16 * ib, d, a);
|
||||
}
|
||||
|
||||
template <typename E>
|
||||
static __dpct_inline__ void fg_stage_a(const block_iq3_xxs * __restrict__ xrow, const int kb, typename E::pair * a) {
|
||||
FG_SUPERBLOCK(block_iq3_xxs);
|
||||
@@ -821,6 +826,22 @@ template <> struct fg_soa<block_q6_K> {
|
||||
}
|
||||
};
|
||||
|
||||
template <ggml_type type> struct fg_soa_iq4 {
|
||||
static constexpr bool supported = true;
|
||||
// [qs][per-block records]; k step kb is 32-value group kb % groups of block ib
|
||||
template <typename E>
|
||||
static __dpct_inline__ void stage(const uint8_t * x, const size_t nblocks, const size_t ib, const int kb,
|
||||
typename E::pair * a) {
|
||||
constexpr int groups = ggml_sycl_reordered::block_q_t<type>::traits::qk / QK4_NL;
|
||||
const int64_t g = (int64_t) ib * groups + kb % groups;
|
||||
fg_decode_iq4<E>(x + 16 * g, ggml_sycl_reordered::iq4_group_scale<type>(x + nblocks * groups * 16, g), a);
|
||||
}
|
||||
};
|
||||
|
||||
template <> struct fg_soa<block_iq4_nl> : fg_soa_iq4<GGML_TYPE_IQ4_NL> {};
|
||||
|
||||
template <> struct fg_soa<block_iq4_xs> : fg_soa_iq4<GGML_TYPE_IQ4_XS> {};
|
||||
|
||||
|
||||
// one SG_ROWS x BN output tile: B columns [b0, b0 + BN) of packed_b go to dst columns [n0, n1),
|
||||
// n1 - n0 <= BN
|
||||
|
||||
@@ -121,6 +121,28 @@ bool ggml_sycl_can_fuse(const ggml_cgraph * cgraph, int node_idx, std::initializ
|
||||
return ggml_sycl_should_fuse_mul_mat_glu(gate, up, glu);
|
||||
}
|
||||
|
||||
// the residual sum stays materialised (a later residual add reads it), so ggml_can_fuse cannot
|
||||
// express this either: the add and the mul are the subgraph's outputs
|
||||
if (ops.size() == 3 && ops.begin()[0] == GGML_OP_ADD && ops.begin()[1] == GGML_OP_RMS_NORM &&
|
||||
ops.begin()[2] == GGML_OP_MUL) {
|
||||
if (!ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx, node_idx + 2 })) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ggml_tensor * add = cgraph->nodes[node_idx];
|
||||
if (cgraph->nodes[node_idx + 1]->src[0] != add) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// the fused kernel does not broadcast the add
|
||||
if (add->src[0]->type != GGML_TYPE_F32 || add->src[1]->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32 ||
|
||||
!ggml_are_same_shape(add->src[0], add) || !ggml_are_same_shape(add->src[1], add)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ggml_sycl_can_fuse(cgraph, node_idx + 1, { GGML_OP_RMS_NORM, GGML_OP_MUL }, {});
|
||||
}
|
||||
|
||||
if (!ggml_can_fuse(cgraph, node_idx, ops)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,13 @@
|
||||
#include <cmath>
|
||||
|
||||
|
||||
template <int S_v, bool KDA, bool keep_rs_t>
|
||||
// Warps per work-group. 2 is 13% faster than 4 at 4 columns per warp on Arc Pro B70.
|
||||
static constexpr int gdn_warps = 2;
|
||||
// State columns per warp when there are enough heads, see launch_gated_delta_net.
|
||||
static constexpr int gdn_cols_wide = 4;
|
||||
|
||||
// C is the number of state columns per warp: a token's q/k shard is loaded once and shared by these columns.
|
||||
template <int S_v, int C, bool KDA, bool keep_rs_t>
|
||||
void gated_delta_net_sycl(const float * q,
|
||||
const float * k,
|
||||
const float * v,
|
||||
@@ -34,9 +40,10 @@ void gated_delta_net_sycl(const float * q,
|
||||
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
||||
const uint32_t h_idx = item_ct1.get_group(2);
|
||||
const uint32_t sequence = item_ct1.get_group(1);
|
||||
// each warp owns one column, using warp-level primitives to reduce across rows
|
||||
// each warp owns C columns, using warp-level primitives to reduce across rows
|
||||
const int lane = item_ct1.get_local_id(2);
|
||||
const int col = item_ct1.get_group(0) * item_ct1.get_local_range(1) + item_ct1.get_local_id(1);
|
||||
const int warp = item_ct1.get_group(0) * item_ct1.get_local_range(1) + item_ct1.get_local_id(1);
|
||||
const int col0 = warp * C;
|
||||
|
||||
const uint32_t iq1 = fastmodulo(h_idx, neqk1_magic);
|
||||
const uint32_t iq3 = fastdiv(sequence, rq3_magic);
|
||||
@@ -48,94 +55,145 @@ void gated_delta_net_sycl(const float * q,
|
||||
const int64_t state_in_offset = sequence * H * S_v * S_v + h_idx * S_v * S_v;
|
||||
const int64_t state_out_offset = (sequence * H + h_idx) * S_v * S_v;
|
||||
state += state_out_offset;
|
||||
curr_state += state_in_offset + col * S_v;
|
||||
curr_state += state_in_offset;
|
||||
attn_data += (sequence * n_tokens * H + h_idx) * S_v;
|
||||
|
||||
constexpr int warp_size = ggml_sycl_get_physical_warp_size() < S_v ? ggml_sycl_get_physical_warp_size() : S_v;
|
||||
static_assert(S_v % warp_size == 0, "S_v must be a multiple of warp_size");
|
||||
static_assert(S_v % (C * gdn_warps) == 0, "S_v must be a multiple of the columns per work-group");
|
||||
static_assert(C <= warp_size, "the attn store puts column c in lane c");
|
||||
constexpr int rows_per_lane = (S_v + warp_size - 1) / warp_size;
|
||||
float s_shard[rows_per_lane];
|
||||
float s_shard[C][rows_per_lane];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
const int i = r * warp_size + lane;
|
||||
s_shard[r] = curr_state[i];
|
||||
for (int c = 0; c < C; c++) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
const int i = r * warp_size + lane;
|
||||
s_shard[c][r] = curr_state[(col0 + c) * S_v + i];
|
||||
}
|
||||
}
|
||||
|
||||
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
|
||||
// When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned.
|
||||
|
||||
const float * qp = q + iq3 * sq3 + iq1 * sq1 + lane;
|
||||
const float * kp = k + iq3 * sq3 + iq1 * sq1 + lane;
|
||||
const float * vp = v + sequence * sv3 + h_idx * sv1 + col0;
|
||||
const float * bp = beta + sequence * sb3 + h_idx * sb1;
|
||||
const float * gp = g + (sequence * sb3 + h_idx * sb1) * (KDA ? S_v : 1);
|
||||
|
||||
// q/k of the next token are loaded one iteration ahead to hide the load latency.
|
||||
float q_next[rows_per_lane];
|
||||
float k_next[rows_per_lane];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
q_next[r] = qp[r * warp_size];
|
||||
k_next[r] = kp[r * warp_size];
|
||||
}
|
||||
|
||||
for (int t = 0; t < n_tokens; t++) {
|
||||
const float * q_t = q + iq3 * sq3 + t * sq2 + iq1 * sq1;
|
||||
const float * k_t = k + iq3 * sq3 + t * sq2 + iq1 * sq1;
|
||||
const float * v_t = v + sequence * sv3 + t * sv2 + h_idx * sv1;
|
||||
const float beta_val = *bp;
|
||||
const float * g_t = gp;
|
||||
bp += sb2;
|
||||
gp += sb2 * (KDA ? S_v : 1);
|
||||
|
||||
const int64_t gb_offset = sequence * sb3 + t * sb2 + h_idx * sb1;
|
||||
const float * beta_t = beta + gb_offset;
|
||||
const float * g_t = g + gb_offset * (KDA ? S_v : 1);
|
||||
float q_reg[rows_per_lane];
|
||||
float k_reg[rows_per_lane];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
q_reg[r] = q_next[r];
|
||||
k_reg[r] = k_next[r];
|
||||
}
|
||||
if (t + 1 < n_tokens) {
|
||||
qp += sq2;
|
||||
kp += sq2;
|
||||
}
|
||||
// Load outside the branch: the last token reads its own row again.
|
||||
// A guarded load is 20% slower at 32 heads on Arc Pro B70.
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
q_next[r] = qp[r * warp_size];
|
||||
k_next[r] = kp[r * warp_size];
|
||||
}
|
||||
|
||||
const float beta_val = *beta_t;
|
||||
float v_reg[C];
|
||||
#pragma unroll
|
||||
for (int c = 0; c < C; c++) {
|
||||
v_reg[c] = vp[c];
|
||||
}
|
||||
vp += sv2;
|
||||
|
||||
// attn[col] = g * (S^T q)[col] + delta[col] * (k . q), so no reduction waits for delta
|
||||
float kq_shard = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
kq_shard += k_reg[r] * q_reg[r];
|
||||
}
|
||||
const float kq = warp_reduce_sum<warp_size>(kq_shard);
|
||||
|
||||
float out_lane = 0.0f;
|
||||
if constexpr (!KDA) {
|
||||
const float g_val = sycl::native::exp(*g_t);
|
||||
|
||||
// kv[col] = (S^T @ k)[col] = sum_i S[i][col] * k[i]
|
||||
float kv_shard = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
const int i = r * warp_size + lane;
|
||||
kv_shard += s_shard[r] * k_t[i];
|
||||
}
|
||||
float kv_col = warp_reduce_sum<warp_size>(kv_shard);
|
||||
|
||||
// delta[col] = (v[col] - g * kv[col]) * beta
|
||||
float delta_col = (v_t[col] - g_val * kv_col) * beta_val;
|
||||
|
||||
// fused: S[i][col] = g * S[i][col] + k[i] * delta[col]
|
||||
// attn[col] = (S^T @ q)[col] = sum_i S[i][col] * q[i]
|
||||
float attn_partial = 0.0f;
|
||||
for (int c = 0; c < C; c++) {
|
||||
// x: kv[col] = (S^T k)[col], y: (S^T q)[col]
|
||||
sycl::float2 acc(0.0f, 0.0f);
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
const int i = r * warp_size + lane;
|
||||
s_shard[r] = g_val * s_shard[r] + k_t[i] * delta_col;
|
||||
attn_partial += s_shard[r] * q_t[i];
|
||||
}
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
acc.x() += s_shard[c][r] * k_reg[r];
|
||||
acc.y() += s_shard[c][r] * q_reg[r];
|
||||
}
|
||||
acc = warp_reduce_sum<warp_size>(acc);
|
||||
|
||||
float attn_col = warp_reduce_sum<warp_size>(attn_partial);
|
||||
// delta[col] = (v[col] - g * kv[col]) * beta
|
||||
const float delta_col = (v_reg[c] - g_val * acc.x()) * beta_val;
|
||||
|
||||
if (lane == 0) {
|
||||
attn_data[col] = attn_col * scale;
|
||||
// S[i][col] = g * S[i][col] + k[i] * delta[col]
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
s_shard[c][r] = g_val * s_shard[c][r] + k_reg[r] * delta_col;
|
||||
}
|
||||
|
||||
// the reductions broadcast, so lane c already holds column c's result
|
||||
out_lane = (lane == c) ? (g_val * acc.y() + delta_col * kq) * scale : out_lane;
|
||||
}
|
||||
} else {
|
||||
// kv[col] = sum_i g[i] * S[i][col] * k[i]
|
||||
float kv_shard = 0.0f;
|
||||
float g_reg[rows_per_lane];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
const int i = r * warp_size + lane;
|
||||
kv_shard += sycl::native::exp(g_t[i]) * s_shard[r] * k_t[i];
|
||||
g_reg[r] = sycl::native::exp(g_t[r * warp_size + lane]);
|
||||
}
|
||||
|
||||
float kv_col = warp_reduce_sum<warp_size>(kv_shard);
|
||||
|
||||
// delta[col] = (v[col] - kv[col]) * beta
|
||||
float delta_col = (v_t[col] - kv_col) * beta_val;
|
||||
|
||||
// fused: S[i][col] = g[i] * S[i][col] + k[i] * delta[col]
|
||||
// attn[col] = (S^T @ q)[col] = sum_i S[i][col] * q[i]
|
||||
float attn_partial = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
const int i = r * warp_size + lane;
|
||||
s_shard[r] = sycl::native::exp(g_t[i]) * s_shard[r] + k_t[i] * delta_col;
|
||||
attn_partial += s_shard[r] * q_t[i];
|
||||
}
|
||||
for (int c = 0; c < C; c++) {
|
||||
// x: kv[col] = sum_i g[i] * S[i][col] * k[i], y: sum_i g[i] * S[i][col] * q[i]
|
||||
sycl::float2 acc(0.0f, 0.0f);
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
const float gs = g_reg[r] * s_shard[c][r];
|
||||
acc.x() += gs * k_reg[r];
|
||||
acc.y() += gs * q_reg[r];
|
||||
}
|
||||
acc = warp_reduce_sum<warp_size>(acc);
|
||||
|
||||
float attn_col = warp_reduce_sum<warp_size>(attn_partial);
|
||||
// delta[col] = (v[col] - kv[col]) * beta
|
||||
const float delta_col = (v_reg[c] - acc.x()) * beta_val;
|
||||
|
||||
if (lane == 0) {
|
||||
attn_data[col] = attn_col * scale;
|
||||
// S[i][col] = g[i] * S[i][col] + k[i] * delta[col]
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
s_shard[c][r] = g_reg[r] * s_shard[c][r] + k_reg[r] * delta_col;
|
||||
}
|
||||
|
||||
out_lane = (lane == c) ? (acc.y() + delta_col * kq) * scale : out_lane;
|
||||
}
|
||||
}
|
||||
|
||||
if (lane < C) {
|
||||
attn_data[col0 + lane] = out_lane;
|
||||
}
|
||||
|
||||
attn_data += S_v * H;
|
||||
|
||||
|
||||
@@ -143,21 +201,26 @@ void gated_delta_net_sycl(const float * q,
|
||||
if constexpr (keep_rs_t) {
|
||||
const int target_slot = (int) n_tokens - 1 - t;
|
||||
if (target_slot >= 0 && target_slot < K) {
|
||||
float * curr_state = state + target_slot * state_slot_stride;
|
||||
float * slot_col = state + target_slot * state_slot_stride + col0 * S_v + lane;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
const int i = r * warp_size + lane;
|
||||
curr_state[col * S_v + i] = s_shard[r];
|
||||
for (int c = 0; c < C; c++) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
slot_col[c * S_v + r * warp_size] = s_shard[c][r];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (!keep_rs_t) {
|
||||
float * out_col = state + col0 * S_v + lane;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
const int i = r * warp_size + lane;
|
||||
state[col * S_v + i] = s_shard[r];
|
||||
for (int c = 0; c < C; c++) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
out_col[c * S_v + r * warp_size] = s_shard[c][r];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,60 +256,36 @@ static void launch_gated_delta_net(const float * q_d,
|
||||
//TODO: Add chunked kernel for even faster pre-fill
|
||||
const int warp_size = ggml_sycl_info().devices[ggml_sycl_get_device()].warp_size;
|
||||
|
||||
const int num_warps = 4;
|
||||
dpct::dim3 grid_dims(H, n_seqs, (S_v + num_warps - 1) / num_warps);
|
||||
dpct::dim3 block_dims(warp_size <= S_v ? warp_size : S_v, num_warps, 1);
|
||||
|
||||
const sycl::uint3 neqk1_magic = init_fastdiv_values(neqk1);
|
||||
const sycl::uint3 rq3_magic = init_fastdiv_values(rq3);
|
||||
|
||||
auto launch = [&](auto sv_c, auto c_c) {
|
||||
constexpr int sv = decltype(sv_c)::value;
|
||||
constexpr int C = decltype(c_c)::value;
|
||||
dpct::dim3 grid_dims(H, n_seqs, sv / (C * gdn_warps));
|
||||
dpct::dim3 block_dims(warp_size <= sv ? warp_size : sv, gdn_warps, 1);
|
||||
stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims),
|
||||
[=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
|
||||
gated_delta_net_sycl<sv, C, KDA, keep_rs_t>(
|
||||
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sv1, sv2,
|
||||
sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
|
||||
});
|
||||
};
|
||||
// gdn_cols_wide columns per warp cut the q/k loads but launch fewer warps, so with few heads 1 column is faster.
|
||||
// The 1024-warp switch point is measured on Arc Pro B70.
|
||||
auto launch_sv = [&](auto sv_c) {
|
||||
if (H * n_seqs * S_v / gdn_cols_wide >= 1024) {
|
||||
launch(sv_c, std::integral_constant<int, gdn_cols_wide>{});
|
||||
} else {
|
||||
launch(sv_c, std::integral_constant<int, 1>{});
|
||||
}
|
||||
};
|
||||
|
||||
switch (S_v) {
|
||||
case 16:
|
||||
{
|
||||
constexpr int sv = 16;
|
||||
stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims),
|
||||
[=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
|
||||
gated_delta_net_sycl<sv, KDA, keep_rs_t>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens,
|
||||
sq1, sq2, sq3, sv1, sv2, sv3, sb1, sb2,
|
||||
sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
|
||||
});
|
||||
}
|
||||
break;
|
||||
case 32:
|
||||
{
|
||||
constexpr int sv = 32;
|
||||
stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims),
|
||||
[=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
|
||||
gated_delta_net_sycl<sv, KDA, keep_rs_t>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens,
|
||||
sq1, sq2, sq3, sv1, sv2, sv3, sb1, sb2,
|
||||
sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
|
||||
});
|
||||
}
|
||||
break;
|
||||
case 64: {
|
||||
{
|
||||
constexpr int sv = 64;
|
||||
stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims),
|
||||
[=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
|
||||
gated_delta_net_sycl<sv, KDA, keep_rs_t>(
|
||||
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2,
|
||||
sq3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 128: {
|
||||
{
|
||||
constexpr int sv = 128;
|
||||
stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims),
|
||||
[=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
|
||||
gated_delta_net_sycl<sv, KDA, keep_rs_t>(
|
||||
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2,
|
||||
sq3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 16: launch_sv(std::integral_constant<int, 16>{}); break;
|
||||
case 32: launch_sv(std::integral_constant<int, 32>{}); break;
|
||||
case 64: launch_sv(std::integral_constant<int, 64>{}); break;
|
||||
case 128: launch_sv(std::integral_constant<int, 128>{}); break;
|
||||
default:
|
||||
GGML_ABORT("fatal error");
|
||||
break;
|
||||
|
||||
@@ -588,10 +588,24 @@ void ggml_sycl_op_get_rows(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
|
||||
src1_i32, (float *)dst->data, ctx.stream());
|
||||
break;
|
||||
case GGML_TYPE_IQ4_NL:
|
||||
if (src0_reordered) {
|
||||
get_rows_sycl_reorder<QK4_NL, QR4_NL, dequantize_iq4_nl_reorder>(dst->src[0], dst->src[1], dst, dst->src[0]->data,
|
||||
src1_i32, (float *)dst->data, ctx.stream());
|
||||
break;
|
||||
}
|
||||
get_rows_sycl<QK4_NL, 1, dequantize_iq4_nl>(ctx, dst->src[0], dst->src[1], dst, (const float *)dst->src[0]->data,
|
||||
src1_i32, (float *)dst->data, ctx.stream());
|
||||
break;
|
||||
case GGML_TYPE_IQ4_XS:
|
||||
if (src0_reordered) {
|
||||
const void * vx = dst->src[0]->data;
|
||||
get_rows_sycl_reorder_k<1, QK_K / 8, 1>(dst->src[0], dst->src[1], dst, src1_i32, (float *)dst->data, ctx.stream(),
|
||||
[=](float * y, int64_t ib, uint8_t * scales_local, const sycl::nd_item<1> & item_ct1, int64_t nb) {
|
||||
dequantize_block_iq4_xs_reorder(vx, y, ib, (int) item_ct1.get_local_id(0), nb);
|
||||
GGML_UNUSED(scales_local);
|
||||
});
|
||||
break;
|
||||
}
|
||||
get_rows_sycl<QK_K, 1, dequantize_iq4_xs>(ctx, dst->src[0], dst->src[1], dst, (const float *)dst->src[0]->data,
|
||||
src1_i32, (float *)dst->data, ctx.stream());
|
||||
break;
|
||||
|
||||
@@ -832,6 +832,8 @@ ggml_backend_sycl_buffer_init_tensor(ggml_backend_buffer_t buffer,
|
||||
case GGML_TYPE_Q6_K:
|
||||
case GGML_TYPE_IQ3_XXS:
|
||||
case GGML_TYPE_IQ3_S:
|
||||
case GGML_TYPE_IQ4_NL:
|
||||
case GGML_TYPE_IQ4_XS:
|
||||
case GGML_TYPE_MXFP4:{
|
||||
ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu{};
|
||||
tensor->extra = extra;
|
||||
@@ -4386,6 +4388,8 @@ inline bool ggml_sycl_supports_reorder_mmvq(enum ggml_type type) {
|
||||
case GGML_TYPE_Q6_K:
|
||||
case GGML_TYPE_IQ3_XXS:
|
||||
case GGML_TYPE_IQ3_S:
|
||||
case GGML_TYPE_IQ4_NL:
|
||||
case GGML_TYPE_IQ4_XS:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
@@ -4975,6 +4979,20 @@ static bool reorder_qw_iq3_xxs(uint8_t * data_device, size_t size, dpct::queue_p
|
||||
}, stream);
|
||||
}
|
||||
|
||||
// IQ4_NL / IQ4_XS: the qs go to the front, everything before them (d, plus the IQ4_XS scales) is the block's
|
||||
// record in the tail
|
||||
template <typename block_t>
|
||||
static bool reorder_qw_iq4(uint8_t * data_device, size_t size, dpct::queue_ptr stream) {
|
||||
constexpr size_t record_size = offsetof(block_t, qs);
|
||||
return reorder_qw_planar<block_t>(__func__, data_device, size, record_size, sizeof(block_t) - record_size,
|
||||
[](const block_t & x, int64_t ib, uint8_t * tail, int64_t) {
|
||||
const uint8_t * record = reinterpret_cast<const uint8_t *>(&x);
|
||||
for (size_t j = 0; j < record_size; ++j) {
|
||||
tail[ib * record_size + j] = record[j];
|
||||
}
|
||||
}, stream);
|
||||
}
|
||||
|
||||
static bool reorder_qw(const ggml_tensor * src0, dpct::queue_ptr stream) {
|
||||
uint8_t * data_device = (uint8_t *) src0->data;
|
||||
size_t ncols = src0->ne[0];
|
||||
@@ -5022,6 +5040,10 @@ static bool reorder_qw(const ggml_tensor * src0, dpct::queue_ptr stream) {
|
||||
return reorder_qw_iq3_xxs(data_device, size, stream);
|
||||
case GGML_TYPE_IQ3_S:
|
||||
return reorder_qw_iq3_s(data_device, size, stream);
|
||||
case GGML_TYPE_IQ4_NL:
|
||||
return reorder_qw_iq4<block_iq4_nl>(data_device, size, stream);
|
||||
case GGML_TYPE_IQ4_XS:
|
||||
return reorder_qw_iq4<block_iq4_xs>(data_device, size, stream);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -5384,8 +5406,8 @@ static bool ggml_sycl_mul_mat_glu_fused(ggml_backend_sycl_context & ctx, ggml_cg
|
||||
}
|
||||
|
||||
// gate and up of one type the XMX kernel handles, it needs the reorder layout like the unfused mmvq path
|
||||
if (wg->type == wu->type && gate->src[1] == act && act->ne[1] >= ggml_sycl_xmx_min_cols(wu->type) &&
|
||||
act->ne[1] <= g_ggml_sycl_xmx_glu_max_cols) {
|
||||
if (wg->type == wu->type && ggml_sycl_xmx_supports_type(wu->type) && gate->src[1] == act &&
|
||||
act->ne[1] >= ggml_sycl_xmx_min_cols(wu->type) && act->ne[1] <= g_ggml_sycl_xmx_glu_max_cols) {
|
||||
opt_for_reorder(&ctx, wu, act, up, mul_mat_algo::MMVQ);
|
||||
opt_for_reorder(&ctx, wg, act, gate, mul_mat_algo::MMVQ);
|
||||
if (can_use_xmx_batch(ctx.device, wu, act) && can_use_xmx_batch(ctx.device, wg, act) &&
|
||||
@@ -6708,6 +6730,12 @@ static void ggml_backend_sycl_graph_compute_impl(ggml_backend_sycl_context * syc
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (node->op == GGML_OP_ADD &&
|
||||
ggml_sycl_can_fuse(cgraph, i, { GGML_OP_ADD, GGML_OP_RMS_NORM, GGML_OP_MUL }, {}) &&
|
||||
ggml_sycl_op_add_rms_norm_fused(*sycl_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2])) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (node->op == GGML_OP_RMS_NORM &&
|
||||
ggml_sycl_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD }, {})) {
|
||||
ggml_sycl_op_rms_norm_fused_add(*sycl_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]);
|
||||
|
||||
+57
-23
@@ -1776,10 +1776,11 @@ static void mul_mat_vec_iq3_xxs_q8_1_sycl(const void *vx, const void *vy,
|
||||
}
|
||||
|
||||
template <ggml_type type>
|
||||
static void reorder_mul_mat_vec_iq3_q8_1_sycl(const void * vx, const void * vy, float * dst, const int ncols,
|
||||
const int nrows, dpct::queue_ptr stream) {
|
||||
static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S);
|
||||
GGML_ASSERT(ncols % QK_K == 0);
|
||||
static void reorder_mul_mat_vec_iq_q8_1_sycl(const void * vx, const void * vy, float * dst, const int ncols,
|
||||
const int nrows, dpct::queue_ptr stream) {
|
||||
static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL ||
|
||||
type == GGML_TYPE_IQ4_XS);
|
||||
GGML_ASSERT(ncols % ggml_sycl_reordered::block_q_t<type>::traits::qk == 0);
|
||||
constexpr size_t num_subgroups = WARP_SIZE;
|
||||
const int block_num_y = ceil_div(nrows, GGML_SYCL_MMV_Y * (int) num_subgroups);
|
||||
const sycl::range<3> block_nums(1, 1, block_num_y);
|
||||
@@ -1795,13 +1796,14 @@ static void reorder_mul_mat_vec_iq3_q8_1_sycl(const void * vx, const void * vy,
|
||||
}
|
||||
|
||||
template <ggml_type type, int ncols_dst>
|
||||
static void reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(
|
||||
static void reorder_mul_mat_vec_iq_q8_1_sycl_ncols(
|
||||
const void * vx, const void * vy, float * dst,
|
||||
const int ncols, const int nrows,
|
||||
const int stride_col_y_bytes, const int stride_col_dst,
|
||||
dpct::queue_ptr stream) {
|
||||
static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S);
|
||||
GGML_ASSERT(ncols % QK_K == 0);
|
||||
static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL ||
|
||||
type == GGML_TYPE_IQ4_XS);
|
||||
GGML_ASSERT(ncols % ggml_sycl_reordered::block_q_t<type>::traits::qk == 0);
|
||||
constexpr size_t num_subgroups = WARP_SIZE;
|
||||
const int block_num_y = ceil_div(nrows, GGML_SYCL_MMV_Y * (int) num_subgroups);
|
||||
const sycl::range<3> block_nums(1, 1, block_num_y);
|
||||
@@ -1818,21 +1820,21 @@ static void reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(
|
||||
}
|
||||
|
||||
template <ggml_type type>
|
||||
static void reorder_mul_mat_vec_iq3_q8_1_sycl_switch_ncols(
|
||||
static void reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols(
|
||||
const void * vx, const void * vy, float * dst,
|
||||
const int ncols, const int nrows, const int ncols_dst,
|
||||
const int stride_col_y_bytes, const int stride_col_dst,
|
||||
dpct::queue_ptr stream) {
|
||||
switch (ncols_dst) {
|
||||
case 1: reorder_mul_mat_vec_iq3_q8_1_sycl<type>(vx, vy, dst, ncols, nrows, stream); break;
|
||||
case 2: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols<type, 2>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 3: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols<type, 3>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 4: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols<type, 4>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 5: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols<type, 5>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 6: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols<type, 6>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 7: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols<type, 7>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 8: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols<type, 8>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
default: GGML_ABORT("unsupported ncols_dst=%d for reordered IQ3 multi-col MMVQ", ncols_dst);
|
||||
case 1: reorder_mul_mat_vec_iq_q8_1_sycl<type>(vx, vy, dst, ncols, nrows, stream); break;
|
||||
case 2: reorder_mul_mat_vec_iq_q8_1_sycl_ncols<type, 2>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 3: reorder_mul_mat_vec_iq_q8_1_sycl_ncols<type, 3>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 4: reorder_mul_mat_vec_iq_q8_1_sycl_ncols<type, 4>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 5: reorder_mul_mat_vec_iq_q8_1_sycl_ncols<type, 5>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 6: reorder_mul_mat_vec_iq_q8_1_sycl_ncols<type, 6>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 7: reorder_mul_mat_vec_iq_q8_1_sycl_ncols<type, 7>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
case 8: reorder_mul_mat_vec_iq_q8_1_sycl_ncols<type, 8>(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break;
|
||||
default: GGML_ABORT("unsupported ncols_dst=%d for reordered IQ multi-col MMVQ", ncols_dst);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2518,13 +2520,13 @@ void ggml_sycl_op_mul_mat_vec_q(ggml_backend_sycl_context & ctx, const ggml_tens
|
||||
const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs;
|
||||
const int stride_col_dst = dst->ne[0];
|
||||
GGML_SYCL_DEBUG("Calling reordered IQ3_XXS multi-col MMVQ ncols=%d\n", (int) src1_ncols);
|
||||
reorder_mul_mat_vec_iq3_q8_1_sycl_switch_ncols<GGML_TYPE_IQ3_XXS>(
|
||||
reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols<GGML_TYPE_IQ3_XXS>(
|
||||
src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff,
|
||||
src1_ncols, stride_col_y_bytes, stride_col_dst, stream);
|
||||
return;
|
||||
} else {
|
||||
GGML_SYCL_DEBUG("Calling reordered IQ3_XXS MMVQ\n");
|
||||
reorder_mul_mat_vec_iq3_q8_1_sycl<GGML_TYPE_IQ3_XXS>(
|
||||
reorder_mul_mat_vec_iq_q8_1_sycl<GGML_TYPE_IQ3_XXS>(
|
||||
src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream);
|
||||
}
|
||||
} else {
|
||||
@@ -2539,13 +2541,13 @@ void ggml_sycl_op_mul_mat_vec_q(ggml_backend_sycl_context & ctx, const ggml_tens
|
||||
const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs;
|
||||
const int stride_col_dst = dst->ne[0];
|
||||
GGML_SYCL_DEBUG("Calling reordered IQ3_S multi-col MMVQ ncols=%d\n", (int) src1_ncols);
|
||||
reorder_mul_mat_vec_iq3_q8_1_sycl_switch_ncols<GGML_TYPE_IQ3_S>(
|
||||
reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols<GGML_TYPE_IQ3_S>(
|
||||
src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff,
|
||||
src1_ncols, stride_col_y_bytes, stride_col_dst, stream);
|
||||
return;
|
||||
} else {
|
||||
GGML_SYCL_DEBUG("Calling reordered IQ3_S MMVQ\n");
|
||||
reorder_mul_mat_vec_iq3_q8_1_sycl<GGML_TYPE_IQ3_S>(
|
||||
reorder_mul_mat_vec_iq_q8_1_sycl<GGML_TYPE_IQ3_S>(
|
||||
src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream);
|
||||
}
|
||||
} else if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) {
|
||||
@@ -2561,10 +2563,42 @@ void ggml_sycl_op_mul_mat_vec_q(ggml_backend_sycl_context & ctx, const ggml_tens
|
||||
}
|
||||
break;
|
||||
case GGML_TYPE_IQ4_NL:
|
||||
mul_mat_vec_iq4_nl_q8_1_sycl(src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream);
|
||||
if ((ggml_tensor_extra_gpu *) dst->src[0]->extra &&
|
||||
((ggml_tensor_extra_gpu *) dst->src[0]->extra)->optimized_feature.reorder) {
|
||||
if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) {
|
||||
const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs;
|
||||
const int stride_col_dst = dst->ne[0];
|
||||
GGML_SYCL_DEBUG("Calling reordered IQ4_NL multi-col MMVQ ncols=%d\n", (int) src1_ncols);
|
||||
reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols<GGML_TYPE_IQ4_NL>(
|
||||
src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff,
|
||||
src1_ncols, stride_col_y_bytes, stride_col_dst, stream);
|
||||
return;
|
||||
} else {
|
||||
GGML_SYCL_DEBUG("Calling reordered IQ4_NL MMVQ\n");
|
||||
reorder_mul_mat_vec_iq_q8_1_sycl<GGML_TYPE_IQ4_NL>(
|
||||
src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream);
|
||||
}
|
||||
} else {
|
||||
mul_mat_vec_iq4_nl_q8_1_sycl(src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream);
|
||||
}
|
||||
break;
|
||||
case GGML_TYPE_IQ4_XS:
|
||||
if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) {
|
||||
if ((ggml_tensor_extra_gpu *) dst->src[0]->extra &&
|
||||
((ggml_tensor_extra_gpu *) dst->src[0]->extra)->optimized_feature.reorder) {
|
||||
if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) {
|
||||
const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs;
|
||||
const int stride_col_dst = dst->ne[0];
|
||||
GGML_SYCL_DEBUG("Calling reordered IQ4_XS multi-col MMVQ ncols=%d\n", (int) src1_ncols);
|
||||
reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols<GGML_TYPE_IQ4_XS>(
|
||||
src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff,
|
||||
src1_ncols, stride_col_y_bytes, stride_col_dst, stream);
|
||||
return;
|
||||
} else {
|
||||
GGML_SYCL_DEBUG("Calling reordered IQ4_XS MMVQ\n");
|
||||
reorder_mul_mat_vec_iq_q8_1_sycl<GGML_TYPE_IQ4_XS>(
|
||||
src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream);
|
||||
}
|
||||
} else if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) {
|
||||
const int stride_col_y = src1_padded_col_size / QK8_1;
|
||||
const int stride_col_dst = dst->ne[0];
|
||||
GGML_SYCL_DEBUG("Calling mul_mat_vec_iq4_xs_q8_1_sycl_switch_ncols ncols=%d\n", (int)src1_ncols);
|
||||
|
||||
+176
-14
@@ -1,4 +1,6 @@
|
||||
#include "norm.hpp"
|
||||
|
||||
#include "fusion.hpp"
|
||||
#include "ggml-sycl/common.hpp"
|
||||
#include "ggml-sycl/presets.hpp"
|
||||
|
||||
@@ -188,9 +190,28 @@ static void rms_norm_f32(const float* x, float* dst, const int ncols,
|
||||
|
||||
float tmp = 0.0f; // partial sum for thread in warp
|
||||
|
||||
for (int col = tid; col < ncols; col += block_size) {
|
||||
const float xi = x[col * src_stride_col];
|
||||
tmp += xi * xi;
|
||||
// float4 path for contiguous, 16-byte aligned rows (decode), views and odd lengths stay strided
|
||||
bool contig = src_stride_col == 1 && dst_stride_col == 1 && ncols % 4 == 0 && (uintptr_t) x % 16 == 0 &&
|
||||
(uintptr_t) dst % 16 == 0;
|
||||
if constexpr (do_multiply) {
|
||||
contig = contig && (uintptr_t) mul % 16 == 0;
|
||||
}
|
||||
if constexpr (do_add) {
|
||||
contig = contig && (uintptr_t) add % 16 == 0;
|
||||
}
|
||||
const int n4 = ncols / 4;
|
||||
|
||||
if (contig) {
|
||||
const sycl::float4 * x4 = reinterpret_cast<const sycl::float4 *>(x);
|
||||
for (int i = tid; i < n4; i += block_size) {
|
||||
const sycl::float4 v = x4[i];
|
||||
tmp += sycl::dot(v, v);
|
||||
}
|
||||
} else {
|
||||
for (int col = tid; col < ncols; col += block_size) {
|
||||
const float xi = x[col * src_stride_col];
|
||||
tmp += xi * xi;
|
||||
}
|
||||
}
|
||||
|
||||
// sum up partial sums
|
||||
@@ -216,17 +237,37 @@ static void rms_norm_f32(const float* x, float* dst, const int ncols,
|
||||
const float mean = tmp / ncols;
|
||||
const float scale = sycl::rsqrt(mean + eps);
|
||||
|
||||
for (int col = tid; col < ncols; col += block_size) {
|
||||
if constexpr (do_multiply && do_add) {
|
||||
dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col] + add[col];
|
||||
} else if constexpr (do_multiply) {
|
||||
dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col];
|
||||
} else {
|
||||
// folded epilogue of a fused GGML_OP_SCALE consumer (qwen35 GDN l2 norms);
|
||||
// the explicit temporary keeps the float evaluation order identical to
|
||||
// running rms_norm and scale as two separate kernels
|
||||
const float v = scale * x[col * src_stride_col];
|
||||
dst[col * dst_stride_col] = v * scale_mul;
|
||||
if (contig) {
|
||||
const sycl::float4 * x4 = reinterpret_cast<const sycl::float4 *>(x);
|
||||
sycl::float4 * d4 = reinterpret_cast<sycl::float4 *>(dst);
|
||||
const sycl::float4 * m4 = reinterpret_cast<const sycl::float4 *>(mul);
|
||||
const sycl::float4 * a4 = reinterpret_cast<const sycl::float4 *>(add);
|
||||
for (int i = tid; i < n4; i += block_size) {
|
||||
const sycl::float4 v = x4[i];
|
||||
if constexpr (do_multiply && do_add) {
|
||||
const sycl::float4 m = m4[i];
|
||||
const sycl::float4 a = a4[i];
|
||||
d4[i] = scale * v * m + a;
|
||||
} else if constexpr (do_multiply) {
|
||||
const sycl::float4 m = m4[i];
|
||||
d4[i] = scale * v * m;
|
||||
} else {
|
||||
d4[i] = scale * v * scale_mul;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (int col = tid; col < ncols; col += block_size) {
|
||||
if constexpr (do_multiply && do_add) {
|
||||
dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col] + add[col];
|
||||
} else if constexpr (do_multiply) {
|
||||
dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col];
|
||||
} else {
|
||||
// folded epilogue of a fused GGML_OP_SCALE consumer (qwen35 GDN l2 norms);
|
||||
// the explicit temporary keeps the float evaluation order identical to
|
||||
// running rms_norm and scale as two separate kernels
|
||||
const float v = scale * x[col * src_stride_col];
|
||||
dst[col * dst_stride_col] = v * scale_mul;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -918,6 +959,127 @@ void ggml_sycl_op_rms_norm_fused_add(ggml_backend_sycl_context & ctx, ggml_tenso
|
||||
add_s01, add_s02, add_s03, add_nrows, add_nchannels, add_nsamples, eps, main_stream, ctx.device);
|
||||
}
|
||||
|
||||
// ADD(a, b) -> RMS_NORM -> MUL(w) in one launch. The sum (read by a later residual add) and
|
||||
// normed * w are written after a barrier, as mul->data may alias a.
|
||||
static void add_rms_norm_mul_f32(const float * a,
|
||||
const float * b,
|
||||
float * sum,
|
||||
const float * mul,
|
||||
float * dst,
|
||||
const int ncols,
|
||||
const float eps,
|
||||
const sycl::nd_item<3> & item_ct1,
|
||||
float * s_sum,
|
||||
const int block_size) {
|
||||
const int row = item_ct1.get_group(2);
|
||||
const size_t off = (size_t) row * ncols;
|
||||
const int tid = item_ct1.get_local_id(2);
|
||||
const int n4 = ncols / 4;
|
||||
|
||||
const sycl::float4 * a4 = reinterpret_cast<const sycl::float4 *>(a + off);
|
||||
const sycl::float4 * b4 = reinterpret_cast<const sycl::float4 *>(b + off);
|
||||
|
||||
sycl::float4 v[2];
|
||||
float tmp = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
const int i = tid + k * block_size;
|
||||
if (i < n4) {
|
||||
const sycl::float4 va = a4[i];
|
||||
const sycl::float4 vb = b4[i];
|
||||
v[k] = va + vb;
|
||||
tmp += sycl::dot(v[k], v[k]);
|
||||
}
|
||||
}
|
||||
|
||||
const int nwarps = block_size / WARP_SIZE;
|
||||
tmp = warp_reduce_sum(tmp, item_ct1);
|
||||
if (block_size > WARP_SIZE) {
|
||||
const auto sub_group = item_ct1.get_sub_group();
|
||||
if (sub_group.get_local_linear_id() == 0) {
|
||||
s_sum[sub_group.get_group_linear_id()] = tmp;
|
||||
}
|
||||
item_ct1.barrier(sycl::access::fence_space::local_space);
|
||||
const size_t nreduce = ceil_div(nwarps, WARP_SIZE);
|
||||
tmp = 0.0f;
|
||||
for (size_t i = 0; i < nreduce; i += 1) {
|
||||
tmp += s_sum[sub_group.get_local_linear_id() + i * WARP_SIZE];
|
||||
}
|
||||
tmp = warp_reduce_sum(tmp, item_ct1);
|
||||
}
|
||||
|
||||
const float mean = tmp / ncols;
|
||||
const float scale = sycl::rsqrt(mean + eps);
|
||||
|
||||
sycl::float4 * s4 = reinterpret_cast<sycl::float4 *>(sum + off);
|
||||
sycl::float4 * d4 = reinterpret_cast<sycl::float4 *>(dst + off);
|
||||
const sycl::float4 * m4 = reinterpret_cast<const sycl::float4 *>(mul);
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
const int i = tid + k * block_size;
|
||||
if (i < n4) {
|
||||
const sycl::float4 m = m4[i];
|
||||
const sycl::float4 u = scale * v[k] * m;
|
||||
s4[i] = v[k];
|
||||
d4[i] = u;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void add_rms_norm_mul_f32_sycl(const float * a,
|
||||
const float * b,
|
||||
float * sum,
|
||||
const float * mul,
|
||||
float * dst,
|
||||
const int ncols,
|
||||
const int nrows,
|
||||
const float eps,
|
||||
queue_ptr stream,
|
||||
int device) {
|
||||
const int work_group_size = ggml_sycl_info().max_work_group_sizes[device];
|
||||
GGML_ASSERT(work_group_size % (WARP_SIZE * WARP_SIZE) == 0);
|
||||
const sycl::range<3> global_dims(1, 1, nrows);
|
||||
const sycl::range<3> block_dims(1, 1, work_group_size);
|
||||
stream->submit([&](sycl::handler & cgh) {
|
||||
sycl::local_accessor<float, 1> s_sum(sycl::range<1>(work_group_size / WARP_SIZE), cgh);
|
||||
cgh.parallel_for(sycl::nd_range<3>(global_dims * block_dims, block_dims),
|
||||
[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
|
||||
add_rms_norm_mul_f32(a, b, sum, mul, dst, ncols, eps, item_ct1, get_pointer(s_sum),
|
||||
work_group_size);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
bool ggml_sycl_op_add_rms_norm_fused(ggml_backend_sycl_context & ctx,
|
||||
ggml_tensor * add,
|
||||
ggml_tensor * rms,
|
||||
ggml_tensor * mul) {
|
||||
ggml_tensor * a = add->src[0];
|
||||
ggml_tensor * b = add->src[1];
|
||||
ggml_tensor * w = mul->src[0] == rms ? mul->src[1] : mul->src[0];
|
||||
const int64_t ncols = add->ne[0];
|
||||
const int wg = ggml_sycl_info().max_work_group_sizes[ctx.device];
|
||||
// whole rows of float4, at most two per work-item, from 16-byte aligned contiguous tensors
|
||||
if (add->ne[2] != 1 || add->ne[3] != 1 || ncols < 1024 || ncols % 4 != 0 || ncols > 8 * (int64_t) wg ||
|
||||
w->ne[1] != 1) {
|
||||
return false;
|
||||
}
|
||||
for (const ggml_tensor * t : { a, b, add, mul, w }) {
|
||||
if (!ggml_is_contiguous(t) || (uintptr_t) t->data % 16 != 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
float eps = 0.0f;
|
||||
memcpy(&eps, rms->op_params, sizeof(float));
|
||||
if (!(eps >= 0.0f)) {
|
||||
return false;
|
||||
}
|
||||
add_rms_norm_mul_f32_sycl((const float *) a->data, (const float *) b->data, (float *) add->data,
|
||||
(const float *) w->data, (float *) mul->data, (int) ncols, (int) add->ne[1], eps,
|
||||
ctx.stream(), ctx.device);
|
||||
return true;
|
||||
}
|
||||
|
||||
void ggml_sycl_op_rms_norm_back(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
|
||||
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/2);
|
||||
|
||||
|
||||
@@ -25,6 +25,11 @@ void ggml_sycl_op_rms_norm_scale_fused(ggml_backend_sycl_context& ctx, ggml_tens
|
||||
|
||||
void ggml_sycl_op_rms_norm_fused_add(ggml_backend_sycl_context& ctx, ggml_tensor* dst, ggml_tensor* mul_tensor, ggml_tensor* add_tensor);
|
||||
|
||||
bool ggml_sycl_op_add_rms_norm_fused(ggml_backend_sycl_context & ctx,
|
||||
ggml_tensor * add,
|
||||
ggml_tensor * rms,
|
||||
ggml_tensor * mul);
|
||||
|
||||
void ggml_sycl_op_rms_norm_back(ggml_backend_sycl_context& ctx, ggml_tensor* dst);
|
||||
|
||||
void ggml_sycl_op_group_norm(ggml_backend_sycl_context& ctx, ggml_tensor* dst);
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#ifndef GGML_SYCL_QUANTS_HPP
|
||||
#define GGML_SYCL_QUANTS_HPP
|
||||
|
||||
#include <cstddef>
|
||||
#include <utility>
|
||||
|
||||
#include "ggml-common.h"
|
||||
@@ -225,6 +226,70 @@ template <> struct block_q_t<GGML_TYPE_IQ3_S> {
|
||||
static constexpr int block_to_q8_1_ratio() { return traits::qk / QK8_1; }
|
||||
};
|
||||
|
||||
template <> struct block_q_t<GGML_TYPE_IQ4_NL> {
|
||||
struct traits {
|
||||
static constexpr uint32_t qk = QK4_NL;
|
||||
static constexpr uint32_t qi = QI4_NL;
|
||||
static constexpr uint32_t qr = QR4_NL;
|
||||
static constexpr uint32_t vdr_mmvq = 4;
|
||||
};
|
||||
|
||||
// Reordered layout: [qs (QK4_NL/2 per block)][d]
|
||||
static constexpr int record_size = offsetof(block_iq4_nl, qs);
|
||||
|
||||
static constexpr std::pair<int, int> get_block_offset(const int block_index, const int /* nblocks */) {
|
||||
return { block_index * (QK4_NL / 2), 0 };
|
||||
}
|
||||
|
||||
static constexpr std::pair<int, int> get_d_offset(int nrows, int ncols, const int block_index) {
|
||||
return { (ncols / QR4_NL * nrows) + block_index * sizeof(ggml_half), 0 };
|
||||
}
|
||||
|
||||
static float group_scale(const uint8_t * record, const int /* group */) {
|
||||
return *reinterpret_cast<const ggml_half *>(record);
|
||||
}
|
||||
|
||||
static constexpr int block_to_q8_1_ratio() { return traits::qk / QK8_1; }
|
||||
};
|
||||
|
||||
template <> struct block_q_t<GGML_TYPE_IQ4_XS> {
|
||||
struct traits {
|
||||
static constexpr uint32_t qk = QK_K;
|
||||
static constexpr uint32_t qi = QI4_XS;
|
||||
static constexpr uint32_t qr = QR4_XS;
|
||||
static constexpr uint32_t vdr_mmvq = 4;
|
||||
};
|
||||
|
||||
// Reordered layout: [qs (QK_K/2 per block)][{d, scales_h, scales_l} per block, as in block_iq4_xs]
|
||||
static constexpr int record_size = offsetof(block_iq4_xs, qs);
|
||||
|
||||
static constexpr std::pair<int, int> get_block_offset(const int block_index, const int /* nblocks */) {
|
||||
return { block_index * (QK_K / 2), 0 };
|
||||
}
|
||||
|
||||
static constexpr std::pair<int, int> get_d_offset(int nrows, int ncols, const int block_index) {
|
||||
const int nblocks = nrows * (ncols / QK_K);
|
||||
return { nblocks * (QK_K / 2) + block_index * (int) offsetof(block_iq4_xs, qs), 0 };
|
||||
}
|
||||
|
||||
static float group_scale(const uint8_t * record, const int group) {
|
||||
const uint16_t scales_h = *reinterpret_cast<const uint16_t *>(record + offsetof(block_iq4_xs, scales_h));
|
||||
const uint8_t scales_l = record[offsetof(block_iq4_xs, scales_l) + group / 2];
|
||||
const int ls = ((scales_l >> (4 * (group % 2))) & 0xf) | (((scales_h >> (2 * group)) & 3) << 4);
|
||||
return (float) *reinterpret_cast<const ggml_half *>(record + offsetof(block_iq4_xs, d)) * (ls - 32);
|
||||
}
|
||||
|
||||
static constexpr int block_to_q8_1_ratio() { return traits::qk / QK8_1; }
|
||||
};
|
||||
|
||||
// IQ4_NL blocks and IQ4_XS sub-blocks are 32-value groups of 16 qs bytes, so in both layouts the qs of
|
||||
// group g start at 16 * g; tail is the first byte after all qs, where the per-block records start
|
||||
template <ggml_type type> inline float iq4_group_scale(const uint8_t * tail, const int64_t g) {
|
||||
using block_t = block_q_t<type>;
|
||||
constexpr int64_t groups = block_t::traits::qk / QK4_NL;
|
||||
return block_t::group_scale(tail + g / groups * block_t::record_size, (int) (g % groups));
|
||||
}
|
||||
|
||||
template <> struct block_q_t<GGML_TYPE_Q8_0> {
|
||||
struct traits {
|
||||
static constexpr uint32_t qk = QK8_0; // 32
|
||||
|
||||
@@ -388,6 +388,14 @@ template <> struct reorder_vec_dot_shared_weights<GGML_TYPE_Q5_K> {
|
||||
static constexpr bool value = true;
|
||||
};
|
||||
|
||||
template <> struct reorder_vec_dot_shared_weights<GGML_TYPE_IQ4_NL> {
|
||||
static constexpr bool value = true;
|
||||
};
|
||||
|
||||
template <> struct reorder_vec_dot_shared_weights<GGML_TYPE_IQ4_XS> {
|
||||
static constexpr bool value = true;
|
||||
};
|
||||
|
||||
template <ggml_type T> struct reorder_vec_dot_shared_activations {
|
||||
static constexpr bool value = false;
|
||||
};
|
||||
@@ -1956,4 +1964,88 @@ vec_dot_iq4_xs_q8_1(const void *__restrict__ vbq,
|
||||
#endif
|
||||
}
|
||||
|
||||
// IQ4_NL blocks and IQ4_XS sub-blocks are both 32 values in 16 qs bytes: the low nibbles pair with
|
||||
// q8_1 ints 0..3 and the high nibbles with ints 4..7. A lane decodes them once for all columns.
|
||||
struct reorder_vec_dot_iq4_32 {
|
||||
struct weights {
|
||||
int v[8];
|
||||
float d;
|
||||
};
|
||||
|
||||
static __dpct_inline__ weights decode(const uint8_t * qs, const float d) {
|
||||
const sycl::int4 q4 = *reinterpret_cast<const sycl::int4 *>(qs);
|
||||
const uint8_t * values = (const uint8_t *) kvalues_iq4nl;
|
||||
|
||||
weights w;
|
||||
get_int_from_table_16((uint32_t) q4.x(), values, w.v[0], w.v[4]);
|
||||
get_int_from_table_16((uint32_t) q4.y(), values, w.v[1], w.v[5]);
|
||||
get_int_from_table_16((uint32_t) q4.z(), values, w.v[2], w.v[6]);
|
||||
get_int_from_table_16((uint32_t) q4.w(), values, w.v[3], w.v[7]);
|
||||
w.d = d;
|
||||
return w;
|
||||
}
|
||||
|
||||
static __dpct_inline__ float dot32(const weights & w, const int8_t * q8, const sycl::half2 ds8) {
|
||||
const int * u = (const int *) q8;
|
||||
int sumi1 = 0;
|
||||
int sumi2 = 0;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
sumi1 = dpct::dp4a(w.v[j + 0], u[j + 0], sumi1);
|
||||
sumi2 = dpct::dp4a(w.v[j + 4], u[j + 4], sumi2);
|
||||
}
|
||||
return w.d * (float) ds8[0] * (sumi1 + sumi2);
|
||||
}
|
||||
};
|
||||
|
||||
template <> struct reorder_vec_dot_q_sycl<GGML_TYPE_IQ4_NL> : reorder_vec_dot_iq4_32 {
|
||||
static constexpr ggml_type gtype = GGML_TYPE_IQ4_NL;
|
||||
|
||||
// a lane holds a whole block, so iqs is always 0
|
||||
__dpct_inline__ static weights load(const void * __restrict__ vbq, const std::pair<int, int> ibx_offset,
|
||||
const std::pair<int, int> d_offset, const int & /* iqs */) {
|
||||
const uint8_t * base = static_cast<const uint8_t *>(vbq);
|
||||
return decode(base + ibx_offset.first, *reinterpret_cast<const ggml_half *>(base + d_offset.first));
|
||||
}
|
||||
|
||||
__dpct_inline__ static float dot(const weights & w, const int8_t * q8_1_quant_ptr, const sycl::half2 * q8_1_ds,
|
||||
const int & /* iqs */) {
|
||||
return dot32(w, q8_1_quant_ptr, *q8_1_ds);
|
||||
}
|
||||
|
||||
__dpct_inline__ float operator()(const void * __restrict__ vbq, const std::pair<int, int> ibx_offset,
|
||||
const std::pair<int, int> d_offset, const int8_t * q8_1_quant_ptr,
|
||||
const sycl::half2 * q8_1_ds, const int & iqs) {
|
||||
return dot(load(vbq, ibx_offset, d_offset, iqs), q8_1_quant_ptr, q8_1_ds, iqs);
|
||||
}
|
||||
};
|
||||
|
||||
template <> struct reorder_vec_dot_q_sycl<GGML_TYPE_IQ4_XS> : reorder_vec_dot_iq4_32 {
|
||||
static constexpr ggml_type gtype = GGML_TYPE_IQ4_XS;
|
||||
|
||||
// iqs is the first qs int of the lane's sub-block
|
||||
__dpct_inline__ static weights load(const void * __restrict__ vbq, const std::pair<int, int> ibx_offset,
|
||||
const std::pair<int, int> d_offset, const int & iqs) {
|
||||
const uint8_t * base = static_cast<const uint8_t *>(vbq);
|
||||
const uint8_t * meta = base + d_offset.first;
|
||||
const int ib32 = iqs / 4;
|
||||
const uint16_t scales_h = *reinterpret_cast<const uint16_t *>(meta + offsetof(block_iq4_xs, scales_h));
|
||||
const uint8_t scales_l = meta[offsetof(block_iq4_xs, scales_l) + ib32 / 2];
|
||||
const int ls = ((scales_l >> (4 * (ib32 % 2))) & 0xf) | (((scales_h >> (2 * ib32)) & 3) << 4);
|
||||
const float d = (float) *reinterpret_cast<const ggml_half *>(meta + offsetof(block_iq4_xs, d));
|
||||
return decode(base + ibx_offset.first + sizeof(int) * iqs, d * (ls - 32));
|
||||
}
|
||||
|
||||
__dpct_inline__ static float dot(const weights & w, const int8_t * q8_1_quant_ptr, const sycl::half2 * q8_1_ds,
|
||||
const int & iqs) {
|
||||
return dot32(w, q8_1_quant_ptr + (iqs / 4) * QK8_1, q8_1_ds[iqs / 4]);
|
||||
}
|
||||
|
||||
__dpct_inline__ float operator()(const void * __restrict__ vbq, const std::pair<int, int> ibx_offset,
|
||||
const std::pair<int, int> d_offset, const int8_t * q8_1_quant_ptr,
|
||||
const sycl::half2 * q8_1_ds, const int & iqs) {
|
||||
return dot(load(vbq, ibx_offset, d_offset, iqs), q8_1_quant_ptr, q8_1_ds, iqs);
|
||||
}
|
||||
};
|
||||
|
||||
#endif // GGML_SYCL_VECDOTQ_HPP
|
||||
|
||||
@@ -809,9 +809,25 @@ void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t siz
|
||||
return;
|
||||
}
|
||||
|
||||
// vkCmdFillBuffer requires a 4-byte aligned offset and size, so write the unaligned ends from the matching bytes of c
|
||||
const size_t end = offset + size;
|
||||
const size_t begin_aligned = std::min(GGML_PAD(offset, 4), end);
|
||||
const size_t end_aligned = std::max(end - end % 4, begin_aligned);
|
||||
|
||||
const uint8_t * c_bytes = (const uint8_t *) &c;
|
||||
if (begin_aligned > offset) {
|
||||
ggml_vk_buffer_write(dst, offset, c_bytes + offset % 4, begin_aligned - offset);
|
||||
}
|
||||
if (end > end_aligned) {
|
||||
ggml_vk_buffer_write(dst, end_aligned, c_bytes, end - end_aligned);
|
||||
}
|
||||
if (end_aligned == begin_aligned) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
|
||||
vk_context subctx = ggml_vk_begin_sync_ctx(dst->device, dst->device->transfer_queue->cmd_pool);
|
||||
subctx->s->buffer->buf.fillBuffer(dst->buffer, offset, size, c);
|
||||
subctx->s->buffer->buf.fillBuffer(dst->buffer, begin_aligned, end_aligned - begin_aligned, c);
|
||||
ggml_vk_submit_sync(dst->device, subctx);
|
||||
}
|
||||
|
||||
|
||||
@@ -1323,7 +1323,9 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device
|
||||
}
|
||||
|
||||
// Br=32 spills registers, only prefill benefits
|
||||
result.q_in_regs = result.block_rows == coopmat_block_rows && device->vendor_id == VK_VENDOR_ID_AMD && n_rows >= 64;
|
||||
// AMD proprietary driver crashes compiling the loop-indexed Qreg array
|
||||
result.q_in_regs = result.block_rows == coopmat_block_rows && device->vendor_id == VK_VENDOR_ID_AMD && n_rows >= 64 &&
|
||||
device->driver_id != vk::DriverId::eAmdProprietary;
|
||||
|
||||
// Flipped ownership: each subgroup owns 16 Q rows.
|
||||
// uma, nvidia: K/V tiles staged in separate LDS buffers; discrete AMD GQA: K/V loaded directly from global memory.
|
||||
@@ -1355,6 +1357,9 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device
|
||||
result.limit_occupancy_shmem = 14 * 1024 / 16;
|
||||
}
|
||||
|
||||
// non-flip shader handles at most two row tiles
|
||||
GGML_ASSERT(result.flip || result.block_rows <= 2 * coopmat_block_rows);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -14274,7 +14279,9 @@ bool ggml_backend_vk_buffer_cpy_tensor_n(ggml_backend_buffer_t buffer, const ggm
|
||||
void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
|
||||
ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
|
||||
|
||||
ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
|
||||
// set all bytes of a u32 to the same 1 byte value
|
||||
uint32_t val32 = (uint32_t)value * 0x01010101;
|
||||
ggml_vk_buffer_memset(ctx->dev_buffer, 0, val32, buffer->size);
|
||||
}
|
||||
|
||||
const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
|
||||
@@ -17041,7 +17048,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
|
||||
case GGML_OP_SLEEP:
|
||||
return device->shader_clock;
|
||||
case GGML_OP_SCALE:
|
||||
return ggml_is_contiguous(op->src[0]) && ggml_vk_is_float_elementwise(op);
|
||||
return ggml_vk_is_float_elementwise(op);
|
||||
case GGML_OP_PAD:
|
||||
case GGML_OP_PAD_REFLECT_1D:
|
||||
case GGML_OP_ROLL:
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
// These need to be supported N,M values for a MatBc x MatBr x 16 coopmatmuladd
|
||||
const uint32_t MatBr = 16;
|
||||
const uint32_t MatBc = 16;
|
||||
const uint32_t q_tiles = Br / MatBr;
|
||||
|
||||
const uint32_t rows_per_thread = Br / row_split;
|
||||
const uint32_t cols_per_iter = gl_WorkGroupSize.x / row_split;
|
||||
@@ -64,15 +65,14 @@ shared FLOAT_TYPEV4 kvsh[(kvsh_stride >= vsh_stride) ? (Bc * kvsh_stride) : (Bc
|
||||
shared ACC_TYPE slope[Br];
|
||||
|
||||
// row-tiled builds stage the PV result through sfsh
|
||||
const bool PV_IN_SFSH = Br > MatBr;
|
||||
const uint32_t osh_stride = row_split * MatBr / 4;
|
||||
shared O_TYPEV4 pvsh[PV_IN_SFSH ? 2 : Br * osh_stride];
|
||||
shared O_TYPEV4 pvsh[q_tiles > 1 ? 2 : Br * osh_stride];
|
||||
|
||||
shared vec4 occupancy_limiter[LIMIT_OCCUPANCY_SHMEM > 0 ? LIMIT_OCCUPANCY_SHMEM : 1];
|
||||
#if defined(FLOAT16) && !defined(ACC_TYPE_MAX)
|
||||
const uint32_t pv_per_acc = 2;
|
||||
O_TYPEV4 pvsh_load(const uint32_t i) {
|
||||
if (!PV_IN_SFSH) {
|
||||
if (q_tiles == 1) {
|
||||
return pvsh[i];
|
||||
}
|
||||
const uvec2 u = floatBitsToUint(vec2(sfsh[i / 2][(i % 2) * 2], sfsh[i / 2][(i % 2) * 2 + 1]));
|
||||
@@ -81,7 +81,7 @@ O_TYPEV4 pvsh_load(const uint32_t i) {
|
||||
#else
|
||||
const uint32_t pv_per_acc = 1;
|
||||
O_TYPEV4 pvsh_load(const uint32_t i) {
|
||||
if (!PV_IN_SFSH) {
|
||||
if (q_tiles == 1) {
|
||||
return pvsh[i];
|
||||
}
|
||||
return O_TYPEV4(sfsh[i]);
|
||||
@@ -117,7 +117,6 @@ void main() {
|
||||
|
||||
#define tile_row(r) (row_tid * rows_per_thread + (r))
|
||||
|
||||
const uint32_t q_tiles = Br / MatBr;
|
||||
const uint32_t d_tiles = HSK_pad / 16;
|
||||
|
||||
uint32_t q_offset = gqa_iq1*p.nb01 + (iq2*p.nb02+iq3*p.nb03) / 4;
|
||||
@@ -329,10 +328,9 @@ void main() {
|
||||
// K * Q^T -> S^T: Bc x HSK_pad * HSK_pad x Br -> Bc x Br
|
||||
// Bc split across workgroup (four subgroups), loop over HSK in chunks of 16: 16 x 16 * 16 x 16 -> 16 x 16
|
||||
// This is written transposed in order to allow for N being 8 if implementations need it
|
||||
coopmat<ACC_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator> SfMat[q_tiles];
|
||||
[[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) {
|
||||
SfMat[q] = coopmat<ACC_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator>(0);
|
||||
}
|
||||
// No coopmat arrays: AMD's Windows compiler crashes on loop-indexed ones. q_tiles <= 2.
|
||||
coopmat<ACC_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator> SfMat0 = coopmat<ACC_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator>(0);
|
||||
coopmat<ACC_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator> SfMat1 = coopmat<ACC_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator>(0);
|
||||
coopmat<FLOAT_TYPE, gl_ScopeSubgroup, MatBc, 16, gl_MatrixUseA> KMat;
|
||||
coopmat<FLOAT_TYPE, gl_ScopeSubgroup, 16, MatBr, gl_MatrixUseB> QMat;
|
||||
|
||||
@@ -386,19 +384,24 @@ void main() {
|
||||
coopMatLoad(KMat, kvsh, coord, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor);
|
||||
}
|
||||
|
||||
[[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) {
|
||||
if (Q_IN_REGS) {
|
||||
SfMat[q] = coopMatMulAdd(KMat, Qreg[d * q_tiles + q], SfMat[q]);
|
||||
} else {
|
||||
coopMatLoad(QMat, Qf, d * 16 / 4 + q * MatBr * qstride, qstride, gl_CooperativeMatrixLayoutColumnMajor);
|
||||
SfMat[q] = coopMatMulAdd(KMat, QMat, SfMat[q]);
|
||||
if (Q_IN_REGS) {
|
||||
SfMat0 = coopMatMulAdd(KMat, Qreg[d * q_tiles], SfMat0);
|
||||
if (q_tiles > 1) {
|
||||
SfMat1 = coopMatMulAdd(KMat, Qreg[d * q_tiles + 1], SfMat1);
|
||||
}
|
||||
} else {
|
||||
coopMatLoad(QMat, Qf, d * 16 / 4, qstride, gl_CooperativeMatrixLayoutColumnMajor);
|
||||
SfMat0 = coopMatMulAdd(KMat, QMat, SfMat0);
|
||||
if (q_tiles > 1) {
|
||||
coopMatLoad(QMat, Qf, d * 16 / 4 + MatBr * qstride, qstride, gl_CooperativeMatrixLayoutColumnMajor);
|
||||
SfMat1 = coopMatMulAdd(KMat, QMat, SfMat1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) {
|
||||
uint coord = gl_SubgroupID * MatBc * sfshstride + q * (MatBr / 4);
|
||||
coopMatStore(SfMat[q], sfsh, coord, sfshstride, gl_CooperativeMatrixLayoutRowMajor);
|
||||
coopMatStore(SfMat0, sfsh, gl_SubgroupID * MatBc * sfshstride, sfshstride, gl_CooperativeMatrixLayoutRowMajor);
|
||||
if (q_tiles > 1) {
|
||||
coopMatStore(SfMat1, sfsh, gl_SubgroupID * MatBc * sfshstride + MatBr / 4, sfshstride, gl_CooperativeMatrixLayoutRowMajor);
|
||||
}
|
||||
barrier();
|
||||
|
||||
@@ -516,10 +519,8 @@ void main() {
|
||||
[[unroll]] for (uint32_t hsv_tile = 0; hsv_tile < num_hsv_tiles; ++hsv_tile) {
|
||||
const uint hsv_offset = (hsv_tile * row_split + gl_SubgroupID) * 16;
|
||||
|
||||
coopmat<O_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator> PVMat[q_tiles];
|
||||
[[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) {
|
||||
PVMat[q] = coopmat<O_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator>(0);
|
||||
}
|
||||
coopmat<O_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator> PVMat0 = coopmat<O_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator>(0);
|
||||
coopmat<O_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator> PVMat1 = coopmat<O_TYPE, gl_ScopeSubgroup, MatBc, MatBr, gl_MatrixUseAccumulator>(0);
|
||||
|
||||
// Preload V tiles for [Bc, 16 * num subgroups]
|
||||
const uint v_rows = Bc;
|
||||
@@ -584,18 +585,19 @@ void main() {
|
||||
coopMatLoad(QMat, kvsh, v_tile_offset, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor);
|
||||
}
|
||||
|
||||
[[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) {
|
||||
coopMatLoad(KMat, Psh, bc_chunk * MatBc * psh_stride + q * (MatBc / 4), psh_stride, gl_CooperativeMatrixLayoutColumnMajor);
|
||||
PVMat[q] = coopMatMulAdd(KMat, QMat, PVMat[q]);
|
||||
coopMatLoad(KMat, Psh, bc_chunk * MatBc * psh_stride, psh_stride, gl_CooperativeMatrixLayoutColumnMajor);
|
||||
PVMat0 = coopMatMulAdd(KMat, QMat, PVMat0);
|
||||
if (q_tiles > 1) {
|
||||
coopMatLoad(KMat, Psh, bc_chunk * MatBc * psh_stride + MatBc / 4, psh_stride, gl_CooperativeMatrixLayoutColumnMajor);
|
||||
PVMat1 = coopMatMulAdd(KMat, QMat, PVMat1);
|
||||
}
|
||||
}
|
||||
|
||||
[[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) {
|
||||
if (PV_IN_SFSH) {
|
||||
coopMatStore(PVMat[q], sfsh, (o_offset + q * MatBc * osh_stride) / pv_per_acc, osh_stride / pv_per_acc, gl_CooperativeMatrixLayoutRowMajor);
|
||||
} else {
|
||||
coopMatStore(PVMat[q], pvsh, o_offset + q * MatBc * osh_stride, osh_stride, gl_CooperativeMatrixLayoutRowMajor);
|
||||
}
|
||||
if (q_tiles > 1) {
|
||||
coopMatStore(PVMat0, sfsh, o_offset / pv_per_acc, osh_stride / pv_per_acc, gl_CooperativeMatrixLayoutRowMajor);
|
||||
coopMatStore(PVMat1, sfsh, (o_offset + MatBc * osh_stride) / pv_per_acc, osh_stride / pv_per_acc, gl_CooperativeMatrixLayoutRowMajor);
|
||||
} else {
|
||||
coopMatStore(PVMat0, pvsh, o_offset, osh_stride, gl_CooperativeMatrixLayoutRowMajor);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ void main() {
|
||||
continue;
|
||||
}
|
||||
|
||||
data_d[get_doffset() + idx] = FLOAT_TO_D(A_TO_FLOAT(data_a[get_aoffset() + idx]) * FLOAT_TYPE(p.param1) + FLOAT_TYPE(p.param2));
|
||||
data_d[get_doffset() + dst_idx(idx)] = FLOAT_TO_D(A_TO_FLOAT(data_a[get_aoffset() + src0_idx(idx)]) * FLOAT_TYPE(p.param1) + FLOAT_TYPE(p.param2));
|
||||
idx += num_threads;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4066,7 +4066,7 @@ static void ggml_backend_webgpu_buffer_memset_tensor(ggml_backend_buffer_t buffe
|
||||
|
||||
size_t total_offset = ggml_webgpu_tensor_offset(tensor) + offset;
|
||||
|
||||
// This is a trick to set all bytes of a u32 to the same 1 byte value.
|
||||
// set all bytes of a u32 to the same 1 byte value
|
||||
uint32_t val32 = (uint32_t) value * 0x01010101;
|
||||
ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, val32, total_offset, size);
|
||||
WEBGPU_CPU_PROFILE_TOTAL_END(memset_tensor, buf_ctx->global_ctx);
|
||||
@@ -4406,7 +4406,10 @@ static void ggml_backend_webgpu_buffer_clear(ggml_backend_buffer_t buffer, uint8
|
||||
WEBGPU_LOG_DEBUG("ggml_backend_webgpu_buffer_clear(" << buffer << ", " << (uint32_t) value << ")");
|
||||
WEBGPU_CPU_PROFILE_TOTAL_START(clear);
|
||||
ggml_backend_webgpu_buffer_context * buf_ctx = (ggml_backend_webgpu_buffer_context *) buffer->context;
|
||||
ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, value, 0, buffer->size);
|
||||
|
||||
// set all bytes of a u32 to the same 1 byte value
|
||||
uint32_t val32 = (uint32_t) value * 0x01010101;
|
||||
ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, val32, 0, buffer->size);
|
||||
WEBGPU_CPU_PROFILE_TOTAL_END(clear, buf_ctx->global_ctx);
|
||||
}
|
||||
|
||||
@@ -5262,7 +5265,8 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
|
||||
supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 &&
|
||||
src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 &&
|
||||
op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 &&
|
||||
s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
|
||||
s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup &&
|
||||
ggml_are_same_stride(src0, src1);
|
||||
}
|
||||
break;
|
||||
case GGML_OP_CLAMP:
|
||||
|
||||
+26
-2
@@ -1116,9 +1116,11 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = {
|
||||
"GLU",
|
||||
|
||||
"SLEEP",
|
||||
|
||||
"SIGMOID_BACK",
|
||||
};
|
||||
|
||||
static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT != 100");
|
||||
static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101");
|
||||
|
||||
static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = {
|
||||
"none",
|
||||
@@ -1231,9 +1233,11 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = {
|
||||
"glu(x)",
|
||||
|
||||
"sleep(x)",
|
||||
|
||||
"sigmoid_back(x)",
|
||||
};
|
||||
|
||||
static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT != 100");
|
||||
static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101");
|
||||
|
||||
static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2");
|
||||
|
||||
@@ -2866,6 +2870,21 @@ struct ggml_tensor * ggml_silu_back(
|
||||
return result;
|
||||
}
|
||||
|
||||
// ggml_sigmoid_back
|
||||
|
||||
struct ggml_tensor * ggml_sigmoid_back(
|
||||
struct ggml_context * ctx,
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * b) {
|
||||
struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
|
||||
|
||||
result->op = GGML_OP_SIGMOID_BACK;
|
||||
result->src[0] = a;
|
||||
result->src[1] = b;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ggml hardswish
|
||||
|
||||
struct ggml_tensor * ggml_hardswish(
|
||||
@@ -7148,6 +7167,11 @@ static void ggml_compute_backward(
|
||||
ggml_add_or_set(ctx, cgraph, isrc0, ggml_silu_back(ctx, grad, src0));
|
||||
}
|
||||
} break;
|
||||
case GGML_UNARY_OP_SIGMOID: {
|
||||
if (src0_needs_grads) {
|
||||
ggml_add_or_set(ctx, cgraph, isrc0, ggml_sigmoid_back(ctx, grad, src0));
|
||||
}
|
||||
} break;
|
||||
case GGML_UNARY_OP_EXP: {
|
||||
if (src0_needs_grads) {
|
||||
ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, tensor, grad));
|
||||
|
||||
+9
-22
@@ -322,24 +322,6 @@ struct gguf_reader {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read(enum ggml_type & dst) const {
|
||||
int32_t tmp = -1;
|
||||
if (!read(tmp)) {
|
||||
return false;
|
||||
}
|
||||
dst = ggml_type(tmp);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read(enum gguf_type & dst) const {
|
||||
int32_t tmp = -1;
|
||||
if (!read(tmp)) {
|
||||
return false;
|
||||
}
|
||||
dst = gguf_type(tmp);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read(std::string & dst) const {
|
||||
uint64_t size = 0;
|
||||
if (!read(size)) {
|
||||
@@ -555,7 +537,7 @@ static struct gguf_context * gguf_init_from_reader(const struct gguf_reader & gr
|
||||
|
||||
for (int64_t i = 0; ok && i < n_kv; ++i) {
|
||||
std::string key;
|
||||
gguf_type type = gguf_type(-1);
|
||||
int32_t type = -1;
|
||||
bool is_array = false;
|
||||
uint64_t n = 1;
|
||||
|
||||
@@ -724,15 +706,20 @@ static struct gguf_context * gguf_init_from_reader(const struct gguf_reader & gr
|
||||
|
||||
// tensor type
|
||||
{
|
||||
ok = ok && gr.read(info.t.type);
|
||||
int32_t type = -1;
|
||||
ok = ok && gr.read(type);
|
||||
if (!ok) {
|
||||
break;
|
||||
}
|
||||
|
||||
// check that tensor type is within defined range
|
||||
if (info.t.type < 0 || info.t.type >= GGML_TYPE_COUNT) {
|
||||
if (type < 0 || type >= GGML_TYPE_COUNT) {
|
||||
GGML_LOG_ERROR("%s: tensor '%s' has invalid ggml type %d. should be in [0, %d)\n",
|
||||
__func__, info.t.name, info.t.type, GGML_TYPE_COUNT);
|
||||
__func__, info.t.name, type, GGML_TYPE_COUNT);
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
info.t.type = ggml_type(type);
|
||||
const size_t type_size = ggml_type_size(info.t.type);
|
||||
const int64_t blck_size = ggml_blck_size(info.t.type);
|
||||
|
||||
|
||||
@@ -778,6 +778,7 @@ class MODEL_ARCH(IntEnum):
|
||||
NANBEIGE = auto()
|
||||
QWEN3TTS = auto()
|
||||
POCKETTTS = auto()
|
||||
MOSHI = auto()
|
||||
ZONOS3 = auto()
|
||||
KOKORO = auto()
|
||||
TINY_VOCA = auto()
|
||||
@@ -1793,6 +1794,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
|
||||
MODEL_ARCH.NANBEIGE: "nanbeige",
|
||||
MODEL_ARCH.QWEN3TTS: "qwen3tts",
|
||||
MODEL_ARCH.POCKETTTS: "pockettts",
|
||||
MODEL_ARCH.MOSHI: "moshi",
|
||||
MODEL_ARCH.ZONOS3: "zonos3",
|
||||
MODEL_ARCH.KOKORO: "kokoro",
|
||||
MODEL_ARCH.TINY_VOCA: "tiny-voca",
|
||||
@@ -6957,6 +6959,20 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
|
||||
MODEL_TENSOR.FFN_DOWN,
|
||||
MODEL_TENSOR.FFN_UP,
|
||||
],
|
||||
MODEL_ARCH.MOSHI: [
|
||||
MODEL_TENSOR.TOKEN_EMBD,
|
||||
MODEL_TENSOR.OUTPUT_NORM,
|
||||
MODEL_TENSOR.OUTPUT,
|
||||
MODEL_TENSOR.ATTN_NORM,
|
||||
MODEL_TENSOR.ATTN_Q,
|
||||
MODEL_TENSOR.ATTN_K,
|
||||
MODEL_TENSOR.ATTN_V,
|
||||
MODEL_TENSOR.ATTN_OUT,
|
||||
MODEL_TENSOR.FFN_NORM,
|
||||
MODEL_TENSOR.FFN_GATE,
|
||||
MODEL_TENSOR.FFN_DOWN,
|
||||
MODEL_TENSOR.FFN_UP,
|
||||
],
|
||||
MODEL_ARCH.TINY_VOCA: [
|
||||
MODEL_TENSOR.TOKEN_EMBD,
|
||||
MODEL_TENSOR.OUTPUT_NORM,
|
||||
@@ -7514,6 +7530,8 @@ class VisionProjectorType:
|
||||
QWEN3TTS_GEN = "qwen3tts_gen" # audio generation: code_predictor
|
||||
POCKETTTS_SPKENC = "pockettts_spkenc" # audio: mimi encoder as voice-prompt encoder
|
||||
POCKETTTS_GEN = "pockettts_gen" # audio generation: flow-matching decoder + mimi decoder
|
||||
MOSHI = "moshi" # audio: streaming mimi encoder, input audio codes -> backbone rows
|
||||
MOSHI_GEN = "moshi_gen" # audio generation: depformer + mimi decoder
|
||||
CHATTERBOX_SPKENC = "chatterbox_spkenc" # audio: CAMPPlus speaker encoder
|
||||
CHATTERBOX = "chatterbox" # audio generation: s3gen flow matching + HiFT vocoder
|
||||
SOPRANO = "soprano" # audio generation: Vocos decoder
|
||||
|
||||
+4
-2
@@ -73,11 +73,13 @@ Tokens allow grammars to match specific tokenizer tokens rather than character s
|
||||
|
||||
Tokens can be specified in two ways:
|
||||
|
||||
1. **Token ID**: Use angle brackets with the token ID in square brackets: `<[token-id]>`. For example, `<[1000]>` matches the token with ID 1000.
|
||||
1. **Token ID**: Use angle brackets with the token ID in square brackets: `<[token-id]>`. For example, `<[1000]>` matches the token with ID 1000. Multiple IDs and inclusive ranges can be combined: `<[1000,1005-1010]>` matches token 1000 or any token from 1005 to 1010.
|
||||
|
||||
2. **Token string**: Use angle brackets with the token text directly: `<token>`. For example, `<think>` will match the token whose text is exactly `<think>`. This only works if the string tokenizes to exactly one token in the vocabulary, otherwise the grammar will fail to parse.
|
||||
|
||||
You can negate token matches using the `!` prefix: `!<[1000]>` or `!<think>` matches any token *except* the specified one.
|
||||
You can negate token matches using the `!` prefix: `!<[1000]>` or `!<think>` matches any token *except* the specified one, and `!<[1000,1005-1010]>` matches any token outside the set.
|
||||
|
||||
Tokens are matched whole, so a token rule can only match at the start of a token, never after a character rule has consumed part of its text. Any token named by a token rule is also excluded from character rules: once `<think>` appears as a token in a grammar, `.*` in that grammar will not match the `<think>` token.
|
||||
|
||||
```
|
||||
# Match a thinking block: <think>...</think>
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
{{- bos_token -}}
|
||||
{%- set keep_past_thinking = keep_past_thinking | default(false) -%}
|
||||
|
||||
{%- macro format_arg_value(arg_value) -%}
|
||||
{%- if arg_value is string -%}
|
||||
{{- '"' + arg_value + '"' -}}
|
||||
{%- elif arg_value is mapping -%}
|
||||
{{- arg_value | tojson -}}
|
||||
{%- else -%}
|
||||
{{- arg_value | string -}}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{%- macro parse_content(content) -%}
|
||||
{%- if content is string -%}
|
||||
{{- content -}}
|
||||
{%- else -%}
|
||||
{%- set _ns = namespace(result="") -%}
|
||||
{%- for item in content -%}
|
||||
{%- if item.type == "image" -%}
|
||||
{%- set _ns.result = _ns.result + "<image>" -%}
|
||||
{%- elif item.type == "text" -%}
|
||||
{%- set _ns.result = _ns.result + item.text -%}
|
||||
{%- else -%}
|
||||
{%- set _ns.result = _ns.result + item | tojson -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{{- _ns.result -}}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{%- macro render_tool_calls(tool_calls) -%}
|
||||
{%- set tool_calls_ns = namespace(tool_calls=[]) -%}
|
||||
{%- for tool_call in tool_calls -%}
|
||||
{%- set func_name = tool_call.function.name -%}
|
||||
{%- set func_args = tool_call.function.arguments -%}
|
||||
{%- set args_ns = namespace(arg_strings=[]) -%}
|
||||
{%- for arg_name, arg_value in func_args.items() -%}
|
||||
{%- set args_ns.arg_strings = args_ns.arg_strings + [arg_name + "=" + format_arg_value(arg_value)] -%}
|
||||
{%- endfor -%}
|
||||
{%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls + [func_name + "(" + (args_ns.arg_strings | join(", ")) + ")"] -%}
|
||||
{%- endfor -%}
|
||||
{{- "<|tool_call_start|>[" + (tool_calls_ns.tool_calls | join(", ")) + "]<|tool_call_end|>" -}}
|
||||
{%- endmacro -%}
|
||||
|
||||
{%- set ns = namespace(system_prompt="", last_assistant_index=-1) -%}
|
||||
{%- if messages[0].role == "system" -%}
|
||||
{%- if messages[0].content is defined -%}
|
||||
{%- set ns.system_prompt = parse_content(messages[0].content) -%}
|
||||
{%- endif -%}
|
||||
{%- set messages = messages[1:] -%}
|
||||
{%- endif -%}
|
||||
{%- if tools -%}
|
||||
{%- set ns.system_prompt = ns.system_prompt + ("\n\n" if ns.system_prompt else "") + "Today's date: " + strftime_now("%Y-%m-%d") + "\n\nList of tools: " + (tools | tojson) -%}
|
||||
{%- endif -%}
|
||||
{%- if ns.system_prompt -%}
|
||||
{{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}}
|
||||
{%- endif -%}
|
||||
{%- for message in messages -%}
|
||||
{%- if message.role == "assistant" -%}
|
||||
{%- set ns.last_assistant_index = loop.index0 -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- for message in messages -%}
|
||||
{{- "<|im_start|>" + message.role + "\n" -}}
|
||||
{%- if message.role == "assistant" -%}
|
||||
{%- generation -%}
|
||||
{%- if message.thinking is defined and (keep_past_thinking or loop.index0 == ns.last_assistant_index) -%}
|
||||
{{- "<think>" + message.thinking + "</think>" -}}
|
||||
{%- endif -%}
|
||||
{%- if message.tool_calls is defined -%}
|
||||
{{- render_tool_calls(message.tool_calls) -}}
|
||||
{%- endif -%}
|
||||
{%- if message.content is defined -%}
|
||||
{%- set content = parse_content(message.content) -%}
|
||||
{%- if not keep_past_thinking and loop.index0 != ns.last_assistant_index -%}
|
||||
{%- if "</think>" in content -%}
|
||||
{%- set content = content.split("</think>")[-1] | trim -%}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{{- content + ("" if (continue_final_message and loop.last) else "<|im_end|>\n") -}}
|
||||
{%- endif -%}
|
||||
{%- endgeneration -%}
|
||||
{%- else %}
|
||||
{%- if message.content is defined -%}
|
||||
{{- parse_content(message.content) + "<|im_end|>\n" -}}
|
||||
{%- endif -%}
|
||||
{%- endif %}
|
||||
{%- endfor -%}
|
||||
{%- if add_generation_prompt -%}
|
||||
{{- "<|im_start|>assistant\n" -}}
|
||||
{%- endif -%}
|
||||
@@ -69,6 +69,7 @@ These recur often enough in review comments on past add-model PRs that they're w
|
||||
- Before writing a dedicated tool-call/output parser, check whether the existing autoparser already handles the template (`test-chat-auto-parser <jinja>` shows what it detects).
|
||||
- Marking a custom EOS/closing-tag token as `eot` at conversion time isn't always sufficient - in long/agentic generations a model can emit the closing sequence as literal text instead of the token, so generation never stops on EOG and raw text leaks past the parser. Verify this case, not just the token path.
|
||||
- If reusing or aliasing an existing pre-tokenizer for convenience, justify and test that choice explicitly - silent reuse is an easy source of subtle tokenizer bugs.
|
||||
- The GGUF only stores the pre-tokenizer name (`tokenizer.pre`), the behavior flags are hard-coded per name in `src/llama-vocab.cpp`. When adding a new name, set each flag from the HF `tokenizer.json`, not from the case you copied. Examples: `model.ignore_merges` -> `ignore_merges`, the BOS/EOS of the post-processor -> `special_bos_id` / `add_bos`, prefix space and space cleanup -> `add_space_prefix` / `clean_spaces`. The `chkhsh` check in the converter only identifies the pre-tokenizer on a short text, it may not catch a wrong flag.
|
||||
- Watch for excessive graph splits caused by building per-layer view/index tensors inside the layer loop - hoist tensors that don't vary per layer out of the loop (relevant if you hit `GGML_SCHED_MAX_SPLIT_INPUTS`).
|
||||
- A custom KQ mask fed into flash attention must match FA's expected dtype - cast it to F16 before passing it to `build_attn_mha` when FA is enabled.
|
||||
- When padding a custom KV-cache size to an alignment (e.g. `GGML_PAD(..., 256)`), apply the padding after all other size adjustments, not before - otherwise later logic can un-align it again.
|
||||
@@ -83,12 +84,13 @@ These recur often enough in review comments on past add-model PRs that they're w
|
||||
Reference: `examples/model-conversion/README.md`.
|
||||
|
||||
1. Convert to GGUF, then inspect/run both the original and converted tensors.
|
||||
2. Run logits verification (original vs converted). If this model is a new version of an already-supported family, verify the *previous* version still passes logits verification first - numerical differences may be pre-existing, not caused by the new work. The tools to perform full logits validation are available in `examples/model-conversion`.
|
||||
3. Quantize (including QAT variants if relevant) and re-verify.
|
||||
4. Run perplexity evaluation (simple and full).
|
||||
5. Sanity-check across `tools/cli`, `tools/completion`, `tools/imatrix`, `tools/quantize`, and `tools/server`.
|
||||
6. CPU backend first; other backends (CUDA, Metal, ...) can be separate follow-up PRs per `CONTRIBUTING.md`.
|
||||
7. Re-review every changed file against the coding/naming guidelines in `AGENTS.md` (and `CONTRIBUTING.md`'s "Coding guidelines"/"Naming guidelines" sections) - this is a separate pass from functional testing and is just as important: no forced line-wrapping, no unicode punctuation, minimal/non-redundant comments, `snake_case` naming (`kebab-case` for file names), matching indentation/brace style, etc.
|
||||
2. If the model adds a new pre-tokenizer, compare the token ids of `llama-tokenize -f <file> --ids --no-escape` with the HF tokenizer on whole files of prose, code and multilingual text (e.g. wikitext-2 and a few source files).
|
||||
3. Run logits verification (original vs converted). If this model is a new version of an already-supported family, verify the *previous* version still passes logits verification first - numerical differences may be pre-existing, not caused by the new work. The tools to perform full logits validation are available in `examples/model-conversion`.
|
||||
4. Quantize (including QAT variants if relevant) and re-verify.
|
||||
5. Run perplexity evaluation (simple and full).
|
||||
6. Sanity-check across `tools/cli`, `tools/completion`, `tools/imatrix`, `tools/quantize`, and `tools/server`.
|
||||
7. CPU backend first; other backends (CUDA, Metal, ...) can be separate follow-up PRs per `CONTRIBUTING.md`.
|
||||
8. Re-review every changed file against the coding/naming guidelines in `AGENTS.md` (and `CONTRIBUTING.md`'s "Coding guidelines"/"Naming guidelines" sections) - this is a separate pass from functional testing and is just as important: no forced line-wrapping, no unicode punctuation, minimal/non-redundant comments, `snake_case` naming (`kebab-case` for file names), matching indentation/brace style, etc.
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
|
||||
@@ -176,6 +176,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
|
||||
{ LLM_ARCH_NANBEIGE, "nanbeige" },
|
||||
{ LLM_ARCH_QWEN3TTS, "qwen3tts" },
|
||||
{ LLM_ARCH_POCKETTTS, "pockettts" },
|
||||
{ LLM_ARCH_MOSHI, "moshi" },
|
||||
{ LLM_ARCH_ZONOS3, "zonos3" },
|
||||
{ LLM_ARCH_KOKORO, "kokoro" },
|
||||
{ LLM_ARCH_TINY_VOCA, "tiny-voca" },
|
||||
|
||||
@@ -177,6 +177,7 @@ enum llm_arch {
|
||||
LLM_ARCH_NANBEIGE,
|
||||
LLM_ARCH_QWEN3TTS,
|
||||
LLM_ARCH_POCKETTTS,
|
||||
LLM_ARCH_MOSHI,
|
||||
LLM_ARCH_ZONOS3,
|
||||
LLM_ARCH_KOKORO,
|
||||
LLM_ARCH_TINY_VOCA,
|
||||
|
||||
@@ -3143,6 +3143,12 @@ bool llama_context::sched_copy_experts(ggml_backend_t backend, const ggml_tensor
|
||||
return false;
|
||||
}
|
||||
|
||||
// Later loop passes can select different experts from the same device copy.
|
||||
// TODO: copy only the experts needed by each pass (see #32807 and #32809).
|
||||
if (lctx->model.arch == LLM_ARCH_INKLING2_LOOP) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ggml_tensor * ids = node->src[2];
|
||||
if (ggml_nelements(ids) == 0) {
|
||||
return true;
|
||||
|
||||
+165
-51
@@ -7,6 +7,7 @@
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <numeric>
|
||||
#include <stdexcept>
|
||||
@@ -33,9 +34,9 @@ static std::pair<uint32_t, const char *> decode_utf8(const char * src) {
|
||||
return std::make_pair(value, pos);
|
||||
}
|
||||
|
||||
static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
|
||||
const std::string & src,
|
||||
llama_partial_utf8 partial_start) {
|
||||
std::pair<std::vector<uint32_t>, llama_partial_utf8> llama_grammar_decode_utf8(
|
||||
const std::string & src,
|
||||
llama_partial_utf8 partial_start) {
|
||||
static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
|
||||
const char * pos = src.c_str();
|
||||
std::vector<uint32_t> code_points;
|
||||
@@ -185,23 +186,45 @@ static std::pair<uint32_t, const char *> parse_char(const char * src) {
|
||||
throw std::runtime_error("unexpected end of input");
|
||||
}
|
||||
|
||||
static std::pair<uint32_t, const char *> parse_token(const llama_vocab * vocab, const char * src) {
|
||||
static std::pair<uint32_t, const char *> parse_token_id(const char * src) {
|
||||
const char * int_end = parse_int(src);
|
||||
unsigned long id = std::stoul(std::string(src, int_end - src));
|
||||
if (id > std::numeric_limits<uint32_t>::max()) {
|
||||
throw std::runtime_error(std::string("parsed token id is too big at ") + src);
|
||||
}
|
||||
return std::make_pair(static_cast<uint32_t>(id), int_end);
|
||||
}
|
||||
|
||||
static const char * parse_token(const llama_vocab * vocab, const char * src, llama_gretype type, llama_grammar_rule & rule) {
|
||||
const char * pos = src;
|
||||
if (*pos != '<') {
|
||||
throw std::runtime_error(std::string("expecting '<' at ") + pos);
|
||||
}
|
||||
pos++;
|
||||
|
||||
// Parse <[id]>
|
||||
// Parse <[id,id-id,...]>
|
||||
if (*pos == '[') {
|
||||
pos++;
|
||||
const char * int_end = parse_int(pos);
|
||||
unsigned long id = std::stoul(std::string(pos, int_end - pos));
|
||||
if (id > std::numeric_limits<uint32_t>::max()) {
|
||||
throw std::runtime_error(std::string("parsed token id is too big at ") + pos);
|
||||
const size_t start = rule.size();
|
||||
while (true) {
|
||||
auto id_pair = parse_token_id(pos);
|
||||
uint32_t token_id = id_pair.first;
|
||||
pos = id_pair.second;
|
||||
rule.push_back({rule.size() == start ? type : LLAMA_GRETYPE_TOKEN_ALT, token_id});
|
||||
if (*pos == '-') {
|
||||
pos++;
|
||||
auto end_pair = parse_token_id(pos);
|
||||
if (end_pair.first < token_id) {
|
||||
throw std::runtime_error(std::string("invalid token range at ") + pos);
|
||||
}
|
||||
pos = end_pair.second;
|
||||
rule.push_back({LLAMA_GRETYPE_TOKEN_RNG_UPPER, end_pair.first});
|
||||
}
|
||||
if (*pos != ',') {
|
||||
break;
|
||||
}
|
||||
pos++;
|
||||
}
|
||||
uint32_t token_id = static_cast<uint32_t>(id);
|
||||
pos = int_end;
|
||||
if (*pos != ']') {
|
||||
throw std::runtime_error(std::string("expecting ']' at ") + pos);
|
||||
}
|
||||
@@ -210,7 +233,7 @@ static std::pair<uint32_t, const char *> parse_token(const llama_vocab * vocab,
|
||||
throw std::runtime_error(std::string("expecting '>' at ") + pos);
|
||||
}
|
||||
pos++;
|
||||
return std::make_pair(token_id, pos);
|
||||
return pos;
|
||||
}
|
||||
|
||||
if (vocab == nullptr) {
|
||||
@@ -232,7 +255,8 @@ static std::pair<uint32_t, const char *> parse_token(const llama_vocab * vocab,
|
||||
// must tokenize to exactly 1 token
|
||||
throw std::runtime_error("invalid token '" + std::string(src, pos - src) + "'");
|
||||
}
|
||||
return std::make_pair(tokens[0], pos);
|
||||
rule.push_back({type, static_cast<uint32_t>(tokens[0])});
|
||||
return pos;
|
||||
}
|
||||
|
||||
static void print_grammar_char(FILE * file, uint32_t c) {
|
||||
@@ -244,6 +268,16 @@ static void print_grammar_char(FILE * file, uint32_t c) {
|
||||
}
|
||||
}
|
||||
|
||||
static bool is_token_element(llama_grammar_element elem) {
|
||||
switch (elem.type) {
|
||||
case LLAMA_GRETYPE_TOKEN: return true;
|
||||
case LLAMA_GRETYPE_TOKEN_NOT: return true;
|
||||
case LLAMA_GRETYPE_TOKEN_ALT: return true;
|
||||
case LLAMA_GRETYPE_TOKEN_RNG_UPPER: return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
static bool is_char_element(llama_grammar_element elem) {
|
||||
switch (elem.type) {
|
||||
case LLAMA_GRETYPE_CHAR: return true;
|
||||
@@ -258,16 +292,18 @@ static bool is_char_element(llama_grammar_element elem) {
|
||||
static void print_rule_binary(FILE * file, const llama_grammar_rule & rule) {
|
||||
for (auto elem : rule) {
|
||||
switch (elem.type) {
|
||||
case LLAMA_GRETYPE_END: fprintf(file, "END"); break;
|
||||
case LLAMA_GRETYPE_ALT: fprintf(file, "ALT"); break;
|
||||
case LLAMA_GRETYPE_RULE_REF: fprintf(file, "RULE_REF"); break;
|
||||
case LLAMA_GRETYPE_CHAR: fprintf(file, "CHAR"); break;
|
||||
case LLAMA_GRETYPE_CHAR_NOT: fprintf(file, "CHAR_NOT"); break;
|
||||
case LLAMA_GRETYPE_CHAR_RNG_UPPER: fprintf(file, "CHAR_RNG_UPPER"); break;
|
||||
case LLAMA_GRETYPE_CHAR_ALT: fprintf(file, "CHAR_ALT"); break;
|
||||
case LLAMA_GRETYPE_CHAR_ANY: fprintf(file, "CHAR_ANY"); break;
|
||||
case LLAMA_GRETYPE_TOKEN: fprintf(file, "TOKEN"); break;
|
||||
case LLAMA_GRETYPE_TOKEN_NOT: fprintf(file, "TOKEN_NOT"); break;
|
||||
case LLAMA_GRETYPE_END: fprintf(file, "END"); break;
|
||||
case LLAMA_GRETYPE_ALT: fprintf(file, "ALT"); break;
|
||||
case LLAMA_GRETYPE_RULE_REF: fprintf(file, "RULE_REF"); break;
|
||||
case LLAMA_GRETYPE_CHAR: fprintf(file, "CHAR"); break;
|
||||
case LLAMA_GRETYPE_CHAR_NOT: fprintf(file, "CHAR_NOT"); break;
|
||||
case LLAMA_GRETYPE_CHAR_RNG_UPPER: fprintf(file, "CHAR_RNG_UPPER"); break;
|
||||
case LLAMA_GRETYPE_CHAR_ALT: fprintf(file, "CHAR_ALT"); break;
|
||||
case LLAMA_GRETYPE_CHAR_ANY: fprintf(file, "CHAR_ANY"); break;
|
||||
case LLAMA_GRETYPE_TOKEN: fprintf(file, "TOKEN"); break;
|
||||
case LLAMA_GRETYPE_TOKEN_NOT: fprintf(file, "TOKEN_NOT"); break;
|
||||
case LLAMA_GRETYPE_TOKEN_RNG_UPPER: fprintf(file, "TOKEN_RNG_UPPER"); break;
|
||||
case LLAMA_GRETYPE_TOKEN_ALT: fprintf(file, "TOKEN_ALT"); break;
|
||||
}
|
||||
switch (elem.type) {
|
||||
case LLAMA_GRETYPE_END:
|
||||
@@ -295,6 +331,10 @@ static void print_rule_binary(FILE * file, const llama_grammar_rule & rule) {
|
||||
fprintf(file, "%u", elem.value);
|
||||
fprintf(file, "]> ");
|
||||
break;
|
||||
case LLAMA_GRETYPE_TOKEN_RNG_UPPER:
|
||||
case LLAMA_GRETYPE_TOKEN_ALT:
|
||||
fprintf(file, "(%u) ", elem.value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
fprintf(file, "\n");
|
||||
@@ -354,14 +394,32 @@ static void print_rule(
|
||||
case LLAMA_GRETYPE_TOKEN:
|
||||
fprintf(file, "<[");
|
||||
fprintf(file, "%u", elem.value);
|
||||
fprintf(file, "]> ");
|
||||
break;
|
||||
case LLAMA_GRETYPE_TOKEN_NOT:
|
||||
fprintf(file, "!");
|
||||
fprintf(file, "<[");
|
||||
fprintf(file, "%u", elem.value);
|
||||
fprintf(file, "]> ");
|
||||
break;
|
||||
case LLAMA_GRETYPE_TOKEN_RNG_UPPER:
|
||||
if (i == 0 || !is_token_element(rule[i - 1])) {
|
||||
throw std::runtime_error(
|
||||
"LLAMA_GRETYPE_TOKEN_RNG_UPPER without preceding token: " +
|
||||
std::to_string(rule_id) + "," + std::to_string(i));
|
||||
}
|
||||
fprintf(file, "-%u", elem.value);
|
||||
break;
|
||||
case LLAMA_GRETYPE_TOKEN_ALT:
|
||||
if (i == 0 || !is_token_element(rule[i - 1])) {
|
||||
throw std::runtime_error(
|
||||
"LLAMA_GRETYPE_TOKEN_ALT without preceding token: " +
|
||||
std::to_string(rule_id) + "," + std::to_string(i));
|
||||
}
|
||||
fprintf(file, ",%u", elem.value);
|
||||
break;
|
||||
}
|
||||
if (is_token_element(elem) &&
|
||||
rule[i + 1].type != LLAMA_GRETYPE_TOKEN_ALT && rule[i + 1].type != LLAMA_GRETYPE_TOKEN_RNG_UPPER) {
|
||||
fprintf(file, "]> ");
|
||||
}
|
||||
if (is_char_element(elem)) {
|
||||
switch (rule[i + 1].type) {
|
||||
@@ -587,11 +645,9 @@ const char * llama_grammar_parser::parse_sequence(
|
||||
type = LLAMA_GRETYPE_TOKEN_NOT;
|
||||
pos++;
|
||||
}
|
||||
auto token_pair = parse_token(vocab, pos);
|
||||
const char * token_end = token_pair.second;
|
||||
last_sym_start = rule.size();
|
||||
n_prev_rules = 1;
|
||||
rule.push_back({type, token_pair.first});
|
||||
const char * token_end = parse_token(vocab, pos, type, rule);
|
||||
pos = parse_space(token_end, is_nested);
|
||||
} else if (is_word_char(*pos)) { // rule reference
|
||||
const char * name_end = parse_name(pos);
|
||||
@@ -854,17 +910,58 @@ static bool llama_grammar_match_partial_char(
|
||||
|
||||
// returns true iff token matches the rule at pos (regular or inverse)
|
||||
// asserts that pos is pointing to a token element
|
||||
static bool llama_grammar_match_token(
|
||||
static std::pair<bool, const llama_grammar_element *> llama_grammar_match_token(
|
||||
const llama_grammar_element * pos,
|
||||
const llama_token token) {
|
||||
GGML_ASSERT(pos->type == LLAMA_GRETYPE_TOKEN || pos->type == LLAMA_GRETYPE_TOKEN_NOT);
|
||||
if (pos->type == LLAMA_GRETYPE_TOKEN) {
|
||||
return pos->value == static_cast<uint32_t>(token);
|
||||
bool is_positive_token = pos->type == LLAMA_GRETYPE_TOKEN;
|
||||
|
||||
GGML_ASSERT(is_positive_token || pos->type == LLAMA_GRETYPE_TOKEN_NOT);
|
||||
|
||||
const uint32_t id = static_cast<uint32_t>(token);
|
||||
|
||||
bool found = false;
|
||||
do {
|
||||
if (pos[1].type == LLAMA_GRETYPE_TOKEN_RNG_UPPER) {
|
||||
// inclusive range, e.g. <[1-5]>
|
||||
found = found || (pos->value <= id && id <= pos[1].value);
|
||||
pos += 2;
|
||||
} else {
|
||||
found = found || pos->value == id;
|
||||
pos += 1;
|
||||
}
|
||||
} while (pos->type == LLAMA_GRETYPE_TOKEN_ALT);
|
||||
|
||||
return std::make_pair(found == is_positive_token, pos);
|
||||
}
|
||||
|
||||
// every token id a token rule names, merged into sorted inclusive ranges
|
||||
static std::vector<std::pair<uint32_t, uint32_t>> llama_grammar_opaque_tokens(const llama_grammar_rules & rules) {
|
||||
std::vector<std::pair<uint32_t, uint32_t>> ranges;
|
||||
for (const auto & rule : rules) {
|
||||
for (size_t i = 0; i < rule.size(); i++) {
|
||||
const auto type = rule[i].type;
|
||||
if (type == LLAMA_GRETYPE_TOKEN || type == LLAMA_GRETYPE_TOKEN_NOT || type == LLAMA_GRETYPE_TOKEN_ALT) {
|
||||
const bool is_range = i + 1 < rule.size() && rule[i + 1].type == LLAMA_GRETYPE_TOKEN_RNG_UPPER;
|
||||
ranges.emplace_back(rule[i].value, is_range ? rule[i + 1].value : rule[i].value);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pos->type == LLAMA_GRETYPE_TOKEN_NOT) {
|
||||
return pos->value != static_cast<uint32_t>(token);
|
||||
std::sort(ranges.begin(), ranges.end());
|
||||
std::vector<std::pair<uint32_t, uint32_t>> merged;
|
||||
for (const auto & r : ranges) {
|
||||
if (!merged.empty() && r.first <= (uint64_t) merged.back().second + 1) {
|
||||
merged.back().second = std::max(merged.back().second, r.second);
|
||||
} else {
|
||||
merged.push_back(r);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return merged;
|
||||
}
|
||||
|
||||
bool llama_grammar_is_opaque(const llama_grammar & grammar, llama_token token) {
|
||||
const auto id = static_cast<uint32_t>(token);
|
||||
auto it = std::upper_bound(grammar.opaque_tokens.begin(), grammar.opaque_tokens.end(), std::make_pair(id, UINT32_MAX));
|
||||
return it != grammar.opaque_tokens.begin() && std::prev(it)->second >= id;
|
||||
}
|
||||
|
||||
// transforms a grammar pushdown stack into N possible stacks, all ending
|
||||
@@ -946,8 +1043,7 @@ static void llama_grammar_advance_stack(
|
||||
break;
|
||||
default:
|
||||
// end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
|
||||
// (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
|
||||
// those
|
||||
// (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER) or token set (LLAMA_GRETYPE_TOKEN_ALT, LLAMA_GRETYPE_TOKEN_RNG_UPPER); stack should never be left on those
|
||||
GGML_ABORT("fatal error");
|
||||
}
|
||||
}
|
||||
@@ -1238,13 +1334,13 @@ static bool llama_grammar_reject_step(
|
||||
if (stack_pos->type == LLAMA_GRETYPE_TOKEN || stack_pos->type == LLAMA_GRETYPE_TOKEN_NOT) {
|
||||
for (const uint32_t i : cur) {
|
||||
const auto & tok = candidates[i];
|
||||
if (tok.code_points[depth] == 0) {
|
||||
// reached the end of a token consumed by char rules, reject iff it ended
|
||||
// in a partial response
|
||||
if (tok.partial_utf8.n_remain != 0) {
|
||||
if (depth > 0) {
|
||||
// char rules already consumed part of this token, so it cannot match by id.
|
||||
// accept it only if they consumed all of it and did not end in a partial sequence.
|
||||
if (tok.code_points[depth] != 0 || tok.partial_utf8.n_remain != 0) {
|
||||
rejects.push_back(i);
|
||||
}
|
||||
} else if (!llama_grammar_match_token(stack_pos, tok.id)) {
|
||||
} else if (tok.partial_utf8.n_remain < 0 || !llama_grammar_match_token(stack_pos, tok.id).first) {
|
||||
rejects.push_back(i);
|
||||
}
|
||||
}
|
||||
@@ -1255,7 +1351,10 @@ static bool llama_grammar_reject_step(
|
||||
|
||||
for (const uint32_t i : cur) {
|
||||
const auto & tok = candidates[i];
|
||||
if (tok.code_points[depth] == 0) {
|
||||
if (tok.opaque) {
|
||||
// a token named by a token rule only matches token rules
|
||||
rejects.push_back(i);
|
||||
} else if (tok.code_points[depth] == 0) {
|
||||
// reached end of full codepoints in token, reject iff it ended in a partial sequence
|
||||
// that cannot satisfy this position in grammar
|
||||
if (tok.partial_utf8.n_remain != 0 &&
|
||||
@@ -1425,6 +1524,8 @@ struct llama_grammar * llama_grammar_init_impl(
|
||||
}
|
||||
} while (true);
|
||||
|
||||
auto opaque_tokens = llama_grammar_opaque_tokens(vec_rules);
|
||||
|
||||
// Important: vec_rules has to be moved here, not copied, because stacks contains
|
||||
// pointers to elements of vec_rules. If vec_rules were copied into llama_grammar
|
||||
// then the pointers would be invalidated when the local vec_rules goes out of scope.
|
||||
@@ -1439,6 +1540,7 @@ struct llama_grammar * llama_grammar_init_impl(
|
||||
/* .trigger_buffer_positions = */ {},
|
||||
/* .trigger_tokens = */ {},
|
||||
/* .trigger_patterns = */ {},
|
||||
/* .opaque_tokens = */ std::move(opaque_tokens),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1540,6 +1642,8 @@ struct llama_grammar * llama_grammar_init_impl(
|
||||
trigger.regex = std::regex(trigger.pattern);
|
||||
}
|
||||
|
||||
auto opaque_tokens = llama_grammar_opaque_tokens(vec_rules);
|
||||
|
||||
// Important: vec_rules has to be moved here, not copied, because stacks contains
|
||||
// pointers to elements of vec_rules. If vec_rules were copied into llama_grammar
|
||||
// then the pointers would be invalidated when the local vec_rules goes out of scope.
|
||||
@@ -1554,6 +1658,7 @@ struct llama_grammar * llama_grammar_init_impl(
|
||||
/* .trigger_buffer_positions = */ {},
|
||||
std::move(vec_trigger_tokens),
|
||||
std::move(vec_trigger_patterns),
|
||||
std::move(opaque_tokens),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1601,8 +1706,9 @@ void llama_grammar_apply_impl(const struct llama_grammar & grammar, llama_token_
|
||||
} else if (piece.empty() || piece[0] == 0) {
|
||||
cur_p->data[i].logit = -INFINITY;
|
||||
} else {
|
||||
candidates_decoded.push_back(decode_utf8(piece, grammar.partial_utf8));
|
||||
candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second, id });
|
||||
candidates_decoded.push_back(llama_grammar_decode_utf8(piece, grammar.partial_utf8));
|
||||
candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second, id,
|
||||
llama_grammar_is_opaque(grammar, id) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1673,7 +1779,7 @@ void llama_grammar_accept_impl(struct llama_grammar & grammar, llama_token token
|
||||
|
||||
void llama_grammar_accept_str(struct llama_grammar & grammar, const std::string & piece) {
|
||||
// Note terminating 0 in decoded string
|
||||
const auto decoded = decode_utf8(piece, grammar.partial_utf8);
|
||||
const auto decoded = llama_grammar_decode_utf8(piece, grammar.partial_utf8);
|
||||
const auto & code_points = decoded.first;
|
||||
|
||||
for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
|
||||
@@ -1688,9 +1794,16 @@ void llama_grammar_accept_str(struct llama_grammar & grammar, const std::string
|
||||
|
||||
void llama_grammar_accept_token(struct llama_grammar & grammar, llama_token token, const std::string & piece) {
|
||||
// Note terminating 0 in decoded string
|
||||
const auto decoded = decode_utf8(piece, grammar.partial_utf8);
|
||||
const auto decoded = llama_grammar_decode_utf8(piece, grammar.partial_utf8);
|
||||
const auto & code_points = decoded.first;
|
||||
|
||||
// the mask rejects a piece that does not continue a partial character, so accepting one has to fail too
|
||||
if (decoded.second.n_remain < 0) {
|
||||
throw std::runtime_error("Invalid UTF-8 continuation in piece: " + piece + " (" + std::to_string(token) + ")");
|
||||
}
|
||||
|
||||
const bool opaque = llama_grammar_is_opaque(grammar, token);
|
||||
|
||||
llama_grammar_stacks stacks_new;
|
||||
stacks_new.reserve(grammar.stacks.size());
|
||||
|
||||
@@ -1702,14 +1815,15 @@ void llama_grammar_accept_token(struct llama_grammar & grammar, llama_token toke
|
||||
const llama_grammar_element * pos = stack.back();
|
||||
|
||||
if (pos->type == LLAMA_GRETYPE_TOKEN || pos->type == LLAMA_GRETYPE_TOKEN_NOT) {
|
||||
if (llama_grammar_match_token(pos, token)) {
|
||||
auto match = llama_grammar_match_token(pos, token);
|
||||
if (match.first) {
|
||||
llama_grammar_stack new_stack(stack.begin(), stack.end() - 1);
|
||||
if (!llama_grammar_is_end_of_sequence(pos + 1)) {
|
||||
new_stack.push_back(pos + 1);
|
||||
if (!llama_grammar_is_end_of_sequence(match.second)) {
|
||||
new_stack.push_back(match.second);
|
||||
}
|
||||
llama_grammar_advance_stack(*grammar.rules, new_stack, stacks_new);
|
||||
}
|
||||
} else {
|
||||
} else if (!opaque) {
|
||||
llama_grammar_stacks current_stacks = {stack};
|
||||
|
||||
for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
|
||||
|
||||
+18
-2
@@ -38,11 +38,17 @@ enum llama_gretype {
|
||||
// any character (.)
|
||||
LLAMA_GRETYPE_CHAR_ANY = 7,
|
||||
|
||||
// terminal element: token (<[token-id]>)
|
||||
// terminal element: token (<[token-id]>, <[token-id,token-id-token-id]>)
|
||||
LLAMA_GRETYPE_TOKEN = 8,
|
||||
|
||||
// inverse token (!<[token-id]>)
|
||||
// inverse token (!<[token-id]>, !<[token-id,token-id-token-id]>)
|
||||
LLAMA_GRETYPE_TOKEN_NOT = 9,
|
||||
|
||||
// modifies a preceding LLAMA_GRETYPE_TOKEN, LLAMA_GRETYPE_TOKEN_NOT, or LLAMA_GRETYPE_TOKEN_ALT to be an inclusive range (<[1-5]>)
|
||||
LLAMA_GRETYPE_TOKEN_RNG_UPPER = 10,
|
||||
|
||||
// modifies a preceding LLAMA_GRETYPE_TOKEN, LLAMA_GRETYPE_TOKEN_NOT, or LLAMA_GRETYPE_TOKEN_RNG_UPPER to add an alternate token to match (<[1,5]>, <[1-5,9]>)
|
||||
LLAMA_GRETYPE_TOKEN_ALT = 11,
|
||||
};
|
||||
|
||||
typedef struct llama_grammar_element {
|
||||
@@ -60,6 +66,7 @@ struct llama_grammar_candidate {
|
||||
const uint32_t * code_points;
|
||||
llama_partial_utf8 partial_utf8;
|
||||
llama_token id;
|
||||
bool opaque;
|
||||
};
|
||||
|
||||
using llama_grammar_rule = std::vector< llama_grammar_element>;
|
||||
@@ -84,6 +91,10 @@ std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
|
||||
const llama_grammar_stack & stack,
|
||||
const llama_grammar_candidates & candidates);
|
||||
|
||||
std::pair<std::vector<uint32_t>, llama_partial_utf8> llama_grammar_decode_utf8(
|
||||
const std::string & src,
|
||||
llama_partial_utf8 partial_start);
|
||||
|
||||
struct llama_grammar_parser {
|
||||
const llama_vocab * vocab;
|
||||
std::map<std::string, uint32_t> symbol_ids;
|
||||
@@ -151,6 +162,8 @@ struct llama_grammar {
|
||||
trigger_patterns; // Regular expressions that trigger a lazy grammar. Must be a full match of the entire generated
|
||||
// string, and the grammar will be given the string from the first match group onwards.
|
||||
|
||||
// token ids named by token rules, as sorted inclusive ranges. char rules never match these tokens.
|
||||
std::vector<std::pair<uint32_t, uint32_t>> opaque_tokens;
|
||||
};
|
||||
|
||||
//
|
||||
@@ -195,3 +208,6 @@ void llama_grammar_accept_token(
|
||||
struct llama_grammar & grammar,
|
||||
llama_token token,
|
||||
const std::string & piece);
|
||||
|
||||
// true if a token rule names the token, char rules do not match it
|
||||
bool llama_grammar_is_opaque(const llama_grammar & grammar, llama_token token);
|
||||
|
||||
+22
-112
@@ -1810,16 +1810,21 @@ ggml_tensor * llm_graph_context::build_lora_mm(
|
||||
ggml_tensor * w,
|
||||
ggml_tensor * cur,
|
||||
ggml_tensor * w_s) const {
|
||||
if (!w_s) {
|
||||
w_s = model.get_w_scale(w);
|
||||
}
|
||||
|
||||
// a Hadamard-folded weight reads the transformed input; a LoRA delta lives in the primal basis and reads `cur`
|
||||
ggml_tensor * cur_mm = build_hadamard_input(w, cur);
|
||||
ggml_tensor * res = ggml_mul_mat(ctx0, w, cur_mm);
|
||||
|
||||
prec_policy.apply(res);
|
||||
|
||||
if (w->type == GGML_TYPE_NVFP4) {
|
||||
ggml_prec_set_acc(res, GGML_PREC_BF16);
|
||||
}
|
||||
|
||||
|
||||
prec_policy.apply(res);
|
||||
|
||||
if (w_s) {
|
||||
res = ggml_mul(ctx0, res, w_s);
|
||||
}
|
||||
@@ -1886,9 +1891,10 @@ ggml_tensor * llm_graph_context::build_lora_mm_id(
|
||||
ggml_tensor * w, // ggml_tensor * as
|
||||
ggml_tensor * cur, // ggml_tensor * b
|
||||
ggml_tensor * ids,
|
||||
ggml_tensor * w_s,
|
||||
ggml_tensor * slots,
|
||||
bool cached) const {
|
||||
ggml_tensor * w_s = model.get_w_scale(w);
|
||||
|
||||
// as in build_lora_mm: the folded weight reads the transformed input, the LoRA delta reads `cur`
|
||||
ggml_tensor * cur_mm = build_hadamard_input(w, cur);
|
||||
// the experts in the MoE cache are selected by their slots
|
||||
@@ -1896,12 +1902,13 @@ ggml_tensor * llm_graph_context::build_lora_mm_id(
|
||||
ggml_mul_mat_id(ctx0, w, cur_mm, ids) :
|
||||
ggml_mul_mat_id(ctx0, cached ? moe_cache->get_experts(w) : w, cur_mm, slots);
|
||||
|
||||
prec_policy.apply(res);
|
||||
|
||||
if (w->type == GGML_TYPE_NVFP4) {
|
||||
ggml_prec_set_acc(res, GGML_PREC_BF16);
|
||||
}
|
||||
|
||||
// after the NVFP4 default, so that the policy can request a higher precision
|
||||
prec_policy.apply(res);
|
||||
|
||||
if (w_s) {
|
||||
const int64_t n_expert = w_s->ne[0];
|
||||
const int64_t n_tokens = cur->ne[2];
|
||||
@@ -2115,34 +2122,7 @@ ggml_tensor * llm_graph_context::build_ffn(
|
||||
int il) const {
|
||||
const llm_arch arch = model.arch;
|
||||
|
||||
// NVFP4 support is currently restricted to
|
||||
// 1) LORA absence (*_s would be applied after LORA residual, which is incorrect)
|
||||
// 2) bias absense (*_s would be applied after bias addition, which is incorrect)
|
||||
// TODO: disambiguate LLM-architectural scales (which use *_s) from NVFP4 scale_2 (which also uses *_s currently)
|
||||
auto has_lora = [this](ggml_tensor * w) {
|
||||
if (!w) {
|
||||
return false;
|
||||
}
|
||||
for (const auto & lora : *loras) {
|
||||
if (lora.first->get_weight(w) != nullptr) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
auto is_scaled_low_precision = [](ggml_tensor * w) {
|
||||
return w && (w->type == GGML_TYPE_NVFP4 || w->type == GGML_TYPE_F8_E4M3);
|
||||
};
|
||||
|
||||
GGML_ASSERT(!up_s || !up_b || !is_scaled_low_precision(up));
|
||||
GGML_ASSERT(!gate_s || !gate_b || !is_scaled_low_precision(gate));
|
||||
GGML_ASSERT(!down_s || !down_b || !is_scaled_low_precision(down));
|
||||
GGML_ASSERT(!up_s || !is_scaled_low_precision(up) || !has_lora(up));
|
||||
GGML_ASSERT(!gate_s || !is_scaled_low_precision(gate) || !has_lora(gate));
|
||||
GGML_ASSERT(!down_s || !is_scaled_low_precision(down) || !has_lora(down));
|
||||
|
||||
ggml_tensor * tmp = up ? build_lora_mm(up, cur) : cur;
|
||||
ggml_tensor * tmp = up ? build_lora_mm(up, cur, up_s) : cur;
|
||||
cb(tmp, "ffn_up", il);
|
||||
|
||||
if (up_b) {
|
||||
@@ -2150,21 +2130,16 @@ ggml_tensor * llm_graph_context::build_ffn(
|
||||
cb(tmp, "ffn_up_b", il);
|
||||
}
|
||||
|
||||
if (up_s) {
|
||||
tmp = ggml_mul(ctx0, tmp, up_s);
|
||||
cb(tmp, "ffn_up_s", il);
|
||||
}
|
||||
|
||||
if (gate) {
|
||||
switch (type_gate) {
|
||||
case LLM_FFN_SEQ:
|
||||
{
|
||||
cur = build_lora_mm(gate, tmp);
|
||||
cur = build_lora_mm(gate, tmp, gate_s);
|
||||
cb(cur, "ffn_gate", il);
|
||||
} break;
|
||||
case LLM_FFN_PAR:
|
||||
{
|
||||
cur = build_lora_mm(gate, cur);
|
||||
cur = build_lora_mm(gate, cur, gate_s);
|
||||
cb(cur, "ffn_gate", il);
|
||||
} break;
|
||||
}
|
||||
@@ -2174,11 +2149,6 @@ ggml_tensor * llm_graph_context::build_ffn(
|
||||
cb(cur, "ffn_gate_b", il);
|
||||
}
|
||||
|
||||
if (gate_s) {
|
||||
cur = ggml_mul(ctx0, cur, gate_s);
|
||||
cb(cur, "ffn_gate_s", il);
|
||||
}
|
||||
|
||||
} else {
|
||||
cur = tmp;
|
||||
}
|
||||
@@ -2300,11 +2270,7 @@ ggml_tensor * llm_graph_context::build_ffn(
|
||||
}
|
||||
|
||||
if (down) {
|
||||
cur = build_lora_mm(down, cur);
|
||||
if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2) {
|
||||
// GLM4, GLM4_MOE, and JAIS2 have numerical issues with F16 accumulators
|
||||
ggml_prec_set_acc(cur, GGML_PREC_BF16);
|
||||
}
|
||||
cur = build_lora_mm(down, cur, down_s);
|
||||
}
|
||||
|
||||
if (down_b) {
|
||||
@@ -2315,11 +2281,6 @@ ggml_tensor * llm_graph_context::build_ffn(
|
||||
cur = ggml_add(ctx0, cur, down_b);
|
||||
}
|
||||
|
||||
if (down_s) {
|
||||
cur = ggml_mul(ctx0, cur, down_s);
|
||||
cb(cur, "ffn_down_s", il);
|
||||
}
|
||||
|
||||
return cur;
|
||||
}
|
||||
|
||||
@@ -2339,9 +2300,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
|
||||
int il,
|
||||
ggml_tensor * probs_in,
|
||||
ggml_tensor * gate_up_exps,
|
||||
ggml_tensor * up_exps_s,
|
||||
ggml_tensor * gate_exps_s,
|
||||
ggml_tensor * down_exps_s,
|
||||
ggml_tensor * selected_experts_in,
|
||||
ggml_tensor * post_exp_norm,
|
||||
float post_exp_norm_eps) const {
|
||||
@@ -2362,9 +2320,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
|
||||
probs_in,
|
||||
gate_up_exps,
|
||||
/* gate_up_exps_b */ nullptr,
|
||||
up_exps_s,
|
||||
gate_exps_s,
|
||||
down_exps_s,
|
||||
selected_experts_in,
|
||||
post_exp_norm,
|
||||
post_exp_norm_eps
|
||||
@@ -2392,9 +2347,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
|
||||
ggml_tensor * probs_in,
|
||||
ggml_tensor * gate_up_exps,
|
||||
ggml_tensor * gate_up_exps_b,
|
||||
ggml_tensor * up_exps_s,
|
||||
ggml_tensor * gate_exps_s,
|
||||
ggml_tensor * down_exps_s,
|
||||
ggml_tensor * selected_experts_in,
|
||||
ggml_tensor * post_exp_norm,
|
||||
float post_exp_norm_eps) const {
|
||||
@@ -2407,10 +2359,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
|
||||
|
||||
if (probs_in == nullptr) {
|
||||
logits = build_lora_mm(gate_inp, cur); // [n_expert, n_tokens]
|
||||
if (gating_op == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) {
|
||||
// the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565
|
||||
ggml_prec_set_acc(logits, GGML_PREC_F32);
|
||||
}
|
||||
cb(logits, "ffn_moe_logits", il);
|
||||
} else {
|
||||
logits = probs_in;
|
||||
@@ -2583,13 +2531,9 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
|
||||
|
||||
if (gate_up_exps) {
|
||||
// merged gate_up path: one mul_mat_id, then split into gate and up views
|
||||
ggml_tensor * gate_up = build_lora_mm_id(gate_up_exps, cur, ids, up_exps_s, mm_ids, cached); // [n_ff*2, n_expert_used, n_tokens]
|
||||
ggml_tensor * gate_up = build_lora_mm_id(gate_up_exps, cur, ids, mm_ids, cached); // [n_ff*2, n_expert_used, n_tokens]
|
||||
cb(gate_up, "ffn_moe_gate_up", il);
|
||||
|
||||
if (up_exps_s) {
|
||||
cb(gate_up, "ffn_moe_gate_up_scaled", il);
|
||||
}
|
||||
|
||||
if (gate_up_exps_b) {
|
||||
gate_up = ggml_add_id(ctx0, gate_up, gate_up_exps_b, ids);
|
||||
cb(gate_up, "ffn_moe_gate_up_biased", il);
|
||||
@@ -2602,29 +2546,21 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
|
||||
cb(up, "ffn_moe_up", il);
|
||||
} else {
|
||||
// separate gate and up path
|
||||
up = build_lora_mm_id(up_exps, cur, ids, up_exps_s, mm_ids, cached); // [n_ff, n_expert_used, n_tokens]
|
||||
up = build_lora_mm_id(up_exps, cur, ids, mm_ids, cached); // [n_ff, n_expert_used, n_tokens]
|
||||
cb(up, "ffn_moe_up", il);
|
||||
|
||||
if (up_exps_s) {
|
||||
cb(up, "ffn_moe_up_scaled", il);
|
||||
}
|
||||
|
||||
if (up_exps_b) {
|
||||
up = ggml_add_id(ctx0, up, up_exps_b, ids);
|
||||
cb(up, "ffn_moe_up_biased", il);
|
||||
}
|
||||
|
||||
if (gate_exps) {
|
||||
cur = build_lora_mm_id(gate_exps, cur, ids, gate_exps_s, mm_ids, cached); // [n_ff, n_expert_used, n_tokens]
|
||||
cur = build_lora_mm_id(gate_exps, cur, ids, mm_ids, cached); // [n_ff, n_expert_used, n_tokens]
|
||||
cb(cur, "ffn_moe_gate", il);
|
||||
} else {
|
||||
cur = up;
|
||||
}
|
||||
|
||||
if (gate_exps_s) {
|
||||
cb(cur, "ffn_moe_gate_scaled", il);
|
||||
}
|
||||
|
||||
if (gate_exps_b) {
|
||||
cur = ggml_add_id(ctx0, cur, gate_exps_b, ids);
|
||||
cb(cur, "ffn_moe_gate_biased", il);
|
||||
@@ -2727,7 +2663,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
|
||||
cur = amax_src1.res;
|
||||
}
|
||||
|
||||
ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, down_exps_s, mm_ids, cached); // [n_embd, n_expert_used, n_tokens]
|
||||
ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, mm_ids, cached); // [n_embd, n_expert_used, n_tokens]
|
||||
//ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // (see TODO above)
|
||||
cb(experts, "ffn_moe_down", il);
|
||||
|
||||
@@ -2745,10 +2681,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
|
||||
return (*static_cast<decltype(build_experts) *>(user_data))(cur, ids, mm_ids, cached);
|
||||
}, &build_experts);
|
||||
|
||||
if (down_exps_s) {
|
||||
cb(experts, "ffn_moe_down_scaled", il);
|
||||
}
|
||||
|
||||
if (down_exps_b) {
|
||||
experts = ggml_add_id(ctx0, experts, down_exps_b, selected_experts);
|
||||
cb(experts, "ffn_moe_down_biased", il);
|
||||
@@ -3485,8 +3417,6 @@ ggml_tensor * llm_graph_context::build_attn(
|
||||
ggml_tensor * v_mla, // TODO: remove
|
||||
float kq_scale,
|
||||
int il) const {
|
||||
const llm_arch arch = model.arch;
|
||||
|
||||
GGML_ASSERT(v_mla == nullptr);
|
||||
|
||||
if (inp->self_k_rot[il]) {
|
||||
@@ -3543,16 +3473,7 @@ ggml_tensor * llm_graph_context::build_attn(
|
||||
}
|
||||
|
||||
if (wo) {
|
||||
if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2) {
|
||||
// GLM4, GLM4_MOE, and JAIS2 have numerical issues with F16 accumulators
|
||||
cur = build_lora_mm(wo, cur);
|
||||
ggml_prec_set_acc(cur, GGML_PREC_BF16);
|
||||
if (wo_s) {
|
||||
cur = ggml_mul(ctx0, cur, wo_s);
|
||||
}
|
||||
} else {
|
||||
cur = build_lora_mm(wo, cur, wo_s);
|
||||
}
|
||||
cur = build_lora_mm(wo, cur, wo_s);
|
||||
}
|
||||
|
||||
if (wo_b) {
|
||||
@@ -3603,8 +3524,6 @@ ggml_tensor * llm_graph_context::build_attn(
|
||||
ggml_tensor * v_mla,
|
||||
float kq_scale,
|
||||
int il) const {
|
||||
const llm_arch arch = model.arch;
|
||||
|
||||
// these nodes are added to the graph together so that they are not reordered
|
||||
// by doing so, the number of splits in the graph is reduced
|
||||
// expand k later to enable rope fusion which directly writes into k-v cache
|
||||
@@ -3632,16 +3551,7 @@ ggml_tensor * llm_graph_context::build_attn(
|
||||
cb(cur, "kqv_out", il);
|
||||
|
||||
if (wo) {
|
||||
if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE) {
|
||||
// GLM4 and GLM4_MOE have numerical issues with F16 accumulators
|
||||
cur = build_lora_mm(wo, cur);
|
||||
ggml_prec_set_acc(cur, GGML_PREC_BF16);
|
||||
if (wo_s) {
|
||||
cur = ggml_mul(ctx0, cur, wo_s);
|
||||
}
|
||||
} else {
|
||||
cur = build_lora_mm(wo, cur, wo_s);
|
||||
}
|
||||
cur = build_lora_mm(wo, cur, wo_s);
|
||||
}
|
||||
|
||||
if (wo_b) {
|
||||
|
||||
+1
-7
@@ -1179,6 +1179,7 @@ struct llm_graph_context {
|
||||
ggml_tensor * cur) const;
|
||||
|
||||
// do mat_mul, while optionally apply lora and per-tensor scale
|
||||
// w_s defaults to the weight scale of w
|
||||
ggml_tensor * build_lora_mm(
|
||||
ggml_tensor * w,
|
||||
ggml_tensor * cur,
|
||||
@@ -1190,7 +1191,6 @@ struct llm_graph_context {
|
||||
ggml_tensor * w, // ggml_tensor * as
|
||||
ggml_tensor * cur, // ggml_tensor * b
|
||||
ggml_tensor * ids,
|
||||
ggml_tensor * w_s = nullptr,
|
||||
ggml_tensor * slots = nullptr,
|
||||
bool cached = true) const;
|
||||
|
||||
@@ -1263,9 +1263,6 @@ struct llm_graph_context {
|
||||
int il,
|
||||
ggml_tensor * probs_in = nullptr,
|
||||
ggml_tensor * gate_up_exps = nullptr,
|
||||
ggml_tensor * up_exps_s = nullptr,
|
||||
ggml_tensor * gate_exps_s = nullptr,
|
||||
ggml_tensor * down_exps_s = nullptr,
|
||||
ggml_tensor * selected_experts_in = nullptr,
|
||||
ggml_tensor * post_exp_norm = nullptr,
|
||||
float post_exp_norm_eps = 1e-5f) const;
|
||||
@@ -1291,9 +1288,6 @@ struct llm_graph_context {
|
||||
ggml_tensor * probs_in = nullptr,
|
||||
ggml_tensor * gate_up_exps = nullptr,
|
||||
ggml_tensor * gate_up_exps_b = nullptr,
|
||||
ggml_tensor * up_exps_s = nullptr,
|
||||
ggml_tensor * gate_exps_s = nullptr,
|
||||
ggml_tensor * down_exps_s = nullptr,
|
||||
ggml_tensor * selected_experts_in = nullptr,
|
||||
ggml_tensor * post_exp_norm = nullptr,
|
||||
float post_exp_norm_eps = 1e-5f) const;
|
||||
|
||||
@@ -88,16 +88,6 @@ void llama_log_callback_default(ggml_log_level level, const char * text, void *
|
||||
fflush(stderr);
|
||||
}
|
||||
|
||||
void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size) {
|
||||
static const std::vector<uint8_t> zeros(1024*1024, 0);
|
||||
|
||||
// not all backend buffers implement ggml_backend_tensor_memset(), so write zeros instead
|
||||
// TODO: make this a generic fallback in `ggml_backend_tensor_memset` when `set_tensor` is available
|
||||
for (size_t ofs = 0; ofs < size; ofs += zeros.size()) {
|
||||
ggml_backend_tensor_set(t, zeros.data(), offset + ofs, std::min(size - ofs, zeros.size()));
|
||||
}
|
||||
}
|
||||
|
||||
void replace_all(std::string & s, const std::string & search, const std::string & replace) {
|
||||
if (search.empty()) {
|
||||
return;
|
||||
|
||||
@@ -96,8 +96,6 @@ struct buffer_view {
|
||||
}
|
||||
};
|
||||
|
||||
void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size);
|
||||
|
||||
void replace_all(std::string & s, const std::string & search, const std::string & replace);
|
||||
|
||||
// TODO: rename to llama_format ?
|
||||
|
||||
@@ -2919,10 +2919,10 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_
|
||||
const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
|
||||
|
||||
if (is_contiguous) {
|
||||
llama_clear_tensor_data(k, sinfo.head() * k_size_row, cell_count * k_size_row);
|
||||
ggml_backend_tensor_memset(k, 0, sinfo.head() * k_size_row, cell_count * k_size_row);
|
||||
} else {
|
||||
for (uint32_t i = 0; i < cell_count; ++i) {
|
||||
llama_clear_tensor_data(k, sinfo.idxs[0][i] * k_size_row, k_size_row);
|
||||
ggml_backend_tensor_memset(k, 0, sinfo.idxs[0][i] * k_size_row, k_size_row);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2941,10 +2941,10 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_
|
||||
const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
|
||||
|
||||
if (is_contiguous) {
|
||||
llama_clear_tensor_data(v, sinfo.head() * v_size_row, cell_count * v_size_row);
|
||||
ggml_backend_tensor_memset(v, 0, sinfo.head() * v_size_row, cell_count * v_size_row);
|
||||
} else {
|
||||
for (uint32_t i = 0; i < cell_count; ++i) {
|
||||
llama_clear_tensor_data(v, sinfo.idxs[0][i] * v_size_row, v_size_row);
|
||||
ggml_backend_tensor_memset(v, 0, sinfo.idxs[0][i] * v_size_row, v_size_row);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -2954,12 +2954,12 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_
|
||||
const uint32_t h = sinfo.head();
|
||||
|
||||
for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
|
||||
llama_clear_tensor_data(v, (h + j * cells.size()) * v_size_el, cell_count * v_size_el);
|
||||
ggml_backend_tensor_memset(v, 0, (h + j * cells.size()) * v_size_el, cell_count * v_size_el);
|
||||
}
|
||||
} else {
|
||||
for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
|
||||
for (uint32_t i = 0; i < cell_count; ++i) {
|
||||
llama_clear_tensor_data(v, (sinfo.idxs[0][i] + j * cells.size()) * v_size_el, v_size_el);
|
||||
ggml_backend_tensor_memset(v, 0, (sinfo.idxs[0][i] + j * cells.size()) * v_size_el, v_size_el);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1265,17 +1265,17 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head
|
||||
for (uint32_t il = 0; il < n_layer; ++il) {
|
||||
if (r_l[il] != nullptr) {
|
||||
const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
|
||||
llama_clear_tensor_data(r_l[il], cell_head * r_size_row, cell_count * r_size_row);
|
||||
ggml_backend_tensor_memset(r_l[il], 0, cell_head * r_size_row, cell_count * r_size_row);
|
||||
}
|
||||
|
||||
if (s_l[il] != nullptr) {
|
||||
const size_t s_size_row = ggml_row_size(s_l[il]->type, hparams.n_embd_s());
|
||||
llama_clear_tensor_data(s_l[il], cell_head * s_size_row, cell_count * s_size_row);
|
||||
ggml_backend_tensor_memset(s_l[il], 0, cell_head * s_size_row, cell_count * s_size_row);
|
||||
}
|
||||
|
||||
if (p_l[il] != nullptr) {
|
||||
const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
|
||||
llama_clear_tensor_data(p_l[il], cell_head * p_size_row, cell_count * p_size_row);
|
||||
ggml_backend_tensor_memset(p_l[il], 0, cell_head * p_size_row, cell_count * p_size_row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+76
-4
@@ -126,6 +126,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params
|
||||
return new llama_model_qwen3tts(params);
|
||||
case LLM_ARCH_POCKETTTS:
|
||||
return new llama_model_pockettts(params);
|
||||
case LLM_ARCH_MOSHI:
|
||||
return new llama_model_moshi(params);
|
||||
case LLM_ARCH_ZONOS3:
|
||||
return new llama_model_zonos3(params);
|
||||
case LLM_ARCH_KOKORO:
|
||||
@@ -1408,12 +1410,19 @@ bool llama_prec_policy::apply(ggml_tensor * res) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto it = prec_src1.find(res->src[0]);
|
||||
if (it == prec_src1.end()) {
|
||||
return false;
|
||||
bool applied = false;
|
||||
|
||||
const auto it_acc = prec_acc.find(res->src[0]);
|
||||
if (it_acc != prec_acc.end()) {
|
||||
applied |= ggml_prec_set_acc(res, it_acc->second);
|
||||
}
|
||||
|
||||
return ggml_prec_set_src(res, it->second, 1);
|
||||
const auto it_src1 = prec_src1.find(res->src[0]);
|
||||
if (it_src1 != prec_src1.end()) {
|
||||
applied |= ggml_prec_set_src(res, it_src1->second, 1);
|
||||
}
|
||||
|
||||
return applied;
|
||||
}
|
||||
|
||||
void llama_prec_policy::load(llama_model_loader & ml, const llama_model & model) {
|
||||
@@ -2042,6 +2051,42 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
|
||||
}
|
||||
}
|
||||
|
||||
// map each weight to its "<name>.scale" tensor: shape {1} for a 2D weight, {n_expert} for a 3D weight
|
||||
{
|
||||
auto ends_with = [](const std::string & str, const std::string & suffix) {
|
||||
return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
|
||||
};
|
||||
std::unordered_map<std::string, ggml_tensor *> weights;
|
||||
for (const auto & [name, cur] : tensors_by_name) {
|
||||
if (ends_with(name, ".weight")) {
|
||||
weights.emplace(name.substr(0, name.size() - 7), cur);
|
||||
}
|
||||
}
|
||||
for (const auto & [name, s] : tensors_by_name) {
|
||||
if (!ends_with(name, ".scale")) {
|
||||
continue;
|
||||
}
|
||||
const auto it = weights.find(name.substr(0, name.size() - 6));
|
||||
if (it == weights.end()) {
|
||||
continue;
|
||||
}
|
||||
ggml_tensor * w = it->second;
|
||||
const bool ok = w->ne[3] == 1 && ggml_nelements(s) == w->ne[2] && s->ne[0] == w->ne[2];
|
||||
if (ok) {
|
||||
w_scales.emplace(w, s);
|
||||
} else {
|
||||
LLAMA_LOG_DEBUG("%s: '%s' is not a weight scale for '%s', skipping\n", __func__, name.c_str(), w->name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565
|
||||
if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) {
|
||||
for (const auto & layer : layers) {
|
||||
prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32);
|
||||
}
|
||||
}
|
||||
|
||||
// per-tensor activation precision policy
|
||||
prec_policy.load(ml, *this);
|
||||
|
||||
@@ -2573,6 +2618,11 @@ size_t llama_model::size() const {
|
||||
return pimpl->n_bytes;
|
||||
}
|
||||
|
||||
ggml_tensor * llama_model::get_w_scale(const ggml_tensor * w) const {
|
||||
const auto it = w_scales.find(w);
|
||||
return it == w_scales.end() ? nullptr : it->second;
|
||||
}
|
||||
|
||||
size_t llama_model::n_tensors() const {
|
||||
return tensors_by_name.size();
|
||||
}
|
||||
@@ -3154,6 +3204,27 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
|
||||
/* filter_recr */ std::move(filter_recr),
|
||||
/* filter_idx */ std::move(filter_idx));
|
||||
} break;
|
||||
case LLM_ARCH_MOSHI:
|
||||
{
|
||||
// every layer attends to the same sliding window: one cache that masks it, the cells past the window are reused
|
||||
res = new llama_kv_cache(
|
||||
*this,
|
||||
params.no_alloc,
|
||||
hparams,
|
||||
params.type_k,
|
||||
params.type_v,
|
||||
!cparams.flash_attn,
|
||||
cparams.offload_kqv,
|
||||
cparams.kv_unified,
|
||||
cparams.n_ctx_seq,
|
||||
cparams.n_seq_max,
|
||||
hparams.n_swa,
|
||||
LLAMA_SWA_TYPE_STANDARD,
|
||||
nullptr,
|
||||
nullptr,
|
||||
nullptr,
|
||||
nullptr);
|
||||
} break;
|
||||
case LLM_ARCH_HY_V4:
|
||||
{
|
||||
if (hparams.indexer_top_k == 0) {
|
||||
@@ -3789,6 +3860,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) {
|
||||
case LLM_ARCH_DOTS3NOTE:
|
||||
case LLM_ARCH_NANBEIGE:
|
||||
case LLM_ARCH_POCKETTTS:
|
||||
case LLM_ARCH_MOSHI:
|
||||
case LLM_ARCH_ZONOS3:
|
||||
case LLM_ARCH_LIMITE:
|
||||
case LLM_ARCH_TINY_VOCA:
|
||||
|
||||
+12
-2
@@ -737,8 +737,7 @@ struct llama_meta_device_get_split_state_userdata {
|
||||
struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const struct ggml_tensor * tensor, void * userdata);
|
||||
|
||||
struct llama_prec_policy {
|
||||
// the key is the weight tensor `res->src[0]`, stores the recommended accumulation type of the op (unused for now)
|
||||
// TODO: migrate ad-hoc ggml_prec_set_acc() calls to this container + update apply() to use it
|
||||
// the key is the weight tensor `res->src[0]`, stores the recommended accumulation type of the op
|
||||
std::unordered_map<const ggml_tensor *, ggml_prec> prec_acc;
|
||||
|
||||
// the key is the weight tensor `res->src[0]`, stores the recommended activation precision type
|
||||
@@ -746,6 +745,12 @@ struct llama_prec_policy {
|
||||
|
||||
bool apply(ggml_tensor * res) const;
|
||||
|
||||
void set_acc(const ggml_tensor * w, ggml_prec prec) {
|
||||
if (w) {
|
||||
prec_acc[w] = prec;
|
||||
}
|
||||
}
|
||||
|
||||
void load(llama_model_loader & ml, const llama_model & model);
|
||||
};
|
||||
|
||||
@@ -818,6 +823,11 @@ struct llama_model {
|
||||
|
||||
llama_hadamard hdmd;
|
||||
|
||||
// weight -> "<name>.scale" tensor (e.g. NVFP4 scale2), applied by build_lora_mm and build_lora_mm_id
|
||||
std::unordered_map<const ggml_tensor *, ggml_tensor *> w_scales;
|
||||
|
||||
ggml_tensor * get_w_scale(const ggml_tensor * w) const;
|
||||
|
||||
// see llama_model_set_attn_rot
|
||||
bool attn_rot = true;
|
||||
|
||||
|
||||
@@ -2673,6 +2673,7 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
|
||||
pre_type = LLAMA_VOCAB_PRE_TYPE_GPT4O;
|
||||
special_bos_id = LLAMA_TOKEN_NULL;
|
||||
clean_spaces = false;
|
||||
ignore_merges = true;
|
||||
} else if (
|
||||
tokenizer_pre == "granite-embed-multi-97m") {
|
||||
pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI;
|
||||
|
||||
+32
-16
@@ -173,22 +173,35 @@ static clef_spans clef_get_spans(const llama_ubatch & ubatch) {
|
||||
return res;
|
||||
}
|
||||
|
||||
// the head always has the max number of spans, so its graph depends only on n_tokens
|
||||
// each span has 1 token or more and each question has an option, so there is always a spare question for the padding options
|
||||
static size_t clef_n_questions(int64_t n_tokens) { return n_tokens / 2 + 1; }
|
||||
static size_t clef_n_options (int64_t n_tokens) { return std::max<int64_t>(n_tokens - 1, 1); }
|
||||
|
||||
// pooling matrices and indices computed from the spans
|
||||
class llama_model_clef::input_decision : public llm_graph_input_i {
|
||||
public:
|
||||
input_decision(const llama_ubatch & ubatch) : n_tokens(ubatch.n_tokens) {
|
||||
const auto spans = clef_get_spans(ubatch);
|
||||
n_questions = spans.questions.size();
|
||||
n_options = spans.options.size();
|
||||
}
|
||||
input_decision(const llama_ubatch & ubatch) :
|
||||
n_tokens(ubatch.n_tokens), n_questions(clef_n_questions(n_tokens)), n_options(clef_n_options(n_tokens)) {}
|
||||
|
||||
void set_input(const llama_ubatch * ubatch) override {
|
||||
// a batch of embeddings has no token ids, and no usable spans
|
||||
const std::vector<llama_token> no_tokens(ubatch->token ? 0 : n_tokens, 0);
|
||||
ggml_backend_tensor_set(tokens, ubatch->token ? ubatch->token : no_tokens.data(), 0, n_tokens * sizeof(llama_token));
|
||||
|
||||
const auto spans = clef_get_spans(*ubatch);
|
||||
GGML_ASSERT(spans.questions.size() == n_questions && spans.options.size() == n_options);
|
||||
auto spans = clef_get_spans(*ubatch);
|
||||
const int32_t n_q_used = spans.questions.size();
|
||||
GGML_ASSERT((size_t) n_q_used < n_questions && spans.options.size() <= n_options);
|
||||
|
||||
// the padding options belong to the first padding question, the questions do not read the padding questions
|
||||
spans.questions.resize(n_questions, { 0, 0, 0 });
|
||||
spans.options.resize(n_options, { n_q_used, 0, 0 });
|
||||
|
||||
std::vector<float> q_mask(n_questions * n_questions, 0.0f);
|
||||
for (size_t i = 0; i < n_questions; i++) {
|
||||
std::fill(q_mask.begin() + i * n_questions + n_q_used, q_mask.begin() + (i + 1) * n_questions, -INFINITY);
|
||||
}
|
||||
ggml_backend_tensor_set(question_mask, q_mask.data(), 0, ggml_nbytes(question_mask));
|
||||
|
||||
// the scores are NaN if the batch has a decision order that cannot be used
|
||||
const float status_data = spans.valid || ubatch->decision_order == nullptr ? 0.0f : NAN;
|
||||
@@ -215,6 +228,8 @@ public:
|
||||
owner[i] = o.question;
|
||||
mask[o.question * n_options + i] = 0.0f;
|
||||
}
|
||||
// a padding question reads all options, a row of -inf gives NaN
|
||||
std::fill(mask.begin() + n_q_used * n_options, mask.end(), 0.0f);
|
||||
|
||||
ggml_backend_tensor_set(pool_q, pool_q_data.data(), 0, ggml_nbytes(pool_q));
|
||||
ggml_backend_tensor_set(pool_o, pool_o_data.data(), 0, ggml_nbytes(pool_o));
|
||||
@@ -225,8 +240,7 @@ public:
|
||||
|
||||
bool can_reuse(const llm_graph_params & params) override {
|
||||
// the values are computed again in set_input(), only the shapes must match
|
||||
const auto spans = clef_get_spans(params.ubatch);
|
||||
return spans.questions.size() == n_questions && spans.options.size() == n_options;
|
||||
return params.ubatch.n_tokens == (uint32_t) n_tokens;
|
||||
}
|
||||
|
||||
ggml_tensor * tokens = nullptr; // I32 [n_tokens]
|
||||
@@ -235,11 +249,12 @@ public:
|
||||
ggml_tensor * question_type = nullptr; // I32 [n_questions]
|
||||
ggml_tensor * option_question = nullptr; // I32 [n_options]
|
||||
ggml_tensor * option_mask = nullptr; // F32 [n_options, n_questions], 0 if the option belongs to the question, else -inf
|
||||
ggml_tensor * question_mask = nullptr; // F32 [n_questions, n_questions], -inf for the padding questions
|
||||
ggml_tensor * status = nullptr; // F32 [1], added to the scores: 0, or NaN on invalid input
|
||||
|
||||
const int64_t n_tokens;
|
||||
size_t n_questions;
|
||||
size_t n_options;
|
||||
const size_t n_questions;
|
||||
const size_t n_options;
|
||||
};
|
||||
|
||||
// the backbone is copied from llama_model_qwen35::graph, without the memory module
|
||||
@@ -479,8 +494,8 @@ ggml_tensor * llama_model_clef::graph::build_head_norm(ggml_tensor * cur, const
|
||||
return build_norm(cur, n.w, n.b, LLM_NORM, -1);
|
||||
}
|
||||
|
||||
// q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], no mask
|
||||
ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a) {
|
||||
// q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], kq_mask: [n_kv, n_q] or null
|
||||
ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) {
|
||||
const int64_t n_embd_h = q->ne[0];
|
||||
const int64_t n_head_h = model.n_head_decision;
|
||||
const int64_t d_head = n_embd_h / n_head_h;
|
||||
@@ -497,7 +512,7 @@ ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_ten
|
||||
Vcur = ggml_cont(ctx0, Vcur);
|
||||
|
||||
ggml_tensor * kq = ggml_mul_mat(ctx0, Kcur, Qcur); // [n_kv, n_q, n_head]
|
||||
kq = ggml_soft_max_ext(ctx0, kq, nullptr, 1.0f / sqrtf(float(d_head)), 0.0f);
|
||||
kq = ggml_soft_max_ext(ctx0, kq, kq_mask, 1.0f / sqrtf(float(d_head)), 0.0f);
|
||||
|
||||
ggml_tensor * cur = ggml_mul_mat(ctx0, Vcur, kq); // [d_head, n_q, n_head]
|
||||
cur = ggml_cont_2d(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3), n_embd_h, n_q);
|
||||
@@ -523,8 +538,9 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
|
||||
inp->question_type = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_questions);
|
||||
inp->option_question = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_options);
|
||||
inp->option_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_options, n_questions);
|
||||
inp->question_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_questions, n_questions);
|
||||
inp->status = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
|
||||
for (ggml_tensor * t : { inp->tokens, inp->pool_q, inp->pool_o, inp->question_type, inp->option_question, inp->option_mask, inp->status }) {
|
||||
for (ggml_tensor * t : { inp->tokens, inp->pool_q, inp->pool_o, inp->question_type, inp->option_question, inp->option_mask, inp->question_mask, inp->status }) {
|
||||
ggml_set_input(t);
|
||||
}
|
||||
|
||||
@@ -584,7 +600,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
|
||||
const auto & layer = model.head_layers[il];
|
||||
|
||||
ggml_tensor * cur = build_head_norm(fields, layer.self_norm);
|
||||
fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn));
|
||||
fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn, inp->question_mask));
|
||||
|
||||
cur = build_head_norm(fields, layer.cross_norm);
|
||||
fields = ggml_add(ctx0, fields, build_head_attn(cur, memory, layer.cross_attn));
|
||||
|
||||
@@ -398,10 +398,7 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_ffn(ggml_tensor * cur,
|
||||
LLM_FFN_SILU, true,
|
||||
hparams.expert_weights_scale,
|
||||
LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il,
|
||||
nullptr, model.layers[il].ffn_gate_up_exps,
|
||||
model.layers[il].ffn_up_exps_s,
|
||||
model.layers[il].ffn_gate_exps_s,
|
||||
model.layers[il].ffn_down_exps_s);
|
||||
nullptr, model.layers[il].ffn_gate_up_exps);
|
||||
cb(moe_out, "ffn_moe_out", il);
|
||||
|
||||
if (model.layers[il].ffn_up_shexp != nullptr) {
|
||||
|
||||
@@ -226,10 +226,7 @@ llama_model_cohere2moe::graph::graph(const llm_graph_params & params) : llm_grap
|
||||
hparams.expert_weights_scale,
|
||||
(llama_expert_gating_func_type) hparams.expert_gating_func,
|
||||
il,
|
||||
nullptr, layer.ffn_gate_up_exps,
|
||||
layer.ffn_up_exps_s,
|
||||
layer.ffn_gate_exps_s,
|
||||
layer.ffn_down_exps_s);
|
||||
nullptr, layer.ffn_gate_up_exps);
|
||||
cb(cur, "ffn_moe_out", il);
|
||||
|
||||
if (layer.ffn_up_shexp) {
|
||||
@@ -371,10 +368,7 @@ llama_model_cohere2moe::graph_mtp::graph_mtp(const llm_graph_params & params) :
|
||||
hparams.expert_weights_scale,
|
||||
(llama_expert_gating_func_type) hparams.expert_gating_func,
|
||||
il,
|
||||
nullptr, layer.ffn_gate_up_exps,
|
||||
layer.ffn_up_exps_s,
|
||||
layer.ffn_gate_exps_s,
|
||||
layer.ffn_down_exps_s);
|
||||
nullptr, layer.ffn_gate_up_exps);
|
||||
cb(cur, "mtp_ffn_moe_out", il);
|
||||
|
||||
if (layer.ffn_up_shexp) {
|
||||
|
||||
@@ -383,10 +383,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
|
||||
(llama_expert_gating_func_type) hparams.expert_gating_func,
|
||||
il,
|
||||
nullptr,
|
||||
model.layers[il].ffn_gate_up_exps,
|
||||
model.layers[il].ffn_up_exps_s,
|
||||
model.layers[il].ffn_gate_exps_s,
|
||||
model.layers[il].ffn_down_exps_s);
|
||||
model.layers[il].ffn_gate_up_exps);
|
||||
cb(moe_out, "ffn_moe_out", il);
|
||||
|
||||
// FFN shared expert
|
||||
@@ -624,10 +621,7 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params)
|
||||
(llama_expert_gating_func_type) hparams.expert_gating_func,
|
||||
il,
|
||||
nullptr,
|
||||
layer.ffn_gate_up_exps,
|
||||
layer.ffn_up_exps_s,
|
||||
layer.ffn_gate_exps_s,
|
||||
layer.ffn_down_exps_s);
|
||||
layer.ffn_gate_up_exps);
|
||||
cb(moe_out, "mtp_ffn_moe_out", il);
|
||||
|
||||
// FFN shared expert
|
||||
|
||||
@@ -1284,9 +1284,6 @@ llama_model_deepseek4::graph::graph(const llm_graph_params & params) :
|
||||
il,
|
||||
nullptr,
|
||||
nullptr,
|
||||
nullptr,
|
||||
nullptr,
|
||||
nullptr,
|
||||
selected_experts);
|
||||
cb(moe_out, "ffn_moe_out", il);
|
||||
|
||||
|
||||
@@ -203,6 +203,8 @@ void llama_model_deepseek41::load_arch_tensors(llama_model_loader & ml) {
|
||||
}
|
||||
|
||||
layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
|
||||
// the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/blob/1bae0e1088993b9b82de08f59de5be5a34e42170/inference/model.py#L813
|
||||
prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32);
|
||||
layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0);
|
||||
layer.ffn_exp_probs_b_vl = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B_VL, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED);
|
||||
layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
|
||||
@@ -874,9 +876,7 @@ llama_model_deepseek41::graph::graph(const llm_graph_params & params) :
|
||||
cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il);
|
||||
cb(cur, "ffn_norm", il);
|
||||
|
||||
// the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/blob/1bae0e1088993b9b82de08f59de5be5a34e42170/inference/model.py#L813
|
||||
ggml_tensor * logits = build_lora_mm(layer.ffn_gate_inp, cur);
|
||||
ggml_prec_set_acc(logits, GGML_PREC_F32);
|
||||
cb(logits, "ffn_moe_logits", il);
|
||||
|
||||
// image (embedding) tokens use the vision router bias, as DeepSeek-V4
|
||||
|
||||
@@ -401,10 +401,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
|
||||
(llama_expert_gating_func_type) hparams.expert_gating_func,
|
||||
il,
|
||||
nullptr,
|
||||
model.layers[il].ffn_gate_up_exps,
|
||||
model.layers[il].ffn_up_exps_s,
|
||||
model.layers[il].ffn_gate_exps_s,
|
||||
model.layers[il].ffn_down_exps_s);
|
||||
model.layers[il].ffn_gate_up_exps);
|
||||
cb(moe_out, "ffn_moe_out", il);
|
||||
|
||||
ggml_tensor * ffn_shexp =
|
||||
|
||||
@@ -158,10 +158,7 @@ llama_model_flint::graph::graph(const llm_graph_params & params) :
|
||||
LLM_FFN_SILU, hparams.expert_weights_norm,
|
||||
hparams.expert_weights_scale,
|
||||
(llama_expert_gating_func_type) hparams.expert_gating_func,
|
||||
il, nullptr, nullptr,
|
||||
model.layers[il].ffn_up_exps_s,
|
||||
model.layers[il].ffn_gate_exps_s,
|
||||
model.layers[il].ffn_down_exps_s);
|
||||
il);
|
||||
cb(moe_out, "ffn_moe_out", il);
|
||||
|
||||
{
|
||||
|
||||
@@ -406,10 +406,7 @@ llama_model_gemma4::graph::graph(const llm_graph_params & params) :
|
||||
1.0f,
|
||||
LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
|
||||
il, logits,
|
||||
model.layers[il].ffn_gate_up_exps,
|
||||
model.layers[il].ffn_up_exps_s,
|
||||
model.layers[il].ffn_gate_exps_s,
|
||||
model.layers[il].ffn_down_exps_s);
|
||||
model.layers[il].ffn_gate_up_exps);
|
||||
cur_moe = build_norm(cur_moe,
|
||||
model.layers[il].ffn_post_norm_2, nullptr,
|
||||
LLM_NORM_RMS, il);
|
||||
|
||||
@@ -431,10 +431,7 @@ llama_model_glm_dsa::graph::graph(const llm_graph_params & params) :
|
||||
(llama_expert_gating_func_type) hparams.expert_gating_func,
|
||||
il,
|
||||
nullptr,
|
||||
model.layers[il].ffn_gate_up_exps,
|
||||
model.layers[il].ffn_up_exps_s,
|
||||
model.layers[il].ffn_gate_exps_s,
|
||||
model.layers[il].ffn_down_exps_s);
|
||||
model.layers[il].ffn_gate_up_exps);
|
||||
cb(moe_out, "ffn_moe_out", il);
|
||||
|
||||
// FFN shared expert
|
||||
@@ -672,10 +669,7 @@ llama_model_glm_dsa::graph_mtp::graph_mtp(const llm_graph_params & params)
|
||||
(llama_expert_gating_func_type) hparams.expert_gating_func,
|
||||
il,
|
||||
nullptr,
|
||||
layer.ffn_gate_up_exps,
|
||||
layer.ffn_up_exps_s,
|
||||
layer.ffn_gate_exps_s,
|
||||
layer.ffn_down_exps_s);
|
||||
layer.ffn_gate_up_exps);
|
||||
cb(moe_out, "mtp_ffn_moe_out", il);
|
||||
|
||||
// FFN shared expert
|
||||
|
||||
@@ -113,6 +113,11 @@ void llama_model_glm4_moe::load_arch_tensors(llama_model_loader & ml) {
|
||||
layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED | flags);
|
||||
layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd }, TENSOR_NOT_REQUIRED | flags);
|
||||
}
|
||||
|
||||
// numerical issues with F16 accumulators
|
||||
prec_policy.set_acc(layer.wo, GGML_PREC_BF16);
|
||||
prec_policy.set_acc(layer.ffn_down, GGML_PREC_BF16);
|
||||
prec_policy.set_acc(layer.ffn_down_shexp, GGML_PREC_BF16);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user