mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-23 03:07:37 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
212c547fe9 | ||
|
|
f5e6915c28 | ||
|
|
dd53f70d08 | ||
|
|
1f8baae28d | ||
|
|
44d50873b5 | ||
|
|
7778de0c3f | ||
|
|
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 | ||
|
|
fb7090df56 | ||
|
|
690b87d881 | ||
|
|
838d942438 | ||
|
|
3da11de1f1 | ||
|
|
93cb37ea7b | ||
|
|
1fdda89a4d | ||
|
|
e412c6f468 | ||
|
|
40b7a546de | ||
|
|
46eb1742db | ||
|
|
6792507b7f | ||
|
|
418fe97b5f | ||
|
|
7476e47261 | ||
|
|
29b52d398b |
@@ -137,8 +137,8 @@ jobs:
|
||||
-DCMAKE_CXX_FLAGS="-march=arch15"
|
||||
time cmake --build build --config Release -j $(nproc)
|
||||
|
||||
ubuntu-24-ppc64le:
|
||||
runs-on: ubuntu-24.04-ppc64le
|
||||
ubuntu-26-ppc64le:
|
||||
runs-on: ubuntu-26.04-ppc64le
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
@@ -154,12 +154,6 @@ jobs:
|
||||
libjpeg-dev build-essential libssl-dev \
|
||||
git-lfs
|
||||
|
||||
- name: Toolchain workaround (GCC 14)
|
||||
run: |
|
||||
sudo apt-get install -y gcc-14 g++-14
|
||||
echo "CC=gcc-14" >> "$GITHUB_ENV"
|
||||
echo "CXX=g++-14" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Python Dependencies
|
||||
id: python_depends
|
||||
run: |
|
||||
|
||||
@@ -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 \
|
||||
|
||||
@@ -42,6 +42,8 @@ env:
|
||||
LLAMA_ARG_LOG_PREFIX: 1
|
||||
LLAMA_ARG_LOG_TIMESTAMPS: 1
|
||||
LLAMA_ARG_LOG_VERBOSITY: 10
|
||||
# [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc
|
||||
GGML_SCHED_NO_REALLOC: ON
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }}
|
||||
|
||||
@@ -39,6 +39,8 @@ env:
|
||||
LLAMA_ARG_LOG_PREFIX: 1
|
||||
LLAMA_ARG_LOG_TIMESTAMPS: 1
|
||||
LLAMA_ARG_LOG_VERBOSITY: 10
|
||||
# [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc
|
||||
GGML_SCHED_NO_REALLOC: ON
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }}
|
||||
|
||||
+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|>");
|
||||
|
||||
+36
-38
@@ -100,18 +100,18 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
|
||||
auto use_tools = 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 header = p.literal(HEADER);
|
||||
auto end = p.literal(END);
|
||||
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto header = p.token(HEADER);
|
||||
auto end = p.token(END);
|
||||
|
||||
auto think = p.literal(THINK);
|
||||
auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(END)) + end :
|
||||
p.atomic(p.content(think)) + p.content(p.until(END) + end));
|
||||
auto text = p.rule("text", p.literal(TEXT) + p.content(p.until(END)) + end);
|
||||
auto think = p.token(THINK);
|
||||
auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(end)) + end :
|
||||
p.atomic(p.content(think)) + p.content(p.until(end) + end));
|
||||
auto text = p.rule("text", p.token(TEXT) + p.content(p.until(end)) + end);
|
||||
|
||||
if (has_response_format) {
|
||||
auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)));
|
||||
return p.zero_or_more(header + thinking) + header + p.literal(TEXT) + response_format + end;
|
||||
return p.zero_or_more(header + thinking) + header + p.token(TEXT) + response_format + end;
|
||||
}
|
||||
|
||||
auto blocks = p.zero_or_more(header + (thinking | text));
|
||||
@@ -120,45 +120,43 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
|
||||
return blocks;
|
||||
}
|
||||
|
||||
auto tool_choice = 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");
|
||||
|
||||
auto open = p.tool_name(p.literal(name)) + p.literal(TOOL_JSON) + p.literal("{\"name\":" + json(name).dump() + ",\"args\":");
|
||||
auto args = p.tool_args(p.json());
|
||||
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.tool_open(open) + args + p.tool_close(p.literal("}")) + end));
|
||||
});
|
||||
|
||||
// tool calls are the last blocks of the turn
|
||||
auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
|
||||
auto tool_calls = header + p.trigger_rule("tool-calls", calls);
|
||||
// the call takes the name in the JSON
|
||||
auto tool_json = p.token(TOOL_JSON);
|
||||
auto tool_body = [&](const common_peg_parser & json_name) {
|
||||
return p.tool_open(p.literal("{")) << p.json_member("name", p.literal("\"") + p.tool_name(json_name) + p.literal("\"")) << p.literal(",")
|
||||
<< p.json_member("args", p.tool_args(p.json())) << p.tool_close(p.literal("}")) + end;
|
||||
};
|
||||
|
||||
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
return blocks + tool_calls;
|
||||
auto tool_choice = 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");
|
||||
std::string quoted = json(name).dump();
|
||||
|
||||
// The research model does not generate a tool name before the tool call token
|
||||
auto json_name = p.literal(quoted.substr(1, quoted.size() - 2));
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.optional(p.literal(name)) + tool_json + tool_body(json_name)));
|
||||
});
|
||||
|
||||
auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
|
||||
return blocks + header + calls;
|
||||
}
|
||||
|
||||
return blocks + p.optional(tool_calls);
|
||||
auto name = p.until(tool_json);
|
||||
auto body = tool_body(p.string_content('"'));
|
||||
auto next = p.rule("tool-call", header + p.tool(name + tool_json + body));
|
||||
auto more = inputs.parallel_tool_calls ? p.zero_or_more(next) : p.eps();
|
||||
auto calls = header + name + p.trigger_rule("tool-calls", tool_json, body + more);
|
||||
|
||||
return blocks + p.optional(calls);
|
||||
});
|
||||
|
||||
if (has_response_format || use_tools) {
|
||||
data.grammar_lazy = !has_response_format && 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 && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO);
|
||||
});
|
||||
|
||||
if (data.grammar_lazy) {
|
||||
// a header followed by text and not by a content token is a tool call, the grammar starts at the name
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" },
|
||||
};
|
||||
// Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt.
|
||||
// an output that starts with no content token is a tool call. not for a continuation, it starts with text
|
||||
if (!inputs.has_continuation()) {
|
||||
data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL, "[^<]+" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -148,7 +148,9 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"HYV4ForCausalLM": "hy_v4",
|
||||
"IQuestCoderForCausalLM": "llama",
|
||||
"Inkling2ForCausalLM": "inkling2",
|
||||
"Inkling2LoopForCausalLM": "inkling2",
|
||||
"Inkling2ForConditionalGeneration": "inkling2",
|
||||
"Inkling2LoopForConditionalGeneration": "inkling2",
|
||||
"InternLM2ForCausalLM": "internlm",
|
||||
"InternLM3ForCausalLM": "internlm",
|
||||
"JAISLMHeadModel": "jais",
|
||||
@@ -284,6 +286,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"Qwen3NextForCausalLM": "qwen",
|
||||
"Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
|
||||
"PocketTTSModel": "pockettts",
|
||||
"MoshiModel": "moshi",
|
||||
"KokoroModel": "kokoro",
|
||||
"TinyVocaModel": "tiny_voca",
|
||||
"Zonos3Model": "zonos3",
|
||||
@@ -389,6 +392,7 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
|
||||
"HunYuanVLForConditionalGeneration": "hunyuan",
|
||||
"Idefics3ForConditionalGeneration": "smolvlm",
|
||||
"Inkling2ForConditionalGeneration": "inkling2",
|
||||
"Inkling2LoopForConditionalGeneration": "inkling2",
|
||||
"InternVisionModel": "internvl",
|
||||
"JanusForConditionalGeneration": "januspro",
|
||||
"KimiK25ForConditionalGeneration": "kimivl",
|
||||
@@ -429,6 +433,7 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
|
||||
"Qwen3ASRForConditionalGeneration": "qwen3vl",
|
||||
"Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
|
||||
"PocketTTSModel": "pockettts",
|
||||
"MoshiModel": "moshi",
|
||||
"KokoroModel": "kokoro",
|
||||
"TinyVocaModel": "tiny_voca",
|
||||
"SopranoModel": "soprano",
|
||||
|
||||
+57
-2
@@ -69,7 +69,7 @@ def _is_inkling2(dir_model: Path) -> bool:
|
||||
if not (dir_model / "config.json").is_file():
|
||||
return False
|
||||
with open(dir_model / "config.json", encoding="utf-8") as f:
|
||||
return json.load(f).get("model_type") in ("inkling2", "inkling2_text")
|
||||
return json.load(f).get("model_type") in ("inkling2", "inkling2_text", "inkling2_loop", "inkling2_loop_text")
|
||||
|
||||
|
||||
@ModelBase.register_hparams_loader(_is_inkling2)
|
||||
@@ -274,7 +274,62 @@ class Inkling2Model(TextModel):
|
||||
yield from super().modify_tensors(data_torch, name, bid)
|
||||
|
||||
|
||||
@ModelBase.register("Inkling2ForConditionalGeneration")
|
||||
@ModelBase.register("Inkling2LoopForConditionalGeneration", "Inkling2LoopForCausalLM")
|
||||
class Inkling2LoopModel(Inkling2Model):
|
||||
model_arch = gguf.MODEL_ARCH.INKLING2_LOOP
|
||||
|
||||
# raw checkpoint and transformers names of the cross-pass message queries
|
||||
_query_kinds = {
|
||||
"model.middle_cycle_cross_pass_queries": "q",
|
||||
"model.middle_cycle_cross_pass_kv_queries": "kv",
|
||||
"model.cross_pass_messages.queries": "q",
|
||||
"model.cross_pass_messages.kv_queries": "kv",
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._queries: dict[str, Tensor] = {}
|
||||
self.loop = self.hparams["loop_config"]
|
||||
if set(self.loop) != {"core_start", "core_end", "num_passes", "gate_rank", "is_varloop"}:
|
||||
raise ValueError(f"Inkling2Loop: unsupported loop_config keys {sorted(self.loop)}")
|
||||
start, end, block = self.loop["core_start"], self.loop["core_end"], self.hparams["n_layers_per_attn_res_block"]
|
||||
# a fixed loop needs at least 2 passes, a variable loop at least 1
|
||||
min_passes = 1 if self.loop["is_varloop"] else 2
|
||||
if not 0 < start < end <= self.block_count or start % block or end % block or self.loop["num_passes"] < min_passes or self.loop["gate_rank"] < 1:
|
||||
raise ValueError(f"Inkling2Loop: invalid loop_config {self.loop}")
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
super().set_gguf_parameters()
|
||||
self.gguf_writer.add_loop_start(self.loop["core_start"])
|
||||
self.gguf_writer.add_loop_end(self.loop["core_end"])
|
||||
self.gguf_writer.add_loop_count(self.loop["num_passes"])
|
||||
self.gguf_writer.add_loop_gate_rank(self.loop["gate_rank"])
|
||||
self.gguf_writer.add_loop_varying(self.loop["is_varloop"])
|
||||
|
||||
def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool:
|
||||
# the reference does not quantize the loop tensors
|
||||
if new_name.endswith(("loop_msg_query.weight", "_ctrl_down.weight", "_ctrl_gain.weight", "_ctrl_forget.weight")):
|
||||
return gguf.GGMLQuantizationType.F32
|
||||
return super().tensor_force_quant(name, new_name, bid, n_dims)
|
||||
|
||||
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
|
||||
if name not in self._query_kinds:
|
||||
yield from super().modify_tensors(data_torch, name, bid)
|
||||
return
|
||||
self._queries[self._query_kinds[name]] = data_torch
|
||||
if len(self._queries) < 2:
|
||||
return
|
||||
q, kv = self._queries["q"], self._queries["kv"]
|
||||
start = self.loop["core_start"]
|
||||
if q.shape[0] != 2 * (self.loop["core_end"] - start) or kv.shape != q.shape:
|
||||
raise ValueError(f"Inkling2Loop: cross-pass queries {tuple(q.shape)} and {tuple(kv.shape)} do not match the loop core")
|
||||
# core layer start + i mixes its q, k, v and mlp messages with these four queries
|
||||
for i in range(q.shape[0] // 2):
|
||||
query = torch.stack([q[2 * i], kv[2 * i], kv[2 * i + 1], q[2 * i + 1]])
|
||||
yield self.format_tensor_name(gguf.MODEL_TENSOR.LOOP_MSG_QUERY, start + i, ".weight"), query
|
||||
|
||||
|
||||
@ModelBase.register("Inkling2ForConditionalGeneration", "Inkling2LoopForConditionalGeneration")
|
||||
class Inkling2VisionModel(MmprojModel):
|
||||
def get_vision_config(self):
|
||||
config = self.global_config.get("vision_config")
|
||||
|
||||
@@ -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
|
||||
|
||||
+15
-17
@@ -62,7 +62,7 @@ The packages for FP32 and FP16 would have different accuracy and performance on
|
||||
- 2026.04-05
|
||||
- Optimize mul_mat by reorder feature for data type: Q4_K, Q5_K, Q6_K, Q8_0.
|
||||
- Fused MoE.
|
||||
- Upgrate CI and built package for oneAPI 2025.3.3, support Ubuntu 24.04 built package.
|
||||
- Upgrade CI and built package for oneAPI 2025.3.3, support Ubuntu 24.04 built package.
|
||||
|
||||
- 2026.03
|
||||
- Support Flash-Attention: less memory usage, performance impact depends on LLM.
|
||||
@@ -131,8 +131,6 @@ SYCL backend supports Intel GPU Family:
|
||||
- Intel Built-in Arc GPU
|
||||
- Intel iGPU in Core CPU (11th Generation Core CPU and newer, refer to [oneAPI supported GPU](https://www.intel.com/content/www/us/en/developer/articles/system-requirements/intel-oneapi-base-toolkit-system-requirements.html#inpage-nav-1-1)).
|
||||
|
||||
On older Intel GPUs, you may try [OpenCL](/docs/backend/OPENCL.md) although the performance is not optimal, and some GPUs may not support OpenCL nor have any GPGPU capabilities.
|
||||
|
||||
#### Verified devices
|
||||
|
||||
| Intel GPU | Status | Verified Model |
|
||||
@@ -147,7 +145,7 @@ On older Intel GPUs, you may try [OpenCL](/docs/backend/OPENCL.md) although the
|
||||
*Notes:*
|
||||
|
||||
- **Memory**
|
||||
- The device memory is a limitation when running a large model. The loaded model size, *`llm_load_tensors: buffer_size`*, is displayed in the log when running `./bin/llama-completion`.
|
||||
- The device memory is a limitation when running a large model. The loaded model size is displayed in the log when running `./bin/llama-completion`, for example *`load_tensors: SYCL0 model buffer size = 3577.56 MiB`*.
|
||||
- Please make sure the GPU shared memory from the host is large enough to account for the model's size. For e.g. the *llama-2-7b.Q4_0* requires at least 8.0GB for integrated GPU and 4.0GB for discrete GPU.
|
||||
|
||||
- **Execution Unit (EU)**
|
||||
@@ -172,12 +170,12 @@ Please refer to [Docker with SYCL](../docker.md#docker-with-sycl) for details.
|
||||
|
||||
This chapter is for quick development & try with SYCL backend on Intel GPU.
|
||||
|
||||
You need to install following sofeware before development:
|
||||
You need to install following software before development:
|
||||
- Intel GPU driver
|
||||
- oneAPI package
|
||||
- other development tools.
|
||||
|
||||
Please refer to [Linux](#linux) or [Windows](#windows-1) for above installation and resolve the trouble in usage. There are the detailed guide.
|
||||
Please refer to [Linux](#linux) or [Windows](#windows-1) for above installation and resolve the trouble in usage. They have the detailed guide.
|
||||
|
||||
- Linux
|
||||
|
||||
@@ -474,7 +472,7 @@ Download the binary package for Windows from: https://github.com/ggml-org/llama.
|
||||
|
||||
Extract the package to local folder, run the llama tools directly. Refer to [Run the inference](#iii-run-the-inference-1).
|
||||
|
||||
Note, the package includes the SYCL running time and all depended dll files, no need to install oneAPI package and activte them.
|
||||
Note, the package includes the SYCL running time and all depended dll files, no need to install oneAPI package and activate them.
|
||||
|
||||
### Option 2: build locally from the source code.
|
||||
|
||||
@@ -484,7 +482,7 @@ Note, the package includes the SYCL running time and all depended dll files, no
|
||||
|
||||
If you already have a recent version of Microsoft Visual Studio, you can skip this step. Otherwise, please refer to the official download page for [Microsoft Visual Studio](https://visualstudio.microsoft.com/).
|
||||
|
||||
2. Install Intel® oneAPI Base toolkit
|
||||
2. Install Intel® oneAPI Toolkit
|
||||
|
||||
SYCL backend depends on:
|
||||
- Intel® oneAPI DPC++/C++ compiler/running-time.
|
||||
@@ -492,11 +490,10 @@ SYCL backend depends on:
|
||||
- Intel® oneAPI Deep Neural Network Library (oneDNN).
|
||||
- Intel® oneAPI Math Kernel Library (oneMKL).
|
||||
|
||||
All above are included in both **Intel® oneAPI Base toolkit** and **Intel® Deep Learning Essentials** packages.
|
||||
a. Install the toolkit
|
||||
|
||||
It's recommended to install **Intel® Deep Learning Essentials** which only provides the necessary libraries with less size.
|
||||
|
||||
The **Intel® oneAPI Base toolkit** and **Intel® Deep Learning Essentials** can be obtained from the official [Intel® oneAPI Base Toolkit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit.html) page.
|
||||
It's recommended to install the [Intel® oneAPI Toolkit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit.html).
|
||||
Alternatively, users can install **Intel® Deep Learning Essentials** + **oneDNN** to provide the necessary libraries with lesser size.
|
||||
|
||||
Please follow the instructions for downloading and installing the Toolkit for Windows, and preferably keep the default installation values unchanged, notably the installation path *(`C:\Program Files (x86)\Intel\oneAPI` by default)*.
|
||||
|
||||
@@ -792,7 +789,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
|
||||
| GGML_SYCL_GRAPH | ON *(default)* \|OFF *(Optional)* | Enable build with [SYCL Graph extension](https://github.com/intel/llvm/blob/sycl/sycl/doc/extensions/experimental/sycl_ext_oneapi_graph.asciidoc). |
|
||||
| GGML_SYCL_DNN | ON *(default)* \|OFF *(Optional)* | Enable build with oneDNN. |
|
||||
| GGML_SYCL_HOST_MEM_FALLBACK | ON *(default)* \|OFF *(Optional)* | Allow host memory fallback when device memory is full during quantized weight reorder. Enables inference to continue at reduced speed (reading over PCIe) instead of failing. Requires Linux kernel 6.8+. |
|
||||
| GGML_SYCL_SUPPORT_LEVEL_ZERO_API | ON *(default)* \|OFF *(Optional)* | Support to use Level Zero API for device memory allocation. Requires Level Zero headers/library at build time and Intel GPU driver (Level Zero runtime) at run time. Reduces system RAM usage during multi-GPU inference. SYCL backend always runs on Level Zero running time even if it's set as OFF (The SYCL api will be usage for memory allocation).|
|
||||
| GGML_SYCL_SUPPORT_LEVEL_ZERO_API | ON *(default)* \|OFF *(Optional)* | Support to use Level Zero API for device memory allocation. Requires Level Zero headers/library at build time and Intel GPU driver (Level Zero runtime) at run time. Reduces system RAM usage during multi-GPU inference. SYCL backend always runs on Level Zero running time even if it's set as OFF (the SYCL API is then used for memory allocation).|
|
||||
| CMAKE_C_COMPILER | `icx` *(Linux)*, `icx/cl` *(Windows)* | Set `icx` compiler for SYCL code path. |
|
||||
| CMAKE_CXX_COMPILER | `icpx` *(Linux)*, `icx` *(Windows)* | Set `icpx/icx` compiler for SYCL code path. |
|
||||
|
||||
@@ -809,11 +806,11 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
|
||||
| GGML_SYCL_ENABLE_OPT | 0 or 1 (default)| Enable optimize features for Intel GPUs. (Recommended to 0 for Intel devices older than Gen 10) |
|
||||
| GGML_SYCL_ENABLE_GRAPH | 0 (default) or 1 | Enable running computations through SYCL Graphs feature. Disabled by default because SYCL Graph is still in development, performance depends on model and device. [1.](#sycl-graph-footnote) |
|
||||
| GGML_SYCL_GRAPH_EVICTION_TIMEOUT | 10 (default) or positive integer | Seconds a cached SYCL graph can go unused before it is evicted. Checked on a sweep that runs every half of this timeout. |
|
||||
| GGML_SYCL_ENABLE_HOST_PINNED_MEM | 0 or 1 (default) | Enable host pinned memory to speed up copy data from host to device. When disable it, host memory will common malloc() on CPU. Disable it when use `--load-model mlock`.|
|
||||
| GGML_SYCL_ENABLE_HOST_PINNED_MEM | 0 or 1 (default) | Enable host pinned memory to speed up copy data from host to device. When disable it, host memory will common malloc() on CPU. Disable it when use `--load-mode mlock`.|
|
||||
| GGML_SYCL_HOST_PINNED_MEM_2G | 0 (default) or 1 | Limit the max memory allocation to be no more than 2GB when enable host pinned memory. USM allocations above 2 GiB take the relaxed/large-allocation path, which serializes H2D copies with compute and prevents copy/compute overlap. It will impact the startup time. Need more test. Depend on `GGML_SYCL_ENABLE_HOST_PINNED_MEM=1`.|
|
||||
| GGML_SYCL_UPLOAD_STAGING_SLOTS | 4 (default) or non-negative integer | Number of 8 MiB pinned host slots used to stage tensor uploads (model loading), so the host copy of one slot overlaps the transfer of the previous one. Set to 0 to use the old path: a malloc'd bounce buffer and a blocking copy per tensor. |
|
||||
| GGML_SYCL_GET_MEM_API | 0 (default) or 1 | Set to get memory info (free, total) by Level Zero or SYCL API:<br>0 - Level Zero API: support more GPUs, only run on Level Zero running time. When there is an error, fallback to call SYCL API. Depend on GGML_SYCL_SUPPORT_LEVEL_ZERO_API.<br>1 - SYCL API: legacy, support more running time, it can't get the free size of some GPUs (like Arc770). In such case, return the free size as value of total size.|
|
||||
| GGML_SYCL_USE_LEVEL_ZERO_API | 1 (default) or 0 | Use Level Zero API for device memory allocation instead of SYCL. Reduces system RAM usage on Intel dGPUs by avoiding DMA-buf/TTM host memory staging. Requires GGML_SYCL_SUPPORT_LEVEL_ZERO_API=ON at build time. SYCL backend always runs on Level Zero running time even if it's set as OFF (The SYCL api will be usage for memory allocation).|
|
||||
| GGML_SYCL_USE_LEVEL_ZERO_API | 1 (default) or 0 | Use Level Zero API for device memory allocation instead of SYCL. Reduces system RAM usage on Intel dGPUs by avoiding DMA-buf/TTM host memory staging. Requires GGML_SYCL_SUPPORT_LEVEL_ZERO_API=ON at build time. SYCL backend always runs on Level Zero running time even if it's set as OFF (the SYCL API is then used for memory allocation).|
|
||||
| GGML_SYCL_ENABLE_DNN | 0 or 1 (default)| Enable running computations through oneDNN and always use oneMKL. |
|
||||
| GGML_SYCL_FA_ONEDNN | 1 (default) or 0 | Enable the oneDNN fused SDPA (flash-attention) path on supported GPUs. Set to 0 to always use the native SYCL flash-attention kernel. |
|
||||
| GGML_SYCL_FA_ONEDNN_MAX_KV | 0 (default, disabled) or positive integer | By default (0), all sequences are handled by the oneDNN fused SDPA path, regardless of KV length; a positive value caps that length, past which sequences fall back to the native kernel. If GPU driver watchdog resets (DEVICE_LOST) occur during long-context inference, set this near the context depth where they start, e.g. 24576. |
|
||||
@@ -830,6 +827,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
|
||||
| GGML_SYCL_XMX_MAX_COLS | non-negative integer, 80 (default) | Most activation columns (batch size) the `GGML_SYCL_ENABLE_XMX_ESIMD` kernels take; wider batches use the other mat-mul kernels. A larger value keeps XMX for bigger batches (as repeated launches), `0` never uses it. |
|
||||
| GGML_SYCL_XMX_GLU_MAX_COLS | 0 to 16, 16 (default) | Most columns the fused gate and up XMX kernel takes; wider batches run gate and up as separate mat-vecs. 16 is the most the kernel is built for, larger values are clamped to 16 and `0` turns the fused kernel off. |
|
||||
| GGML_SYCL_XMX_GATHER_TYPES | decimal bitmask, all bits set (default) | Weight formats that may use the XMX dequant-GEMM paths, which dequantize weights straight into the XMX tiles. This speeds up prompt processing of MoE models on GPUs with XMX units (Arc A- and B-series, Arc Pro, Data Center GPU Max), for example pp512 of Qwen3-30B-A3B UD-IQ3_XXS by about 50% on an Arc Pro B60. Bits:<br>* 1: IQ4_NL, 2: IQ3_S, 4: IQ4_XS, 8: IQ3_XXS, 16: IQ2_XXS, 32: IQ2_XS, 64: IQ2_S, 128: IQ1_S, 256: IQ1_M<br>* 512: Q8_0, 1024: Q4_K, 2048: Q5_K, 4096: Q6_K, 8192: Q2_K, 16384: Q3_K (MoE `MUL_MAT_ID` only)<br>Add values to combine them, for example `3` for IQ4_NL and IQ3_S; `0` disables the paths. A set bit does not force the path: batches of more than 64 tokens per expert use the library GEMM unless the device schedule width heuristic is overridden with `GGML_SYCL_MMID_SCHED=3`. Row lengths must be a multiple of 256 (32 for IQ4_NL and Q8_0). |
|
||||
| GGML_SYCL_MMID_ESIMD | 0, 1 (default), 2 | The `MUL_MAT_ID` grouped XMX dequant-GEMM as an ESIMD kernel that dequantizes the weights straight into the `dpas` register operands, with no shared local memory image of them, from either weight layout (the per-expert reorder or the canonical blocks). q8_0, iq4_nl, iq4_xs, iq3_s, iq3_xxs and q2_K to q6_K. It stands in for the 8x16x16 sub-group-16 combination of f16 or bf16 (Xe2, Xe-HPC) and for the 8x8x16 sub-group-8 one (Xe-HPG: Arc A-series, ARL-H; there it works on 16 rows a thread and reads with 1D block loads, since that architecture has half the register file and no 2D block loads); while it is on, a grouped call whose weight type it covers is moved to that combination from any other shape of its type and sub-group size, whatever `GGML_SYCL_XMX_GATHER_SHAPES` allows, because the shape bits choose among `joint_matrix` tiles and the ESIMD kernel tiles on its own. A call it declines runs that combination's `joint_matrix` kernel. 0 uses the `joint_matrix` kernel, 1 the ESIMD one, 2 the ESIMD one summing K in the `joint_matrix` kernel's order (bit-identical output for f16; slower). An AOT build gets its 256-register file through `-ze-opt-enable-auto-large-GRF-mode` (set by the CMake build). Not built with `GGML_SYCL_SUPPORT_XMX=OFF`. |
|
||||
| GGML_SYCL_MMID_SCHED | decimal bitmask, 1 (default) | Build the grouped MoE routing and tile schedule on the GPU, avoiding the expert-ID host readback and CPU sort.<br>* 1: enable the device schedule.<br>* 2: override the fallback for models with few routed experts by disabling the performance heuristic that rejects batches averaging more than 64 routed rows per expert. This may reduce performance; type, shape, precision and device capability checks still apply.<br>Use `3` to enable the device schedule and override this heuristic, or `0` to use the host schedule. Bit 2 alone does not enable the device schedule. Higher bits are ignored. |
|
||||
| GGML_SYCL_XMX_GATHER_SHAPES | decimal bitmask, 255 (default) | XMX `joint_matrix` combinations the paths of `GGML_SYCL_XMX_GATHER_TYPES` may use; the operand type comes from `GGML_SYCL_DYNAMIC_PRECISION` and the best supported combination is picked automatically (logged as `fg_pick_combo`). Bits:<br>* Xe2, Xe3, Xe-HPC: 1: f16 8x16x16, 2: f16 16x16x16, 4: f16 32x64x16, 8: f16 32x64x32, 32: tf32 8x16x8, 64: bf16 8x16x16<br>* Xe-HPG (Arc A770, ARL-H): 16: f16 8x8x16, 128: bf16 8x8x16<br>Clear a bit to exclude a combination, or set a single bit to force one for testing. |
|
||||
| GGML_SYCL_DYNAMIC_PRECISION | `F16` (default with `GGML_SYCL_F16=ON`), `BF16`, `TF32` or `F32` (default otherwise) | Operand type of the XMX dequant-GEMM paths (`GGML_SYCL_XMX_GATHER_TYPES`); accumulation is always f32. `F16` is the fastest, but activations above 65504 overflow. `BF16` keeps the f32 range at a 7-bit mantissa, `TF32` keeps the range and the f16 mantissa but is about 30% slower and needs Xe2, Xe3 or Xe-HPC, and `F32` turns the XMX paths off. Ops that request a higher src1 precision ([TAG_GGML_PREC]) get it regardless of this setting. |
|
||||
@@ -839,7 +837,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
|
||||
| GGML_SYCL_SPARSE_FA_DEBUG | 0 (default) or 1 | Enable to debug for Sparse Flash-attention.|
|
||||
| GGML_SYCL_SPARSE_FA_MARGIN | [0,..] default:256 | Set the margin value for Sparse Flash-attention.|
|
||||
| ZES_ENABLE_SYSMAN | 0 (default) or 1 | Support to get free memory of GPU by sycl::aspect::ext_intel_free_memory.<br>Recommended to use when --split-mode = layer |
|
||||
| UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS | 0 (default) or 1 | Allow SYCL/Unified Runtime Level Zero device allocations larger than 4 GiB. llama.cpp's direct Level Zero allocation path requests the relaxed maximum-size limit itself when GGML_SYCL_ENABLE_LEVEL_ZERO=1. |
|
||||
| UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS | 0 (default) or 1 | Allow SYCL/Unified Runtime Level Zero device allocations larger than 4 GiB. llama.cpp's direct Level Zero allocation path requests the relaxed maximum-size limit itself when GGML_SYCL_USE_LEVEL_ZERO_API=1. |
|
||||
| GGML_SYCL_USM_SYSTEM | 0 (default) or 1 | Enable experimental support for [USM system allocations](https://github.khronos.org/SYCL_Reference/iface/usm_basic_concept.html#system-allocations) for large GPU buffers. This requires enough host memory for model weights and caches, an Intel Xe2+ GPU such as BMG or newer and supported on Linux only, with CONFIG_DRM_XE_GPUSVM enabled. |
|
||||
| GGML_SYCL_BMG_VRAM_CHECK | 1 (default) or 0 | Workaround for BMG (Arc B-series) GPUs, where the Level Zero driver accepts device allocations beyond VRAM and moves the overflow to system RAM, which can exhaust host memory when a model does not fit (e.g. `-ngl 999`, see https://github.com/intel/compute-runtime/issues/1047). When enabled, a model or split buffer that does not fit in the device's free memory is refused and the model load fails with an error. Set to 0 to disable. |
|
||||
|
||||
@@ -950,7 +948,7 @@ Pass these via `CXXFLAGS` or add a one-off `#define` to enable a flag on the spo
|
||||
|
||||
- `ggml_backend_sycl_buffer_type_alloc_buffer: can't allocate 5000000000 Bytes of memory on device`
|
||||
|
||||
With the default `GGML_SYCL_ENABLE_LEVEL_ZERO=1`, llama.cpp requests Level Zero's relaxed maximum-size allocation limit directly. If Level Zero support is disabled at build time or runtime and the allocation goes through SYCL/Unified Runtime instead, enable support for allocations larger than 4 GiB by:
|
||||
With the default `GGML_SYCL_USE_LEVEL_ZERO_API=1`, llama.cpp requests Level Zero's relaxed maximum-size allocation limit directly. If Level Zero support is disabled at build time or runtime and the allocation goes through SYCL/Unified Runtime instead, enable support for allocations larger than 4 GiB by:
|
||||
```
|
||||
export UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS=1
|
||||
set UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS=1
|
||||
|
||||
+13
-5
@@ -132,7 +132,10 @@ Full steps, threading notes, and a fallback for older CMake: [AOCL.md](./backend
|
||||
|
||||
### Intel oneMKL
|
||||
|
||||
Building through oneAPI compilers will make avx_vnni instruction set available for intel processors that do not support avx512 and avx512_vnni. Please note that this build config **does not support Intel GPU**. For Intel GPU support, please refer to [llama.cpp for SYCL](./backend/SYCL.md).
|
||||
Building through oneAPI compilers will make avx_vnni instruction set available for intel processors that do not support avx512 and avx512_vnni.
|
||||
> Note: This build config **does not support Intel GPU and NPU**.
|
||||
> - For Intel GPU support, refer to [OpenVINO](#openvino), [SYCL](#sycl) and [Vulkan](#vulkan) backends.
|
||||
> - For Intel NPU support, refer to [OpenVINO](#openvino) backend.
|
||||
|
||||
- Using manual oneAPI installation:
|
||||
By default, `GGML_BLAS_VENDOR` is set to `Generic`, so if you already sourced intel environment script and assign `-DGGML_BLAS=ON` in cmake, the mkl version of Blas will automatically been selected. Otherwise please install oneAPI and follow the below steps:
|
||||
@@ -444,9 +447,9 @@ Launch `w64devkit.exe` and run the following commands to copy Vulkan dependencie
|
||||
```sh
|
||||
SDK_VERSION=1.3.283.0
|
||||
cp /VulkanSDK/$SDK_VERSION/Bin/glslc.exe $W64DEVKIT_HOME/bin/
|
||||
cp /VulkanSDK/$SDK_VERSION/Lib/vulkan-1.lib $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/
|
||||
cp -r /VulkanSDK/$SDK_VERSION/Include/* $W64DEVKIT_HOME/x86_64-w64-mingw32/include/
|
||||
cat > $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/pkgconfig/vulkan.pc <<EOF
|
||||
cp /VulkanSDK/$SDK_VERSION/Lib/vulkan-1.lib $W64DEVKIT_HOME/lib/
|
||||
cp -r /VulkanSDK/$SDK_VERSION/Include/* $W64DEVKIT_HOME/include/
|
||||
cat > $W64DEVKIT_HOME/lib/pkgconfig/vulkan.pc <<EOF
|
||||
Name: Vulkan-Loader
|
||||
Description: Vulkan Loader
|
||||
Version: $SDK_VERSION
|
||||
@@ -890,9 +893,14 @@ To read documentation for how to build on IBM Z & LinuxONE, [click here](./build
|
||||
|
||||
[OpenVINO](https://docs.openvino.ai/) is an open-source toolkit for optimizing and deploying high-performance AI inference, specifically designed for Intel hardware (CPUs, GPUs, and NPUs).
|
||||
|
||||
Use this backend when you want to:
|
||||
|
||||
- Accelerate execution across Intel CPU, GPU and NPU with one runtime, selected at run time with `GGML_OPENVINO_DEVICE`. OpenVINO is the only backend with support for Intel NPU.
|
||||
- Let the runtime repack weights: GGUF quantized weights are repacked, or re-quantized where needed, to match OpenVINO's optimized low-bit kernels.
|
||||
|
||||
For build instructions and usage examples, refer to [OPENVINO.md](backend/OPENVINO.md).
|
||||
|
||||
### Hexagon
|
||||
## Hexagon
|
||||
|
||||
Check [README.md](./backend/snapdragon/README.md) for target specific build and run info.
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
+2
-2
@@ -97,7 +97,7 @@ Legend:
|
||||
| REPEAT_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| RMS_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RMS_NORM_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROUND | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
@@ -133,4 +133,4 @@ Legend:
|
||||
| TRI | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TRUNC | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| UPSCALE | ❌ | 🟡 | ✅ | ✅ | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
|
||||
+4
-4
@@ -16812,11 +16812,11 @@
|
||||
"OpenCL","CUMSUM","type=f32,ne=[242004,1,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","CUMSUM","type=f32,ne=[375960,1,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","CUMSUM","type=f32,ne=[20481,4,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=bf16,ne=[10,5,4,3]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=bf16,ne=[512,16,1,1]","support","0","no","OpenCL"
|
||||
"OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=3","support","1","yes","OpenCL"
|
||||
"OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=2","support","1","yes","OpenCL"
|
||||
|
||||
|
Can't render this file because it is too large.
|
+7
-1
@@ -12345,7 +12345,13 @@
|
||||
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[257,7,1,1],pad_0=0,pad_1=256,view=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[2,16777217,1,1],pad_0=1,pad_1=1,view=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[3000,384,4,1],pad_0=10,pad_1=9,view=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=0,ne_a=[10,5,4,3]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=1,ne_a=[10,5,4,3]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=0,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[1,1,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=256,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[257,1,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=-16,shift1=6,shift3=-2,shift4=1,permute=0,ne_a=[17,7,3,2]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[42,512,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[380,512,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ARANGE","type=f32,start=0.000000,stop=10.000000,step=1.000000","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ARANGE","type=f32,start=3.000000,stop=3.500000,step=1.000000","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ARANGE","type=f32,start=-10.000000,stop=10.000000,step=0.300000","support","1","yes","WebGPU"
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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:
|
||||
|
||||
@@ -2981,8 +2981,6 @@ class tinyBLAS_Q0_PPC {
|
||||
int64_t n_aligned = 0;
|
||||
if (n % n_chunk == 0) {
|
||||
n_aligned = n;
|
||||
} else if (n == 4) {
|
||||
n_aligned = 4;
|
||||
} else if (n < n_chunk) {
|
||||
n_aligned = (n / 8) * 8;
|
||||
} else {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -226,7 +226,15 @@ set(GGML_OPENCL_KERNELS
|
||||
gemm_noshuffle_q4_0_q8_1_dp4a
|
||||
gemm_coopk_q4_0_q8_1_dp4a
|
||||
gemm_coopk_q4_k_q8_1_dp4a
|
||||
gemm_coopk_q4_k_q8_1_dp4a_bin_c8
|
||||
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
|
||||
|
||||
@@ -1163,6 +1163,8 @@ struct ggml_backend_opencl_context {
|
||||
cl_kernel kernel_sgn_f32, kernel_sgn_f32_4, kernel_sgn_f32_nc, kernel_sgn_f16, kernel_sgn_f16_4, kernel_sgn_f16_nc;
|
||||
cl_kernel kernel_step_f32, kernel_step_f32_4, kernel_step_f32_nc, kernel_step_f16, kernel_step_f16_4, kernel_step_f16_nc;
|
||||
cl_kernel kernel_elu_f32, kernel_elu_f32_4, kernel_elu_f32_nc, kernel_elu_f16, kernel_elu_f16_4, kernel_elu_f16_nc;
|
||||
cl_kernel kernel_xielu_f32 = nullptr;
|
||||
cl_kernel kernel_xielu_f16 = nullptr;
|
||||
cl_kernel kernel_hardswish_f32, kernel_hardswish_f32_4, kernel_hardswish_f32_nc, kernel_hardswish_f16, kernel_hardswish_f16_4, kernel_hardswish_f16_nc;
|
||||
cl_kernel kernel_hardsigmoid_f32, kernel_hardsigmoid_f32_4, kernel_hardsigmoid_f32_nc, kernel_hardsigmoid_f16, kernel_hardsigmoid_f16_4, kernel_hardsigmoid_f16_nc;
|
||||
cl_kernel kernel_floor_f32, kernel_floor_f32_4, kernel_floor_f32_nc, kernel_floor_f16, kernel_floor_f16_4, kernel_floor_f16_nc;
|
||||
@@ -1495,6 +1497,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;
|
||||
@@ -1507,6 +1516,15 @@ struct ggml_backend_opencl_context {
|
||||
cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 = nullptr;
|
||||
int nsg_coopk_dp4a_q4_k_bin_c4 = 8;
|
||||
int nsg_coopk_dp4a_q4_k_bin_c2 = 8;
|
||||
cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = nullptr;
|
||||
cl_kernel kernel_quant_a_q8_1_k4 = nullptr;
|
||||
int nsg_coopk_dp4a_q4_k_bin_c8 = 4;
|
||||
cl_mem coopk_c8_qa_image = nullptr;
|
||||
cl_mem coopk_c8_qa_buffer = nullptr;
|
||||
size_t coopk_c8_qa_image_bytes = 0;
|
||||
cl_mem coopk_c8_ds_image = nullptr;
|
||||
cl_mem coopk_c8_ds_buffer = nullptr;
|
||||
size_t coopk_c8_ds_image_bytes = 0;
|
||||
cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c4 = nullptr;
|
||||
cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 = nullptr;
|
||||
int nsg_coopk_dp4a_q6_k = 8;
|
||||
@@ -1514,7 +1532,25 @@ struct ggml_backend_opencl_context {
|
||||
#endif // GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
|
||||
~ggml_backend_opencl_context() {
|
||||
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
for (cl_kernel kernel : {
|
||||
kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8,
|
||||
kernel_quant_a_q8_1_k4
|
||||
}
|
||||
) {
|
||||
if (kernel != nullptr) {
|
||||
CL_CHECK(clReleaseKernel(kernel));
|
||||
}
|
||||
}
|
||||
for (cl_mem image : {coopk_c8_qa_image, coopk_c8_ds_image}) {
|
||||
if (image != nullptr) {
|
||||
CL_CHECK(clReleaseMemObject(image));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
for (cl_kernel kernel : {
|
||||
kernel_xielu_f32,
|
||||
kernel_xielu_f16,
|
||||
kernel_mul_mm_f16_f32_kq_p8,
|
||||
kernel_mul_mm_q8_f32_kqv,
|
||||
kernel_fa_p8_fixup,
|
||||
@@ -1844,13 +1880,22 @@ static bool ggml_cl_coopk_dp4a_narrow_on(const ggml_backend_opencl_context * bac
|
||||
// COOPK_NSG sizes the local reduction buffer, so a smaller workgroup requires a rebuild.
|
||||
static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * backend_ctx,
|
||||
const char * kernel_src, const char * kernel_name,
|
||||
const std::string & opts_base, int & nsg) {
|
||||
const std::string & opts_base, int & nsg, bool fatal = true) {
|
||||
while (nsg >= 2) {
|
||||
const std::string opts = opts_base + " -DCOOPK_NSG=" + std::to_string(nsg);
|
||||
cl_program program = build_program_from_source(backend_ctx, kernel_src, opts);
|
||||
cl_program program = build_program_from_source(backend_ctx, kernel_src, opts, fatal);
|
||||
if (program == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
cl_int err;
|
||||
cl_kernel kernel = clCreateKernel(program, kernel_name, &err);
|
||||
CL_CHECK(err);
|
||||
if (err != CL_SUCCESS) {
|
||||
CL_CHECK(clReleaseProgram(program));
|
||||
if (fatal) {
|
||||
CL_CHECK(err);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
size_t max_workgroup_size = 0;
|
||||
CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE,
|
||||
sizeof(max_workgroup_size), &max_workgroup_size, NULL));
|
||||
@@ -1864,6 +1909,46 @@ static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * back
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backend_ctx) {
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
const std::string kernel_src {
|
||||
#include "gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl.h"
|
||||
};
|
||||
#else
|
||||
const std::string kernel_src = read_file("gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl");
|
||||
#endif
|
||||
cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(),
|
||||
"kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts,
|
||||
backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8, false);
|
||||
if (program == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
cl_int err;
|
||||
|
||||
cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", &err);
|
||||
if (err != CL_SUCCESS) {
|
||||
CL_CHECK(clReleaseProgram(program));
|
||||
return;
|
||||
}
|
||||
|
||||
cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4", &err);
|
||||
CL_CHECK(clReleaseProgram(program));
|
||||
if (err != CL_SUCCESS) {
|
||||
CL_CHECK(clReleaseKernel(gemm));
|
||||
return;
|
||||
}
|
||||
|
||||
if (backend_ctx->get_kernel_workgroup_size(quant) < 64) {
|
||||
CL_CHECK(clReleaseKernel(gemm));
|
||||
CL_CHECK(clReleaseKernel(quant));
|
||||
return;
|
||||
}
|
||||
|
||||
backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = gemm;
|
||||
backend_ctx->kernel_quant_a_q8_1_k4 = quant;
|
||||
}
|
||||
|
||||
static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx,
|
||||
const std::string & kernel_src, const char * kernel_name,
|
||||
int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) {
|
||||
@@ -1933,8 +2018,12 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx
|
||||
backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c4,
|
||||
backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c2);
|
||||
|
||||
const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN");
|
||||
if (use_adreno_bin_kernels(backend_ctx) && (!env || !*env || atoi(env) != 0)) {
|
||||
static const bool use_coopk_bin = [] {
|
||||
const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN");
|
||||
return !env || !*env || atoi(env) != 0;
|
||||
}();
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) {
|
||||
const std::string base_opts = backend_ctx->kernel_compile_opts
|
||||
+ " -DCOOPK_Q_BIN=1 -DCOOPK_ROWS=" + std::to_string(backend_ctx->rows_coopk_dp4a_q4_k);
|
||||
for (int cols = 4; cols >= 2; cols -= 2) {
|
||||
@@ -1958,6 +2047,7 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx
|
||||
}
|
||||
nsg = nsg_eff;
|
||||
}
|
||||
load_cl_kernel_coopk_q4_k_bin_c8(backend_ctx);
|
||||
}
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
@@ -1979,6 +2069,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) {
|
||||
@@ -4701,6 +4922,8 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
|
||||
CL_UNARY_EXT_K(round)
|
||||
CL_UNARY_EXT_K(trunc)
|
||||
#undef CL_UNARY_EXT_K
|
||||
CL_CHECK((backend_ctx->kernel_xielu_f32 = clCreateKernel(prog, "kernel_xielu_f32", &err), err));
|
||||
CL_CHECK((backend_ctx->kernel_xielu_f16 = clCreateKernel(prog, "kernel_xielu_f16", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
@@ -7813,6 +8036,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 +11963,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 +12118,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 +12137,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 +12156,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);
|
||||
@@ -12064,6 +12292,14 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
|
||||
case GGML_UNARY_OP_SILU:
|
||||
return op->src[0]->type == op->type &&
|
||||
(op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
|
||||
case GGML_UNARY_OP_XIELU:
|
||||
for (int64_t ne : op->src[0]->ne) {
|
||||
if (ne > INT_MAX) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return op->src[0]->type == op->type &&
|
||||
(op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
|
||||
case GGML_UNARY_OP_GELU:
|
||||
case GGML_UNARY_OP_RELU:
|
||||
case GGML_UNARY_OP_GELU_ERF:
|
||||
@@ -21096,6 +21332,51 @@ GGML_CL_UNARY_EXT_WRAP(ggml_cl_trunc, trunc)
|
||||
|
||||
#undef GGML_CL_UNARY_EXT_WRAP
|
||||
|
||||
static void ggml_cl_xielu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
UNUSED(src1);
|
||||
|
||||
auto * backend_ctx = (ggml_backend_opencl_context *) backend->context;
|
||||
cl_kernel kernel = src0->type == GGML_TYPE_F16 ? backend_ctx->kernel_xielu_f16 : backend_ctx->kernel_xielu_f32;
|
||||
|
||||
const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra;
|
||||
const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra;
|
||||
|
||||
const cl_ulong offset0 = extra0->offset + src0->view_offs;
|
||||
const cl_ulong offsetd = extrad->offset + dst->view_offs;
|
||||
|
||||
GGML_TENSOR_LOCALS(int, ne0, src0, ne);
|
||||
GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb);
|
||||
GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb);
|
||||
|
||||
const float alpha_n = ggml_get_op_params_f32(dst, 1);
|
||||
const float alpha_p = ggml_get_op_params_f32(dst, 2);
|
||||
const float beta = ggml_get_op_params_f32(dst, 3);
|
||||
const float eps = ggml_get_op_params_f32(dst, 4);
|
||||
|
||||
CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device));
|
||||
CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0));
|
||||
CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device));
|
||||
CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd));
|
||||
CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00));
|
||||
CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00));
|
||||
CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01));
|
||||
CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02));
|
||||
CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03));
|
||||
CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0));
|
||||
CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1));
|
||||
CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2));
|
||||
CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3));
|
||||
CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &alpha_n));
|
||||
CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &alpha_p));
|
||||
CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &beta));
|
||||
CL_CHECK(clSetKernelArg(kernel, 16, sizeof(float), &eps));
|
||||
|
||||
const size_t nth = 64;
|
||||
size_t global[] = {(size_t) ne01*nth, (size_t) ne02, (size_t) ne03};
|
||||
size_t local[] = {nth, 1, 1};
|
||||
backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst);
|
||||
}
|
||||
|
||||
static void ggml_cl_softplus(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
GGML_ASSERT(src0);
|
||||
GGML_ASSERT(src0->extra);
|
||||
@@ -25619,6 +25900,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 +26257,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 +26826,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 +27673,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");
|
||||
@@ -27917,6 +28255,69 @@ static void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_t
|
||||
}
|
||||
|
||||
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
// make sure the image1d_buffer `image` is a proper view of `buffer` by either
|
||||
// creating a new image1d_buffer or reuse existing one.
|
||||
// upon success, `image_buffer` is set to the cl_mem in `buffer` and
|
||||
// `image_bytes` the size in `buffer` and `image` is the image1d_buffer.
|
||||
static bool ggml_cl_coopk_c8_image(
|
||||
ggml_backend_opencl_context * backend_ctx,
|
||||
ggml_cl_buffer & buffer,
|
||||
size_t bytes,
|
||||
cl_mem & image,
|
||||
cl_mem & image_buffer,
|
||||
size_t & image_bytes
|
||||
) {
|
||||
// required bytes exceed image1d_buffer limit
|
||||
if (bytes / 16 > backend_ctx->image_max_buffer_size) {
|
||||
return false;
|
||||
}
|
||||
// existing image1d_buffer can be reused
|
||||
if (image != nullptr && image_buffer == buffer.buffer && image_bytes >= bytes) {
|
||||
return true;
|
||||
}
|
||||
// a new one is needed, so release the existing one
|
||||
if (image != nullptr) {
|
||||
CL_CHECK(clReleaseMemObject(image));
|
||||
image = nullptr;
|
||||
}
|
||||
|
||||
image_buffer = nullptr;
|
||||
image_bytes = 0;
|
||||
|
||||
cl_image_format format = {CL_RGBA, CL_UNSIGNED_INT32};
|
||||
cl_image_desc desc = {};
|
||||
desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER;
|
||||
desc.image_width = bytes / 16;
|
||||
desc.buffer = buffer.buffer;
|
||||
|
||||
cl_int err;
|
||||
image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err);
|
||||
if (err != CL_SUCCESS) {
|
||||
image = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
image_buffer = buffer.buffer;
|
||||
image_bytes = bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
static int ggml_cl_coopk_ksplit(const ggml_backend_opencl_context * backend_ctx, int base_wg, int n_blocks) {
|
||||
const int cu = MAX(1, (int) backend_ctx->fa.compute_units);
|
||||
int ksplit = 1;
|
||||
float best_eff = 0.0f;
|
||||
for (int k = 1; k <= MIN(8, n_blocks); ++k) {
|
||||
const int wg = base_wg * k;
|
||||
const int waves = CEIL_DIV(wg, cu);
|
||||
const float eff = (float) wg / (waves * cu);
|
||||
if (eff > best_eff + 0.06f) {
|
||||
best_eff = eff;
|
||||
ksplit = k;
|
||||
}
|
||||
}
|
||||
return ksplit;
|
||||
}
|
||||
|
||||
static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
GGML_ASSERT(src0);
|
||||
@@ -27954,11 +28355,100 @@ static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const gg
|
||||
int N = ne1;
|
||||
int K = ne00;
|
||||
|
||||
const int coopk_c8_min_n = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 2 : 5;
|
||||
if (backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 != nullptr &&
|
||||
N >= coopk_c8_min_n && N <= 8 && M > 0 && K > 0 && M % 256 == 0 && K % 256 == 0 &&
|
||||
src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N &&
|
||||
K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX &&
|
||||
src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr &&
|
||||
src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 &&
|
||||
ggml_is_contiguous(src1) && ggml_is_contiguous(dst)
|
||||
) {
|
||||
const int kb = K / 32;
|
||||
const size_t qa_bytes = (size_t)8 * K;
|
||||
const size_t ds_bytes = (size_t)16 * kb * sizeof(cl_half);
|
||||
|
||||
backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes);
|
||||
backend_ctx->prealloc_moe_da.allocate(context, ds_bytes);
|
||||
|
||||
if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes,
|
||||
backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) &&
|
||||
ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes,
|
||||
backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes)
|
||||
) {
|
||||
const int n_blocks = N * kb;
|
||||
|
||||
cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4;
|
||||
CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device));
|
||||
CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer));
|
||||
CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer));
|
||||
CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1));
|
||||
CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks));
|
||||
CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb));
|
||||
|
||||
size_t quant_local[] = {64};
|
||||
size_t quant_global[] = {(size_t)8 * kb};
|
||||
backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst);
|
||||
|
||||
int ksplit = ggml_cl_coopk_ksplit(backend_ctx, M / 256, kb);
|
||||
if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) {
|
||||
ksplit = 1;
|
||||
}
|
||||
|
||||
cl_mem out = extrad->data_device;
|
||||
cl_ulong out_offset = offsetd;
|
||||
|
||||
if (ksplit > 1) {
|
||||
backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float));
|
||||
out = backend_ctx->prealloc_splitk_partial.buffer;
|
||||
out_offset = 0;
|
||||
}
|
||||
|
||||
const cl_uchar mask_d6 = 0x3F;
|
||||
const cl_uchar mask_d4 = 0x0F;
|
||||
const cl_uchar mask_hi2 = 0xC0;
|
||||
|
||||
const size_t nsg = backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8;
|
||||
cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8;
|
||||
|
||||
CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q4_k->q));
|
||||
CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q4_k->s));
|
||||
CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q4_k->d));
|
||||
CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q4_k->dm));
|
||||
CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image));
|
||||
CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image));
|
||||
CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out));
|
||||
CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset));
|
||||
CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M));
|
||||
CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K));
|
||||
CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N));
|
||||
CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_d6));
|
||||
CL_CHECK(clSetKernelArg(gemm, 12, sizeof(cl_uchar), &mask_d4));
|
||||
CL_CHECK(clSetKernelArg(gemm, 13, sizeof(cl_uchar), &mask_hi2));
|
||||
CL_CHECK(clSetKernelArg(gemm, 14, sizeof(int), &ksplit));
|
||||
|
||||
size_t local[] = {64, nsg, 1};
|
||||
size_t global[] = {(size_t)M / 4, nsg * ksplit, 1};
|
||||
backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst);
|
||||
|
||||
if (ksplit > 1) {
|
||||
const int rows = M * N;
|
||||
cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32;
|
||||
CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out));
|
||||
CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device));
|
||||
CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd));
|
||||
CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows));
|
||||
CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit));
|
||||
size_t reduce_local[] = {64};
|
||||
size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64};
|
||||
backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// CoopK handles with _bin use the bin weight layout (uint-transposed q), with K-major Q8_1 activations (K contiguous).
|
||||
// This switch disables only this bin-layout path; weight conversion is unchanged.
|
||||
static const char * env_coopk_bin = getenv("GGML_OPENCL_COOPK_Q4_K_BIN");
|
||||
const bool use_coopk_bin = !env_coopk_bin || !*env_coopk_bin || atoi(env_coopk_bin) != 0;
|
||||
if (use_coopk_bin && ne1 >= 2 && ne1 <= 4 &&
|
||||
if (ne1 >= 2 && ne1 <= 4 &&
|
||||
ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->rows_coopk_dp4a_q4_k) &&
|
||||
backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4 != nullptr &&
|
||||
((ne1 <= 2) ? backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2
|
||||
@@ -28321,6 +28811,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 +29726,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 +30471,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;
|
||||
@@ -40301,6 +40806,10 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor
|
||||
if (!any_on_device) { return false; }
|
||||
func = ggml_cl_elu;
|
||||
break;
|
||||
case GGML_UNARY_OP_XIELU:
|
||||
if (!any_on_device) { return false; }
|
||||
func = ggml_cl_xielu;
|
||||
break;
|
||||
case GGML_UNARY_OP_HARDSWISH:
|
||||
if (!any_on_device) { return false; }
|
||||
func = ggml_cl_hardswish;
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
|
||||
#ifdef cl_khr_integer_dot_product
|
||||
#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable
|
||||
#endif
|
||||
|
||||
#ifndef COOPK_NSG
|
||||
#define COOPK_NSG 4
|
||||
#endif
|
||||
#define COK_SG 64
|
||||
#define COK_ROWS 4
|
||||
|
||||
#define COK_PACK4(a, b, c, e) \
|
||||
(((uint)(a) & 0xFFu) | (((uint)(b) & 0xFFu) << 8) | (((uint)(c) & 0xFFu) << 16) | (((uint)(e) & 0xFFu) << 24))
|
||||
|
||||
// Pack each four K values as (0, 2, 1, 3); scales and sums are interleaved at width eight.
|
||||
kernel void kernel_quant_a_q8_1_k4(
|
||||
global const float * src,
|
||||
global uint * qa,
|
||||
global half * ds,
|
||||
ulong offset_src,
|
||||
int total_blocks,
|
||||
int k_b
|
||||
) {
|
||||
const int blk = get_global_id(0);
|
||||
if (blk >= 8 * k_b) {
|
||||
return;
|
||||
}
|
||||
const int col = blk / k_b;
|
||||
const int b = blk % k_b;
|
||||
if (blk >= total_blocks) {
|
||||
vstore8((uint8)(0), 0, qa + blk * 8);
|
||||
ds[(2 * b) * 8 + col] = (half)0;
|
||||
ds[(2 * b + 1) * 8 + col] = (half)0;
|
||||
return;
|
||||
}
|
||||
src = (global const float *)((global const char *)src + offset_src);
|
||||
const int base = blk * 32;
|
||||
float v[32];
|
||||
float amax = 0.0f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
v[i] = src[base + i];
|
||||
amax = fmax(amax, fabs(v[i]));
|
||||
}
|
||||
const float d = amax / 127.0f;
|
||||
const float id = amax > 0.0f ? 127.0f / amax : 0.0f;
|
||||
int q[32];
|
||||
int sum = 0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
q[i] = (int)rint(v[i] * id);
|
||||
sum += q[i];
|
||||
}
|
||||
uint8 out;
|
||||
out.s0 = COK_PACK4(q[ 0], q[ 2], q[ 1], q[ 3]);
|
||||
out.s1 = COK_PACK4(q[ 4], q[ 6], q[ 5], q[ 7]);
|
||||
out.s2 = COK_PACK4(q[ 8], q[10], q[ 9], q[11]);
|
||||
out.s3 = COK_PACK4(q[12], q[14], q[13], q[15]);
|
||||
out.s4 = COK_PACK4(q[16], q[18], q[17], q[19]);
|
||||
out.s5 = COK_PACK4(q[20], q[22], q[21], q[23]);
|
||||
out.s6 = COK_PACK4(q[24], q[26], q[25], q[27]);
|
||||
out.s7 = COK_PACK4(q[28], q[30], q[29], q[31]);
|
||||
vstore8(out, 0, qa + blk * 8);
|
||||
ds[(2 * b) * 8 + col] = (half)d;
|
||||
ds[(2 * b + 1) * 8 + col] = (half)(d * (float)sum);
|
||||
}
|
||||
|
||||
#define COK_SPREAD(t) (((t) | ((t) << 12)) & 0x0F0F0F0Fu)
|
||||
#define COK_DOT_RC4(r, c) \
|
||||
d##r.s##c = dot_acc_sat_4x8packed_ss_int(W0.s##r, A.s0, d##r.s##c); \
|
||||
d##r.s##c = dot_acc_sat_4x8packed_ss_int(W1.s##r, A.s1, d##r.s##c); \
|
||||
d##r.s##c = dot_acc_sat_4x8packed_ss_int(W2.s##r, A.s2, d##r.s##c); \
|
||||
d##r.s##c = dot_acc_sat_4x8packed_ss_int(W3.s##r, A.s3, d##r.s##c);
|
||||
#define COK_DOT_COL4(c, t) \
|
||||
{ const uint4 A = read_imageui(src1_qa, (c) * k_t + (t)); \
|
||||
COK_DOT_RC4(0, c) COK_DOT_RC4(1, c) COK_DOT_RC4(2, c) COK_DOT_RC4(3, c) }
|
||||
|
||||
kernel void kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8(
|
||||
global const uint * src0_q,
|
||||
global const uchar * src0_s,
|
||||
global const half * src0_d,
|
||||
global const half * src0_dm,
|
||||
read_only image1d_buffer_t src1_qa,
|
||||
read_only image1d_buffer_t src1_ds,
|
||||
global float * dst,
|
||||
ulong offsetd,
|
||||
int m,
|
||||
int k,
|
||||
int n_no_padding,
|
||||
uchar mask_d6,
|
||||
uchar mask_d4,
|
||||
uchar mask_hi2,
|
||||
int ksplit
|
||||
) {
|
||||
dst = (global float *)((global char *)dst + offsetd);
|
||||
const int gx = get_global_id(0);
|
||||
const int sg = get_local_id(1);
|
||||
const int lane = get_local_id(0);
|
||||
const int ks = get_group_id(1);
|
||||
const int row0 = gx * COK_ROWS;
|
||||
const int num_32blk = k / 32;
|
||||
const int k_t = k >> 4;
|
||||
const int fence = (int)(mask_d6 >> 6);
|
||||
const int nslice = ksplit * COOPK_NSG;
|
||||
const int chunk = (num_32blk + nslice - 1) / nslice;
|
||||
const int b_beg = (ks * COOPK_NSG + sg) * chunk;
|
||||
const int b_end = min(b_beg + chunk, num_32blk);
|
||||
float8 acc0 = (float8)(0.0f), acc1 = (float8)(0.0f);
|
||||
float8 acc2 = (float8)(0.0f), acc3 = (float8)(0.0f);
|
||||
|
||||
for (int sb = b_beg >> 3; sb * 8 < b_end; ++sb) {
|
||||
const half4 dd = vload4(0, src0_d + row0 + sb * m);
|
||||
const half4 dmm = vload4(0, src0_dm + row0 + sb * m);
|
||||
global const uchar * sc = src0_s + sb * 12 * m + row0;
|
||||
const int j_beg = max(b_beg - sb * 8, 0);
|
||||
const int j_end = min(b_end - sb * 8, 8);
|
||||
for (int j = j_beg; j < j_end; ++j) {
|
||||
const int blk = sb * 8 + j;
|
||||
int8 d0 = (int8)(0), d1 = (int8)(0), d2 = (int8)(0), d3 = (int8)(0);
|
||||
for (int h = 0; h < 2; ++h) {
|
||||
const int u0 = (blk << 2) + (h << 1);
|
||||
const int at = (blk << 1) + h;
|
||||
const uint4 wa = vload4(0, src0_q + row0 + u0 * m);
|
||||
const uint4 wb = vload4(0, src0_q + row0 + (u0 + 1) * m);
|
||||
const uint4 W0 = COK_SPREAD(wa & 0xFFFFu);
|
||||
const uint4 W1 = COK_SPREAD(wa >> 16);
|
||||
const uint4 W2 = COK_SPREAD(wb & 0xFFFFu);
|
||||
const uint4 W3 = COK_SPREAD(wb >> 16);
|
||||
COK_DOT_COL4(0, at) COK_DOT_COL4(1, at) COK_DOT_COL4(2, at) COK_DOT_COL4(3, at)
|
||||
// Keep the second activation group dependent on the first dot products.
|
||||
const int at4 = at + (d0.s0 & fence);
|
||||
COK_DOT_COL4(4, at4) COK_DOT_COL4(5, at4) COK_DOT_COL4(6, at4) COK_DOT_COL4(7, at4)
|
||||
}
|
||||
uchar4 scv, mnv;
|
||||
if (j < 4) {
|
||||
scv = vload4(0, sc + j * m) & (uchar4)(mask_d6);
|
||||
mnv = vload4(0, sc + (j + 4) * m) & (uchar4)(mask_d6);
|
||||
} else {
|
||||
const uchar4 bh = vload4(0, sc + (j + 4) * m);
|
||||
const uchar4 bl = vload4(0, sc + (j - 4) * m);
|
||||
const uchar4 bj = vload4(0, sc + j * m);
|
||||
scv = (bh & (uchar4)(mask_d4)) | ((bl >> (uchar4)(6)) << (uchar4)(4));
|
||||
mnv = (bh >> (uchar4)(4)) | ((bj >> (uchar4)(6)) << (uchar4)(4));
|
||||
}
|
||||
const float4 scf = convert_float4(dd) * convert_float4(scv);
|
||||
const float4 mnf = convert_float4(dmm) * convert_float4(mnv);
|
||||
const float8 da = convert_float8(as_half8(read_imageui(src1_ds, 2 * blk)));
|
||||
acc0 = mad(convert_float8(d0), da * scf.s0, acc0);
|
||||
acc1 = mad(convert_float8(d1), da * scf.s1, acc1);
|
||||
acc2 = mad(convert_float8(d2), da * scf.s2, acc2);
|
||||
acc3 = mad(convert_float8(d3), da * scf.s3, acc3);
|
||||
const float8 sa = convert_float8(as_half8(read_imageui(src1_ds, 2 * blk + 1)));
|
||||
acc0 = mad(sa, -mnf.s0, acc0);
|
||||
acc1 = mad(sa, -mnf.s1, acc1);
|
||||
acc2 = mad(sa, -mnf.s2, acc2);
|
||||
acc3 = mad(sa, -mnf.s3, acc3);
|
||||
}
|
||||
}
|
||||
|
||||
local float8 reduceLM[COK_SG * (COOPK_NSG - 1)];
|
||||
float8 out0 = (float8)(0.0f), out1 = (float8)(0.0f);
|
||||
float8 out2 = (float8)(0.0f), out3 = (float8)(0.0f);
|
||||
#define COK_REDUCE(accv, outv) \
|
||||
barrier(CLK_LOCAL_MEM_FENCE); \
|
||||
if (sg > 0) { reduceLM[(sg - 1) * COK_SG + lane] = (accv); } \
|
||||
barrier(CLK_LOCAL_MEM_FENCE); \
|
||||
if (sg == 0) { \
|
||||
float8 sum = (accv); \
|
||||
for (int s = 0; s < COOPK_NSG - 1; s++) { sum += reduceLM[s * COK_SG + lane]; } \
|
||||
(outv) = sum; \
|
||||
}
|
||||
COK_REDUCE(acc0, out0)
|
||||
COK_REDUCE(acc1, out1)
|
||||
COK_REDUCE(acc2, out2)
|
||||
COK_REDUCE(acc3, out3)
|
||||
#undef COK_REDUCE
|
||||
#define COK_STORE_COL(c) \
|
||||
if ((c) < n_no_padding) { \
|
||||
vstore4((float4)(out0.s##c, out1.s##c, out2.s##c, out3.s##c), 0, dst + (c) * m + row0); \
|
||||
}
|
||||
if (sg == 0) {
|
||||
dst += (size_t)ks * (size_t)m * (size_t)n_no_padding;
|
||||
COK_STORE_COL(0) COK_STORE_COL(1) COK_STORE_COL(2) COK_STORE_COL(3)
|
||||
COK_STORE_COL(4) COK_STORE_COL(5) COK_STORE_COL(6) COK_STORE_COL(7)
|
||||
}
|
||||
#undef COK_STORE_COL
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,3 +83,29 @@ UNARY_EXT(floor, floor(x), floor
|
||||
UNARY_EXT(ceil, ceil(x), ceil(x))
|
||||
UNARY_EXT(round, round(x), round(x))
|
||||
UNARY_EXT(trunc, trunc(x), trunc(x))
|
||||
|
||||
// xielu has more args, cannot fit in UNARY_EXT
|
||||
inline float xielu(float x, float alpha_n, float alpha_p, float beta, float eps) {
|
||||
return x > 0.0f ? alpha_p*x*x + beta*x : (expm1(fmin(x, eps)) - x)*alpha_n + beta*x;
|
||||
}
|
||||
|
||||
#define XIELU_KERNEL(NAME, TYPE) \
|
||||
kernel void kernel_xielu_##NAME( \
|
||||
global const char * src0, ulong offset0, \
|
||||
global char * dst, ulong offsetd, \
|
||||
int ne00, ulong nb00, ulong nb01, ulong nb02, ulong nb03, \
|
||||
ulong nb0, ulong nb1, ulong nb2, ulong nb3, \
|
||||
float alpha_n, float alpha_p, float beta, float eps) { \
|
||||
const size_t i3 = get_group_id(2); \
|
||||
const size_t i2 = get_group_id(1); \
|
||||
const size_t i1 = get_group_id(0); \
|
||||
src0 += offset0 + i3*nb03 + i2*nb02 + i1*nb01; \
|
||||
dst += offsetd + i3*nb3 + i2*nb2 + i1*nb1; \
|
||||
for (size_t i0 = get_local_id(0); i0 < (size_t) ne00; i0 += get_local_size(0)) { \
|
||||
const float x = *(global const TYPE *)(src0 + i0*nb00); \
|
||||
*(global TYPE *)(dst + i0*nb0) = xielu(x, alpha_n, alpha_p, beta, eps); \
|
||||
} \
|
||||
}
|
||||
|
||||
XIELU_KERNEL(f32, float)
|
||||
XIELU_KERNEL(f16, half)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -218,6 +218,8 @@ endif()
|
||||
|
||||
if (GGML_SYCL_TARGET STREQUAL "INTEL")
|
||||
add_compile_definitions(GGML_SYCL_WARP_SIZE=16)
|
||||
# With AOT the option goes to ocloc inside -options (see GGML_SYCL_DEVICE_ARCH below): a bare
|
||||
# -Xs hands it to ocloc as a command-line flag, which fails the device link.
|
||||
if (NOT GGML_SYCL_DEVICE_ARCH)
|
||||
target_link_options(ggml-sycl PRIVATE -Xs -ze-intel-greater-than-4GB-buffer-required)
|
||||
else()
|
||||
@@ -248,10 +250,18 @@ endif()
|
||||
|
||||
if (GGML_SYCL_DEVICE_ARCH)
|
||||
message(STATUS "GGML_SYCL_DEVICE_ARCH=${GGML_SYCL_DEVICE_ARCH} (AOT via spir64_gen)")
|
||||
# AOT (oneAPI 2026.2) ignores the grf_size<256> kernel property on ESIMD kernels and builds them
|
||||
# with 128 registers, which made the ESIMD MoE GEMM 1.7-3.9x slower than under JIT; SPMD kernels
|
||||
# keep honouring the property. A module-wide -doubleGRF also moves the ESIMD kernels that ask for
|
||||
# 128 to 256, and a server built with it hung on its first request, so IGC picks the size per
|
||||
# kernel from its register pressure instead (ESIMD kernels too; -ze-opt-large-grf-kernel does not
|
||||
# reach them).
|
||||
set(GGML_SYCL_AOT_BACKEND_OPTIONS
|
||||
"-device ${GGML_SYCL_DEVICE_ARCH} -options '-ze-intel-greater-than-4GB-buffer-required -ze-opt-enable-auto-large-GRF-mode'")
|
||||
target_compile_options(
|
||||
ggml-sycl PRIVATE
|
||||
-fsycl-targets=spir64_gen
|
||||
"SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH} -options -ze-intel-greater-than-4GB-buffer-required\""
|
||||
"SHELL:-Xsycl-target-backend=spir64_gen \"${GGML_SYCL_AOT_BACKEND_OPTIONS}\""
|
||||
)
|
||||
|
||||
# Pass through parallel job (process) count for parallelising the
|
||||
@@ -266,7 +276,7 @@ if (GGML_SYCL_DEVICE_ARCH)
|
||||
target_link_options(
|
||||
ggml-sycl PRIVATE
|
||||
-fsycl-targets=spir64_gen
|
||||
"SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH} -options -ze-intel-greater-than-4GB-buffer-required\""
|
||||
"SHELL:-Xsycl-target-backend=spir64_gen \"${GGML_SYCL_AOT_BACKEND_OPTIONS}\""
|
||||
-fsycl-max-parallel-link-jobs=${GGML_SYCL_MAX_PARALLEL_LINK_JOBS}
|
||||
)
|
||||
|
||||
|
||||
@@ -72,6 +72,7 @@ extern int g_ggml_sycl_debug;
|
||||
extern int g_ggml_sycl_enable_optimize;
|
||||
extern int g_ggml_sycl_enable_fusion;
|
||||
extern int g_ggml_sycl_enable_esimd;
|
||||
extern int g_ggml_sycl_mmid_esimd;
|
||||
extern int g_ggml_sycl_mmvq_wide;
|
||||
extern int g_ggml_sycl_enable_xmx_esimd;
|
||||
extern int g_ggml_sycl_xmx_max_cols;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,33 @@
|
||||
#ifndef GGML_SYCL_FUSED_GEMM_ESIMD_HPP
|
||||
#define GGML_SYCL_FUSED_GEMM_ESIMD_HPP
|
||||
|
||||
#include "fused-gemm.hpp"
|
||||
|
||||
// The grouped (MUL_MAT_ID) dequant GEMM, written with ESIMD so the dequantized weights go from
|
||||
// registers straight into the dpas A operand: no SLM, no barrier. Same inputs and outputs as the
|
||||
// joint_matrix grouped kernel of the 8 x NW x 16 sub-group-NW combination of T (sycl::half or
|
||||
// bfloat16): NW = 16 on Xe2 and Xe-HPC, 8 on Xe-HPG (Arc A, ARL-H). The schedule's tiles, B packed as
|
||||
// [K/2][Npad][2] T, and dst through dst_rows. The weight is in the reorder (SoA) layout if
|
||||
// `reordered`, else in the canonical block layout. Returns false when the shape is not covered.
|
||||
template <typename block_q_t>
|
||||
constexpr bool ggml_sycl_grouped_gemm_esimd_has = std::is_same_v<block_q_t, block_q8_0> ||
|
||||
std::is_same_v<block_q_t, block_iq4_nl> ||
|
||||
std::is_same_v<block_q_t, block_iq4_xs> ||
|
||||
std::is_same_v<block_q_t, block_iq3_s> ||
|
||||
std::is_same_v<block_q_t, block_iq3_xxs> ||
|
||||
std::is_same_v<block_q_t, block_q2_K> ||
|
||||
std::is_same_v<block_q_t, block_q3_K> ||
|
||||
std::is_same_v<block_q_t, block_q4_K> ||
|
||||
std::is_same_v<block_q_t, block_q5_K> ||
|
||||
std::is_same_v<block_q_t, block_q6_K>;
|
||||
|
||||
template <typename block_q_t, typename T, int NW>
|
||||
bool ggml_sycl_grouped_gemm_esimd(const char * src0_dd, size_t expert_stride, const ggml_sycl_grouped_gemm_tile * tiles,
|
||||
const T * packed, float * dst, int M, int Npad, int K,
|
||||
const ggml_sycl_grouped_gemm_rows & dst_rows, bool reordered, int64_t n_tiles,
|
||||
dpct::queue_ptr stream);
|
||||
|
||||
// GGML_SYCL_MMID_ESIMD: 1 (default) takes the ESIMD kernel above where it applies, 0 never does
|
||||
bool ggml_sycl_grouped_gemm_esimd_enabled();
|
||||
|
||||
#endif // GGML_SYCL_FUSED_GEMM_ESIMD_HPP
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "fused-gemm.hpp"
|
||||
#include "fused-gemm-esimd.hpp"
|
||||
#include "quants.hpp"
|
||||
|
||||
#include <sycl/ext/oneapi/matrix/matrix.hpp>
|
||||
|
||||
@@ -17,7 +19,6 @@ namespace mx = sycl::ext::oneapi::experimental::matrix;
|
||||
// superblock into steps of this width. The sub-groups of a work-group each walk their own K range
|
||||
// and are summed at the end.
|
||||
static constexpr int FG_BK = QK4_NL;
|
||||
static constexpr int FG_KSPLIT = 4;
|
||||
|
||||
// Element traits of one joint_matrix operand type. The A stage and the B pack compute in f32 and
|
||||
// convert once, in registers, when they write the element, so any type costs the same one pass.
|
||||
@@ -113,6 +114,15 @@ using fg_half = sycl::half;
|
||||
using fg_bf16 = sycl::ext::oneapi::bfloat16;
|
||||
using fg_tf32 = mx::precision::tf32;
|
||||
|
||||
// The combinations the ESIMD grouped GEMM (fused-gemm-esimd.cpp) stands in for: 8 x SG x 16 with f16
|
||||
// or bf16 operands, the shape of one dpas, on sub-group 16 (Xe2, Xe-HPC) or 8 (Xe-HPG). Its B is
|
||||
// packed and tiled as theirs is.
|
||||
template <typename S> static constexpr bool fg_esimd_combo() {
|
||||
return S::TM == 8 && S::TN == S::SG && S::TK == 16 && (S::SG == 16 || S::SG == 8) &&
|
||||
std::is_same_v<typename S::ta, typename S::tb> &&
|
||||
(std::is_same_v<typename S::ta, fg_half> || std::is_same_v<typename S::ta, fg_bf16>);
|
||||
}
|
||||
|
||||
// One bit of GGML_SYCL_XMX_GATHER_SHAPES per combination. Only combinations some device lists in
|
||||
// matrix_combinations are built (appendix of sycl_ext_oneapi_matrix and the runtime's own list).
|
||||
template <typename F> static void fg_visit_combo(int idx, F && f);
|
||||
@@ -152,29 +162,7 @@ template <typename F> static void fg_visit_combo(int idx, F && f) {
|
||||
// size, since IGC fails on the other ones. A JIT build keeps them all, but each combination lands in
|
||||
// its own device image (joint_matrix is an optional kernel feature) and only a combination the
|
||||
// device reports is launched, so the runtime never asks IGC for the others.
|
||||
#if defined(__SYCL_DEVICE_ONLY__)
|
||||
# if __SYCL_TARGET_INTEL_GPU_ACM_G10__ || __SYCL_TARGET_INTEL_GPU_ACM_G11__ || __SYCL_TARGET_INTEL_GPU_ACM_G12__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_ARL_H__
|
||||
# define FG_AOT_SG 8
|
||||
# elif __SYCL_TARGET_INTEL_GPU_PVC__ || __SYCL_TARGET_INTEL_GPU_PVC_VG__ || __SYCL_TARGET_INTEL_GPU_BMG_G21__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_BMG_G31__ || __SYCL_TARGET_INTEL_GPU_LNL_M__ || __SYCL_TARGET_INTEL_GPU_PTL_H__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_PTL_U__ || __SYCL_TARGET_INTEL_GPU_WCL__ || __SYCL_TARGET_INTEL_GPU_NVL_S__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_NVL_U__ || __SYCL_TARGET_INTEL_GPU_NVL_P__
|
||||
# define FG_AOT_SG 16
|
||||
# elif __SYCL_TARGET_INTEL_GPU_TGLLP__ || __SYCL_TARGET_INTEL_GPU_RKL__ || __SYCL_TARGET_INTEL_GPU_ADL_S__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_ADL_P__ || __SYCL_TARGET_INTEL_GPU_ADL_N__ || __SYCL_TARGET_INTEL_GPU_DG1__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_MTL_U__ || __SYCL_TARGET_INTEL_GPU_MTL_H__
|
||||
# define FG_AOT_SG 0 // no XMX
|
||||
# endif
|
||||
#endif
|
||||
|
||||
template <int SG> static constexpr bool fg_built() {
|
||||
#if defined(FG_AOT_SG)
|
||||
return SG == FG_AOT_SG;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
// (FG_AOT_SG is defined in fused-gemm.hpp, which the ESIMD kernels share)
|
||||
|
||||
// Upper bound on the tile count when total_rows rows are routed to n_as experts: the worst case gives
|
||||
// each expert one row and fills whole tiles with the rest. The bound depends only on the shape, not
|
||||
@@ -434,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]);
|
||||
@@ -449,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);
|
||||
@@ -834,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
|
||||
@@ -991,6 +999,15 @@ static void grouped_dequant_gemm_launch(const char * src0_dd, const size_t exper
|
||||
float * dst, const int M, const int Npad, const int K, const int64_t n_tiles,
|
||||
const int64_t groups_m, dpct::queue_ptr stream,
|
||||
ggml_sycl_grouped_gemm_rows dst_rows = {}) {
|
||||
if constexpr (fg_esimd_combo<S>() && ggml_sycl_grouped_gemm_esimd_has<block_q_t>) {
|
||||
// the register-operand ESIMD kernel, either weight layout: no SLM A image (GGML_SYCL_MMID_ESIMD)
|
||||
if (ggml_sycl_grouped_gemm_esimd_enabled() &&
|
||||
ggml_sycl_grouped_gemm_esimd<block_q_t, typename S::tsb, S::SG>(src0_dd, expert_stride, tiles_ptr, packed,
|
||||
dst, M, Npad, K, dst_rows, reordered,
|
||||
n_tiles, stream)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
stream->submit([&](sycl::handler & cgh) {
|
||||
sycl::local_accessor<typename S::tsa, 1> tile_a(FG_KSPLIT * S::SG_ROWS * FG_BK, cgh);
|
||||
sycl::local_accessor<float, 1> tile_c(FG_KSPLIT * S::SG_ROWS * S::BN, cgh);
|
||||
@@ -1087,6 +1104,45 @@ template <typename F> static bool fg_visit_type(ggml_type type, bool reordered,
|
||||
}
|
||||
}
|
||||
|
||||
// The ESIMD grouped GEMM loads A straight into its dpas operands, so the joint_matrix tile shape
|
||||
// means nothing to it; it runs on the fg_esimd_combo of the picked operand type and sub-group size. A
|
||||
// grouped call whose weight it covers is moved there from any other shape of that type and sub-group
|
||||
// size, if the device lists it, whatever GGML_SYCL_XMX_GATHER_SHAPES allows: the shape bits choose
|
||||
// among joint_matrix tiles.
|
||||
// A call the ESIMD kernel then declines (a shape it does not take) runs that combination's joint_matrix
|
||||
// kernel.
|
||||
static int fg_esimd_remap(dpct::queue_ptr stream, int combo, ggml_type src0_type, bool reordered) {
|
||||
if (combo < 0 || !ggml_sycl_grouped_gemm_esimd_enabled()) {
|
||||
return combo;
|
||||
}
|
||||
bool covered = false;
|
||||
fg_visit_type(src0_type, reordered, [&](auto tag) {
|
||||
using T = decltype(tag);
|
||||
covered = ggml_sycl_grouped_gemm_esimd_has<typename T::type>;
|
||||
});
|
||||
if (!covered) {
|
||||
return combo;
|
||||
}
|
||||
int target = -1;
|
||||
fg_visit_combo(combo, [&](auto s) {
|
||||
using S = decltype(s);
|
||||
if constexpr (std::is_same_v<typename S::ta, typename S::tb>) {
|
||||
for (int idx = 0; idx < FG_N_COMBOS; ++idx) {
|
||||
fg_visit_combo(idx, [&](auto t) {
|
||||
using U = decltype(t);
|
||||
if constexpr (fg_esimd_combo<U>() && U::SG == S::SG && std::is_same_v<typename U::ta, typename S::ta>) {
|
||||
target = idx;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
if (target < 0 || target == combo || !(fg_device_combos(stream->get_device()) & (1 << target))) {
|
||||
return combo;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
template <typename S>
|
||||
static bool fg_fused_run(ggml_type src0_type, bool src0_reordered, const void * src0, const void * src1, ggml_type src1_type,
|
||||
float * dst, int64_t M, int64_t N, int64_t K, int64_t ldd, ggml_sycl_pool & pool,
|
||||
@@ -1201,7 +1257,7 @@ bool ggml_sycl_grouped_dequant_gemm(ggml_type src0_type, bool reordered, const v
|
||||
if (!ggml_sycl_grouped_dequant_gemm_shape_ok(src0_type, M, K, total_rows, n_active)) {
|
||||
return false;
|
||||
}
|
||||
const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec);
|
||||
const int combo = fg_esimd_remap(stream, fg_pick_combo(stream, GGML_TYPE_F32, src1_prec), src0_type, reordered);
|
||||
if (combo < 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -1407,7 +1463,7 @@ bool ggml_sycl_grouped_dequant_gemm_device_supported(ggml_type src0_type, bool r
|
||||
if (grouped_gemm_max_tiles(total_rows, n_as, GGML_SYCL_FG_BN) > INT32_MAX / GGML_SYCL_FG_BN) {
|
||||
return false;
|
||||
}
|
||||
const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec);
|
||||
const int combo = fg_esimd_remap(stream, fg_pick_combo(stream, GGML_TYPE_F32, src1_prec), src0_type, reordered);
|
||||
if (combo < 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -1428,7 +1484,7 @@ bool ggml_sycl_grouped_dequant_gemm_device(ggml_type src0_type, bool reordered,
|
||||
n_tokens, M, K, stream)) {
|
||||
return false;
|
||||
}
|
||||
const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec);
|
||||
const int combo = fg_esimd_remap(stream, fg_pick_combo(stream, GGML_TYPE_F32, src1_prec), src0_type, reordered);
|
||||
bool launched = false;
|
||||
fg_visit_combo(combo, [&](auto s) {
|
||||
launched = fg_grouped_device_run<decltype(s)>(src0_type, reordered, src0_base, expert_stride, src1, dst,
|
||||
|
||||
@@ -13,7 +13,34 @@ struct ggml_sycl_grouped_gemm_rows {
|
||||
size_t nb2;
|
||||
};
|
||||
|
||||
// AOT: the sub-group size of the XMX combinations of the target, 0 for a target without XMX.
|
||||
// Undefined in a JIT build, which keeps every combination.
|
||||
#if defined(__SYCL_DEVICE_ONLY__)
|
||||
# if __SYCL_TARGET_INTEL_GPU_ACM_G10__ || __SYCL_TARGET_INTEL_GPU_ACM_G11__ || __SYCL_TARGET_INTEL_GPU_ACM_G12__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_ARL_H__
|
||||
# define FG_AOT_SG 8
|
||||
# elif __SYCL_TARGET_INTEL_GPU_PVC__ || __SYCL_TARGET_INTEL_GPU_PVC_VG__ || __SYCL_TARGET_INTEL_GPU_BMG_G21__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_BMG_G31__ || __SYCL_TARGET_INTEL_GPU_LNL_M__ || __SYCL_TARGET_INTEL_GPU_PTL_H__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_PTL_U__ || __SYCL_TARGET_INTEL_GPU_WCL__ || __SYCL_TARGET_INTEL_GPU_NVL_S__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_NVL_U__ || __SYCL_TARGET_INTEL_GPU_NVL_P__
|
||||
# define FG_AOT_SG 16
|
||||
# elif __SYCL_TARGET_INTEL_GPU_TGLLP__ || __SYCL_TARGET_INTEL_GPU_RKL__ || __SYCL_TARGET_INTEL_GPU_ADL_S__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_ADL_P__ || __SYCL_TARGET_INTEL_GPU_ADL_N__ || __SYCL_TARGET_INTEL_GPU_DG1__ || \
|
||||
__SYCL_TARGET_INTEL_GPU_MTL_U__ || __SYCL_TARGET_INTEL_GPU_MTL_H__
|
||||
# define FG_AOT_SG 0 // no XMX
|
||||
# endif
|
||||
#endif
|
||||
|
||||
template <int SG> static constexpr bool fg_built() {
|
||||
#if defined(FG_AOT_SG)
|
||||
return SG == FG_AOT_SG;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
static constexpr int GGML_SYCL_FG_BN = 32;
|
||||
static constexpr int FG_KSPLIT = 4;
|
||||
static constexpr int64_t GGML_SYCL_MMID_SCHED_MAX_EXPERTS = 4096;
|
||||
|
||||
// Shape and type gates for the kernels below. Device capability is separate: it needs a queue to ask.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -111,6 +111,7 @@ int g_ggml_sycl_memtrace_step = 64;
|
||||
int g_ggml_sycl_enable_vmm = 1;
|
||||
int g_ggml_sycl_enable_fusion = 1;
|
||||
int g_ggml_sycl_enable_esimd = 1;
|
||||
int g_ggml_sycl_mmid_esimd = 1;
|
||||
int g_ggml_sycl_mmvq_wide = 1;
|
||||
int g_ggml_sycl_enable_xmx_esimd = 1;
|
||||
int g_ggml_sycl_xmx_max_cols = GGML_SYCL_XMX_MAX_COLS_DEFAULT;
|
||||
@@ -444,6 +445,7 @@ static void ggml_check_sycl() try {
|
||||
g_ggml_sycl_enable_vmm = ggml_sycl_get_env("GGML_SYCL_ENABLE_VMM", 1);
|
||||
g_ggml_sycl_enable_fusion = ggml_sycl_get_env("GGML_SYCL_ENABLE_FUSION", 1);
|
||||
g_ggml_sycl_enable_esimd = ggml_sycl_get_env("GGML_SYCL_ENABLE_ESIMD", 1);
|
||||
g_ggml_sycl_mmid_esimd = ggml_sycl_get_env("GGML_SYCL_MMID_ESIMD", 1);
|
||||
g_ggml_sycl_mmvq_wide = ggml_sycl_get_env("GGML_SYCL_MMVQ_WIDE", 1);
|
||||
g_ggml_sycl_enable_xmx_esimd = ggml_sycl_get_env("GGML_SYCL_ENABLE_XMX_ESIMD", 1);
|
||||
g_ggml_sycl_xmx_max_cols = std::max(0, ggml_sycl_get_env("GGML_SYCL_XMX_MAX_COLS", GGML_SYCL_XMX_MAX_COLS_DEFAULT));
|
||||
@@ -578,6 +580,7 @@ static void ggml_check_sycl() try {
|
||||
GGML_LOG_INFO(" GGML_SYCL_ENABLE_OPT: %d\n", g_ggml_sycl_enable_optimize);
|
||||
GGML_LOG_INFO(" GGML_SYCL_XMX_GATHER_TYPES: %d\n", g_ggml_sycl_xmx_gather_types);
|
||||
GGML_LOG_INFO(" GGML_SYCL_MMID_SCHED: %d\n", g_ggml_sycl_mmid_sched);
|
||||
GGML_LOG_INFO(" GGML_SYCL_MMID_ESIMD: %d\n", g_ggml_sycl_mmid_esimd);
|
||||
GGML_LOG_INFO(" GGML_SYCL_XMX_GATHER_SHAPES: %d\n", g_ggml_sycl_xmx_gather_shapes);
|
||||
GGML_LOG_INFO(" GGML_SYCL_DYNAMIC_PRECISION: %s\n",
|
||||
ggml_sycl_dynamic_precision_names[g_ggml_sycl_dynamic_precision]);
|
||||
@@ -829,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;
|
||||
@@ -4383,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;
|
||||
@@ -4972,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];
|
||||
@@ -5019,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;
|
||||
}
|
||||
@@ -5381,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) &&
|
||||
@@ -6705,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;
|
||||
}
|
||||
|
||||
@@ -3278,9 +3283,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
rm_stdq = 2;
|
||||
rm_stdq_int = 2;
|
||||
}
|
||||
// RDNA3/4: above four columns, static 4 rows for all types bench faster than the default
|
||||
const bool is_rdna3_or_4 = device->vendor_id == VK_VENDOR_ID_AMD && (device->architecture == AMD_RDNA3 || device->architecture == AMD_RDNA4);
|
||||
auto const &rm_int_n = [&](uint32_t rows, uint32_t i) { return (is_rdna3_or_4 && i >= 4) ? 4u : rows; };
|
||||
// RDNA3/4 and NVIDIA except pre-Turing: use 4 rows for MUL_MAT_ID MMVQ.
|
||||
auto const &rm_id = [&](uint32_t rows) {
|
||||
if (device->vendor_id == VK_VENDOR_ID_NVIDIA &&
|
||||
@@ -3391,25 +3394,43 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
|
||||
const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_q8_1_f32", arr_dmmv_q2_0_q8_1_f32_len[reduc], arr_dmmv_q2_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
const struct {
|
||||
ggml_type type;
|
||||
const char * name;
|
||||
size_t spv_size;
|
||||
const void * spv_data;
|
||||
uint32_t default_rows;
|
||||
} shaders[] = {
|
||||
{GGML_TYPE_Q2_0, "mul_mat_vec_q2_0_q8_1_f32", arr_dmmv_q2_0_q8_1_f32_len[reduc], arr_dmmv_q2_0_q8_1_f32_data[reduc], 2*rm_kq_int},
|
||||
{GGML_TYPE_Q4_0, "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], rm_stdq_int},
|
||||
{GGML_TYPE_Q4_1, "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], rm_stdq_int},
|
||||
{GGML_TYPE_Q5_0, "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], rm_stdq_int},
|
||||
{GGML_TYPE_Q5_1, "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], rm_stdq_int},
|
||||
{GGML_TYPE_Q8_0, "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], rm_stdq_int},
|
||||
{GGML_TYPE_MXFP4, "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], 2*rm_stdq_int},
|
||||
{GGML_TYPE_Q2_K, "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], 2*rm_kq_int},
|
||||
{GGML_TYPE_Q3_K, "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], rm_kq_int},
|
||||
{GGML_TYPE_Q4_K, "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], rm_kq_int},
|
||||
{GGML_TYPE_Q5_K, "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], rm_kq_int},
|
||||
{GGML_TYPE_Q6_K, "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], rm_kq_int},
|
||||
{GGML_TYPE_IQ1_S, "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], rm_iq_int(i)},
|
||||
{GGML_TYPE_IQ1_M, "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], rm_iq_int(i)},
|
||||
{GGML_TYPE_IQ4_XS, "mul_mat_vec_iq4_xs_q8_1_f32", arr_dmmv_iq4_xs_q8_1_f32_len[reduc], arr_dmmv_iq4_xs_q8_1_f32_data[reduc], rm_stdq_int},
|
||||
};
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_q8_1_f32", arr_dmmv_iq4_xs_q8_1_f32_len[reduc], arr_dmmv_iq4_xs_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int);
|
||||
const bool use_four_rows = is_rdna3_or_4 && i >= 4;
|
||||
const bool rdna4_amd_prop = device->architecture == AMD_RDNA4 && device->driver_id == vk::DriverId::eAmdProprietary;
|
||||
for (const auto & shader : shaders) {
|
||||
// Four rows can be slower for these quants on the AMD proprietary driver.
|
||||
const bool use_default_rows = rdna4_amd_prop &&
|
||||
(shader.type == GGML_TYPE_Q3_K || shader.type == GGML_TYPE_Q5_K || shader.type == GGML_TYPE_IQ4_XS);
|
||||
const uint32_t rows = use_four_rows && !use_default_rows ? 4u : shader.default_rows;
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][shader.type][i],
|
||||
shader.name, shader.spv_size, shader.spv_data, "main", mul_mat_vec_num_bindings,
|
||||
sizeof(vk_mat_vec_push_constants), {rows, 1, 1}, {wg_size_subgroup_int, rows, i+1},
|
||||
1, true, use_subgroups, subgroup_size_int);
|
||||
}
|
||||
}
|
||||
#endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
|
||||
}
|
||||
@@ -3477,7 +3498,6 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
GGML_UNUSED(rm_stdq_int);
|
||||
GGML_UNUSED(rm_kq_int);
|
||||
GGML_UNUSED(is_rdna3_or_4);
|
||||
GGML_UNUSED(rm_int_n);
|
||||
GGML_UNUSED(rm_id);
|
||||
GGML_UNUSED(rm_iq_int);
|
||||
#endif
|
||||
@@ -14259,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) {
|
||||
@@ -17026,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2117,7 +2117,7 @@ class ggml_webgpu_shader_lib {
|
||||
webgpu_pipeline get_pad_pipeline(const ggml_webgpu_shader_lib_context & context) {
|
||||
ggml_webgpu_pad_pipeline_key key = {};
|
||||
key.reflect = context.dst->op == GGML_OP_PAD_REFLECT_1D;
|
||||
key.circular = !key.reflect && ggml_get_op_params_i32(context.dst, 8) != 0;
|
||||
key.circular = context.dst->op == GGML_OP_ROLL || (!key.reflect && ggml_get_op_params_i32(context.dst, 8) != 0);
|
||||
|
||||
auto it = pad_pipelines.find(key);
|
||||
if (it != pad_pipelines.end()) {
|
||||
|
||||
@@ -964,16 +964,18 @@ static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src
|
||||
(uint32_t) dst->ne[1],
|
||||
(uint32_t) dst->ne[2],
|
||||
(uint32_t) dst->ne[3],
|
||||
// Pad sizes
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 0),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 1),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 2),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 3),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 4),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 5),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 6),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 7),
|
||||
};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
if (dst->op == GGML_OP_ROLL) {
|
||||
// Circular padding with unchanged dimensions implements a roll.
|
||||
const int64_t shift = ggml_get_op_params_i32(dst, i);
|
||||
params.push_back((uint32_t) (shift < 0 ? shift + src->ne[i] : shift));
|
||||
params.push_back(0);
|
||||
} else {
|
||||
params.push_back((uint32_t) ggml_get_op_params_i32(dst, 2 * i));
|
||||
params.push_back((uint32_t) ggml_get_op_params_i32(dst, 2 * i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<wgpu::BindGroupEntry> entries = {
|
||||
ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
|
||||
@@ -3740,6 +3742,7 @@ static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
|
||||
return ggml_webgpu_pool2d(ctx, src0, node);
|
||||
case GGML_OP_COL2IM_1D:
|
||||
return ggml_webgpu_col2im_1d(ctx, src0, node);
|
||||
case GGML_OP_ROLL:
|
||||
case GGML_OP_PAD_REFLECT_1D:
|
||||
case GGML_OP_PAD:
|
||||
return ggml_webgpu_pad(ctx, src0, node);
|
||||
@@ -4066,7 +4069,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 +4409,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 +5268,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:
|
||||
@@ -5295,6 +5302,7 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
|
||||
case GGML_OP_PAD_REFLECT_1D:
|
||||
supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32;
|
||||
break;
|
||||
case GGML_OP_ROLL:
|
||||
case GGML_OP_PAD:
|
||||
supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32;
|
||||
break;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
@@ -50,6 +51,8 @@ struct ggml_backend_zdnn_buffer {
|
||||
std::vector<float> scales; // per-row scales for quantized weights
|
||||
std::vector<float> channel_scales; // per-input-channel scales for quantized weights, applied to the inputs
|
||||
|
||||
std::mutex mutex;
|
||||
|
||||
char name[GGML_MAX_NAME];
|
||||
};
|
||||
|
||||
|
||||
@@ -61,9 +61,7 @@ void ggml_zdnn_mul_mat_f(
|
||||
GGML_ASSERT(weights_extra->pre_tfm_desc.dim2 == weights->ne[1] && "weights_extra->pre_tfm_desc.dim2 must match weights->ne[1]");
|
||||
|
||||
// weights read straight into a host buffer skip set_tensor, so transform them on first use
|
||||
if (!weights_extra->ztensor.is_transformed) {
|
||||
ggml_zdnn_load_tensor(weights_extra->ztensor, weights->data);
|
||||
}
|
||||
ggml_zdnn_load_weights(weights_extra, weights);
|
||||
|
||||
// the inputs can be in any host buffer or be a view, so transform them from their data on every call
|
||||
{
|
||||
|
||||
@@ -190,9 +190,7 @@ void ggml_zdnn_mul_mat_q(
|
||||
ggml_backend_zdnn_buffer * weights_extra = (ggml_backend_zdnn_buffer *)weights->extra;
|
||||
|
||||
// weights read straight into a host buffer skip set_tensor, so transform them on first use
|
||||
if (!weights_extra->ztensor.is_transformed) {
|
||||
ggml_zdnn_load_tensor_q(weights_extra, weights);
|
||||
}
|
||||
ggml_zdnn_load_weights(weights_extra, weights);
|
||||
|
||||
// starting threads costs more than it saves for small inputs, e.g. during token generation
|
||||
const int32_t n_threads = ne10*ne11 >= 65536 ? ctx->n_threads : 1;
|
||||
|
||||
@@ -144,6 +144,20 @@ void ggml_zdnn_load_tensor_q(ggml_backend_zdnn_buffer * buffer, const ggml_tenso
|
||||
ZDNN_CHECK(zdnn_transform_quantized_ztensor(&buffer->ztensor, false, -127, 127, q.data()));
|
||||
}
|
||||
|
||||
void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) {
|
||||
std::lock_guard<std::mutex> lock(buffer->mutex);
|
||||
|
||||
if (buffer->ztensor.is_transformed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ggml_is_quantized(tensor->type)) {
|
||||
ggml_zdnn_load_tensor_q(buffer, tensor);
|
||||
} else {
|
||||
ggml_zdnn_load_tensor(buffer->ztensor, tensor->data);
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) {
|
||||
if (ggml_is_quantized(tensor->type)) {
|
||||
GGML_ASSERT(ggml_is_matrix(tensor));
|
||||
|
||||
@@ -18,6 +18,8 @@ int64_t ggml_zdnn_q_group_size(const ggml_tensor * tensor);
|
||||
|
||||
void ggml_zdnn_load_tensor_q(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor);
|
||||
|
||||
void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor);
|
||||
|
||||
void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor);
|
||||
|
||||
#endif // GGML_ZDNN_UTILITIES_HPP
|
||||
|
||||
+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);
|
||||
|
||||
|
||||
@@ -326,6 +326,13 @@ class Keys:
|
||||
L_CYCLES = "{arch}.hrm.l_cycles"
|
||||
PREFIX_LM = "{arch}.hrm.prefix_lm"
|
||||
|
||||
class Loop:
|
||||
START = "{arch}.loop.start"
|
||||
END = "{arch}.loop.end"
|
||||
COUNT = "{arch}.loop.count"
|
||||
GATE_RANK = "{arch}.loop.gate_rank"
|
||||
VARYING = "{arch}.loop.varying"
|
||||
|
||||
class Metis:
|
||||
PASS_COUNT = "{arch}.metis.pass_count"
|
||||
MEMORY_LENGTH = "{arch}.metis.memory_length"
|
||||
@@ -771,6 +778,7 @@ class MODEL_ARCH(IntEnum):
|
||||
NANBEIGE = auto()
|
||||
QWEN3TTS = auto()
|
||||
POCKETTTS = auto()
|
||||
MOSHI = auto()
|
||||
ZONOS3 = auto()
|
||||
KOKORO = auto()
|
||||
TINY_VOCA = auto()
|
||||
@@ -778,6 +786,7 @@ class MODEL_ARCH(IntEnum):
|
||||
KOLIBRI1 = auto()
|
||||
LIMITE = auto()
|
||||
INKLING2 = auto()
|
||||
INKLING2_LOOP = auto()
|
||||
DOMYN_EDGE = auto()
|
||||
|
||||
|
||||
@@ -880,6 +889,19 @@ class MODEL_TENSOR(IntEnum):
|
||||
MOE_LATENT_UP = auto() # nemotron 3 super
|
||||
FFN_POST_CONV = auto()
|
||||
FFN_RES_QUERY = auto()
|
||||
LOOP_MSG_QUERY = auto()
|
||||
LOOP_Q_CTRL_DOWN = auto()
|
||||
LOOP_Q_CTRL_GAIN = auto()
|
||||
LOOP_Q_CTRL_FORGET = auto()
|
||||
LOOP_K_CTRL_DOWN = auto()
|
||||
LOOP_K_CTRL_GAIN = auto()
|
||||
LOOP_K_CTRL_FORGET = auto()
|
||||
LOOP_V_CTRL_DOWN = auto()
|
||||
LOOP_V_CTRL_GAIN = auto()
|
||||
LOOP_V_CTRL_FORGET = auto()
|
||||
LOOP_FFN_CTRL_DOWN = auto()
|
||||
LOOP_FFN_CTRL_GAIN = auto()
|
||||
LOOP_FFN_CTRL_FORGET = auto()
|
||||
STREAM_EMBD = auto()
|
||||
DEPTH_MEM_STATE_WRITE = auto()
|
||||
DEPTH_MEM_META_WRITE = auto()
|
||||
@@ -1772,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",
|
||||
@@ -1779,6 +1802,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
|
||||
MODEL_ARCH.KOLIBRI1: "kolibri1",
|
||||
MODEL_ARCH.LIMITE: "limite",
|
||||
MODEL_ARCH.INKLING2: "inkling2",
|
||||
MODEL_ARCH.INKLING2_LOOP: "inkling2_loop",
|
||||
MODEL_ARCH.DOMYN_EDGE: "domynedge",
|
||||
}
|
||||
|
||||
@@ -1881,6 +1905,19 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
|
||||
MODEL_TENSOR.MOE_LATENT_UP: "blk.{bid}.ffn_latent_up", # nemotron 3 super
|
||||
MODEL_TENSOR.FFN_POST_CONV: "blk.{bid}.ffn_post_conv",
|
||||
MODEL_TENSOR.FFN_RES_QUERY: "blk.{bid}.ffn_res_query",
|
||||
MODEL_TENSOR.LOOP_MSG_QUERY: "blk.{bid}.loop_msg_query",
|
||||
MODEL_TENSOR.LOOP_Q_CTRL_DOWN: "blk.{bid}.loop_q_ctrl_down",
|
||||
MODEL_TENSOR.LOOP_Q_CTRL_GAIN: "blk.{bid}.loop_q_ctrl_gain",
|
||||
MODEL_TENSOR.LOOP_Q_CTRL_FORGET: "blk.{bid}.loop_q_ctrl_forget",
|
||||
MODEL_TENSOR.LOOP_K_CTRL_DOWN: "blk.{bid}.loop_k_ctrl_down",
|
||||
MODEL_TENSOR.LOOP_K_CTRL_GAIN: "blk.{bid}.loop_k_ctrl_gain",
|
||||
MODEL_TENSOR.LOOP_K_CTRL_FORGET: "blk.{bid}.loop_k_ctrl_forget",
|
||||
MODEL_TENSOR.LOOP_V_CTRL_DOWN: "blk.{bid}.loop_v_ctrl_down",
|
||||
MODEL_TENSOR.LOOP_V_CTRL_GAIN: "blk.{bid}.loop_v_ctrl_gain",
|
||||
MODEL_TENSOR.LOOP_V_CTRL_FORGET: "blk.{bid}.loop_v_ctrl_forget",
|
||||
MODEL_TENSOR.LOOP_FFN_CTRL_DOWN: "blk.{bid}.loop_ffn_ctrl_down",
|
||||
MODEL_TENSOR.LOOP_FFN_CTRL_GAIN: "blk.{bid}.loop_ffn_ctrl_gain",
|
||||
MODEL_TENSOR.LOOP_FFN_CTRL_FORGET: "blk.{bid}.loop_ffn_ctrl_forget",
|
||||
MODEL_TENSOR.STREAM_EMBD: "stream_embd",
|
||||
MODEL_TENSOR.DEPTH_MEM_STATE_WRITE: "depth_mem_state_write",
|
||||
MODEL_TENSOR.DEPTH_MEM_META_WRITE: "depth_mem_meta_write",
|
||||
@@ -6922,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,
|
||||
@@ -7087,6 +7138,55 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
|
||||
MODEL_TENSOR.FFN_POST_CONV,
|
||||
MODEL_TENSOR.FFN_RES_QUERY,
|
||||
],
|
||||
MODEL_ARCH.INKLING2_LOOP: [
|
||||
MODEL_TENSOR.TOKEN_EMBD,
|
||||
MODEL_TENSOR.TOKEN_EMBD_NORM,
|
||||
MODEL_TENSOR.OUTPUT,
|
||||
MODEL_TENSOR.OUTPUT_NORM,
|
||||
MODEL_TENSOR.OUTPUT_RES_QUERY,
|
||||
MODEL_TENSOR.ATTN_NORM,
|
||||
MODEL_TENSOR.ATTN_Q,
|
||||
MODEL_TENSOR.ATTN_K,
|
||||
MODEL_TENSOR.ATTN_V,
|
||||
MODEL_TENSOR.ATTN_OUT,
|
||||
MODEL_TENSOR.ATTN_GATE,
|
||||
MODEL_TENSOR.ATTN_REL,
|
||||
MODEL_TENSOR.ATTN_REL_BIAS,
|
||||
MODEL_TENSOR.ATTN_Q_CLIP,
|
||||
MODEL_TENSOR.ATTN_REL_CLIP,
|
||||
MODEL_TENSOR.ATTN_SINK_PROJ,
|
||||
MODEL_TENSOR.ATTN_Q_INP_NORM,
|
||||
MODEL_TENSOR.ATTN_K_INP_NORM,
|
||||
MODEL_TENSOR.ATTN_V_INP_NORM,
|
||||
MODEL_TENSOR.ATTN_K_CONV,
|
||||
MODEL_TENSOR.ATTN_V_CONV,
|
||||
MODEL_TENSOR.ATTN_K_CONV_PROJ,
|
||||
MODEL_TENSOR.ATTN_V_CONV_PROJ,
|
||||
MODEL_TENSOR.ATTN_POST_CONV,
|
||||
MODEL_TENSOR.ATTN_RES_QUERY,
|
||||
MODEL_TENSOR.FFN_NORM,
|
||||
MODEL_TENSOR.FFN_GATE_INP,
|
||||
MODEL_TENSOR.FFN_EXP_PROBS_B,
|
||||
MODEL_TENSOR.FFN_GATE_EXP,
|
||||
MODEL_TENSOR.FFN_UP_EXP,
|
||||
MODEL_TENSOR.FFN_GATE_UP_EXP,
|
||||
MODEL_TENSOR.FFN_DOWN_EXP,
|
||||
MODEL_TENSOR.FFN_POST_CONV,
|
||||
MODEL_TENSOR.FFN_RES_QUERY,
|
||||
MODEL_TENSOR.LOOP_MSG_QUERY,
|
||||
MODEL_TENSOR.LOOP_Q_CTRL_DOWN,
|
||||
MODEL_TENSOR.LOOP_Q_CTRL_GAIN,
|
||||
MODEL_TENSOR.LOOP_Q_CTRL_FORGET,
|
||||
MODEL_TENSOR.LOOP_K_CTRL_DOWN,
|
||||
MODEL_TENSOR.LOOP_K_CTRL_GAIN,
|
||||
MODEL_TENSOR.LOOP_K_CTRL_FORGET,
|
||||
MODEL_TENSOR.LOOP_V_CTRL_DOWN,
|
||||
MODEL_TENSOR.LOOP_V_CTRL_GAIN,
|
||||
MODEL_TENSOR.LOOP_V_CTRL_FORGET,
|
||||
MODEL_TENSOR.LOOP_FFN_CTRL_DOWN,
|
||||
MODEL_TENSOR.LOOP_FFN_CTRL_GAIN,
|
||||
MODEL_TENSOR.LOOP_FFN_CTRL_FORGET,
|
||||
],
|
||||
MODEL_ARCH.DOMYN_EDGE: [
|
||||
MODEL_TENSOR.TOKEN_EMBD,
|
||||
MODEL_TENSOR.ATTN_Q,
|
||||
@@ -7430,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
|
||||
|
||||
@@ -990,6 +990,21 @@ class GGUFWriter:
|
||||
def add_hrm_prefix_lm(self, value: bool) -> None:
|
||||
self.add_bool(Keys.HRM.PREFIX_LM.format(arch=self.arch), value)
|
||||
|
||||
def add_loop_start(self, value: int) -> None:
|
||||
self.add_uint32(Keys.Loop.START.format(arch=self.arch), value)
|
||||
|
||||
def add_loop_end(self, value: int) -> None:
|
||||
self.add_uint32(Keys.Loop.END.format(arch=self.arch), value)
|
||||
|
||||
def add_loop_count(self, value: int) -> None:
|
||||
self.add_uint32(Keys.Loop.COUNT.format(arch=self.arch), value)
|
||||
|
||||
def add_loop_gate_rank(self, value: int) -> None:
|
||||
self.add_uint32(Keys.Loop.GATE_RANK.format(arch=self.arch), value)
|
||||
|
||||
def add_loop_varying(self, value: bool) -> None:
|
||||
self.add_bool(Keys.Loop.VARYING.format(arch=self.arch), value)
|
||||
|
||||
def add_metis_pass_count(self, value: int) -> None:
|
||||
self.add_uint32(Keys.Metis.PASS_COUNT.format(arch=self.arch), value)
|
||||
|
||||
|
||||
@@ -543,6 +543,66 @@ class TensorNameMap:
|
||||
"model.layers.{bid}.attention_input.query", # inkling2
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_Q_CTRL_DOWN: (
|
||||
"model.layers.{bid}.q_controller.down_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.attn.down_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_Q_CTRL_GAIN: (
|
||||
"model.layers.{bid}.q_controller.gain_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.attn.gain_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_Q_CTRL_FORGET: (
|
||||
"model.layers.{bid}.q_controller.forget_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.attn.forget_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_K_CTRL_DOWN: (
|
||||
"model.layers.{bid}.k_controller.down_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.k.down_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_K_CTRL_GAIN: (
|
||||
"model.layers.{bid}.k_controller.gain_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.k.gain_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_K_CTRL_FORGET: (
|
||||
"model.layers.{bid}.k_controller.forget_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.k.forget_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_V_CTRL_DOWN: (
|
||||
"model.layers.{bid}.v_controller.down_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.v.down_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_V_CTRL_GAIN: (
|
||||
"model.layers.{bid}.v_controller.gain_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.v.gain_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_V_CTRL_FORGET: (
|
||||
"model.layers.{bid}.v_controller.forget_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.v.forget_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_FFN_CTRL_DOWN: (
|
||||
"model.layers.{bid}.mlp_controller.down_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.mlp.down_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_FFN_CTRL_GAIN: (
|
||||
"model.layers.{bid}.mlp_controller.gain_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.mlp.gain_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
MODEL_TENSOR.LOOP_FFN_CTRL_FORGET: (
|
||||
"model.layers.{bid}.mlp_controller.forget_proj", # inkling2_loop
|
||||
"model.layers.{bid}.controllers.mlp.forget_weight", # inkling2_loop
|
||||
),
|
||||
|
||||
# Feed-forward norm
|
||||
MODEL_TENSOR.FFN_NORM: (
|
||||
"layers.{bid}.moe_connection.norm", # metis16
|
||||
|
||||
+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 -%}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user