diff --git a/common/arg.cpp b/common/arg.cpp index c322b5c0fcfc..d626a00a1dea 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -4214,7 +4214,8 @@ common_params_context common_params_parser_init(common_params & params, llama_ex if (value < 0) { throw std::invalid_argument("invalid value"); } - params.speculative.draft.n_max = value; + params.speculative.draft.n_max = value; + params.speculative.draft.n_max_set = true; } ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_N_MAX")); add_opt(common_arg( diff --git a/common/common.cpp b/common/common.cpp index b009d460d697..e01fb33cbdfd 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1153,6 +1153,8 @@ struct common_init_result::impl { std::vector samplers_seq_config; }; +extern "C" void llama_s23_set_single_slot_tree_swa(bool v); + static const std::map COMMON_DECISION_TYPE_NAMES = { { COMMON_DECISION_TYPE_OPENJEV, "openjev" }, { COMMON_DECISION_TYPE_LEV, "lev" }, @@ -1318,10 +1320,21 @@ common_init_result::common_init_result(common_params & params, bool model_only) cparams.n_outputs_max = std::max(cparams.n_outputs_max, (uint32_t) COMMON_DECISION_LFM3_D1_SET_SIZE); } + char arch_buf[64] = {}; + const bool is_inkling2_arch = + llama_model_meta_val_str(model, "general.architecture", arch_buf, sizeof(arch_buf)) >= 0 && + std::strncmp(arch_buf, "inkling2", 8) == 0; + + bool s23_single_slot_tree_swa = false; if (llama_model_classifier_free_guidance(model)) { params.kv_unified = true; cparams.kv_unified = true; cparams.n_seq_max *= 2; + } else if (is_inkling2_arch && params.n_parallel == 1 && params.speculative.has_dft() && + !cparams.embeddings && getenv("LLAMA_DSPARK_ENABLE_2BRANCH") && !getenv("LLAMA_DSPARK_NO_TREE")) { + s23_single_slot_tree_swa = (!params.kv_unified && cparams.n_seq_max == 1); + cparams.kv_unified = true; + cparams.n_seq_max = std::max(cparams.n_seq_max, 2); } // embeddings need the whole batch in one ubatch, so n_batch must not be larger than n_ubatch @@ -1383,12 +1396,24 @@ common_init_result::common_init_result(common_params & params, bool model_only) pimpl->samplers_seq_config[i] = { i, common_sampler_get(pimpl->samplers[i].get()) }; } - if (params.sampling.backend_sampling) { + const bool init_pure_greedy_fast = + is_inkling2_arch && + !pimpl->samplers.empty() && + params.sampling.n_probs == 0 && + common_sampler_is_pure_argmax(pimpl->samplers[0].get()) && + !getenv("LLAMA_FORCE_BACKEND_ARGMAX_CHAIN"); + if (params.sampling.backend_sampling && !init_pure_greedy_fast) { cparams.samplers = pimpl->samplers_seq_config.data(); cparams.n_samplers = pimpl->samplers_seq_config.size(); } + if (s23_single_slot_tree_swa) { + llama_s23_set_single_slot_tree_swa(true); + } llama_context * lctx = llama_init_from_model(model, cparams); + if (s23_single_slot_tree_swa) { + llama_s23_set_single_slot_tree_swa(false); + } if (lctx == NULL) { COM_ERR("failed to create context with model '%s'\n", params.model.path.c_str()); return; diff --git a/common/common.h b/common/common.h index 22724e817436..6ea96300010b 100644 --- a/common/common.h +++ b/common/common.h @@ -344,6 +344,7 @@ struct common_params_model { struct common_params_speculative_draft { int32_t n_max = 3; // maximum number of tokens to draft during speculative decoding int32_t n_min = 0; // minimum number of draft tokens to use for speculative decoding + bool n_max_set = false; // true if --spec-draft-n-max was explicitly provided float p_split = 0.1f; // speculative decoding split probability float p_min = 0.0f; // minimum speculative decoding probability (greedy) @@ -424,7 +425,9 @@ struct common_params_speculative { t == COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR; }); - return needs_rs_seq ? draft.n_max : 0u; + const bool has_dspark = std::find(types.begin(), types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) != types.end(); + const int32_t eff_n_max = (has_dspark && !draft.n_max_set) ? std::max(draft.n_max, 7) : draft.n_max; + return needs_rs_seq ? eff_n_max : 0u; } }; diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp index 4690a57fa4ca..52008288aed0 100644 --- a/common/json-schema-to-grammar.cpp +++ b/common/json-schema-to-grammar.cpp @@ -352,6 +352,30 @@ static size_t gbnf_escape_length(const std::string & pattern, size_t pos) { return 2 + n_hex; } +static const char * gbnf_shorthand_to_rule(char c) { + switch (c) { + case 'd': return "[0-9]"; + case 'D': return "[^0-9]"; + case 's': return "[ \\t\\n\\r\\x0B\\x0C]"; + case 'S': return "[^ \\t\\n\\r\\x0B\\x0C]"; + case 'w': return "[0-9A-Za-z_]"; + case 'W': return "[^0-9A-Za-z_]"; + default: return nullptr; + } +} + +static const char * gbnf_shorthand_in_char_class(char c) { + switch (c) { + case 'd': return "0-9"; + case 'D': return "\\x00-\\x2F\\x3A-\\U0010FFFF"; + case 's': return " \\t\\n\\r\\x0B\\x0C"; + case 'S': return "\\x00-\\x08\\x0E-\\x1F\\x21-\\U0010FFFF"; + case 'w': return "0-9A-Za-z_"; + case 'W': return "\\x00-\\x2F\\x3A-\\x40\\x5B-\\x5E\\x60\\x7B-\\U0010FFFF"; + default: return nullptr; + } +} + class common_chat_schema_converter { private: friend std::string build_grammar(const std::function & cb, const common_grammar_options & options); @@ -522,14 +546,34 @@ class common_chat_schema_converter { } else if (c == '[') { std::string square_brackets = std::string(1, c); i++; + if (i < length && sub_pattern[i] == '^') { + square_brackets += '^'; + i++; + } while (i < length && sub_pattern[i] != ']') { if (sub_pattern[i] == '\\') { + if (i + 1 < length) { + if (const char * expanded = gbnf_shorthand_in_char_class(sub_pattern[i + 1])) { + square_brackets += expanded; + i += 2; + if (i < length && sub_pattern[i] == '-' && i + 1 < length && sub_pattern[i + 1] != ']') { + square_brackets += "\\-"; + i++; + } + continue; + } + } auto escape_length = gbnf_escape_length(sub_pattern, i); if (escape_length == 0) { throw unsupported_pattern("unsupported escape in character class: " + sub_pattern.substr(i, 2)); } square_brackets += sub_pattern.substr(i, escape_length); i += escape_length; + } else if (sub_pattern[i] == '-' && + i + 1 < length && sub_pattern[i + 1] == '\\' && + i + 2 < length && gbnf_shorthand_in_char_class(sub_pattern[i + 2]) != nullptr) { + square_brackets += "\\-"; + i++; } else { square_brackets += sub_pattern[i]; i++; @@ -541,6 +585,9 @@ class common_chat_schema_converter { square_brackets += ']'; i++; seq.emplace_back(square_brackets, false); + } else if (c == '\\' && i + 1 < length && gbnf_shorthand_to_rule(sub_pattern[i + 1]) != nullptr) { + seq.emplace_back(gbnf_shorthand_to_rule(sub_pattern[i + 1]), false); + i += 2; } else if (c == '|') { seq.emplace_back("|", false); i++; @@ -614,6 +661,9 @@ class common_chat_schema_converter { throw invalid_pattern("trailing backslash"); } char next = sub_pattern[i + 1]; + if (gbnf_shorthand_to_rule(next) != nullptr) { + break; + } if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) { i++; literal += sub_pattern[i]; diff --git a/common/parsers/inkling.cpp b/common/parsers/inkling.cpp index 082bd86fdfd2..4c38233a7efc 100644 --- a/common/parsers/inkling.cpp +++ b/common/parsers/inkling.cpp @@ -1,5 +1,8 @@ #include "parsers.h" +#include +#include "log.h" + bool is_inkling_template(const std::string & src) { return src.find("<|message_user|>") != std::string::npos && src.find("<|content_image|>") != std::string::npos; @@ -122,9 +125,9 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template & // the call takes the name in the JSON auto tool_json = p.token(TOOL_JSON); - auto tool_body = [&](const common_peg_parser & json_name) { + auto tool_body = [&](const common_peg_parser & json_name, const common_peg_parser & args_parser) { 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; + << p.json_member("args", p.tool_args(args_parser)) << p.tool_close(p.literal("}")) + end; }; if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { @@ -134,9 +137,67 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template & std::string name = function.at("name"); std::string quoted = json(name).dump(); + auto args_inner = p.json(); + try { + auto params = common_chat_tool_parameters(function); + auto doc = std::make_shared(common_chat_schema_from_json(params)); + const auto * obj = dynamic_cast(doc->root.get()); + if (obj && !obj->additional_properties) { + if (obj->properties.empty()) { + args_inner = p.literal("{") + p.optional(p.space()) + p.literal("}"); + } else { + std::vector sorted; + sorted.reserve(obj->properties.size()); + for (const auto & prop : obj->properties) { + sorted.push_back(&prop); + } + std::sort(sorted.begin(), sorted.end(), [](const auto * a, const auto * b) { + return a->name < b->name; + }); + size_t first_req = sorted.size(); + for (size_t j = 0; j < sorted.size(); ++j) { + if (sorted[j]->required) { + first_req = j; + break; + } + } + if (first_req < sorted.size()) { + std::vector kv_rules; + kv_rules.reserve(sorted.size()); + for (size_t j = 0; j < sorted.size(); ++j) { + const std::string base = "tool-" + std::to_string(tool_index) + "-p" + std::to_string(j); + auto val = p.schema(p.json(), base + "-val", doc, *sorted[j]->schema); + kv_rules.push_back(p.rule(base + "-kv", + p.literal(json(sorted[j]->name).dump()) + p.optional(p.space()) + + p.literal(":") + p.optional(p.space()) + val)); + } + auto comma = p.optional(p.space()) + p.literal(",") + p.optional(p.space()); + auto chain = kv_rules[first_req]; + for (size_t j = first_req + 1; j < sorted.size(); ++j) { + chain = sorted[j]->required ? (chain + comma + kv_rules[j]) + : (chain + p.optional(comma + kv_rules[j])); + } + for (size_t j = first_req; j > 0; --j) { + chain = p.optional(kv_rules[j - 1] + comma) + chain; + } + args_inner = p.literal("{") + p.optional(p.space()) + chain + p.optional(p.space()) + p.literal("}"); + } else if (params.contains("properties") && params.at("properties").is_object()) { + json sorted_props = json::object(); + for (const auto * sp : sorted) { + sorted_props[sp->name] = params.at("properties").at(sp->name); + } + params["properties"] = sorted_props; + args_inner = p.schema(p.json(), "tool-" + std::to_string(tool_index) + "-schema", params); + } + } + } + } catch (const std::exception & e) { + LOG_WRN("%s: tool %s uses generic JSON args: %s\n", __func__, name.c_str(), e.what()); + } + // 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))); + tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.optional(p.literal(name)) + tool_json + tool_body(json_name, args_inner))); }); auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice; @@ -144,7 +205,7 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template & } auto name = p.until(tool_json); - auto body = tool_body(p.string_content('"')); + auto body = tool_body(p.string_content('"'), p.json()); 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); diff --git a/common/sampling.cpp b/common/sampling.cpp index 078bfd984f42..1a6242ad574c 100644 --- a/common/sampling.cpp +++ b/common/sampling.cpp @@ -12,7 +12,12 @@ #include #include #include +#include +#include +#include +#include #include +#include #include #include @@ -125,6 +130,9 @@ struct common_sampler { // for rejection sampling; independent of the draft, or the target distribution is not preserved std::mt19937 rng; + bool pure_argmax_fast = false; + bool stateless_dist_fast = false; + void reset() { prev.clear(); @@ -349,10 +357,58 @@ struct common_sampler * common_sampler_init( } } + bool pure_argmax_fast = false; + if (params.mirostat == 0) { bool use_adaptive_p = false; // see below + const bool greedy = params.n_probs == 0 && !params.samplers.empty() && + ((params.samplers.back() == COMMON_SAMPLER_TYPE_TEMPERATURE && params.temp <= 0.0f && params.dynatemp_range == 0.0f) || + (params.samplers.back() == COMMON_SAMPLER_TYPE_TOP_K && params.top_k == 1)); + + const bool rbudget_unlimited = !rbudget || (params.reasoning_budget_tokens < 0 && + common_reasoning_budget_get_state(rbudget) != REASONING_BUDGET_FORCING); + bool pure_argmax_chain = greedy && !grmr && rbudget_unlimited && !getenv("GGML_VK_DISABLE_GREEDY_FAST"); + if (pure_argmax_chain) { + for (const auto & cnstr : params.samplers) { + switch (cnstr) { + case COMMON_SAMPLER_TYPE_TOP_K: + break; + case COMMON_SAMPLER_TYPE_TOP_P: + case COMMON_SAMPLER_TYPE_MIN_P: + if (params.min_keep < 1) { pure_argmax_chain = false; } + break; + case COMMON_SAMPLER_TYPE_TYPICAL_P: + if (params.typ_p < 1.0f) { pure_argmax_chain = false; } + break; + case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: + if (params.top_n_sigma > 0.0f) { pure_argmax_chain = false; } + break; + case COMMON_SAMPLER_TYPE_TEMPERATURE: + if (params.temp > 0.0f || params.dynatemp_range != 0.0f) { pure_argmax_chain = false; } + break; + case COMMON_SAMPLER_TYPE_PENALTIES: + if (params.penalty_last_n != 0 && + (params.penalty_repeat != 1.0f || params.penalty_freq != 0.0f || params.penalty_present != 0.0f)) { + pure_argmax_chain = false; + } + break; + case COMMON_SAMPLER_TYPE_DRY: + if (params.dry_multiplier > 0.0f) { pure_argmax_chain = false; } + break; + case COMMON_SAMPLER_TYPE_XTC: + if (params.xtc_probability > 0.0f) { pure_argmax_chain = false; } + break; + default: + pure_argmax_chain = false; + break; + } + } + } + pure_argmax_fast = pure_argmax_chain && samplers.empty(); + + if (!pure_argmax_chain) { for (const auto & cnstr : params.samplers) { switch (cnstr) { case COMMON_SAMPLER_TYPE_DRY: @@ -403,14 +459,12 @@ struct common_sampler * common_sampler_init( GGML_ASSERT(false && "unknown sampler type"); } } + } if (use_adaptive_p) { // only if user explicitly included adaptive-p sampler samplers.push_back(llama_sampler_init_adaptive_p(params.adaptive_target, params.adaptive_decay, params.seed)); } else { // Keep distribution sampling when callers request probabilities. - const bool greedy = params.n_probs == 0 && !params.samplers.empty() && - ((params.samplers.back() == COMMON_SAMPLER_TYPE_TEMPERATURE && params.temp == 0.0f && params.dynatemp_range == 0.0f) || - (params.samplers.back() == COMMON_SAMPLER_TYPE_TOP_K && params.top_k == 1)); samplers.push_back(greedy ? llama_sampler_init_greedy() : llama_sampler_init_dist(params.seed)); } } else if (params.mirostat == 1) { @@ -439,6 +493,37 @@ struct common_sampler * common_sampler_init( params.backend_sampling = false; } + bool stateless_dist_fast = !pure_argmax_fast && !grmr && !rbudget && + params.mirostat == 0 && params.n_probs == 0 && !getenv("LLAMA_NO_PAR_VERIFY"); + if (stateless_dist_fast) { + const int n_sc = llama_sampler_chain_n(chain); + if (n_sc < 1 || std::strcmp(llama_sampler_name(llama_sampler_chain_get(chain, n_sc - 1)), "dist") != 0) { + stateless_dist_fast = false; + } + for (const auto & cnstr : params.samplers) { + switch (cnstr) { + case COMMON_SAMPLER_TYPE_PENALTIES: + if (params.penalty_last_n != 0 && + (params.penalty_repeat != 1.0f || params.penalty_freq != 0.0f || params.penalty_present != 0.0f)) { + stateless_dist_fast = false; + } + break; + case COMMON_SAMPLER_TYPE_DRY: + if (params.dry_multiplier > 0.0f) { stateless_dist_fast = false; } + break; + case COMMON_SAMPLER_TYPE_XTC: + if (params.xtc_probability > 0.0f) { stateless_dist_fast = false; } + break; + case COMMON_SAMPLER_TYPE_ADAPTIVE_P: + case COMMON_SAMPLER_TYPE_INFILL: + stateless_dist_fast = false; + break; + default: + break; + } + } + } + auto * result = new common_sampler { /* .params = */ params, /* .grmr = */ grmr, @@ -449,6 +534,8 @@ struct common_sampler * common_sampler_init( /* .cur_p = */ {}, // mix it, the chain and the draft are seeded from this one too /* .rng = */ std::mt19937(llama_sampler_get_seed(chain) ^ 0x9e3779b9u), + /* .pure_argmax_fast = */ pure_argmax_fast, + /* .stateless_dist_fast = */ stateless_dist_fast, }; return result; @@ -481,6 +568,16 @@ static bool grammar_should_apply(struct common_sampler * gsmpl) { return true; } +static bool common_sampler_constraints_are_noop(struct common_sampler * gsmpl) { + if (gsmpl->rbudget && common_reasoning_budget_get_state(gsmpl->rbudget) == REASONING_BUDGET_FORCING) { + return false; + } + if (grammar_should_apply(gsmpl) && !llama_sampler_grammar_is_dormant(gsmpl->grmr)) { + return false; + } + return true; +} + void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool is_generated) { if (!gsmpl) { return; @@ -533,6 +630,8 @@ struct common_sampler * common_sampler_clone(common_sampler * gsmpl) { /* .cur = */ gsmpl->cur, /* .cur_p = */ gsmpl->cur_p, /* .rng = */ gsmpl->rng, + /* .pure_argmax_fast = */ gsmpl->pure_argmax_fast, + /* .stateless_dist_fast = */ gsmpl->stateless_dist_fast, }; } @@ -554,6 +653,8 @@ void common_sampler_copy(const common_sampler * src, common_sampler * dst) { dst->cur_p = src->cur_p; dst->cur_p.data = src->cur_p.data ? dst->cur.data() : nullptr; // re-point to dst's buffer dst->rng = src->rng; + dst->pure_argmax_fast = src->pure_argmax_fast; + dst->stateless_dist_fast = src->stateless_dist_fast; dst->t_total_us = src->t_total_us; } @@ -611,7 +712,16 @@ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl) { return gsmpl->chain; } -llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) { +static llama_token common_sampler_sample_impl( + struct common_sampler * gsmpl, + struct llama_context * ctx, + int idx, + bool grammar_first, + bool need_candidates, + bool * out_grmr_applied = nullptr) { + if (out_grmr_applied) { + *out_grmr_applied = false; + } llama_synchronize(ctx); // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations @@ -624,6 +734,82 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co auto & chain = gsmpl->chain; auto & cur_p = gsmpl->cur_p; // initialized by set_logits + const bool can_pure_argmax = !need_candidates && gsmpl->pure_argmax_fast && !gsmpl->grmr && + (!gsmpl->rbudget || (gsmpl->params.reasoning_budget_tokens < 0 && + common_reasoning_budget_get_state(gsmpl->rbudget) != REASONING_BUDGET_FORCING)); + if (can_pure_argmax) { + const llama_token backend_id = llama_get_sampled_token_ith(ctx, idx); + if (backend_id != LLAMA_TOKEN_NULL) { + gsmpl->cur.resize(1); + gsmpl->cur[0] = llama_token_data{ backend_id, 0.0f, 1.0f }; + cur_p = { gsmpl->cur.data(), 1, 0, true }; + return backend_id; + } + } + + if (can_pure_argmax && + !llama_get_sampled_probs_ith(ctx, idx) && + !llama_get_sampled_logits_ith(ctx, idx)) { + const float * logits = llama_get_logits_ith_ro(ctx, idx); + GGML_ASSERT(logits != nullptr); + const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + llama_token best_id = 0; + float best_val = logits[0]; + for (llama_token token_id = 1; token_id < n_vocab; ++token_id) { + const float v = logits[token_id]; + if (v > best_val) { + best_val = v; + best_id = token_id; + } + } + gsmpl->cur.resize(1); + gsmpl->cur[0] = llama_token_data{ best_id, best_val, 1.0f }; + cur_p = { gsmpl->cur.data(), 1, 0, true }; + return best_id; + } + + // Series 20/21 (Pillar S20.5 + S21.B): Single-row zero-copy UMA + AoS-free 0-ULP fastpath + // Active whenever rbudget is not forcing and any grammar is either suppressed (COUNTING) or lazy-dormant (awaiting_trigger). + if (!need_candidates && !grammar_first && common_sampler_constraints_are_noop(gsmpl) && + gsmpl->params.mirostat == 0 && gsmpl->params.n_probs == 0 && + !getenv("LLAMA_NO_S20_DIST_FAST") && + llama_get_sampled_token_ith(ctx, idx) == LLAMA_TOKEN_NULL && + !llama_get_sampled_probs_ith(ctx, idx) && + !llama_get_sampled_logits_ith(ctx, idx)) { + float eff_temp = 1.0f; + struct llama_sampler * dist_smpl = nullptr; + struct llama_sampler * lb_smpl = nullptr; + if (llama_sampler_chain_is_bias_temp_dist(chain, &eff_temp, &dist_smpl, &lb_smpl)) { + const float * logits = llama_get_logits_ith_ro(ctx, idx); + GGML_ASSERT(logits != nullptr); + const int32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + id = llama_sampler_temp_dist_probs_raw_0ulp(dist_smpl, lb_smpl, logits, n_vocab, eff_temp, nullptr, nullptr); + const float picked_logit = logits[id]; + gsmpl->cur.resize(1); + gsmpl->cur[0] = llama_token_data{ id, picked_logit, 1.0f }; + cur_p = { gsmpl->cur.data(), 1, 0, true }; + return id; + } + if (!getenv("GGML_VK_DISABLE_GREEDY_FAST") && llama_sampler_chain_is_pure_greedy(chain)) { + const float * logits = llama_get_logits_ith_ro(ctx, idx); + GGML_ASSERT(logits != nullptr); + const int32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + llama_token best_id = 0; + float best_val = logits[0]; + for (llama_token token_id = 1; token_id < n_vocab; ++token_id) { + const float v = logits[token_id]; + if (v > best_val) { + best_val = v; + best_id = token_id; + } + } + gsmpl->cur.resize(1); + gsmpl->cur[0] = llama_token_data{ best_id, best_val, 1.0f }; + cur_p = { gsmpl->cur.data(), 1, 0, true }; + return best_id; + } + } + gsmpl->set_logits(ctx, idx); // Check if a backend sampler has already sampled a token in which case we @@ -651,15 +837,18 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co // apply reasoning budget first llama_sampler_apply(rbudget, &cur_p); - if (grammar_first && grammar_should_apply(gsmpl)) { + if (grammar_first && grammar_should_apply(gsmpl) && !llama_sampler_grammar_is_dormant(grmr)) { llama_sampler_apply(grmr, &cur_p); + if (out_grmr_applied) { + *out_grmr_applied = true; + } } llama_sampler_apply(chain, &cur_p); id = cur_p.data[cur_p.selected].id; - if (grammar_first || !grammar_should_apply(gsmpl)) { + if (grammar_first || !grammar_should_apply(gsmpl) || llama_sampler_grammar_is_dormant(grmr)) { return id; } @@ -678,12 +867,37 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co // resampling: // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain + if (!need_candidates && gsmpl->pure_argmax_fast && !gsmpl->grmr && !gsmpl->rbudget && + llama_get_sampled_token_ith(ctx, idx) == LLAMA_TOKEN_NULL && + !llama_get_sampled_probs_ith(ctx, idx) && + !llama_get_sampled_logits_ith(ctx, idx)) { + const float * logits = llama_get_logits_ith_ro(ctx, idx); + GGML_ASSERT(logits != nullptr); + const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + llama_token best_id = 0; + float best_val = logits[0]; + for (llama_token token_id = 1; token_id < n_vocab; ++token_id) { + const float v = logits[token_id]; + if (v > best_val) { + best_val = v; + best_id = token_id; + } + } + gsmpl->cur.resize(1); + gsmpl->cur[0] = llama_token_data{ best_id, best_val, 1.0f }; + cur_p = { gsmpl->cur.data(), 1, 0, true }; + return best_id; + } + gsmpl->set_logits(ctx, idx); llama_sampler_apply(rbudget, &cur_p); - if (grammar_should_apply(gsmpl)) { + if (grammar_should_apply(gsmpl) && !llama_sampler_grammar_is_dormant(grmr)) { llama_sampler_apply(grmr, &cur_p); + if (out_grmr_applied) { + *out_grmr_applied = true; + } } llama_sampler_apply(chain, &cur_p); @@ -695,6 +909,16 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co return id; } +llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) { + return common_sampler_sample_impl(gsmpl, ctx, idx, grammar_first, false, nullptr); +} + +bool common_sampler_is_pure_argmax(const struct common_sampler * gsmpl) { + return gsmpl && gsmpl->pure_argmax_fast && !gsmpl->grmr && + (!gsmpl->rbudget || (gsmpl->params.reasoning_budget_tokens < 0 && + common_reasoning_budget_get_state(gsmpl->rbudget) != REASONING_BUDGET_FORCING)); +} + std::vector common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector & idxs, const llama_tokens & draft, bool grammar_first) { GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1"); @@ -703,9 +927,72 @@ std::vector common_sampler_sample_and_accept_n(struct common_sample const llama_vocab * vocab = llama_model_get_vocab(llama_get_model(ctx)); + // Series 20/21 (Pillar S20.5 + S21.B): Per-token zero-copy UMA + AoS-free EOG-exact verification (0-ULP, 0-RNG-drift). + // Evaluates common_sampler_constraints_are_noop(gsmpl) dynamically BEFORE each position idxs[i] and calls + // common_sampler_accept(gsmpl, id, true) IMMEDIATELY, so if id triggers lazy grmr (e.g. <|tool_call_start|>) + // or transitions rbudget into FORCING, position i+1 automatically switches to common_sampler_sample (cleanly + // materializing logits_uma_view via set_logits) with 0-ULP and 0 RNG drift. + float eff_temp = 1.0f; + struct llama_sampler * dist_smpl = nullptr; + bool raw_pure_temp_dist = false; + bool raw_pure_greedy = false; + + if (!grammar_first && + gsmpl->params.mirostat == 0 && + gsmpl->params.n_probs == 0 && + !getenv("LLAMA_NO_S20_DIST_FAST") && + llama_get_sampled_token_ith(ctx, idxs[0]) == LLAMA_TOKEN_NULL && + !llama_get_sampled_probs_ith(ctx, idxs[0]) && + !llama_get_sampled_logits_ith(ctx, idxs[0])) { + raw_pure_temp_dist = llama_sampler_chain_is_pure_temp_dist(gsmpl->chain, &eff_temp, &dist_smpl); + if (!raw_pure_temp_dist && !getenv("GGML_VK_DISABLE_GREEDY_FAST")) { + raw_pure_greedy = llama_sampler_chain_is_pure_greedy(gsmpl->chain); + } + } + + const int32_t n_vocab = llama_vocab_n_tokens(vocab); + bool synced = false; + + auto sample_step = [&](int batch_idx) -> llama_token { + if ((raw_pure_temp_dist || raw_pure_greedy) && + common_sampler_constraints_are_noop(gsmpl) && + llama_get_sampled_token_ith(ctx, batch_idx) == LLAMA_TOKEN_NULL && + !llama_get_sampled_probs_ith(ctx, batch_idx) && + !llama_get_sampled_logits_ith(ctx, batch_idx)) { + if (!synced) { + llama_synchronize(ctx); + synced = true; + } + const auto tm = gsmpl->tm(); + const float * row = llama_get_logits_ith_ro(ctx, batch_idx); + GGML_ASSERT(row != nullptr); + + llama_token id = 0; + if (raw_pure_temp_dist) { + id = llama_sampler_temp_dist_sample_raw_0ulp(dist_smpl, row, n_vocab, eff_temp); + } else { + float best_val = row[0]; + for (llama_token token_id = 1; token_id < n_vocab; ++token_id) { + const float v = row[token_id]; + if (v > best_val) { + best_val = v; + id = token_id; + } + } + } + const float picked_logit = row[id]; + gsmpl->cur.resize(1); + gsmpl->cur[0] = llama_token_data{ id, picked_logit, 1.0f }; + gsmpl->cur_p = { gsmpl->cur.data(), 1, 0, true }; + return id; + } + + return common_sampler_sample(gsmpl, ctx, batch_idx, grammar_first); + }; + size_t i = 0; for (; i < draft.size(); i++) { - const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first); + const llama_token id = sample_step(idxs[i]); common_sampler_accept(gsmpl, id, true); @@ -719,7 +1006,7 @@ std::vector common_sampler_sample_and_accept_n(struct common_sample } if (i == draft.size()) { - const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first); + const llama_token id = sample_step(idxs[i]); common_sampler_accept(gsmpl, id, true); @@ -748,22 +1035,118 @@ std::vector common_sampler_sample_and_accept_n_rejection(struct com std::vector result; result.reserve(idxs.size()); + const llama_vocab * vocab = llama_model_get_vocab(llama_get_model(ctx)); + const int32_t n_vocab = llama_vocab_n_tokens(vocab); + // draws come from the sampler's own stream, so they stay independent of what was drafted std::uniform_real_distribution uni(0.0f, 1.0f); - std::vector residual; + float eff_temp = 1.0f; + struct llama_sampler * dist_smpl = nullptr; + struct llama_sampler * lb_smpl = nullptr; + bool raw_bias_temp_dist = false; + if (!grammar_first && + gsmpl->params.mirostat == 0 && + gsmpl->params.n_probs == 0 && + !getenv("LLAMA_NO_S20_DIST_FAST") && + llama_get_sampled_token_ith(ctx, idxs[0]) == LLAMA_TOKEN_NULL && + !llama_get_sampled_probs_ith(ctx, idxs[0]) && + !llama_get_sampled_logits_ith(ctx, idxs[0])) { + raw_bias_temp_dist = llama_sampler_chain_is_bias_temp_dist(gsmpl->chain, &eff_temp, &dist_smpl, &lb_smpl); + } + static thread_local std::vector q_dense; + if ((int32_t) q_dense.size() < n_vocab) { + q_dense.assign(n_vocab, 0.0f); + } + + std::vector residual; std::vector cand; // candidate array masked by the grammar, if there is one + bool synced = false; size_t i = 0; for (; i < draft.size(); i++) { - // leaves the target distribution in the candidate array - const llama_token id_tgt = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first); + const auto & q = draft_q[i]; + + if (raw_bias_temp_dist && common_sampler_constraints_are_noop(gsmpl) && + llama_get_sampled_token_ith(ctx, idxs[i]) == LLAMA_TOKEN_NULL && + !llama_get_sampled_probs_ith(ctx, idxs[i]) && + !llama_get_sampled_logits_ith(ctx, idxs[i])) { + if (!synced) { + llama_synchronize(ctx); + synced = true; + } + const auto tm = gsmpl->tm(); + const float * row = llama_get_logits_ith_ro(ctx, idxs[i]); + GGML_ASSERT(row != nullptr); + const float * unnorm_p = nullptr; + double sum_p = 0.0; + const llama_token id_tgt = llama_sampler_temp_dist_probs_raw_0ulp( + dist_smpl, lb_smpl, row, n_vocab, eff_temp, &unnorm_p, &sum_p); + const float inv_sum = sum_p > 0.0 ? (float) (1.0 / sum_p) : 0.0f; + const float q_x = prob_of(q.data(), q.size(), draft[i]); + const float p_x = (draft[i] >= 0 && draft[i] < n_vocab) ? unnorm_p[draft[i]] * inv_sum : 0.0f; + + if (q_x > 0.0f && (p_x >= q_x || uni(gsmpl->rng) < p_x / q_x)) { + common_sampler_accept(gsmpl, draft[i], true); + result.push_back(draft[i]); + if (llama_vocab_is_eog(vocab, draft[i]) && i + 1 < draft.size()) { + break; + } + continue; + } - const auto * cur_p = common_sampler_get_candidates(gsmpl, true); - const auto & q = draft_q[i]; + for (const auto & qe : q) { + if (qe.id >= 0 && qe.id < n_vocab) { + q_dense[qe.id] = qe.p; + } + } + float sum = 0.0f; + for (int32_t k = 0; k < n_vocab; ++k) { + const float r = unnorm_p[k] * inv_sum - q_dense[k]; + if (r > 0.0f) { + sum += r; + } + } + llama_token id = id_tgt; + if (sum > 0.0f) { + float u = uni(gsmpl->rng) * sum; + int32_t last_pos = id_tgt; + for (int32_t k = 0; k < n_vocab; ++k) { + const float r = unnorm_p[k] * inv_sum - q_dense[k]; + if (r > 0.0f) { + last_pos = k; + u -= r; + if (u <= 0.0f) { + id = k; + last_pos = -1; + break; + } + } + } + if (last_pos >= 0) { + id = last_pos; + } + } + for (const auto & qe : q) { + if (qe.id >= 0 && qe.id < n_vocab) { + q_dense[qe.id] = 0.0f; + } + } + + common_sampler_accept(gsmpl, id, true); + result.push_back(id); + break; + } + + // leaves the target distribution in the candidate array (without std::sort) + bool grmr_applied = false; + const llama_token id_tgt = common_sampler_sample_impl(gsmpl, ctx, idxs[i], grammar_first, true, &grmr_applied); + synced = true; - const bool masked = !grammar_first && grammar_should_apply(gsmpl); + const auto * cur_p = common_sampler_get_candidates(gsmpl, false); + + const bool masked = !grammar_first && !grmr_applied && grammar_should_apply(gsmpl) && !llama_sampler_grammar_is_dormant(gsmpl->grmr); if (masked) { cand.assign(cur_p->data, cur_p->data + cur_p->size); llama_token_data_array arr = { cand.data(), cand.size(), -1, false }; @@ -793,29 +1176,48 @@ std::vector common_sampler_sample_and_accept_n_rejection(struct com const float q_x = prob_of(q.data(), q.size(), draft[i]); float p_x = 0.0f; - for (size_t k = 0; k < cur_p->size; ++k) { - if (cur_p->data[k].id == draft[i]) { - p_x = p_of(k); - break; + if (draft[i] >= 0 && (size_t) draft[i] < cur_p->size && cur_p->data[draft[i]].id == draft[i]) { + p_x = p_of((size_t) draft[i]); + } else { + for (size_t k = 0; k < cur_p->size; ++k) { + if (cur_p->data[k].id == draft[i]) { + p_x = p_of(k); + break; + } } } if (q_x > 0.0f && (p_x >= q_x || uni(gsmpl->rng) < p_x / q_x)) { common_sampler_accept(gsmpl, draft[i], true); result.push_back(draft[i]); + if (llama_vocab_is_eog(vocab, draft[i]) && i + 1 < draft.size()) { + break; + } continue; } // rejected: tokens outside q's support keep all of p + for (const auto & qe : q) { + if (qe.id >= 0 && qe.id < n_vocab) { + q_dense[qe.id] = qe.p; + } + } residual.clear(); float sum = 0.0f; for (size_t k = 0; k < cur_p->size; ++k) { - const float r = p_of(k) - prob_of(q.data(), q.size(), cur_p->data[k].id); + const llama_token tid = cur_p->data[k].id; + const float q_k = (tid >= 0 && tid < n_vocab) ? q_dense[tid] : prob_of(q.data(), q.size(), tid); + const float r = p_of(k) - q_k; if (r > 0.0f) { - residual.push_back({ cur_p->data[k].id, 0.0f, r }); + residual.push_back({ tid, 0.0f, r }); sum += r; } } + for (const auto & qe : q) { + if (qe.id >= 0 && qe.id < n_vocab) { + q_dense[qe.id] = 0.0f; + } + } llama_token id = id_tgt; if (sum > 0.0f) { @@ -847,6 +1249,287 @@ std::vector common_sampler_sample_and_accept_n_rejection(struct com return result; } +std::vector common_sampler_sample_and_accept_n_tree( + struct common_sampler * gsmpl, + struct llama_context * ctx, + const std::vector & idxs_b0, + const llama_tokens & draft_b0, + const std::vector & idxs_b1, + const llama_tokens & draft_b1, + int branch_pos, + int * out_won_branch, + bool grammar_first) { + GGML_ASSERT(draft_b0.size() == draft_b1.size()); + GGML_ASSERT(idxs_b0.size() == draft_b0.size() + 1); + GGML_ASSERT(idxs_b1.size() == draft_b1.size() + 1); + GGML_ASSERT(branch_pos >= 0 && branch_pos < (int) draft_b0.size()); + + if (out_won_branch) { + *out_won_branch = 0; + } + + std::vector result; + result.reserve(idxs_b0.size()); + + const llama_vocab * vocab = llama_model_get_vocab(llama_get_model(ctx)); + + float eff_temp = 1.0f; + struct llama_sampler * dist_smpl = nullptr; + bool raw_pure_temp_dist = false; + bool raw_pure_greedy = false; + + if (!grammar_first && + gsmpl->params.mirostat == 0 && + gsmpl->params.n_probs == 0 && + !getenv("LLAMA_NO_S20_DIST_FAST") && + llama_get_sampled_token_ith(ctx, idxs_b0[0]) == LLAMA_TOKEN_NULL && + !llama_get_sampled_probs_ith(ctx, idxs_b0[0]) && + !llama_get_sampled_logits_ith(ctx, idxs_b0[0])) { + raw_pure_temp_dist = llama_sampler_chain_is_pure_temp_dist(gsmpl->chain, &eff_temp, &dist_smpl); + if (!raw_pure_temp_dist && !getenv("GGML_VK_DISABLE_GREEDY_FAST")) { + raw_pure_greedy = llama_sampler_chain_is_pure_greedy(gsmpl->chain); + } + } + + const int32_t n_vocab = llama_vocab_n_tokens(vocab); + bool synced = false; + + auto sample_step = [&](int batch_idx) -> llama_token { + if ((raw_pure_temp_dist || raw_pure_greedy) && + common_sampler_constraints_are_noop(gsmpl) && + llama_get_sampled_token_ith(ctx, batch_idx) == LLAMA_TOKEN_NULL && + !llama_get_sampled_probs_ith(ctx, batch_idx) && + !llama_get_sampled_logits_ith(ctx, batch_idx)) { + if (!synced) { + llama_synchronize(ctx); + synced = true; + } + const auto tm = gsmpl->tm(); + const float * row = llama_get_logits_ith_ro(ctx, batch_idx); + GGML_ASSERT(row != nullptr); + + llama_token id = 0; + if (raw_pure_temp_dist) { + id = llama_sampler_temp_dist_sample_raw_0ulp(dist_smpl, row, n_vocab, eff_temp); + } else { + float best_val = row[0]; + for (llama_token token_id = 1; token_id < n_vocab; ++token_id) { + const float v = row[token_id]; + if (v > best_val) { + best_val = v; + id = token_id; + } + } + } + const float picked_logit = row[id]; + gsmpl->cur.resize(1); + gsmpl->cur[0] = llama_token_data{ id, picked_logit, 1.0f }; + gsmpl->cur_p = { gsmpl->cur.data(), 1, 0, true }; + return id; + } + + return common_sampler_sample(gsmpl, ctx, batch_idx, grammar_first); + }; + + const size_t n_draft = draft_b0.size(); + int win = 0; + size_t i = 0; + for (; i < n_draft; ++i) { + const auto & cur_idxs = (win == 0) ? idxs_b0 : idxs_b1; + const auto & cur_draft = (win == 0) ? draft_b0 : draft_b1; + const llama_token id = sample_step(cur_idxs[i]); + + common_sampler_accept(gsmpl, id, true); + result.push_back(id); + + if (llama_vocab_is_eog(vocab, id) && i + 1 < n_draft) { + break; + } + + if ((int) i == branch_pos) { + if (id == draft_b0[i]) { + win = 0; + } else if (id == draft_b1[i]) { + win = 1; + } else { + break; + } + } else if (cur_draft[i] != id) { + break; + } + } + + if (i == n_draft) { + const auto & cur_idxs = (win == 0) ? idxs_b0 : idxs_b1; + const llama_token id = sample_step(cur_idxs[n_draft]); + common_sampler_accept(gsmpl, id, true); + result.push_back(id); + } + + if (out_won_branch) { + *out_won_branch = win; + } + return result; +} + +std::vector common_sampler_sample_and_accept_n_tree_rejection( + struct common_sampler * gsmpl, + struct llama_context * ctx, + const std::vector & idxs_b0, + const llama_tokens & draft_b0, + const std::vector> & draft_q_b0, + const std::vector & idxs_b1, + const llama_tokens & draft_b1, + const std::vector> & draft_q_b1, + int branch_pos, + int * out_won_branch, + bool grammar_first) { + GGML_ASSERT(draft_b0.size() == draft_b1.size()); + GGML_ASSERT(idxs_b0.size() == draft_b0.size() + 1); + GGML_ASSERT(idxs_b1.size() == draft_b1.size() + 1); + GGML_ASSERT(draft_q_b0.size() == draft_b0.size()); + GGML_ASSERT(draft_q_b1.size() == draft_b1.size()); + GGML_ASSERT(branch_pos >= 0 && branch_pos < (int) draft_b0.size()); + + if (out_won_branch) { + *out_won_branch = 0; + } + + std::vector result; + result.reserve(idxs_b0.size()); + + std::uniform_real_distribution uni(0.0f, 1.0f); + std::vector residual; + std::vector cand; + + const size_t n_draft = draft_b0.size(); + int win = 0; + size_t i = 0; + for (; i < n_draft; ++i) { + const auto & cur_idxs = (win == 0) ? idxs_b0 : idxs_b1; + const auto & cur_draft = (win == 0) ? draft_b0 : draft_b1; + const auto & cur_draft_q = (win == 0) ? draft_q_b0 : draft_q_b1; + + bool grmr_applied = false; + const llama_token id_tgt = common_sampler_sample_impl(gsmpl, ctx, cur_idxs[i], grammar_first, true, &grmr_applied); + const auto * cur_p = common_sampler_get_candidates(gsmpl, false); + const auto & q1 = cur_draft_q[i]; + + const bool masked = !grammar_first && !grmr_applied && grammar_should_apply(gsmpl) && !llama_sampler_grammar_is_dormant(gsmpl->grmr); + if (masked) { + cand.assign(cur_p->data, cur_p->data + cur_p->size); + llama_token_data_array arr = { cand.data(), cand.size(), -1, false }; + llama_sampler_apply(gsmpl->grmr, &arr); + } + + auto p_raw = [&](size_t k) { + return masked && cand[k].logit == -INFINITY ? 0.0f : cur_p->data[k].p; + }; + + float p_sum = 0.0f; + if (masked) { + for (size_t k = 0; k < cur_p->size; ++k) { + p_sum += p_raw(k); + } + } + const float p_norm = masked && p_sum > 0.0f ? 1.0f / p_sum : 1.0f; + auto p_of = [&](size_t k) { + return p_raw(k) * p_norm; + }; + + const llama_token a_tok = cur_draft[i]; + const float q1_a = prob_of(q1.data(), q1.size(), a_tok); + float p_a = 0.0f; + for (size_t k = 0; k < cur_p->size; ++k) { + if (cur_p->data[k].id == a_tok) { + p_a = p_of(k); + break; + } + } + + if (q1_a > 0.0f && (p_a >= q1_a || uni(gsmpl->rng) < p_a / q1_a)) { + common_sampler_accept(gsmpl, a_tok, true); + result.push_back(a_tok); + if (llama_vocab_is_eog(llama_model_get_vocab(llama_get_model(ctx)), a_tok) && i + 1 < n_draft) { + break; + } + continue; + } + + // Stage 1 rejected: compute unnormalized residual r_1(x) = max(0, p(x) - q_1(x)) + residual.clear(); + float z1 = 0.0f; + for (size_t k = 0; k < cur_p->size; ++k) { + const float r1 = p_of(k) - prob_of(q1.data(), q1.size(), cur_p->data[k].id); + if (r1 > 0.0f) { + residual.push_back({ cur_p->data[k].id, 0.0f, r1 }); + z1 += r1; + } + } + + // At branch_pos, test Branch 1's candidate b against normalized residual p^(1)(x) = r_1(x) / z_1 + if ((int) i == branch_pos && z1 > 0.0f && draft_b1[i] != draft_b0[i]) { + const llama_token b_tok = draft_b1[i]; + const auto & q2 = draft_q_b1[i]; + const float q2_b = prob_of(q2.data(), q2.size(), b_tok); + const float r1_b = prob_of(residual.data(), residual.size(), b_tok); + const float p1_b = r1_b / z1; + if (q2_b > 0.0f && (p1_b >= q2_b || uni(gsmpl->rng) < p1_b / q2_b)) { + win = 1; + common_sampler_accept(gsmpl, b_tok, true); + result.push_back(b_tok); + if (llama_vocab_is_eog(llama_model_get_vocab(llama_get_model(ctx)), b_tok) && i + 1 < n_draft) { + break; + } + continue; + } + // Stage 2 rejected: update residual to r_2(x) = max(0, p^(1)(x) - q_2(x)) + float z2 = 0.0f; + std::vector res2; + res2.reserve(residual.size()); + const float inv_z1 = 1.0f / z1; + for (const auto & e : residual) { + const float r2 = e.p * inv_z1 - prob_of(q2.data(), q2.size(), e.id); + if (r2 > 0.0f) { + res2.push_back({ e.id, 0.0f, r2 }); + z2 += r2; + } + } + residual = std::move(res2); + z1 = z2; + } + + llama_token id = id_tgt; + if (z1 > 0.0f && !residual.empty()) { + float u = uni(gsmpl->rng) * z1; + id = residual.back().id; + for (const auto & e : residual) { + u -= e.p; + if (u <= 0.0f) { + id = e.id; + break; + } + } + } + + common_sampler_accept(gsmpl, id, true); + result.push_back(id); + break; + } + + if (i == n_draft) { + const auto & cur_idxs = (win == 0) ? idxs_b0 : idxs_b1; + const llama_token id = common_sampler_sample(gsmpl, ctx, cur_idxs[n_draft], grammar_first); + common_sampler_accept(gsmpl, id, true); + result.push_back(id); + } + + if (out_won_branch) { + *out_won_branch = win; + } + return result; +} + std::vector common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first) { std::vector idxs(draft.size() + 1); for (size_t i = 0; i < idxs.size(); ++i) { diff --git a/common/sampling.h b/common/sampling.h index f19bd27c40f8..ece0208585d9 100644 --- a/common/sampling.h +++ b/common/sampling.h @@ -88,10 +88,36 @@ std::vector common_sampler_sample_and_accept_n(struct common_sample // as above, but verifies by rejection sampling; draft_q holds the draft's candidates per token std::vector common_sampler_sample_and_accept_n_rejection(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector & idxs, const llama_tokens & draft, const std::vector> & draft_q, bool grammar_first = false); +// 2-branch speculative tree verification (exact target greedy/sample-and-match + 2-stage residual rejection) +std::vector common_sampler_sample_and_accept_n_tree( + struct common_sampler * gsmpl, + struct llama_context * ctx, + const std::vector & idxs_b0, + const llama_tokens & draft_b0, + const std::vector & idxs_b1, + const llama_tokens & draft_b1, + int branch_pos, + int * out_won_branch, + bool grammar_first = false); + +std::vector common_sampler_sample_and_accept_n_tree_rejection( + struct common_sampler * gsmpl, + struct llama_context * ctx, + const std::vector & idxs_b0, + const llama_tokens & draft_b0, + const std::vector> & draft_q_b0, + const std::vector & idxs_b1, + const llama_tokens & draft_b1, + const std::vector> & draft_q_b1, + int branch_pos, + int * out_won_branch, + bool grammar_first = false); + // assume idxs == [ 0, 1, 2, ..., draft.size() ] std::vector common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first = false); uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl); +bool common_sampler_is_pure_argmax(const struct common_sampler * gsmpl); // force the reasoning budget sampler (if any) to begin forcing its end sequence now. bool common_sampler_reasoning_budget_force(struct common_sampler * gsmpl); diff --git a/common/speculative.cpp b/common/speculative.cpp index db54aef53086..8800b062b61d 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -64,7 +64,11 @@ static void spec_retune( sparams.temp = cur.temp; // must be explicit, the default reseeds at random; mixed so it differs from the target's sparams.seed = cur.seed == LLAMA_DEFAULT_SEED ? cur.seed : cur.seed ^ 0x85ebca6bu; - sparams.samplers = { COMMON_SAMPLER_TYPE_TOP_K, COMMON_SAMPLER_TYPE_TEMPERATURE }; + if (cur.temp <= 0.0f && !getenv("GGML_VK_DISABLE_GREEDY_FAST")) { + sparams.samplers = { COMMON_SAMPLER_TYPE_TEMPERATURE }; + } else { + sparams.samplers = { COMMON_SAMPLER_TYPE_TOP_K, COMMON_SAMPLER_TYPE_TEMPERATURE }; + } smpls[seq_id].reset(common_sampler_init(model, sparams)); } @@ -215,6 +219,9 @@ struct common_speculative_impl { // (optional) serialize/restore per-seq internal state (e.g. eagle3's deferred boundary). virtual bool get_state(llama_seq_id /*seq_id*/, std::vector & /*data*/) const { return false; } virtual void set_state(llama_seq_id /*seq_id*/, const std::vector & /*data*/) {} + + virtual int32_t ctx_window() const { return 0; } + virtual bool should_skip_process(llama_seq_id /*seq_id*/) const { return false; } }; struct common_speculative_impl_draft_simple : public common_speculative_impl { @@ -998,8 +1005,9 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { int32_t n_embd_enc = 0; // target_layer_ids_n * target_hidden_size int32_t n_embd_tgt = 0; // target model hidden size - int32_t block_size = 0; - llama_token mask_token_id = 0; + int32_t block_size = 0; + int32_t dspark_ctx_window = 0; + llama_token mask_token_id = 0; // block-internal attention bool causal_attn = false; @@ -1142,7 +1150,10 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { // LiliCorr and the Inkling2 DSpark keep context features from h_nextn; the other heads only need the KV cache // called after the injection of a chunk, while h_nextn still holds the context features of batch_inject + bool defer_context_features = false; virtual void store_context_features(llama_seq_id /*seq_id*/, int32_t /*n_chunk*/) {} + virtual void flush_context_features() const {} + virtual void on_prefill_interrupt() {} public: ~common_speculative_impl_draft_dflash() override { @@ -1160,6 +1171,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { } void begin(llama_seq_id seq_id, const llama_tokens & prompt) override { + flush_context_features(); if (seq_id < 0 || seq_id >= (llama_seq_id) n_seq) { return; } @@ -1177,7 +1189,11 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { } } + const int32_t * s19_row_map = nullptr; + int32_t s19_row_map_n = 0; + bool process(const common_batch & batch_in) override { + flush_context_features(); if (batch_in.size() <= 0) { return true; } @@ -1197,6 +1213,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { // per-seq inclusive batch range (assumes each seq's tokens are contiguous in the batch) std::vector i_batch_beg(n_seq, -1); std::vector i_batch_end(n_seq, -1); + llama_seq_id last_active_seq = -1; for (int32_t k = 0; k < n_tokens; ++k) { const llama_seq_id seq_id = batch_in.tokens[k].seq_id; if (seq_id < 0 || seq_id >= (llama_seq_id) n_seq) { @@ -1206,6 +1223,9 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { if (i_batch_beg[seq_id] < 0) { i_batch_beg[seq_id] = k; } + if (seq_id > last_active_seq) { + last_active_seq = seq_id; + } } auto * ctx_tgt = this->params.ctx_tgt; @@ -1226,17 +1246,35 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { continue; } - for (int32_t offset = 0; offset < n_rows; offset += n_ubatch) { + if (n_rows > this->n_max + 1) { + on_prefill_interrupt(); + } else if (n_rows == 1 && should_skip_process(seq_id)) { + continue; + } + + int32_t start_offset = 0; + if (dspark_ctx_window > 0 && n_rows > dspark_ctx_window && !getenv("LLAMA_DSPARK_FULL_PREFILL")) { + start_offset = n_rows - dspark_ctx_window; + const llama_pos first_pos = batch_in.tokens[i_batch_beg[seq_id] + start_offset].pos[0]; + const llama_pos cur_max = llama_memory_seq_pos_max(llama_get_memory(ctx_dft), seq_id); + if (cur_max >= 0 && first_pos != cur_max + 1) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), seq_id, -1, -1); + } + } + + for (int32_t offset = start_offset; offset < n_rows; offset += n_ubatch) { const int32_t n_chunk = std::min(n_ubatch, n_rows - offset); + defer_context_features = (seq_id == last_active_seq) && (offset + n_chunk >= n_rows); if (use_dev_features) { // the features are the target batch rows in the target's device buffer batch_inject.clear(); for (int32_t i = 0; i < n_chunk; ++i) { const int32_t row = i_batch_beg[seq_id] + offset + i; + const int32_t tgt_row = (s19_row_map && row < s19_row_map_n) ? s19_row_map[row] : row; const llama_pos p = batch_in.tokens[row].pos[0]; const llama_pos pos_arr[4] = { p, p, p, 0 }; - batch_inject.add_embd_row(row, pos_arr, seq_id, false); + batch_inject.add_embd_row(tgt_row, pos_arr, seq_id, false); } const int32_t rc = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch_inject.get()); @@ -1258,8 +1296,10 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { GGML_ABORT("DFlash: target layer %d input not extracted.", target_layer_ids[k]); } for (int32_t i = 0; i < n_chunk; ++i) { - float * dst = features_buf.data() + (size_t) i * n_embd_enc + k * (size_t) n_embd_tgt; - const float * src = layer + (size_t) (i_batch_beg[seq_id] + offset + i) * n_embd_tgt; + const int32_t row = i_batch_beg[seq_id] + offset + i; + const int32_t tgt_row = (s19_row_map && row < s19_row_map_n) ? s19_row_map[row] : row; + float * dst = features_buf.data() + (size_t) i * n_embd_enc + k * (size_t) n_embd_tgt; + const float * src = layer + (size_t) tgt_row * n_embd_tgt; std::memcpy(dst, src, (size_t) n_embd_tgt * sizeof(float)); } } @@ -1370,6 +1410,8 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { } }; +extern "C" int32_t llama_s23_get_dspark_tree_meta(const llama_context * ctx, float * out, int32_t max_n); + // DSpark: a semi-autoregressive Markov head (+ Confidence head) on the block, anchor-first block layout struct common_speculative_impl_draft_dspark final : public common_speculative_impl_draft_dflash { // bonus anchor (SpecForge exports) when false: slot 0 is a bonus token, not a prediction slot @@ -1388,11 +1430,52 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im std::vector draw_rng; std::vector draw_seed; // the seed each generator was last seeded with (-1: reseed) + // Online adaptive draft depth ({0, 3, n_max}) + plain-decode parking controller (BatchPolicy) + bool adapt_enabled = false; + bool timing_interrupted = true; + bool last_was_pure_plain = false; + bool plain_warmup_done = false; + int64_t last_draft_us = 0; + uint64_t last_active_mask = 0; + int32_t cur_depth = 0; + int32_t last_mode_depth = -1; + int32_t prev_mode_depth = -1; + int32_t mtp_steps = 0; + int32_t losing_streak = 0; + int32_t clear_losing_streak = 0; + int32_t calib_rem = 0; + int32_t park_rem = 0; + int32_t park_cooldown = 128; + uint16_t last_n_accepted = 0; + int32_t prev_drafted = 0; + double ema_mean_len = 2.35; + std::vector last_draft_depth; + std::vector skip_seq; + std::vector> std_ms_cache; + std::vector>> mtp_ms_cache; + + static void push_sample(std::vector & buf, double v) { + if (buf.size() >= 7) { + buf.erase(buf.begin()); + } + buf.push_back(v); + } + + static double median_of(const std::vector & buf, double fallback) { + if (buf.empty()) { + return fallback; + } + std::vector tmp = buf; + std::sort(tmp.begin(), tmp.end()); + return tmp[tmp.size() / 2]; + } + common_speculative_impl_draft_dspark(const common_params_speculative & params, uint32_t n_seq) : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) { const llama_model * model_dft = llama_get_model(this->params.ctx_dft); + int32_t swa_win = 0; { char buf[32] = {}; if (llama_model_meta_val_str(model_dft, "dflash.sample_from_anchor", buf, sizeof(buf)) >= 0) { @@ -1401,6 +1484,17 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im if (llama_model_meta_val_str(model_dft, "dflash.has_markov_context", buf, sizeof(buf)) >= 0) { has_markov_context = std::strcmp(buf, "true") == 0; } + if (llama_model_meta_val_str(model_dft, "dflash.attention.sliding_window", buf, sizeof(buf)) >= 0) { + swa_win = std::atoi(buf); + } + } + + if (!this->params.n_max_set) { + this->params.n_max = std::min(7, sample_from_anchor ? block_size : block_size - 1); + } + + if (has_markov_context && swa_win > 0 && getenv("LLAMA_DSPARK_FORCE_ALL_SWA")) { + dspark_ctx_window = swa_win + block_size; } if (has_markov_context) { @@ -1422,9 +1516,6 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im } } - LOG_INF("%s: - sample_from_anchor=%s, has_markov_context=%s\n", __func__, - sample_from_anchor ? "true" : "false", has_markov_context ? "true" : "false"); - // anchor-first DSpark yields a full block_size draft tokens // the context state is read back from h_nextn at every injected row init({ @@ -1433,31 +1524,80 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im /* .dev_features = */ true, /* .nextn_masked = */ !has_markov_context, }); + + adapt_enabled = has_markov_context && this->params.n_max > 0 && !getenv("LLAMA_DSPARK_FIXED_DEPTH"); + cur_depth = this->params.n_max; + ema_mean_len = 2.35; + last_draft_depth.assign(n_seq, 0); + skip_seq.assign(n_seq, false); + std_ms_cache.resize((size_t) n_seq + 1); + mtp_ms_cache.assign((size_t) n_seq + 1, std::vector>((size_t) this->params.n_max + 2)); + + LOG_INF("%s: - sample_from_anchor=%s, has_markov_context=%s, ctx_window=%d, n_max=%d, adaptive=%s\n", __func__, + sample_from_anchor ? "true" : "false", has_markov_context ? "true" : "false", + dspark_ctx_window, this->params.n_max, adapt_enabled ? "true" : "false"); + } + + int32_t ctx_window() const override { + return dspark_ctx_window; + } + + bool should_skip_process(llama_seq_id /*seq_id*/) const override { + return false; + } + + void on_prefill_interrupt() override { + timing_interrupted = true; } protected: - void store_context_features(llama_seq_id seq_id, int32_t n_chunk) override { - if (!has_markov_context) { + mutable llama_seq_id pending_ctx_seq = -1; + mutable std::vector> pending_ctx_rows; + + void flush_context_features() const override { + if (pending_ctx_seq < 0) { return; } + const llama_seq_id seq_id = pending_ctx_seq; + pending_ctx_seq = -1; const float * state = llama_get_embeddings_nextn(params.ctx_dft); - if (!state) { + if (state) { + auto & embd_mut = const_cast &>(ctx_embd); + auto & pos_mut = const_cast &>(ctx_pos); + for (const auto & pr : pending_ctx_rows) { + const size_t slot = (size_t) seq_id * ctx_rows + (size_t) pr.second % ctx_rows; + std::memcpy(embd_mut.data() + slot * (size_t) n_embd_dec, state + (size_t) pr.first * n_embd_dec, (size_t) n_embd_dec * sizeof(float)); + pos_mut[slot] = pr.second; + } + } + pending_ctx_rows.clear(); + } + + void store_context_features(llama_seq_id seq_id, int32_t n_chunk) override { + if (!has_markov_context) { return; } + flush_context_features(); const llama_pos pos_min = std::max(0, batch_inject.tokens.back().pos[0] - block_size); + pending_ctx_rows.clear(); for (int32_t i = 0; i < n_chunk; ++i) { const llama_pos pos = batch_inject.tokens[i].pos[0]; - if (pos < pos_min) { - continue; + if (pos >= pos_min) { + pending_ctx_rows.emplace_back(i, pos); } - const size_t slot = (size_t) seq_id * ctx_rows + (size_t) pos % ctx_rows; - std::memcpy(ctx_embd.data() + slot * (size_t) n_embd_dec, state + (size_t) i * n_embd_dec, (size_t) n_embd_dec * sizeof(float)); - ctx_pos[slot] = pos; + } + if (pending_ctx_rows.empty()) { + return; + } + pending_ctx_seq = seq_id; + if (!defer_context_features || getenv("LLAMA_DSPARK_SYNC_INJECT")) { + flush_context_features(); } } // context state of the token before the block, nullptr if it was not injected const float * get_context_state(llama_seq_id seq_id, llama_pos pos) const { + flush_context_features(); if (pos < 0) { return nullptr; } @@ -1467,23 +1607,195 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im public: void begin(llama_seq_id seq_id, const llama_tokens & prompt) override { + flush_context_features(); // the markov context draws: reseed per request rather than per round, or two identical requests differ if (has_markov_context && seq_id >= 0 && seq_id < (llama_seq_id) n_seq) { draw_seed[seq_id] = -1; } + if (adapt_enabled && seq_id >= 0 && seq_id < (llama_seq_id) n_seq) { + timing_interrupted = true; + last_was_pure_plain = false; + plain_warmup_done = false; + cur_depth = this->params.n_max; + last_mode_depth = -1; + prev_mode_depth = -1; + mtp_steps = 0; + losing_streak = 0; + clear_losing_streak = 0; + calib_rem = 0; + park_rem = 0; + park_cooldown = 128; + last_n_accepted = 0; + prev_drafted = 0; + ema_mean_len = 2.35; + skip_seq[seq_id] = false; + last_draft_depth[seq_id] = 0; + // Reset per-cohort timing caches because KV depth changes both plain and verify ms + for (auto & v : std_ms_cache) { + v.clear(); + } + for (auto & by_d : mtp_ms_cache) { + for (auto & v : by_d) { + v.clear(); + } + } + } common_speculative_impl_draft_dflash::begin(seq_id, prompt); } + void accept(llama_seq_id seq_id, uint16_t n_accepted, bool is_other) override { + if (!is_other && adapt_enabled && seq_id >= 0 && seq_id < (llama_seq_id) last_draft_depth.size() && + last_draft_depth[seq_id] > 0) { + last_n_accepted = n_accepted; + prev_drafted = last_draft_depth[seq_id]; + ema_mean_len += 0.14 * ((1.0 + (double) n_accepted) - ema_mean_len); + } + } + void draft(common_speculative_draft_params_vec & dparams) override { + flush_context_features(); auto & ctx_dft = params.ctx_dft; + const int64_t t_now = ggml_time_us(); + uint64_t active_mask = 0; + int32_t n_active = 0; + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (dparams[seq_id].drafting) { + if (seq_id < 64) { + active_mask |= (1ULL << seq_id); + } + n_active++; + } + } + + if (adapt_enabled && n_active > 0) { + const int32_t na_key = std::min(n_active, (int32_t) std_ms_cache.size() - 1); + if (!timing_interrupted && last_draft_us > 0 && active_mask == last_active_mask) { + const double dt_ms = std::max(0.05, (t_now - last_draft_us) * 1e-3); + if (last_mode_depth == 0) { + if (last_was_pure_plain && plain_warmup_done) { + push_sample(std_ms_cache[na_key], dt_ms); + } else if (last_was_pure_plain) { + plain_warmup_done = true; + } + } else if (last_mode_depth > 0 && last_mode_depth == prev_mode_depth && + last_mode_depth < (int32_t) mtp_ms_cache[na_key].size()) { + push_sample(mtp_ms_cache[na_key][last_mode_depth], dt_ms); + } + } + timing_interrupted = false; + last_draft_us = t_now; + last_active_mask = active_mask; + + auto set_active_skip = [&](bool skip) { + for (llama_seq_id s = 0; s < (llama_seq_id) n_seq; ++s) { + if (dparams[s].drafting) { + skip_seq[s] = skip; + last_draft_depth[s] = 0; + } + } + }; + + if (park_rem > 0) { + park_rem--; + set_active_skip(false); + prev_mode_depth = last_mode_depth; + last_mode_depth = 0; + last_was_pure_plain = true; + if (park_rem == 0) { + plain_warmup_done = false; + cur_depth = this->params.n_max; + mtp_steps = 0; + losing_streak = 0; + clear_losing_streak = 0; + ema_mean_len = 2.20; + } + return; + } + + if (calib_rem > 0) { + calib_rem--; + set_active_skip(false); + prev_mode_depth = last_mode_depth; + last_mode_depth = 0; + last_was_pure_plain = true; + return; + } + + const int32_t max_d = std::max(1, this->params.n_max); + const double e_max = ema_mean_len; + + if (mtp_steps >= 5 && e_max < 1.75 && std_ms_cache[na_key].empty()) { + calib_rem = 1; + plain_warmup_done = false; + set_active_skip(false); + prev_mode_depth = last_mode_depth; + last_mode_depth = 0; + last_was_pure_plain = true; + return; + } + + if (mtp_steps >= 5 && !std_ms_cache[na_key].empty()) { + const int32_t ref_d = (cur_depth > 0 && cur_depth <= max_d) ? cur_depth : max_d; + const double c_max = median_of(mtp_ms_cache[na_key][ref_d], 65.0); + const double s_best = (n_active * e_max) / std::max(1e-3, c_max); + const double c_std = median_of(std_ms_cache[na_key], 30.0); + const double s_std = n_active / std::max(1e-3, c_std); + if (s_best <= s_std * 0.99) { + losing_streak++; + } else { + losing_streak = 0; + } + if (s_best < s_std * 0.90) { + clear_losing_streak++; + } else { + clear_losing_streak = 0; + } + if (clear_losing_streak >= 4 || losing_streak >= 9) { + if (!getenv("LLAMA_DSPARK_TREE_NO_PARK")) { + park_rem = park_cooldown; + park_cooldown = std::min(2048, park_cooldown * 2); + park_rem--; + set_active_skip(false); + prev_mode_depth = last_mode_depth; + last_mode_depth = 0; + last_was_pure_plain = true; + return; + } + } + } + if (mtp_steps == 0 || cur_depth <= 0 || cur_depth > max_d) { + if (max_d >= 7 && n_active == 1) { + llama_pos active_pos0 = 0; + for (llama_seq_id s = 0; s < (llama_seq_id) n_seq; ++s) { + if (dparams[s].drafting) { active_pos0 = dparams[s].pos0; break; } + } + cur_depth = (active_pos0 >= 24576) ? max_d : 4; + } else { + cur_depth = max_d; + } + } + + for (llama_seq_id s = 0; s < (llama_seq_id) n_seq; ++s) { + if (dparams[s].drafting) { + skip_seq[s] = false; + } + } + prev_mode_depth = last_mode_depth; + last_mode_depth = cur_depth; + last_was_pure_plain = false; + plain_warmup_done = false; + mtp_steps++; + } + batch.clear(); // build one batch holding every drafting sequence's noise block into a single decode // record where each block starts and its size std::vector i_block_beg(n_seq, -1); std::vector n_block (n_seq, 0); + std::vector n_emit_seq (n_seq, 0); std::vector sampled (n_seq, false); block_state.clear(); @@ -1497,11 +1809,13 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im // the Markov head reads the context state of the token before the block, no draft without it const float * state = has_markov_context ? get_context_state(seq_id, dp.pos0 - 1) : nullptr; if (has_markov_context && !state) { + last_draft_depth[seq_id] = 0; continue; } // the graph draws the block at the target's temperature, the verifier then does rejection sampling with q - sampled[seq_id] = has_markov_context && params.probabilistic && dp.result_q && dp.temp > 0.0f; + const bool allow_prob = params.probabilistic || !getenv("LLAMA_DSPARK_FORCE_GREEDY"); + sampled[seq_id] = has_markov_context && allow_prob && dp.result_q && dp.temp > 0.0f; if (sampled[seq_id] && draw_seed[seq_id] != dp.seed) { draw_seed[seq_id] = dp.seed; // the default seed means random; mixed so it differs from the target's, as in spec_retune @@ -1512,18 +1826,24 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im const int32_t n = (int32_t) dp.pos0; - const int32_t n_draft = params.n_max; + const int32_t n_emit = adapt_enabled ? std::min(cur_depth, params.n_max) : params.n_max; + const int32_t n_draft = n_emit; const int32_t n_block_tokens = n_draft + (sample_from_anchor ? 0 : 1); // all blocks share one decode: a block that does not fit in the draft context fails every sequence's draft if ((uint64_t) dp.pos0 + n_block_tokens > llama_n_ctx_seq(ctx_dft)) { + last_draft_depth[seq_id] = 0; continue; } i_block_beg[seq_id] = batch.size(); n_block [seq_id] = n_block_tokens; + n_emit_seq [seq_id] = n_emit; + const bool greedy_ids_only = has_markov_context && !sample_from_anchor && !sampled[seq_id] && + params.p_min <= 0.0f && !getenv("LLAMA_DSPARK_HOST_LOGITS"); for (int32_t i = 0; i < n_block_tokens; ++i) { - const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true); + const bool output = greedy_ids_only ? (i >= 1) : true; + const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, output); if (state) { // reserved up front, so the views of the earlier tokens stay valid GGML_ASSERT(block_state.size() + n_embd_dec <= block_state.capacity()); @@ -1562,20 +1882,27 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im auto & dp = dparams[seq_id]; const int32_t beg = i_block_beg[seq_id]; - const int32_t n_block_tokens = n_block[seq_id]; + const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; + const int32_t i_draft_end = std::min(n_block[seq_id], i_draft_beg + n_emit_seq[seq_id]); auto * smpl = smpls[seq_id].get(); auto & result = *dp.result; - - // bonus-anchor drafts read the mask positions only, like DFlash - const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; + if (dp.result_alt) { + dp.result_alt->clear(); + } + if (dp.result_alt_q) { + dp.result_alt_q->clear(); + } + if (dp.result_branch_pos) { + *dp.result_branch_pos = -1; + } if (sampled[seq_id]) { // the tokens the graph drew, and the distribution q each one was drawn from const float * draws = llama_get_embeddings_nextn(ctx_dft); GGML_ASSERT(draws && "DSpark draws missing from h_nextn"); - for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) { + for (int32_t i = i_draft_beg; i < i_draft_end; ++i) { const float * row = draws + (size_t) (beg + i) * n_embd_dec; const int32_t n_cand = (int32_t) row[1]; @@ -1590,13 +1917,140 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im if (result.size() < (size_t) params.n_min) { result.clear(); dp.result_q->clear(); + } else if (dp.result_alt && dp.result_alt_q && n_seq == 1 && result.size() >= 2 && + !getenv("LLAMA_DSPARK_NO_TREE")) { + const auto & q0 = (*dp.result_q)[0]; + float p_a0 = 0.0f; + float sum_rem = 0.0f; + for (const auto & cd : q0) { + if (cd.id == result[0]) { + p_a0 = cd.p; + } else { + sum_rem += cd.p; + } + } + if (p_a0 < 0.85f && sum_rem > 1e-6f && q0.size() >= 2) { + std::vector q2; + q2.reserve(q0.size() - 1); + const float inv_rem = 1.0f / sum_rem; + for (const auto & cd : q0) { + if (cd.id != result[0]) { + const float pn = cd.p * inv_rem; + q2.push_back({ cd.id, std::log(std::max(pn, 1e-12f)), pn }); + } + } + float u = (float) std::uniform_real_distribution(0.0, 1.0)(draw_rng[seq_id]); + llama_token b0 = q2.back().id; + for (const auto & cd : q2) { + u -= cd.p; + if (u <= 0.0f) { + b0 = cd.id; + break; + } + } + const size_t m_d = std::min(result.size(), 2); + result.resize(m_d); + dp.result_q->resize(m_d); + dp.result_alt->assign(result.begin(), result.end()); + (*dp.result_alt)[0] = b0; + dp.result_alt_q->assign(dp.result_q->begin(), dp.result_q->end()); + (*dp.result_alt_q)[0] = std::move(q2); + if (dp.result_branch_pos) { + *dp.result_branch_pos = 0; + } + } } + last_draft_depth[seq_id] = (int32_t) result.size(); + continue; + } + + if (has_markov_context && !sample_from_anchor && !sampled[seq_id] && + params.p_min <= 0.0f && !getenv("LLAMA_DSPARK_HOST_LOGITS")) { + for (int32_t i = i_draft_beg; i < i_draft_end; ++i) { + const llama_token best = llama_get_sampled_token_ith(ctx_dft, beg + i); + if (best == LLAMA_TOKEN_NULL) { + break; + } + result.push_back(best); + } + if (result.size() < (size_t) params.n_min) { + result.clear(); + } else if (dp.result_alt && n_seq == 1 && result.size() >= 2 && + getenv("LLAMA_DSPARK_ENABLE_2BRANCH") && !getenv("LLAMA_DSPARK_NO_TREE")) { + float tmeta[16] = {}; + const int32_t n_tm = llama_s23_get_dspark_tree_meta(ctx_dft, tmeta, 16); + if (n_tm >= 2) { + const float theta = getenv("LLAMA_DSPARK_TREE_MARGIN") + ? (float) std::atof(getenv("LLAMA_DSPARK_TREE_MARGIN")) + : 0.35f; + const int32_t m_short = getenv("LLAMA_DSPARK_TREE_DRAFT_LEN") + ? std::max(2, std::atoi(getenv("LLAMA_DSPARK_TREE_DRAFT_LEN"))) + : 2; + const int32_t m_long = getenv("LLAMA_DSPARK_TREE_DRAFT_LEN_LONG") + ? std::max(2, std::atoi(getenv("LLAMA_DSPARK_TREE_DRAFT_LEN_LONG"))) + : 3; + const int32_t n_vocab_dft = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx_dft))); + + const float marg_0 = tmeta[0]; + const int64_t cand_id = (int64_t) std::llround(tmeta[1]); + if (marg_0 < theta && cand_id >= 0 && cand_id < n_vocab_dft && + (llama_token) cand_id != result[0]) { + const int32_t full_d = (int32_t) result.size(); + const int32_t target_m = (dp.pos0 >= 24576) ? m_long : m_short; + const int32_t b1_avail = n_tm - 2; + const int32_t m_d = std::min(full_d, std::min(target_m, 1 + b1_avail)); + if (m_d >= 1 && m_d >= std::max(1, params.n_min)) { + result.resize((size_t) m_d); + dp.result_alt->assign(result.begin(), result.end()); + (*dp.result_alt)[0] = (llama_token) cand_id; + for (int32_t k = 1; k < m_d; ++k) { + const int64_t c_id = (int64_t) std::llround(tmeta[2 + (k - 1)]); + if (c_id >= 0 && c_id < n_vocab_dft) { + (*dp.result_alt)[k] = (llama_token) c_id; + } + } + if (dp.result_branch_pos) { + *dp.result_branch_pos = 0; + } + } + } + } + } else if (n_seq == 1 && result.size() >= 4 && + getenv("LLAMA_DSPARK_ENABLE_MARGIN") && !getenv("LLAMA_DSPARK_NO_MARGIN")) { + // Series 23 (B2): Logit-margin guided single-tile verification depth! + // On Apple M4 Max, Q4_K/Q5_K/Q6_K repack dmmv has max_r_cols = 4: + // d = 3 (N = 4) executes in 1 single weight pass across all 36 layers, + // whereas d = 4 (N = 5 = 4 + 1) spills into 2 passes over every repacked dense matrix! + // Only pay the 2nd weight pass (d = 4) when all 4 draft steps have confident logit margins. + float tmeta[8] = {}; + const int32_t n_tm = llama_s23_get_dspark_tree_meta(ctx_dft, tmeta, 8); + if (n_tm >= 4) { + const float theta_d4 = getenv("LLAMA_DSPARK_D4_MARGIN") + ? (float) std::atof(getenv("LLAMA_DSPARK_D4_MARGIN")) + : 1.50f; + const float theta_32k = getenv("LLAMA_DSPARK_D7_MARGIN") + ? (float) std::atof(getenv("LLAMA_DSPARK_D7_MARGIN")) + : 0.60f; + if (dp.pos0 < 24576 && result.size() == 4) { + const float min_m4 = std::min(std::min(tmeta[0], tmeta[1]), std::min(tmeta[2], tmeta[3])); + if (min_m4 < theta_d4 && 3 >= std::max(1, params.n_min)) { + result.resize(3); + } + } else if (dp.pos0 >= 24576 && result.size() > 4) { + const float min_m3 = std::min(tmeta[0], std::min(tmeta[1], tmeta[2])); + if (min_m3 < theta_32k && 3 >= std::max(1, params.n_min)) { + result.resize(3); + } + } + } + } + last_draft_depth[seq_id] = (int32_t) result.size(); continue; } // DSpark: read from the first draft slot, truncate below the confidence threshold const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr; - for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) { + for (int32_t i = i_draft_beg; i < i_draft_end; ++i) { const int32_t idx = beg + i; if (conf && conf[(size_t) idx * n_embd_dec] < params.p_min) { @@ -1623,6 +2077,7 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im if (result.size() < (size_t) params.n_min) { result.clear(); } + last_draft_depth[seq_id] = (int32_t) result.size(); } } }; @@ -3031,6 +3486,8 @@ int32_t common_speculative_n_max(const common_params_speculative * spec) { case COMMON_SPECULATIVE_TYPE_DRAFT_MTP: case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + n_max = std::max(n_max, std::max(0, spec->draft.n_max_set ? spec->draft.n_max : std::max(spec->draft.n_max, 7))); + break; case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2: case COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR: n_max = std::max(n_max, std::max(0, spec->draft.n_max)); @@ -3211,7 +3668,8 @@ common_params common_base_params_to_speculative(const common_params & params) { }); if (has_block_draft) { // per-seq output positions: DFlash decodes anchor + n_max masks (n_max + 1); DSpark n_max -> +1 covers both - const int32_t per_seq = std::max(1, params_spec.n_max + 1); + const int32_t eff_n_max = std::max(params_spec.n_max, common_speculative_n_max(¶ms.speculative)); + const int32_t per_seq = std::max(1, eff_n_max + 1); result.n_outputs_max = params.n_parallel * per_seq; if (params_spec.backend_sampling) { result.n_outputs_max_per_seq = per_seq; @@ -3273,6 +3731,9 @@ common_speculative_init_result::common_speculative_init_result( LOG_ERR("%s: failed to create MTP context\n", __func__); return; } + if (ctx_tgt != nullptr && llama_get_threadpool(ctx_tgt) != nullptr) { + llama_attach_threadpool(ctx_dft, llama_get_threadpool(ctx_tgt), llama_get_threadpool_batch(ctx_tgt)); + } pimpl->context.reset(ctx_dft); } else if (spec_mtp) { @@ -3285,6 +3746,9 @@ common_speculative_init_result::common_speculative_init_result( LOG_ERR("%s: failed to create MTP context\n", __func__); return; } + if (ctx_tgt != nullptr && llama_get_threadpool(ctx_tgt) != nullptr) { + llama_attach_threadpool(ctx_dft, llama_get_threadpool(ctx_tgt), llama_get_threadpool_batch(ctx_tgt)); + } pimpl->context.reset(ctx_dft); } @@ -3561,6 +4025,66 @@ bool common_speculative_process(common_speculative * spec, const common_batch & return result; } +bool common_speculative_process_rows( + common_speculative * spec, + const common_batch & batch_full, + const int32_t * rows, + int32_t n_rows) { + if (spec == nullptr || n_rows <= 0) { + return true; + } + + common_batch sub; + for (int32_t i = 0; i < n_rows; ++i) { + const int32_t r = rows[i]; + GGML_ASSERT(r >= 0 && r < batch_full.size()); + const auto & t = batch_full.tokens[r]; + sub.add(t.id, t.pos[0], t.seq_id, t.output); + } + + bool result = true; + for (auto & impl : spec->impls) { + auto * dflash = dynamic_cast(impl.get()); + if (dflash) { + dflash->s19_row_map = rows; + dflash->s19_row_map_n = n_rows; + result = result && dflash->process(sub); + dflash->s19_row_map = nullptr; + dflash->s19_row_map_n = 0; + } else { + result = result && impl->process(sub); + } + } + return result; +} + +int32_t common_speculative_ctx_window(const common_speculative * spec) { + if (spec == nullptr || spec->impls.empty()) { + return 0; + } + int32_t win = 0; + for (const auto & impl : spec->impls) { + const int32_t w = impl->ctx_window(); + if (w <= 0) { + return 0; + } + win = std::max(win, w); + } + return win; +} + +bool common_speculative_should_skip_process(const common_speculative * spec, llama_seq_id seq_id) { + if (spec == nullptr || spec->impls.empty()) { + return false; + } + for (const auto & impl : spec->impls) { + if (!impl->should_skip_process(seq_id)) { + return false; + } + } + return true; +} + void common_speculative_draft(common_speculative * spec) { if (spec == nullptr) { return; diff --git a/common/speculative.h b/common/speculative.h index 949114f35609..9f776c502319 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -73,8 +73,13 @@ struct common_speculative_draft_params { // the generated draft from the last _draft() call llama_tokens * result; + // optional 2-branch speculative tree candidate chain (same length as *result when populated) + llama_tokens * result_alt = nullptr; + int32_t * result_branch_pos = nullptr; + // candidate distribution per drafted token; set it to make draft-simple, draft-mtp and draft-dflash2 sample - std::vector> * result_q = nullptr; + std::vector> * result_q = nullptr; + std::vector> * result_alt_q = nullptr; // the target's temp and seed, read only when the drafter samples probabilistically float temp = 1.0f; @@ -88,6 +93,13 @@ void common_speculative_begin(common_speculative * spec, llama_seq_id seq_id, co // process the batch and update the internal state of the speculative context bool common_speculative_process(common_speculative * spec, const common_batch & batch); +bool common_speculative_process_rows(common_speculative * spec, const common_batch & batch_full, const int32_t * rows, int32_t n_rows); + +// finite context window of the speculative drafter (0 if unbounded) +int32_t common_speculative_ctx_window(const common_speculative * spec); + +// true when seq_id is parked in plain decode and needs no speculative injection this step +bool common_speculative_should_skip_process(const common_speculative * spec, llama_seq_id seq_id); // generate drafts for the sequences specified with `common_speculative_get_draft_params` void common_speculative_draft(common_speculative * spec); diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h index 062d5004e8d4..792de04ab9d4 100644 --- a/ggml/include/ggml-rpc.h +++ b/ggml/include/ggml-rpc.h @@ -11,7 +11,7 @@ extern "C" { #define RPC_PROTO_PATCH_VERSION 2 #ifdef __cplusplus -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); #endif #define GGML_RPC_MAX_SERVERS 16 diff --git a/ggml/include/ggml-vulkan.h b/ggml/include/ggml-vulkan.h index ed5ea5f798cb..e141164c0b91 100644 --- a/ggml/include/ggml-vulkan.h +++ b/ggml/include/ggml-vulkan.h @@ -22,6 +22,8 @@ GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t d // pinned host buffer for use with the CPU backend for faster copies between CPU and GPU GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type(void); +GGML_BACKEND_API const void * ggml_backend_vk_get_cached_uma_ptr(ggml_backend_t backend, const struct ggml_tensor * tensor); + GGML_BACKEND_API ggml_backend_reg_t ggml_backend_vk_reg(void); #ifdef __cplusplus diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 0007fa18f80e..82b9267991f3 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -434,6 +434,7 @@ extern "C" { GGML_OP_SLEEP, GGML_OP_SIGMOID_BACK, + GGML_OP_INKLING_FUSED, GGML_OP_COUNT, }; @@ -473,6 +474,7 @@ extern "C" { GGML_GLU_OP_GEGLU_ERF, GGML_GLU_OP_GEGLU_QUICK, GGML_GLU_OP_SWIGLU_CLAMP, + GGML_GLU_OP_SITU, GGML_GLU_OP_COUNT, }; @@ -1213,6 +1215,148 @@ extern "C" { struct ggml_tensor * b, float limit); + GGML_API struct ggml_tensor * ggml_situ( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + float beta, + float linear_beta); + + GGML_API struct ggml_tensor * ggml_inkling_l2_clip( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * scale, + struct ggml_tensor * tau, + float threshold, + float eps); + + GGML_API struct ggml_tensor * ggml_inkling_conv( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * history, + struct ggml_tensor * weight, + struct ggml_tensor * dynamic, + struct ggml_tensor * state, + int32_t ch_offset, + int32_t n_seq_tokens, + int32_t n_seqs, + int32_t n_heads, + int32_t st_base_f32, + int32_t st_seq_stride, + int32_t st_slot_stride, + int32_t st_kw, + float scale_out); + + GGML_API struct ggml_tensor * ggml_inkling_rel_gather( + struct ggml_context * ctx, + struct ggml_tensor * table, + struct ggml_tensor * sinks, + struct ggml_tensor * rel_pos, + int64_t n_kv, + int64_t nr, + int64_t n_head, + int64_t n_stream, + int32_t n_seq_tokens, + int32_t r0, + int32_t extent); + + GGML_API struct ggml_tensor * ggml_inkling_rel_gather_f16( + struct ggml_context * ctx, + struct ggml_tensor * kq_b, + struct ggml_tensor * kq_mask, + int32_t mask_r0); + + // S19_WAVE3: Inkling-2 depth-mix with optional 0-ULP 512-tree RMS_NORM_MUL epilogue + GGML_API struct ggml_tensor * ggml_inkling_depth_mix( + struct ggml_context * ctx, + struct ggml_tensor * const * states, + int n_states, + struct ggml_tensor * query, + float eps); + + GGML_API struct ggml_tensor * ggml_inkling_depth_mix_rms( + struct ggml_context * ctx, + struct ggml_tensor * const * states, + int n_states, + struct ggml_tensor * query, + struct ggml_tensor * rms_w, + float eps, + float rms_eps); + + GGML_API struct ggml_tensor * ggml_inkling_rms2_concat( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * message, + float eps); + + GGML_API struct ggml_tensor * ggml_inkling_ctrl_apply( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * message, + struct ggml_tensor * raw_gain, + struct ggml_tensor * raw_forget); + + GGML_API struct ggml_tensor * ggml_inkling_ctrl_apply_rms_mul( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * message, + struct ggml_tensor * up_gf, + struct ggml_tensor * rms_w, + float eps); + + GGML_API struct ggml_tensor * ggml_inkling_l2_clip_qr( + struct ggml_context * ctx, + struct ggml_tensor * q_cur, + struct ggml_tensor * r_cur, + struct ggml_tensor * q_scale, + struct ggml_tensor * r_scale, + struct ggml_tensor * mul_tau, + float q_threshold, + float r_threshold, + float eps); + + GGML_API struct ggml_tensor * ggml_inkling_dspark_concat4( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + struct ggml_tensor * d); + + GGML_API struct ggml_tensor * ggml_inkling_dspark_gru( + struct ggml_context * ctx, + struct ggml_tensor * joint, + struct ggml_tensor * state_in); + + GGML_API struct ggml_tensor * ggml_inkling_softcap( + struct ggml_context * ctx, + struct ggml_tensor * a, + float inv_cap, + float cap); + + GGML_API struct ggml_tensor * ggml_inkling_dspark_joint_gru( + struct ggml_context * ctx, + struct ggml_tensor * prev, + struct ggml_tensor * markov_w1, + struct ggml_tensor * state_in, + struct ggml_tensor * hidden, + struct ggml_tensor * context, + struct ggml_tensor * joint_proj, + struct ggml_tensor * joint_proj_b); + + GGML_API struct ggml_tensor * ggml_inkling_dspark_inject_mix( + struct ggml_context * ctx, + struct ggml_tensor * features, + struct ggml_tensor * fuse_w, + struct ggml_tensor * norm0, + struct ggml_tensor * norm1, + struct ggml_tensor * norm2, + struct ggml_tensor * norm3, + struct ggml_tensor * positions, + struct ggml_tensor * ring_dst, + int32_t ring_seq_offset, + int32_t ring_rows, + float eps); + // normalize along rows GGML_API struct ggml_tensor * ggml_norm( struct ggml_context * ctx, @@ -2301,6 +2445,16 @@ extern "C" { struct ggml_tensor * table, struct ggml_tensor * indices); + GGML_API bool ggml_flash_attn_ext_has_banded_rel_bias(const struct ggml_tensor * a); + + // Add table[q_pos - cell_pos, head, query] for 0 <= q_pos - cell_pos < extent inside FlashAttention. + // pos_info is 1D I32 packing [cell_pos (n_stream*n_kv), q_pos (n_tokens), tile64_minmax (n_stream*ceil(n_kv/64)*2)]. + GGML_API void ggml_flash_attn_ext_add_banded_rel_bias( + struct ggml_tensor * a, + struct ggml_tensor * table, + struct ggml_tensor * pos_info, + int32_t extent); + // TODO: needs to be adapted to ggml_flash_attn_ext GGML_API struct ggml_tensor * ggml_flash_attn_back( struct ggml_context * ctx, diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index c442f603fd25..1c1175ba972c 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -1119,6 +1119,7 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( case GGML_OP_LIGHTNING_INDEXER: { split_state = handle_lightning_indexer(src_ss); } break; + case GGML_OP_INKLING_FUSED: case GGML_OP_DSV4_HC_COMB: case GGML_OP_DSV4_HC_PRE: case GGML_OP_DSV4_HC_POST: diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index dc0c95bf40c4..45bb9201e1a4 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -37,6 +37,15 @@ #include #if defined(__gnu_linux__) #include +#include +static cpu_set_t s20_init_cpuset; +static bool s20_has_init_cpuset = false; +__attribute__((constructor)) static void s20_capture_init_cpuset(void) { + CPU_ZERO(&s20_init_cpuset); + if (sched_getaffinity(0, sizeof(s20_init_cpuset), &s20_init_cpuset) == 0 && CPU_COUNT(&s20_init_cpuset) > 1) { + s20_has_init_cpuset = true; + } +} #endif #ifdef GGML_USE_OPENMP @@ -2103,6 +2112,10 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm { ggml_compute_forward_glu(params, tensor); } break; + case GGML_OP_INKLING_FUSED: + { + ggml_compute_forward_inkling_fused(params, tensor); + } break; case GGML_OP_GET_REL_POS: { ggml_compute_forward_get_rel_pos(params, tensor); @@ -2306,6 +2319,11 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { case GGML_OP_DUP: case GGML_OP_CONT: case GGML_OP_ADD: + { + const size_t nb_dst = ggml_nbytes(node); + const size_t nb_src0 = node->src[0] ? ggml_nbytes(node->src[0]) : 0; + n_tasks = (nb_dst < 256 * 1024 && nb_src0 < 256 * 1024) ? 1 : n_threads; + } break; case GGML_OP_ADD_ID: case GGML_OP_ACC: case GGML_OP_CUMSUM: @@ -2330,6 +2348,7 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { case GGML_OP_COUNT_EQUAL: case GGML_OP_SOLVE_TRI: case GGML_OP_GATED_DELTA_NET: + case GGML_OP_INKLING_FUSED: case GGML_OP_DSV4_HC_COMB: case GGML_OP_DSV4_HC_PRE: case GGML_OP_DSV4_HC_POST: @@ -2388,6 +2407,7 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { case GGML_GLU_OP_GEGLU_ERF: case GGML_GLU_OP_GEGLU_QUICK: case GGML_GLU_OP_SWIGLU_CLAMP: + case GGML_GLU_OP_SITU: { n_tasks = n_threads; } break; @@ -2395,12 +2415,17 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { GGML_ABORT("fatal error"); } break; + case GGML_OP_MUL: + case GGML_OP_RMS_NORM: + { + const size_t nb_dst = ggml_nbytes(node); + const size_t nb_src0 = node->src[0] ? ggml_nbytes(node->src[0]) : 0; + n_tasks = (nb_dst < 256 * 1024 && nb_src0 < 256 * 1024) ? 1 : 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: - case GGML_OP_RMS_NORM: case GGML_OP_RMS_NORM_BACK: case GGML_OP_L2_NORM: case GGML_OP_GROUP_NORM: @@ -3445,6 +3470,19 @@ enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cpl bool disposable_threadpool = false; +#if defined(__gnu_linux__) + cpu_set_t s20_prev_cpuset; + bool s20_restored_full = false; + if (n_threads > 1 && s20_has_init_cpuset) { + CPU_ZERO(&s20_prev_cpuset); + if (sched_getaffinity(0, sizeof(s20_prev_cpuset), &s20_prev_cpuset) == 0 && + CPU_COUNT(&s20_prev_cpuset) < CPU_COUNT(&s20_init_cpuset)) { + (void) sched_setaffinity(0, sizeof(s20_init_cpuset), &s20_init_cpuset); + s20_restored_full = true; + } + } +#endif + if (threadpool == NULL) { //GGML_PRINT_DEBUG("Threadpool is not specified. Will create a disposable threadpool : n_threads %d\n", n_threads); disposable_threadpool = true; @@ -3491,15 +3529,27 @@ enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cpl n_threads = threadpool->n_threads; } - // Kick all threads to start the new graph - ggml_graph_compute_kickoff(threadpool, n_threads); + if (n_threads > 1) { + // Kick all threads to start the new graph + ggml_graph_compute_kickoff(threadpool, n_threads); + } else { + atomic_store_explicit(&threadpool->n_graph, 1, memory_order_relaxed); + } // This is a work thread too ggml_graph_compute_thread(&threadpool->workers[0]); #endif // don't leave affinity set on the main thread - clear_numa_thread_affinity(); + if (n_threads > 1) { + clear_numa_thread_affinity(); + } + +#if defined(__gnu_linux__) + if (s20_restored_full) { + (void) sched_setaffinity(0, sizeof(s20_prev_cpuset), &s20_prev_cpuset); + } +#endif enum ggml_status ret = threadpool->ec; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 72dd3e6910a2..eff5260b0ba8 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -3822,6 +3822,582 @@ static void ggml_compute_forward_swiglu_clamp(const ggml_compute_params * params } } +void ggml_compute_forward_inkling_fused(const ggml_compute_params * params, ggml_tensor * dst) { + const int32_t mode = ggml_get_op_params_i32(dst, 0); + const int ith = params->ith; + const int nth = params->nth; + + if (mode == 0) { + // MODE_L2_CLIP + const ggml_tensor * cur = dst->src[0]; + const ggml_tensor * scale = dst->src[1]; + const ggml_tensor * tau = dst->src[2]; + const float threshold = ggml_get_op_params_f32(dst, 1); + const float eps = ggml_get_op_params_f32(dst, 2); + const int64_t ne0 = cur->ne[0]; + const int64_t ne1 = cur->ne[1]; + const int64_t rows = ne1 * cur->ne[2]; + for (int64_t r = ith; r < rows; r += nth) { + const float * pc = (const float *)cur->data + r * ne0; + const float * ps = scale ? ((const float *)scale->data + (r % ne1) * ne0) : nullptr; + float * pd = (float *)dst->data + r * ne0; + float ss = 0.0f; + for (int64_t c = 0; c < ne0; ++c) { + const float x = pc[c] * (ps ? ps[c] : 1.0f); + ss += x * x; + } + const float factor = std::min(1.0f, std::max(0.0f, threshold / (sqrtf(ss) + eps))); + const float tv = tau ? ((const float *)tau->data)[r / ne1] : 1.0f; + for (int64_t c = 0; c < ne0; ++c) { + float x = pc[c] * (ps ? ps[c] : 1.0f); + float o = x * factor; + if (tau) o *= tv; + pd[c] = o; + } + } + return; + } + + if (mode == 1) { + // MODE_CONV + const ggml_tensor * cur = dst->src[0]; + const ggml_tensor * history = dst->src[1]; + const ggml_tensor * weight = dst->src[2]; + const ggml_tensor * dynamic = dst->src[3]; + ggml_tensor * state = dst->src[4]; + const int32_t ch_offset = ggml_get_op_params_i32(dst, 1); + const int32_t n_seq_tokens = ggml_get_op_params_i32(dst, 2); + const int32_t n_seqs = ggml_get_op_params_i32(dst, 3); + const int32_t n_heads = ggml_get_op_params_i32(dst, 4); + const int32_t st_base_f32 = ggml_get_op_params_i32(dst, 5); + const int32_t st_seq_stride = ggml_get_op_params_i32(dst, 6); + const int32_t st_slot_stride = ggml_get_op_params_i32(dst, 7); + const int32_t st_kw = ggml_get_op_params_i32(dst, 8); + const float scale_out = ggml_get_op_params_f32(dst, 9); + const int64_t n_channels = cur->ne[0]; + const int64_t hist_sconv_ch = history->ne[1]; + const float * pc = (const float *)cur->data; + const float * ph = (const float *)history->data; + const float * pw = (const float *)weight->data; + const float * pdyn = dynamic ? (const float *)dynamic->data : nullptr; + float * pst = (float *)state->data; + float * pd = (float *)dst->data; + + const int32_t * pscopy = dst->src[6] ? (const int32_t *)dst->src[6]->data : nullptr; + const int64_t n_exp = (cur->ne[2] > 1 || cur->ne[1] != (int64_t)n_seq_tokens * n_seqs) ? cur->ne[1] : 1; + auto load_x = [&](int64_t seq, int64_t c, int64_t pos) -> float { + if (pos < 0) { + if (pscopy) { + const int64_t cell = pscopy[seq]; + return pst[cell * st_seq_stride + (ch_offset + c) * 3 + (pos + 3)]; + } + return ph[(seq * hist_sconv_ch + (ch_offset + c)) * 3 + (pos + 3)]; + } + const int64_t tok = seq * n_seq_tokens + pos; + if (n_exp <= 1) { + return *(const float *)((const char *)cur->data + tok * cur->nb[1] + c * sizeof(float)); + } + float s = 0.0f; + const float * pbase = pc + tok * (n_exp * n_channels) + c; + for (int64_t e = 0; e < n_exp; ++e) { + s += pbase[e * n_channels]; + } + return s; + }; + + for (int64_t c = ith; c < n_channels; c += nth) { + for (int64_t seq = 0; seq < n_seqs; ++seq) { + float h0 = load_x(seq, c, -3); + float h1 = load_x(seq, c, -2); + float h2 = load_x(seq, c, -1); + for (int64_t t = 0; t < n_seq_tokens; ++t) { + const float x0 = h0; + const float x1 = h1; + const float x2 = h2; + const float x3 = load_x(seq, c, t); + h0 = x1; h1 = x2; h2 = x3; + float sum = ((x0 * pw[c*4+0] + x1 * pw[c*4+1]) + x2 * pw[c*4+2]) + x3 * pw[c*4+3]; + const int64_t tok_global = seq * n_seq_tokens + t; + if (n_heads > 0 && pdyn) { + const int64_t head = c / (n_channels / n_heads); + const float * db = pdyn + (tok_global * n_heads + head) * 4; + sum += x3 * db[0]; + sum += x2 * db[1]; + sum += x1 * db[2]; + sum += x0 * db[3]; + } + const float scaled = (x3 + sum) * scale_out; + const float * pres = dst->src[5] ? (const float *)dst->src[5]->data : nullptr; + pd[tok_global * n_channels + c] = pres ? (pres[tok_global * n_channels + c] + scaled) : scaled; + const int64_t target_slot = (int64_t)n_seq_tokens - 1 - t; + if (target_slot >= 0 && target_slot < st_kw) { + float * sb = pst + st_base_f32 + target_slot * st_slot_stride + seq * st_seq_stride + c * 3; + sb[0] = x1; sb[1] = x2; sb[2] = x3; + } + } + } + } + return; + } + + if (mode == 2) { + // MODE_REL_GATHER + const ggml_tensor * table = dst->src[0]; + const ggml_tensor * sinks = dst->src[1]; + const ggml_tensor * rel_pos = dst->src[2]; + const ggml_tensor * kq_mask = dst->src[3]; + const int32_t n_seq_tokens = ggml_get_op_params_i32(dst, 1); + const int32_t r0 = ggml_get_op_params_i32(dst, 2); + const int32_t extent = ggml_get_op_params_i32(dst, 3); + const int32_t mask_r0 = ggml_get_op_params_i32(dst, 4); + const int64_t n_kv = dst->ne[0]; + const int64_t nr = dst->ne[1]; + const int64_t n_head = dst->ne[2]; + const int64_t n_stream = dst->ne[3]; + const int64_t table_len = table->ne[0]; + const float * pt = (const float *)table->data; + const float * ps = (const float *)sinks->data; + const int32_t * pr = (const int32_t *)rel_pos->data; + const ggml_fp16_t * pm = kq_mask ? (const ggml_fp16_t *)kq_mask->data : nullptr; + const int64_t m_ne1 = kq_mask ? kq_mask->ne[1] : 1; + const int64_t m_ne2 = kq_mask ? kq_mask->ne[2] : 1; + const int64_t m_ne3 = kq_mask ? kq_mask->ne[3] : 1; + const bool out_f16 = (dst->type == GGML_TYPE_F16); + float * pd32 = (float *)dst->data; + ggml_fp16_t * pd16 = (ggml_fp16_t *)dst->data; + const int64_t outer = nr * n_head * n_stream; + for (int64_t o = ith; o < outer; o += nth) { + const int64_t tok_r = o % nr; + const int64_t h = (o / nr) % n_head; + const int64_t s = o / (nr * n_head); + const int64_t tok_g = s * n_seq_tokens + (r0 + tok_r); + const float sv = ps[tok_g * n_head + h]; + const int64_t m2 = m_ne2 > 1 ? (h % m_ne2) : 0; + const int64_t m3 = m_ne3 > 1 ? (s % m_ne3) : 0; + const int64_t m_row = ((m3 * m_ne2 + m2) * m_ne1 + (mask_r0 + tok_r)) * n_kv; + for (int64_t kv_i = 0; kv_i < n_kv; ++kv_i) { + const int32_t r = pr[tok_g * n_kv + kv_i]; + const float tv = (r >= 0 && r < extent && r < table_len) ? pt[(tok_g * n_head + h) * table_len + r] : 0.0f; + float val = tv - sv; + if (pm) { + val += GGML_FP16_TO_FP32(pm[m_row + kv_i]); + } + if (out_f16) { + pd16[o * n_kv + kv_i] = GGML_FP32_TO_FP16(val); + } else { + pd32[o * n_kv + kv_i] = val; + } + } + } + return; + } + + if (mode == 3) { + // S19_WAVE3: MODE_DEPTH_MIX (+ optional RMS_NORM_MUL epilogue) + const int32_t K = ggml_get_op_params_i32(dst, 1); + const float eps = ggml_get_op_params_f32(dst, 2); + const float rms_eps = ggml_get_op_params_f32(dst, 3); + const ggml_tensor * q_t = dst->src[K]; + const ggml_tensor * w_t = dst->src[K + 1]; + const int64_t n_embd = dst->ne[0]; + const int64_t n_tokens = dst->ne[1]; + const int64_t Q = dst->ne[2]; + const float sm_scale = 1.0f / sqrtf((float)n_embd); + const float * pq = (const float *)q_t->data; + const float * pw = w_t ? (const float *)w_t->data : nullptr; + const int64_t w_s1 = (w_t && w_t->ne[1] > 1) ? n_embd : 0; + float * pd = (float *)dst->data; + for (int64_t tok = ith; tok < n_tokens; tok += nth) { + float rms_inv[6]; + for (int b = 0; b < K; ++b) { + const float * ps = (const float *)dst->src[b]->data + tok * n_embd; + float ss = 0.0f; + for (int64_t c = 0; c < n_embd; ++c) ss += ps[c] * ps[c]; + rms_inv[b] = 1.0f / sqrtf(ss / (float)n_embd + eps); + } + for (int64_t q = 0; q < Q; ++q) { + const float * qrow = pq + q * n_embd; + float sc[6], mx = -INFINITY; + for (int b = 0; b < K; ++b) { + const float * ps = (const float *)dst->src[b]->data + tok * n_embd; + float dp = 0.0f; + for (int64_t c = 0; c < n_embd; ++c) dp += (ps[c] * rms_inv[b]) * qrow[c]; + sc[b] = dp * sm_scale; + if (sc[b] > mx) mx = sc[b]; + } + float ex_sum = 0.0f; + for (int b = 0; b < K; ++b) { sc[b] = expf(sc[b] - mx); ex_sum += sc[b]; } + for (int b = 0; b < K; ++b) sc[b] /= ex_sum; + float * drow = pd + (q * n_tokens + tok) * n_embd; + float ss_out = 0.0f; + for (int64_t c = 0; c < n_embd; ++c) { + float acc = 0.0f; + for (int b = 0; b < K; ++b) { + const float * ps = (const float *)dst->src[b]->data + tok * n_embd; + acc += (ps[c] * rms_inv[b]) * sc[b]; + } + drow[c] = acc; + ss_out += acc * acc; + } + if (pw) { + const float scale = 1.0f / sqrtf(ss_out / (float)n_embd + rms_eps); + const float * wrow = pw + q * w_s1; + for (int64_t c = 0; c < n_embd; ++c) { + drow[c] = scale * drow[c] * wrow[c]; + } + } + } + } + return; + } + + if (mode == 4) { + // MODE_RMS2_CONCAT (C >= 1, optional cur broadcast) + const ggml_tensor * cur = dst->src[0]; + const ggml_tensor * msg = dst->src[1]; + const float eps = ggml_get_op_params_f32(dst, 1); + const int64_t n_embd = cur->ne[0]; + const int64_t n_tokens = cur->ne[1]; + const int64_t C = dst->ne[2]; + const int64_t cur_s2 = cur->ne[2] > 1 ? n_tokens * n_embd : 0; + const int64_t msg_s2 = msg->ne[2] > 1 ? n_tokens * n_embd : 0; + const int64_t rows = C * n_tokens; + for (int64_t r = ith; r < rows; r += nth) { + const int64_t sl = r / n_tokens; + const int64_t tok = r - sl * n_tokens; + const float * pc = (const float *)cur->data + sl * cur_s2 + tok * n_embd; + const float * pm = (const float *)msg->data + sl * msg_s2 + tok * n_embd; + float * pd = (float *)dst->data + r * (2 * n_embd); + float ss0 = 0.0f, ss1 = 0.0f; + for (int64_t c = 0; c < n_embd; ++c) { ss0 += pc[c]*pc[c]; ss1 += pm[c]*pm[c]; } + const float r0 = 1.0f / sqrtf(ss0 / (float)n_embd + eps); + const float r1 = 1.0f / sqrtf(ss1 / (float)n_embd + eps); + for (int64_t c = 0; c < n_embd; ++c) { + pd[c] = pc[c] * r0; + pd[n_embd + c] = pm[c] * r1; + } + } + return; + } + + if (mode == 5) { + // MODE_CTRL_APPLY + const float * pc = (const float *)dst->src[0]->data; + const float * pm = (const float *)dst->src[1]->data; + const float * pgn = (const float *)dst->src[2]->data; + const float * pfg = (const float *)dst->src[3]->data; + float * pd = (float *)dst->data; + const int64_t ne = ggml_nelements(dst); + const int64_t dr = (ne + nth - 1) / nth; + const int64_t i0 = dr * ith; + const int64_t i1 = MIN(i0 + dr, ne); + for (int64_t i = i0; i < i1; ++i) { + pd[i] = (pc[i] - tanhf(pfg[i]) * pc[i]) + tanhf(pgn[i]) * pm[i]; + } + return; + } + + if (mode == 11) { + // MODE_CTRL_APPLY_RMS_MUL + const ggml_tensor * cur = dst->src[0]; + const ggml_tensor * msg = dst->src[1]; + const ggml_tensor * up = dst->src[2]; + const ggml_tensor * w = dst->src[3]; + const float eps = ggml_get_op_params_f32(dst, 1); + const int64_t n_embd = dst->ne[0]; + const int64_t n_tokens = dst->ne[1]; + const int64_t C = dst->ne[2]; + const int64_t cur_s2 = cur->ne[2] > 1 ? n_tokens * n_embd : 0; + const int64_t w_s1 = w->ne[1] > 1 ? n_embd : 0; + const int64_t rows = C * n_tokens; + for (int64_t r = ith; r < rows; r += nth) { + const int64_t sl = r / n_tokens; + const int64_t tok = r - sl * n_tokens; + const float * pc = (const float *)cur->data + sl * cur_s2 + tok * n_embd; + const float * pm = (const float *)msg->data + r * n_embd; + const float * pu = (const float *)up->data + r * (2 * n_embd); + const float * pw = (const float *)w->data + sl * w_s1; + float * pd = (float *)dst->data + r * n_embd; + float ss = 0.0f; + for (int64_t c = 0; c < n_embd; ++c) { + const float y = (pc[c] - tanhf(pu[n_embd + c]) * pc[c]) + tanhf(pu[c]) * pm[c]; + pd[c] = y; + ss += y * y; + } + const float scale = 1.0f / sqrtf(ss / (float)n_embd + eps); + for (int64_t c = 0; c < n_embd; ++c) { + pd[c] = scale * pd[c] * pw[c]; + } + } + return; + } + + if (mode == 12) { + // MODE_L2_CLIP_QR + const ggml_tensor * q_cur = dst->src[0]; + const ggml_tensor * r_cur = dst->src[1]; + const ggml_tensor * q_sc = dst->src[2]; + const ggml_tensor * r_sc = dst->src[3]; + const ggml_tensor * tau = dst->src[4]; + const float q_thresh = ggml_get_op_params_f32(dst, 1); + const float r_thresh = ggml_get_op_params_f32(dst, 2); + const float eps = ggml_get_op_params_f32(dst, 3); + const int64_t q_ne0 = q_cur->ne[0]; + const int64_t r_ne0 = r_cur->ne[0]; + const int64_t n_head = q_cur->ne[1]; + const int64_t n_tokens = q_cur->ne[2]; + const int64_t q_rows = n_head * n_tokens; + const float * pqs = q_sc ? (const float *)q_sc->data : nullptr; + const float * prs = r_sc ? (const float *)r_sc->data : nullptr; + const float * ptau = tau ? (const float *)tau->data : nullptr; + float * pd = (float *)dst->data; + for (int64_t row = ith; row < 2 * q_rows; row += nth) { + const bool is_r = row >= q_rows; + const int64_t sub_row = is_r ? (row - q_rows) : row; + const int64_t head = sub_row % n_head; + const int64_t tok = sub_row / n_head; + const int64_t ne0 = is_r ? r_ne0 : q_ne0; + const float thresh = is_r ? r_thresh : q_thresh; + const ggml_tensor * ct = is_r ? r_cur : q_cur; + const float * pcur = (const float *)((const char *)ct->data + tok * ct->nb[2] + head * ct->nb[1]); + const float * psc = is_r ? (prs ? prs + head * ne0 : nullptr) : (pqs ? pqs + head * ne0 : nullptr); + float * pout = pd + (is_r ? (q_rows * q_ne0 + sub_row * r_ne0) : (sub_row * q_ne0)); + float ss = 0.0f; + for (int64_t c = 0; c < ne0; ++c) { + const float x = psc ? pcur[c] * psc[c] : pcur[c]; + ss += x * x; + } + const float norm = sqrtf(ss) + eps; + const float factor = fminf(1.0f, fmaxf(0.0f, thresh / norm)); + const float tau_v = ptau ? ptau[tok] : 1.0f; + for (int64_t c = 0; c < ne0; ++c) { + const float x = psc ? pcur[c] * psc[c] : pcur[c]; + pout[c] = (x * factor) * tau_v; + } + } + return; + } + + if (mode == 6) { + // MODE_DSPARK_CONCAT4 + const ggml_tensor * s0 = dst->src[0]; + const ggml_tensor * s1 = dst->src[1]; + const ggml_tensor * s2 = dst->src[2]; + const ggml_tensor * s3 = dst->src[3]; + const int64_t n0 = s0->ne[0], n1 = s1->ne[0], n2 = s2->ne[0], n3 = s3->ne[0]; + const int64_t nb = dst->ne[1]; + const int64_t tot = dst->ne[0]; + const float * p0 = (const float *)s0->data; + const float * p1 = (const float *)s1->data; + const float * p2 = (const float *)s2->data; + const float * p3 = (const float *)s3->data; + float * pd = (float *)dst->data; + for (int64_t r = ith; r < nb; r += nth) { + memcpy(pd + r * tot, p0 + r * n0, n0 * sizeof(float)); + memcpy(pd + r * tot + n0, p1 + r * n1, n1 * sizeof(float)); + memcpy(pd + r * tot + n0 + n1, p2 + r * n2, n2 * sizeof(float)); + memcpy(pd + r * tot + n0 + n1 + n2, p3 + r * n3, n3 * sizeof(float)); + } + return; + } + + if (mode == 7) { + // MODE_DSPARK_GRU + const ggml_tensor * joint = dst->src[0]; + const ggml_tensor * st_in = dst->src[1]; + const int64_t rank = st_in->ne[0]; + const int64_t nb = st_in->ne[1]; + const int64_t ne = rank * nb; + const int64_t dr = (ne + nth - 1) / nth; + const int64_t i0 = dr * ith; + const int64_t i1 = MIN(i0 + dr, ne); + const float * pj = (const float *)joint->data; + const float * ps = (const float *)st_in->data; + float * pd = (float *)dst->data; + for (int64_t idx = i0; idx < i1; ++idx) { + const int64_t r = idx / rank; + const int64_t c = idx - r * rank; + const float j0 = pj[r * (3 * rank) + c]; + const float j1 = pj[r * (3 * rank) + rank + c]; + const float j2 = pj[r * (3 * rank) + 2 * rank + c]; + const float gate = 1.0f / (1.0f + expf(-j0)); + const float cand = tanhf(j1); + pd[idx] = cand + gate * (ps[idx] - cand); + pd[ne + idx] = tanhf(j2); + } + return; + } + + if (mode == 8) { + // MODE_SOFTCAP + const float * pa = (const float *)dst->src[0]->data; + float * pd = (float *)dst->data; + const float inv_c = ggml_get_op_params_f32(dst, 1); + const float cap = ggml_get_op_params_f32(dst, 2); + const int64_t ne = ggml_nelements(dst); + const int64_t dr = (ne + nth - 1) / nth; + const int64_t i0 = dr * ith; + const int64_t i1 = MIN(i0 + dr, ne); + for (int64_t i = i0; i < i1; ++i) { + pd[i] = cap * tanhf(pa[i] * inv_c); + } + return; + } + + if (mode == 9) { + // MODE_DSPARK_JOINT_GRU + const int32_t * pprev = (const int32_t *)dst->src[0]->data; + const ggml_tensor * w1 = dst->src[1]; + const float * pst = (const float *)dst->src[2]->data; + const float * phid = (const float *)dst->src[3]->data; + const float * pctx = (const float *)dst->src[4]->data; + const ggml_tensor * jp = dst->src[5]; + const float * pb = dst->src[6] ? (const float *)dst->src[6]->data : nullptr; + float * pd = (float *)dst->data; + const int64_t rank = dst->ne[0]; + const int64_t nb = dst->ne[1]; + const int64_t n_embd = dst->src[3]->ne[0]; + const int64_t K = 2 * rank + 2 * n_embd; + const int64_t slice = rank * nb; + auto ld_elem = [](const ggml_tensor * t, int64_t idx) -> float { + if (t->type == GGML_TYPE_BF16) { + return GGML_BF16_TO_FP32(((const ggml_bf16_t *)t->data)[idx]); + } + return ((const float *)t->data)[idx]; + }; + for (int64_t idx = ith; idx < slice; idx += nth) { + const int64_t b = idx / rank; + const int64_t col = idx - b * rank; + const int64_t pid = pprev[b]; + auto ld_x = [&](int64_t k) -> float { + if (k < rank) return pst[b * rank + k]; + if (k < 2 * rank) return ld_elem(w1, pid * rank + (k - rank)); + if (k < 2 * rank + n_embd) return phid[b * n_embd + (k - 2 * rank)]; + return pctx[b * n_embd + (k - 2 * rank - n_embd)]; + }; + float jv[3] = { 0.0f, 0.0f, 0.0f }; + for (int r = 0; r < 3; ++r) { + const int64_t row_idx = r * rank + col; + float s = 0.0f; + for (int64_t k = 0; k < K; ++k) { + s += ld_elem(jp, row_idx * K + k) * ld_x(k); + } + jv[r] = pb ? (s + pb[row_idx]) : s; + } + const float gate = 1.0f / (1.0f + expf(-jv[0])); + const float cand = tanhf(jv[1]); + pd[idx] = cand + gate * (pst[idx] - cand); + pd[slice + idx] = tanhf(jv[2]); + } + return; + } + + if (mode == 10) { + // MODE_DSPARK_INJECT_MIX + const float * pf = (const float *)dst->src[0]->data; + const float * pfuse = (const float *)dst->src[1]->data; + const float * pn[4] = { + (const float *)dst->src[2]->data, + (const float *)dst->src[3]->data, + (const float *)dst->src[4]->data, + (const float *)dst->src[5]->data, + }; + const int32_t * ppos = dst->src[6] ? (const int32_t *)dst->src[6]->data : nullptr; + float * pring = dst->src[7] ? (float *)dst->src[7]->data : nullptr; + float * pd = (float *)dst->data; + const int32_t seq_off = ggml_get_op_params_i32(dst, 1); + const int32_t r_rows = ggml_get_op_params_i32(dst, 2); + const float eps = ggml_get_op_params_f32(dst, 3); + const int64_t n_embd = dst->ne[0]; + const int64_t n_tok = dst->ne[1]; + const int64_t outer = 4 * n_tok; + for (int64_t o = ith; o < outer; o += nth) { + const int64_t row = o / n_tok; + const int64_t tok = o - row * n_tok; + const float * fb = pfuse + row * 4; + const float mx = MAX(MAX(fb[0], fb[1]), MAX(fb[2], fb[3])); + float e0 = expf(fb[0] - mx), e1 = expf(fb[1] - mx), e2 = expf(fb[2] - mx), e3 = expf(fb[3] - mx); + const float rcp = 1.0f / ((e0 + e2) + (e1 + e3)); + const float w0 = e0 * rcp, w1 = e1 * rcp, w2 = e2 * rcp, w3 = e3 * rcp; + const float * tb = pf + tok * (4 * n_embd); + float * db = pd + (row * n_tok + tok) * n_embd; + float ss = 0.0f; + for (int64_t c = 0; c < n_embd; ++c) { + const float y = ((tb[c] * w0) + (tb[2 * n_embd + c] * w2)) + ((tb[n_embd + c] * w1) + (tb[3 * n_embd + c] * w3)); + db[c] = y; + ss += y * y; + } + const float sc = 1.0f / sqrtf(ss / (float)n_embd + eps); + float * rb = nullptr; + if (row == 3 && pring && ppos && r_rows > 0 && ppos[tok] >= 0) { + rb = pring + (int64_t)(seq_off + (ppos[tok] % r_rows)) * n_embd; + } + for (int64_t c = 0; c < n_embd; ++c) { + const float v = (db[c] * sc) * pn[row][c]; + db[c] = v; + if (rb) rb[c] = v; + } + } + return; + } + + GGML_ABORT("unknown GGML_OP_INKLING_FUSED mode"); +} + +static void ggml_compute_forward_situ(const ggml_compute_params * params, ggml_tensor * dst) { + const ggml_tensor * src0 = dst->src[0]; + const ggml_tensor * src1 = dst->src[1]; + const bool swapped = dst->op_params[1] != 0; + const float beta = ggml_get_op_params_f32(dst, 2); + const float lb = ggml_get_op_params_f32(dst, 3); + const float inv_b = 1.0f / beta; + const float inv_lb = lb > 0.0f ? (1.0f / lb) : 0.0f; + + const int64_t nc = dst->ne[0]; + const int64_t nr = ggml_nrows(dst); + const int ith = params->ith; + const int nth = params->nth; + const int64_t dr = (nr + nth - 1) / nth; + const int64_t ir0 = dr * ith; + const int64_t ir1 = MIN(ir0 + dr, nr); + + for (int64_t ir = ir0; ir < ir1; ++ir) { + const int64_t i3 = ir / (dst->ne[1] * dst->ne[2]); + const int64_t r2 = ir - i3 * (dst->ne[1] * dst->ne[2]); + const int64_t i2 = r2 / dst->ne[1]; + const int64_t i1 = r2 - i2 * dst->ne[1]; + + const char * p0 = (const char *)src0->data + i1 * src0->nb[1] + i2 * src0->nb[2] + i3 * src0->nb[3]; + const char * p1 = src1 + ? ((const char *)src1->data + i1 * src1->nb[1] + i2 * src1->nb[2] + i3 * src1->nb[3]) + : (p0 + nc * src0->nb[0]); + if (!src1 && swapped) { + const char * tmp = p0; p0 = p1; p1 = tmp; + } + char * pd = (char *)dst->data + i1 * dst->nb[1] + i2 * dst->nb[2] + i3 * dst->nb[3]; + + if (src0->type == GGML_TYPE_F32) { + for (int64_t i0 = 0; i0 < nc; ++i0) { + const float g = *(const float *)(p0 + i0 * src0->nb[0]); + const float u = *(const float *)(p1 + i0 * (src1 ? src1->nb[0] : src0->nb[0])); + const float act = (tanhf(g * inv_b) * beta) * (1.0f / (1.0f + expf(-g))); + const float uv = lb > 0.0f ? (tanhf(u * inv_lb) * lb) : u; + *(float *)(pd + i0 * dst->nb[0]) = act * uv; + } + } else if (src0->type == GGML_TYPE_F16) { + for (int64_t i0 = 0; i0 < nc; ++i0) { + const float g = GGML_FP16_TO_FP32(*(const ggml_fp16_t *)(p0 + i0 * src0->nb[0])); + const float u = GGML_FP16_TO_FP32(*(const ggml_fp16_t *)(p1 + i0 * (src1 ? src1->nb[0] : src0->nb[0]))); + const float act = (tanhf(g * inv_b) * beta) * (1.0f / (1.0f + expf(-g))); + const float uv = lb > 0.0f ? (tanhf(u * inv_lb) * lb) : u; + *(ggml_fp16_t *)(pd + i0 * dst->nb[0]) = GGML_FP32_TO_FP16(act * uv); + } + } else { + GGML_ABORT("fatal error"); + } + } +} + // ggml_compute_forward_geglu_erf static void ggml_compute_forward_geglu_erf_f32( @@ -10648,6 +11224,10 @@ void ggml_compute_forward_glu( { ggml_compute_forward_swiglu_clamp(params, dst); } break; + case GGML_GLU_OP_SITU: + { + ggml_compute_forward_situ(params, dst); + } break; default: { GGML_ABORT("fatal error"); diff --git a/ggml/src/ggml-cpu/ops.h b/ggml/src/ggml-cpu/ops.h index 22017df7063d..0f99c227d12f 100644 --- a/ggml/src/ggml-cpu/ops.h +++ b/ggml/src/ggml-cpu/ops.h @@ -119,6 +119,7 @@ void ggml_compute_forward_opt_step_adamw(const struct ggml_compute_params * para void ggml_compute_forward_mul_mat(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_fwht(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_opt_step_sgd(const struct ggml_compute_params * params, struct ggml_tensor * dst); +void ggml_compute_forward_inkling_fused(const struct ggml_compute_params * params, struct ggml_tensor * dst); #ifdef __cplusplus } #endif diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-common.h b/ggml/src/ggml-vulkan/ggml-vulkan-common.h index ea3b3b4b8772..fe6da49f14a0 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-common.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-common.h @@ -35,7 +35,7 @@ bool ggml_vk_intel_windows_driver_in_range(uint32_t driver_version, uint32_t low // shaders void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline); vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool allow_flip = true); -vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool aligned, bool f32acc, bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type); +vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool aligned, bool f32acc, bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type, uint32_t extra_flags = 0u); uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch); void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested = nullptr); bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool f32acc, ggml_type k_type, ggml_type v_type); @@ -111,7 +111,7 @@ void ggml_vk_dsv4_hc_pre(ggml_backend_vk_context * ctx, vk_context& subctx, cons void ggml_vk_dsv4_hc_post(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * x, const ggml_tensor * residual, const ggml_tensor * post, const ggml_tensor * comb, ggml_tensor * dst, const ggml_tensor * gate_scale_in = nullptr); void ggml_vk_top_k_mask(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst); void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx); -bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx); +bool ggml_vk_use_mul_mat_vec_id(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx); void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx); // flash-attn @@ -303,6 +303,14 @@ inline void ggml_vk_dispatch_pipeline(ggml_backend_vk_context* ctx, vk_context& GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size()); GGML_ASSERT(pipeline->push_constant_size == push_constant_size(push_constants)); + ctx->stat_dispatches++; + { + // gen: GGML_VK_GRAPH_STATS=2 lists every dispatch (pipeline and workgroups) + static const int gen_stats_level = getenv("GGML_VK_GRAPH_STATS") ? atoi(getenv("GGML_VK_GRAPH_STATS")) : 0; + if (gen_stats_level >= 2) { + fprintf(stderr, "ggml_vk_dispatch: %s %u %u %u\n", pipeline->name.c_str(), wg0, wg1, wg2); + } + } const uint32_t descriptor_set_idx = ctx->descriptor_set_idx++; vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[descriptor_set_idx]; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index 026ad8935e34..815ac6f277b4 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -45,6 +45,19 @@ struct vk_mat_mat_stream_k_fixup_push_constants { static_assert(sizeof(vk_mat_mat_push_constants) <= 128); +struct vk_mat_mat_fused_push_constants { + uint32_t M; uint32_t N; uint32_t K; + uint32_t stride_a; uint32_t stride_b; uint32_t stride_d; + uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d; + uint32_t base_work_group_z; uint32_t num_batches; + uint32_t k_split; + uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3; + uint32_t padded_N; + uint32_t fusion_flags; + uint32_t pair_m0; + uint32_t stride_d2; + uint32_t batch_stride_d2; +}; struct vk_mat_vec_push_constants { uint32_t ncols; uint32_t stride_a; @@ -59,6 +72,36 @@ struct vk_mat_vec_push_constants { uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3; + uint32_t pair_m0; + uint32_t stride_d2; + uint32_t batch_stride_d2; + uint32_t lora_r; + float lora_scale0; + float lora_scale1; +}; + +struct vk_mat_mv_mma_push_constants { + uint32_t M; + uint32_t N; + uint32_t K; + uint32_t stride_a; + uint32_t stride_b; + uint32_t stride_d; + uint32_t batch_stride_a; + uint32_t batch_stride_b; + uint32_t batch_stride_d; + uint32_t fusion_flags; + uint32_t base_work_group_z; + uint32_t ne02; + uint32_t ne12; + uint32_t broadcast2; + uint32_t broadcast3; + uint32_t pair_m0; + uint32_t stride_d2; + uint32_t batch_stride_d2; + uint32_t lora_r; + float lora_scale0; + float lora_scale1; }; struct vk_mat_vec_p021_push_constants { @@ -96,6 +139,18 @@ struct vk_mat_mat_id_push_constants { uint32_t row_ids_offset; }; +struct vk_mat_mat_id_fused_push_constants { + uint32_t M; uint32_t N; uint32_t K; + uint32_t stride_a; uint32_t stride_b; uint32_t stride_d; + uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d; + uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11; + uint32_t n_experts; + uint32_t row_ids_offset; + uint32_t fusion_flags; + float glu_alpha; + float glu_limit; +}; + struct vk_mat_vec_id_push_constants { uint32_t ncols; uint32_t stride_a; @@ -109,6 +164,8 @@ struct vk_mat_vec_id_push_constants { uint32_t ne11; uint32_t expert_i1; uint32_t nbi1; + float glu_alpha; + float glu_limit; }; struct vk_flash_attn_push_constants { @@ -516,15 +573,23 @@ struct vk_op_multi_add_push_constants { uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; // strides for srcs+dst - uint32_t nb[MAX_PARAMETER_COUNT][4]; + uint32_t nb[12][4]; uint32_t rms_partials; }; -static_assert(MAX_PARAMETER_COUNT == 12); - static_assert(sizeof(vk_op_multi_add_push_constants) <= 256); +struct vk_op_multi_add_rms_push_constants { + uint32_t ne0; + uint32_t nrows; + float eps; + uint32_t write_add_dst; + uint32_t nb1[10]; +}; + +static_assert(sizeof(vk_op_multi_add_rms_push_constants) <= 128); + struct vk_op_topk_moe_push_constants { uint32_t n_rows; uint32_t n_experts_push; @@ -798,6 +863,7 @@ struct vk_op_gated_delta_net_push_constants { uint32_t spk1, spk2, spk3; // replay: pend_k, pend_v and pend_gb strides in floats uint32_t spv1, spv2, spv3; uint32_t spg1, spg2, spg3; + uint32_t sout_nb2; }; struct vk_op_ssm_scan_push_constants { @@ -814,6 +880,9 @@ struct vk_op_ssm_conv_push_constants { uint32_t nb11; uint32_t dst_nb0, dst_nb1, dst_nb2; uint32_t nc, ncs, nr, n_t, n_s; + uint32_t st_nb1, st_nb2; + uint32_t qkv_nb0, qkv_nb1, qkv_nb2; + uint32_t st_k, st_slot_nb; }; struct vk_op_conv2d_push_constants { diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index b71e73dd0d9e..1bdffcfdd335 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -232,9 +232,9 @@ static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; } #define VK_LOG_DEBUG(msg) ((void) 0) #endif // GGML_VULKAN_DEBUG -#define MAX_PARAMETER_COUNT 12 +#define MAX_PARAMETER_COUNT 14 -#define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3) +#define MAX_FUSED_ADDS 9 #define GGML_VK_GDN_CM_V 64u #define GGML_VK_GDN_CM2_V 32u @@ -271,6 +271,13 @@ struct vk_pipeline_struct { // linked list of pipelines for multiple compilation variants. // currently only used to compile a 64-bit indexing variant. vk_pipeline next; + // gen: mat-vec / matmul twins compiled lazily with spec constant = 1 (single-op epilogue), 2 (PAIR_MM), 3 (PAIR_GLU), 4 (fast BIAS/SCALE) + vk_pipeline gen_glu; + vk_pipeline gen_pair_mm; + vk_pipeline gen_pair_glu; + vk_pipeline gen_fast_ep; + vk_pipeline gen_fast_ep_kp2; + vk_pipeline gen_lora_twin; }; typedef std::weak_ptr vk_pipeline_ref; @@ -384,6 +391,7 @@ struct vk_queue { }; static constexpr uint32_t mul_mat_vec_max_cols = 8; +static constexpr uint32_t mul_mat_vec_max_cols_limit = 32; static constexpr uint32_t p021_max_gqa_ratio = 8; @@ -544,6 +552,11 @@ static constexpr std::initializer_list topk_moe_sigmoid_norm_bias{ GGML GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV, GGML_OP_RESHAPE }; +static constexpr std::initializer_list topk_moe_sigmoid_norm_bias_eps{ GGML_OP_UNARY, GGML_OP_RESHAPE, GGML_OP_ADD, + GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS, + GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_SCALE, + GGML_OP_DIV, GGML_OP_RESHAPE }; + static constexpr std::initializer_list topk_moe_sqrt_softplus_norm_bias{ GGML_OP_UNARY, GGML_OP_SQRT, GGML_OP_RESHAPE, GGML_OP_ADD, GGML_OP_ARGSORT, GGML_OP_VIEW, @@ -661,6 +674,7 @@ enum topk_moe_mode { TOPK_MOE_EARLY_SOFTMAX_NORM, TOPK_MOE_LATE_SOFTMAX, TOPK_MOE_SIGMOID_NORM_BIAS, + TOPK_MOE_SIGMOID_NORM_BIAS_EPS, TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS, TOPK_MOE_COUNT, }; @@ -672,6 +686,8 @@ enum rms_norm_mode { RMS_NORM_MUL_ROPE, RMS_NORM_MUL_ROPE_VIEW_SET_ROWS, RMS_NORM_VIEW_SET_ROWS, + RMS_NORM_SCALE, // gen + RMS_NORM_MUL_SILU_GATE, // gen RMS_NORM_COUNT, }; @@ -735,6 +751,10 @@ struct vk_device_struct { vk::Device device; uint32_t vendor_id; vk::DriverId driver_id; + bool borealis_medium_tiles = false; + bool borealis_roll_bk = false; + uint32_t mmv_max_cols = mul_mat_vec_max_cols; + uint32_t mmv_id_max_tokens = 8; vk_device_architecture architecture; std::unique_ptr compute_queue; std::unique_ptr transfer_queue; @@ -796,6 +816,7 @@ struct vk_device_struct { bool coopmat_m1_get_coordinate {}; bool coopmat_support_16x16x16_f16acc {}; bool coopmat_support_16x16x16_f32acc {}; + bool coopmat_support_8x8x8_f32acc {}; bool coopmat1_fa_support {}; uint32_t coopmat_m; uint32_t coopmat_n; @@ -858,11 +879,21 @@ struct vk_device_struct { vk_pipeline pipeline_dequant[GGML_TYPE_COUNT]; vk_pipeline pipeline_dequant_transpose[GGML_TYPE_COUNT]; // fused dequant+transpose for FA quant-KV - vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols]; - vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols]; + vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols_limit]; + vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols_limit]; vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT]; - - vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols]; + vk_pipeline pipeline_mul_mv_mma[GGML_TYPE_COUNT][5][8][2]; + vk_pipeline pipeline_mul_mv_mma_f32_f16[5][8][2]; + vk_pipeline pipeline_mul_mv_mma_id[GGML_TYPE_COUNT][7][5][2]; + + vk_pipeline pipeline_dequant_repack[4]; + vk_pipeline pipeline_dequant_mul_mat_vec_repack_f32_f32[4][mul_mat_vec_max_cols_limit]; + vk_pipeline pipeline_dequant_mul_mat_vec_repack_f16_f32[4][mul_mat_vec_max_cols_limit]; + vk_pipeline pipeline_dequant_mul_mat_vec_id_repack_f32[4]; + vk_pipeline pipeline_mul_mv_mma_repack[4][5][8][2]; + vk_pipeline pipeline_mul_mv_mma_id_repack[4][7][5][2]; + + vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols_limit]; vk_pipeline pipeline_dequant_mul_mat_vec_id_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT]; vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio]; @@ -889,6 +920,7 @@ struct vk_device_struct { // indexed by num_additional_fused_ops == num_adds - 1 vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS]; vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS]; + vk_pipeline pipeline_multi_add_rms_mul[MAX_FUSED_ADDS][3][2]; vk_pipeline pipeline_add_id_f32; @@ -897,6 +929,7 @@ struct vk_device_struct { vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bicubic_f32, pipeline_upscale_bilinear_antialias_f32; // [src/dst 0=fp32,1=fp16,2=bf16] vk_pipeline pipeline_scale[3]; + vk_pipeline pipeline_scale_zero_f32; vk_pipeline pipeline_log[3]; vk_pipeline pipeline_tri[3]; vk_pipeline pipeline_diag[3]; @@ -923,13 +956,18 @@ struct vk_device_struct { vk_pipeline pipeline_norm_f32; vk_pipeline pipeline_group_norm_f32; // [src/dst 0=fp32,1=bf16][mul] - std::array pipeline_rms_norm[2][2]; + std::array pipeline_rms_norm[2][2]; + std::array pipeline_rms_norm_scale_f32; // gen // [src/dst 0=fp32,1=bf16][residual 0=fp32,1=bf16][post mul] - std::array pipeline_rms_norm_mul_add[2][2][2]; + std::array pipeline_rms_norm_mul_add[2][2][2]; + std::array pipeline_rms_norm_mul_silu_f32; // gen vk_pipeline pipeline_rms_norm_mul_add_partials_f32; vk_pipeline pipeline_rms_norm_mul_add_mul_partials_f32; vk_pipeline pipeline_rms_norm_set_rows_f32_f32; vk_pipeline pipeline_rms_norm_set_rows_f32_f16; + vk_pipeline pipeline_rms_norm_set_rows_f32_f32_32; + vk_pipeline pipeline_rms_norm_set_rows_f32_f16_32; + vk_pipeline pipeline_rms_norm_set_rows_f32_q8_0_32; vk_pipeline pipeline_rms_norm_partials_f32; vk_pipeline pipeline_rms_norm_mul_partials_f32; std::array pipeline_rms_norm_mul_rope_f32_f32; @@ -956,6 +994,7 @@ struct vk_device_struct { // [src/dst 0=fp32,1=fp16,2=bf16] vk_pipeline pipeline_glu[GGML_GLU_OP_COUNT][3]; + vk_pipeline pipeline_inkling_fused[16]; vk_pipeline pipeline_silu_back_f32; vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16; @@ -1015,6 +1054,7 @@ struct vk_device_struct { vk_pipeline pipeline_lightning_indexer_f32[GGML_TYPE_COUNT]; // [size_idx][kda][replay] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128 vk_pipeline pipeline_gated_delta_net[4][2][2]; + vk_pipeline pipeline_gated_delta_net_sout[4][2]; // gen: final state to a separate binding vk_pipeline pipeline_gated_delta_net_cm[2]; vk_pipeline pipeline_gated_delta_net_cm_v32[2]; vk_pipeline pipeline_gated_delta_net_cm_v128[2]; @@ -1024,6 +1064,14 @@ struct vk_device_struct { vk_pipeline pipeline_ssm_conv_f32; vk_pipeline pipeline_ssm_conv_silu_f32; vk_pipeline pipeline_ssm_conv_bias_silu_f32; + vk_pipeline pipeline_ssm_conv_1t_f32; + vk_pipeline pipeline_ssm_conv_silu_1t_f32; + vk_pipeline pipeline_ssm_conv_sout_f32; + vk_pipeline pipeline_ssm_conv_silu_sout_f32; + vk_pipeline pipeline_ssm_conv_concat_cpy_f32; + vk_pipeline pipeline_ssm_conv_concat_cpy_silu_f32; + vk_pipeline pipeline_ssm_conv_concat_cpy_mt_f32; + vk_pipeline pipeline_ssm_conv_concat_cpy_mt_silu_f32; vk_pipeline pipeline_opt_step_adamw_f32; vk_pipeline pipeline_opt_step_sgd_f32; std::map pipeline_conv2d_f32[CONV_SHAPE_COUNT]; @@ -1050,6 +1098,7 @@ struct vk_device_struct { // [2] is for whether to take n_experts from spec constant (0) or push constant (1) vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][2]; + vk_pipeline pipeline_topk_moe_count[9][2][2]; std::vector all_pipelines; @@ -1057,6 +1106,8 @@ struct vk_device_struct { vk_buffer sync_staging; ggml_backend_buffer_type buffer_type; + ggml_backend_buffer_type repack_buffer_type {}; + std::array extra_bufts {}; bool disable_fusion; std::atomic fusion_stats_enabled {false}; @@ -1132,6 +1183,8 @@ struct vk_semaphore { uint64_t value; }; +struct ggml_backend_vk_context; + struct vk_event { std::vector events_free; // Events available for reuse std::vector events_submitted; // Events that are fully submitted and can be reused on next synchronize @@ -1141,6 +1194,11 @@ struct vk_event { vk_semaphore tl_semaphore; vk_command_buffer* cmd_buffer = nullptr; uint64_t cmd_buffer_use_counter = 0; + + ggml_backend_vk_context * fence_ctx = nullptr; + std::weak_ptr fence_ctx_alive; + uint64_t fence_target = 0; + bool has_fence_ref = false; }; struct vk_submission { @@ -1161,6 +1219,25 @@ typedef std::vector vk_sequence; #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4 #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8 +#define MAT_VEC_FUSION_FLAGS_GLU_A 0x10 // gen +#define MAT_VEC_FUSION_FLAGS_GLU_B 0x20 // gen +#define MAT_VEC_FUSION_FLAGS_GEN_TOKY 0x40 // gen: MUL_MAT_ID, all tokens in one dispatch (y = slot + nei0 * token) +#define MAT_VEC_FUSION_FLAGS_SIGMOID 0x80 // gen +#define MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE 0x100 // gen +#define MAT_VEC_FUSION_FLAGS_ROW_SCALE0 0x200 // gen +#define MAT_VEC_FUSION_FLAGS_PAIR_GLU 0x400 // gen: gate+up+swiglu in one mat-vec/mat-vec-id dispatch +#define MAT_VEC_FUSION_FLAGS_PAIR_MM 0x800 // gen: two mat-vecs sharing src1 in one dispatch +#define MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1 0x1000 // gen: sigmoid epilogue on second mat-vec output +#define MAT_VEC_FUSION_FLAGS_SCALE0_TOK 0x2000 // s10: MUL_MAT_ID SCALE0 indexed per (slot, token) +#define MAT_VEC_FUSION_FLAGS_SCALE1_TOK 0x4000 // s10: MUL_MAT_ID SCALE1 indexed per (slot, token) +#define MAT_VEC_FUSION_FLAGS_COL_SPLIT 0x8000 // s10: multi-column batch_n split across y workgroups +#define MAT_VEC_FUSION_FLAGS_B_F16 0x10000 // s14: FP16 B buffer bound to mul_mv_mma{_id} +#define MAT_VEC_FUSION_FLAGS_D_F16_AUX1 0x20000 // s14: mul_mv_mma_id _pairglu writes FP16 D to AUX1 (prealloc_y) +#define MAT_VEC_FUSION_FLAGS_SKIP_F32_D 0x40000 // s14: mul_mv_mma_id _pairglu skips dead FP32 D store +#define MAT_VEC_FUSION_FLAGS_LORA0 0x80000 // fused dynamic LoRA0 epilogue +#define MAT_VEC_FUSION_FLAGS_LORA1 0x100000 // fused dynamic LoRA1 epilogue (up in PAIR_GLU, second mm in PAIR_MM) +#define MAT_VEC_FUSION_FLAGS_EXP_SCALE0 0x200000 // per-expert .scale indexed by expert_idx +#define MAT_VEC_FUSION_FLAGS_SITU_MERGED 0x400000 // S19: unsplit MoE gate_up + SITU in mul_mv_mma_id struct vk_staging_memcpy { vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {} @@ -1300,6 +1377,41 @@ class vk_perf_logger { uint32_t print_count {}; }; +static constexpr uint32_t VK_PREALLOC_RING = 8; +static constexpr size_t VK_REPLAY_CACHE_MAX = 16; +static constexpr uint32_t VK_REPLAY_PROB_SLOTS = 16; +static constexpr size_t AGX_REPLAY_MAX_CHUNKS = 8; + +struct vk_graph_replay_entry { + uint64_t hash1 {}; + uint64_t hash2 {}; + uint64_t destroy_count {}; + uint64_t pre_x_handle {}, pre_y_handle {}, pre_sk_handle {}, pre_arp_handle {}, pre_mo_handle {}; + size_t pre_x_size {}, pre_y_size {}, pre_sk_size {}, pre_arp_size {}, pre_mo_size {}; + uint32_t stable_runs {}; + uint64_t lru_tick {}; + bool ready {}; + + std::vector sig_words; + + uint64_t hash3 {}; + uint64_t hash4 {}; + int32_t n_nodes {}; + vk_command_pool cmd_pool; + std::vector cmd_bufs; + std::vector memsets; + + std::vector descriptor_pools; + std::vector descriptor_sets; + std::vector> descriptor_set_bindings; + uint64_t descriptor_destroy_count {}; + + uint64_t total_flops {}; + uint64_t stat_dispatches {}; + uint64_t stat_syncs {}; + double ema_gpu_us {}; +}; + struct ggml_backend_vk_context { std::string name; @@ -1311,17 +1423,75 @@ struct ggml_backend_vk_context { size_t semaphore_idx, binary_semaphore_idx, event_idx; ggml_vk_garbage_collector gc; - size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset; - vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, sync_staging; + size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset, prealloc_size_mask_opt {}; + vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, prealloc_mask_opt, sync_staging; vk::Fence fence, almost_ready_fence; bool submit_pending {}; + bool fence_submitted {}; bool almost_ready_fence_pending {}; + uint64_t fence_epoch {}; + std::shared_ptr alive_token { std::make_shared(true) }; // Set before op_add and unset after op_rms_norm to indicate that the add should // write partial sums to accumulate the square of the vector components bool do_add_rms_partials_offset_calculation; bool do_add_rms_partials; uint64_t last_total_flops {UINT64_MAX}; + // gen instrumentation (GGML_VK_GRAPH_STATS): per-graph counters + uint64_t stat_dispatches {}; + // gen: GATED_DELTA_NET writes its final state into this CPY node's destination (and the CPY is skipped) + const ggml_tensor * gen_gdn_state_out {}; + bool gen_gdn_zero_state {}; + // gen: RMS_NORM_SCALE writes into this SCALE node (found a few nodes later, which is then skipped) + const ggml_tensor * gen_rms_scale_dst {}; + const ggml_tensor * gen_rms_scale_dst2 {}; + const ggml_tensor * gen_rms_scale_rsrc2 {}; + // gen: dense MUL_MAT forward-elision epilogue target and auxiliary inputs (GGML_GEN_FUSE=mmgate,shexp) + // S19_WAVE3: MAT_VEC_FUSION_FLAGS_SRC1_SCALE (0x4000000) + gen_mm_src1_override +#ifndef MAT_VEC_FUSION_FLAGS_SRC1_SCALE +#define MAT_VEC_FUSION_FLAGS_SRC1_SCALE 0x4000000 +#endif + const ggml_tensor * gen_mm_dst {}; + const ggml_tensor * gen_mm_f0 {}; + const ggml_tensor * gen_mm_f1 {}; + const ggml_tensor * gen_mm_src1_override {}; + float gen_glu_alpha {}; + float gen_glu_limit {}; + uint32_t gen_mm_flags {}; + // gen: paired dense MUL_MAT sharing src1 (GGML_GEN_FUSE=pairmm) + const ggml_tensor * gen_pair_mm1 {}; + const ggml_tensor * gen_pair_dst1 {}; + int gen_pair_mul0_rel {}; + // Fused dynamic LoRA epilogue state + const ggml_tensor * gen_lora_b0 {}; + const ggml_tensor * gen_lora_h0 {}; + const ggml_tensor * gen_lora_b1 {}; + const ggml_tensor * gen_lora_h1 {}; + const ggml_tensor * gen_lora_gate_src0 {}; + const ggml_tensor * gen_lora_up_src0 {}; + uint32_t gen_lora_r {}; + float gen_lora_scale0 {}; + float gen_lora_scale1 {}; + // Series 10: SSM_CONV fusion (mode 1 = CONCAT_SLIDING, mode 2 = WRITE_STATE_OUT, mode 3 = CONCAT_SLIDING_ROLLBACK) + int s10_ssm_conv_mode {}; + const ggml_tensor * s10_ssm_state_out {}; + const ggml_tensor * s10_ssm_old_st {}; + const ggml_tensor * s10_ssm_qkv {}; + const ggml_tensor * s10_ssm_conv_node {}; + uint32_t s10_ssm_st_k {}; + uint32_t s10_ssm_st_slot_nb {}; + bool s10_ssm_zero_state {}; + // Series 10: MULTI_ADD + RMS_NORM + [MUL] fusion + const ggml_tensor * s10_add_rms_dst {}; + const ggml_tensor * s10_add_rms_weight {}; + const ggml_tensor * s10_add_rms_add_dst {}; + float s10_add_rms_eps {}; + uint32_t s10_add_rms_num_adds {}; + uint32_t s10_add_rms_tree_mode {}; + uint32_t s10_add_rms_write_add {}; + const ggml_tensor * s10_add_rms_srcs[10] {}; + uint32_t gen_n1_partials_offset {}; + uint64_t stat_syncs {}; // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert. vk_pipeline_struct * prealloc_y_last_pipeline_used {}; @@ -1329,6 +1499,74 @@ struct ggml_backend_vk_context { // True when the K dimension in prealloc_y is padded. bool prealloc_y_last_k_padded {}; + // Series 9: K=4 ring-sliced prealloc_y and prealloc_split_k to eliminate WAR drain barriers + uint32_t prealloc_y_ring_idx {}; + size_t prealloc_y_ring_stride {}; + uint32_t prealloc_y_ring_count {1}; + bool prealloc_y_slot_need_sync[VK_PREALLOC_RING] {}; + vk_pipeline_struct * prealloc_y_last_pipeline_ring[VK_PREALLOC_RING] {}; + const ggml_tensor * prealloc_y_last_tensor_ring[VK_PREALLOC_RING] {}; + bool prealloc_y_last_k_padded_ring[VK_PREALLOC_RING] {}; + int prealloc_y_keep_slot {-1}; + bool gen_pair_glu_sole_mmid_next {}; + bool gen_rms_silu_sole_mm_next {}; + + uint32_t prealloc_split_k_ring_idx {}; + size_t prealloc_split_k_ring_stride {}; + uint32_t prealloc_split_k_ring_count {1}; + bool prealloc_split_k_slot_need_sync[VK_PREALLOC_RING] {}; + + // Series 9: Reuse count_experts output across MoE projections sharing non-negative ARGSORT ids + const ggml_tensor * last_expert_ids_tensor {}; + uint32_t last_expert_bn {}; + uint32_t last_expert_row_ids_offset {}; + uint32_t last_expert_n_as {}; + uint32_t last_expert_slot {}; + vk_subbuffer last_expert_count_buf {}; + bool last_expert_count_valid {}; + + // Series 13: Reuse flash_attn_mask_opt across FA layers sharing the identical mask tensor + const ggml_tensor * last_mask_opt_tensor {}; + VkBuffer last_mask_opt_vk_buf {}; + size_t last_mask_opt_offset {}; + uint32_t last_mask_opt_nem0 {}, last_mask_opt_nem1 {}, last_mask_opt_nem2 {}, last_mask_opt_nem3 {}; + size_t last_mask_opt_nb1 {}, last_mask_opt_nb2 {}, last_mask_opt_nb3 {}; + uint32_t last_mask_opt_br {}, last_mask_opt_bc {}; + bool last_mask_opt_valid {}; + bool prealloc_mask_opt_need_sync {}; + + struct { + const ggml_tensor * mask {}; + const ggml_tensor * rel_pos {}; + uint32_t mask_r0 {}; + uint32_t nr {}; + uint32_t extent {}; + uint32_t kv_min {}; + uint32_t kv_max {}; + uint32_t kv_const_end {}; + bool valid {}; + } mask_span_cache[4]; + + // Series 9: Single-Front reusable command buffer LRU cache + zero-submit UMA async readbacks + std::vector replay_cache; + uint64_t replay_lru_clock {}; + uint64_t replay_probation_h1[VK_REPLAY_PROB_SLOTS] {}; + uint64_t replay_probation_h2[VK_REPLAY_PROB_SLOTS] {}; + uint64_t replay_probation_destroy[VK_REPLAY_PROB_SLOTS] {}; + uint32_t replay_probation_clock {}; + const ggml_cgraph * last_cgraph_ptr {}; + double ema_nonreplay_tail_us {}; + double ema_nonreplay_full_us {}; + int64_t last_submit_us {}; + uint32_t replay_consec_misses {}; + int32_t replay_miss_n_nodes {}; + bool recording_replay {}; + bool replay_abort {}; + vk_command_pool * active_replay_cmd_pool {}; + vk_graph_replay_entry * active_replay_entry {}; + int64_t replay_submit_us {}; + std::vector uma_out_memcpys; + // Track which nodes have been used since the last sync, and whether they were written to std::vector unsynced_nodes_written; std::vector unsynced_nodes_read; @@ -1368,6 +1606,9 @@ struct ggml_backend_vk_context { // QSA indexer gather+add+top_k fused into one radix-select bool fused_topk_qsa {}; bool fused_hc_post_gate {}; + bool fused_softcap_argmax {}; + bool fused_add_softcap_argmax {}; + bool fused_inkling_clip_set_rows {}; rms_norm_mode fused_rms_norm_mode {RMS_NORM_COUNT}; // for GGML_VK_PERF_LOGGER diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index f28690f68215..42cab98499cf 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -338,13 +338,273 @@ static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * return range; } +static inline void ggml_vk_invalidate_prealloc_y_ring(ggml_backend_vk_context * ctx) { + ctx->prealloc_y_last_pipeline_used = nullptr; + ctx->prealloc_y_last_tensor_used = nullptr; + ctx->prealloc_y_last_k_padded = false; + for (uint32_t s = 0; s < VK_PREALLOC_RING; ++s) { + ctx->prealloc_y_last_pipeline_ring[s] = nullptr; + ctx->prealloc_y_last_tensor_ring[s] = nullptr; + ctx->prealloc_y_last_k_padded_ring[s] = false; + } +} + +#if defined(__linux__) && defined(__aarch64__) +#include +static cpu_set_t s21_vk_init_cpuset; +static bool s21_vk_has_init_cpuset = false; +static int s21_vk_decode_cpu = -1; + +__attribute__((constructor)) static void s21_vk_capture_init_cpuset() { + CPU_ZERO(&s21_vk_init_cpuset); + if (sched_getaffinity(0, sizeof(s21_vk_init_cpuset), &s21_vk_init_cpuset) == 0 && + CPU_COUNT(&s21_vk_init_cpuset) > 1) { + s21_vk_has_init_cpuset = true; + for (int c = 1; c < CPU_SETSIZE; ++c) { + if (CPU_ISSET(c, &s21_vk_init_cpuset)) { + s21_vk_decode_cpu = c; // e.g. cpu5 in P0 on taskset 0,5-15, keeping P1 (cpu10..15) dark + break; + } + } + if (s21_vk_decode_cpu < 0 && CPU_ISSET(0, &s21_vk_init_cpuset)) { + s21_vk_decode_cpu = 0; + } + } +} + +static void s21_update_agx_decode_thread_affinity(bool want_decode_pin) { + static const bool no_pin = getenv("GGML_VK_NO_PIN_DECODE") != nullptr && atoi(getenv("GGML_VK_NO_PIN_DECODE")) != 0; + if (no_pin || !s21_vk_has_init_cpuset || s21_vk_decode_cpu < 0 || !want_decode_pin) { + return; + } + // Stateless OS affinity check (~80 ns): immune to stale thread_local state after + // server_restore_init_thread_affinity() runs post-warmup so httplib & worker inherit 0,5-15, + // while the very first live inference ubatch immediately re-pins the decode thread to cpu5! + cpu_set_t cur; + CPU_ZERO(&cur); + if (sched_getaffinity(0, sizeof(cur), &cur) == 0 && CPU_COUNT(&cur) > 1) { + cpu_set_t one; + CPU_ZERO(&one); + CPU_SET(s21_vk_decode_cpu, &one); + (void) sched_setaffinity(0, sizeof(one), &one); + } +} +#endif + +static bool ggml_vk_is_apple_agx_coopmat(const vk_device& device); + void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) { - // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep - // during this wait. + bool gen_had_almost_ready = false; if (ctx->almost_ready_fence_pending) { VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence", ctx->device); ctx->device->device.resetFences({ ctx->almost_ready_fence }); ctx->almost_ready_fence_pending = false; + gen_had_almost_ready = true; + } + const int64_t gen_t_ar = ggml_time_us(); + + auto update_asymmetric_ema = [](double & ema, double sample_us) { + if (sample_us <= 0.0) { + return; + } + if (ema <= 0.0) { + ema = sample_us; + } else if (sample_us < ema) { + ema = 0.50 * ema + 0.50 * sample_us; + } else { + ema = 0.85 * ema + 0.15 * sample_us; + } + }; + + auto finish_fence = [&]() { + const int64_t done_us = ggml_time_us(); + ctx->device->device.resetFences({ ctx->fence }); + ctx->fence_submitted = false; + ctx->fence_epoch++; + if (ctx->active_replay_entry != nullptr) { + const double gpu_us = (double) (done_us - ctx->replay_submit_us); + update_asymmetric_ema(ctx->active_replay_entry->ema_gpu_us, gpu_us); + ctx->active_replay_entry = nullptr; + } else if (gen_had_almost_ready) { + update_asymmetric_ema(ctx->ema_nonreplay_tail_us, (double) (done_us - gen_t_ar)); + } else if (ctx->last_submit_us > 0) { + update_asymmetric_ema(ctx->ema_nonreplay_full_us, (double) (done_us - ctx->last_submit_us)); + } + ctx->last_submit_us = 0; + }; + + // gen: GGML_VK_FENCE_WAIT selects how the last part of the graph is waited for: + // default (AGX) Series 20 two-phase zero-spin kernel waitForFences (<= 2 ioctls, 0 getFenceStatus polls) + // spin explicit getFenceStatus + 1000 YIELDs per poll + // block waitForFences (single UINT64_MAX sleep) + // wfe poll, then WFE (aarch64) + // nap poll, then nanosleep 50 us + static const int gen_wait_mode = [] { + const char * m = getenv("GGML_VK_FENCE_WAIT"); + if (m == nullptr) return 0; + if (strcmp(m, "spin") == 0) return 5; + if (strcmp(m, "block") == 0) return 1; + if (strcmp(m, "wfe") == 0) return 2; + if (strcmp(m, "nap") == 0) return 3; + if (strcmp(m, "hybrid") == 0) return 4; + return 0; + }(); + // Series 20 (Pillar S20.2): Clock-Gated ARM64 Double-WFE (sevl;wfe;wfe) + Tight Tail + Prefill Sleep on Apple AGX. + // On Linux schedutil (# CONFIG_UCLAMP_TASK is not set), sleeping >5 ms in waitForFences decays PELT util_avg and + // collapses P-core clock 3.26x (4.104 GHz -> 1.260 GHz), costing -8.5 tok/s across speculative bridges. + // Instead: + // 1. For long prefills (est_us > 100 ms), sleep in kernel waitForFences up to (est_us - 6 ms). + // 2. For decode/verify (< 100 ms), clock-gate the P-core in hardware via ARM64 `sevl; wfe; wfe` (~100 us arch-timer + // event stream, cutting DRM_IOCTL_SYNCOBJ_WAIT syscalls by >99% from ~61% sys -> <1% sys and dropping P-core + // SMC temp ~15-20 C below s19 while keeping schedutil pinned at 4.104 GHz), switching to tight poll in the final + // 300 us before EMA completion for zero quantization tail, and falling back to blocking waitForFences after 1024 + // WFE ticks (~102 ms) so cold/unpredicted long graphs never busy-wait. + if (gen_wait_mode == 0 && ggml_vk_is_apple_agx_coopmat(ctx->device)) { + static const int64_t sleep_min_est_us = getenv("GGML_VK_SLEEP_MIN_EST_US") ? atoll(getenv("GGML_VK_SLEEP_MIN_EST_US")) : 100000; + static const int64_t warm_margin_us = getenv("GGML_VK_REPLAY_MARGIN_US") ? atoll(getenv("GGML_VK_REPLAY_MARGIN_US")) : 6000; + static const int64_t tight_tail_us = getenv("GGML_VK_TIGHT_TAIL_US") ? atoll(getenv("GGML_VK_TIGHT_TAIL_US")) : 80; + static const uint64_t heavy_prefill_flops = getenv("GGML_VK_PREFILL_SLEEP_FLOPS") ? (uint64_t) atoll(getenv("GGML_VK_PREFILL_SLEEP_FLOPS")) : 800000000000ULL; + + int64_t now_us = ggml_time_us(); + double est_us = 0.0; + int64_t sub_origin = 0; + if (ctx->active_replay_entry != nullptr) { + est_us = ctx->active_replay_entry->ema_gpu_us; + sub_origin = ctx->replay_submit_us; + } else if (gen_had_almost_ready) { + est_us = ctx->ema_nonreplay_tail_us; + sub_origin = gen_t_ar; + } else if (ctx->last_submit_us > 0) { + est_us = ctx->ema_nonreplay_full_us; + sub_origin = ctx->last_submit_us; + } + + const bool has_valid_flops = (ctx->last_total_flops != UINT64_MAX && ctx->last_total_flops > 0); + const bool is_heavy_prefill = has_valid_flops && (ctx->last_total_flops >= heavy_prefill_flops); + +#if defined(__linux__) && defined(__aarch64__) + s21_update_agx_decode_thread_affinity(!is_heavy_prefill); +#endif + + // Multi-hundred-GFLOP prefill / mmproj ViT graphs (including multi-chunk replay record & hit!): + // block cleanly in kernel waitForFences instead of burning 4.5 GHz P-core WFE polls on ubatch #1 (est_us == 0)! + if (is_heavy_prefill) { + VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "fence (s21 heavy prefill)", ctx->device); + finish_fence(); + return; + } + + int64_t elapsed_us = sub_origin > 0 ? std::max(0, now_us - sub_origin) : 0; + if (est_us > (double) sleep_min_est_us) { + const int64_t sleep_us = (int64_t) est_us - elapsed_us - warm_margin_us; + if (sleep_us > 1000) { + const vk::Result r = ctx->device->device.waitForFences({ ctx->fence }, true, (uint64_t) sleep_us * 1000ULL); + if (r == vk::Result::eSuccess) { + finish_fence(); + return; + } + if (r != vk::Result::eTimeout) { + throw vk::SystemError(vk::make_error_code(r), "ggml_vulkan: waitForFences (s20 phase 1)"); + } + } + } + if (est_us > 0.0) { + for (uint32_t wfe_poll = 0; wfe_poll < 1024u; ++wfe_poll) { + const vk::Result r = ctx->device->device.getFenceStatus(ctx->fence); + if (r == vk::Result::eSuccess) { + finish_fence(); + return; + } + if (r != vk::Result::eNotReady) { + throw vk::SystemError(vk::make_error_code(r), "ggml_vulkan: getFenceStatus (s20 wfe)"); + } + if (sub_origin > 0) { + now_us = ggml_time_us(); + if ((now_us - sub_origin) + tight_tail_us >= (int64_t) est_us) { + // Final <= 300 us precision window: catch completion without ~50 us WFE event-stream rounding + for (uint32_t tp = 0; tp < 4096u; ++tp) { + const vk::Result rt = ctx->device->device.getFenceStatus(ctx->fence); + if (rt == vk::Result::eSuccess) { + finish_fence(); + return; + } + if (rt != vk::Result::eNotReady) { + throw vk::SystemError(vk::make_error_code(rt), "ggml_vulkan: getFenceStatus (s20 tail)"); + } + for (uint32_t y = 0; y < 64u; ++y) { + YIELD(); + } + } + } + } +#if defined(__aarch64__) + // ERET from getFenceStatus ioctl sets the local Event Register; SEVL+WFE clears it so the second WFE + // genuinely clock-gates the P-core until the ~100 us arch-timer event stream! + __asm__ __volatile__("sevl; wfe; wfe" ::: "memory"); +#else + YIELD(); +#endif + } + } + VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "fence (s20 adaptive)", ctx->device); + finish_fence(); + return; + } + // hybrid: sleep in waitForFences until GGML_VK_FENCE_MARGIN_US (default 300) before the expected end of the graph + // (moving average of the time from the almost-ready fence to the final fence), then spin + if (gen_wait_mode == 4 && gen_had_almost_ready) { + static const int64_t margin_us = getenv("GGML_VK_FENCE_MARGIN_US") ? atoll(getenv("GGML_VK_FENCE_MARGIN_US")) : 300; + static thread_local double ema_tail_us = 0.0; + const int64_t sleep_us = (int64_t) ema_tail_us - margin_us; + if (sleep_us > 50) { + const vk::Result r = ctx->device->device.waitForFences({ ctx->fence }, true, (uint64_t) sleep_us * 1000); + if (r != vk::Result::eSuccess && r != vk::Result::eTimeout) { + throw vk::SystemError(vk::make_error_code(r), "ggml_vulkan: waitForFences (hybrid)"); + } + } + for (;;) { + const vk::Result r = ctx->device->device.getFenceStatus(ctx->fence); + if (r == vk::Result::eSuccess) { + break; + } + if (r != vk::Result::eNotReady) { + throw vk::SystemError(vk::make_error_code(r), "ggml_vulkan: getFenceStatus"); + } + YIELD(); + } + const double tail = (double) (ggml_time_us() - gen_t_ar); + ema_tail_us = ema_tail_us == 0.0 ? tail : 0.8 * ema_tail_us + 0.2 * tail; + finish_fence(); + return; + } + const bool gen_block_wait = gen_wait_mode == 1; + if (gen_wait_mode == 2 || gen_wait_mode == 3) { + for (;;) { + const vk::Result r = ctx->device->device.getFenceStatus(ctx->fence); + if (r == vk::Result::eSuccess) { + break; + } + if (r != vk::Result::eNotReady) { + throw vk::SystemError(vk::make_error_code(r), "ggml_vulkan: getFenceStatus"); + } + if (gen_wait_mode == 2) { +#if defined(__aarch64__) + __asm__ __volatile__("wfe" ::: "memory"); +#else + YIELD(); +#endif + } else { + struct timespec ts = { 0, 50000 }; + nanosleep(&ts, nullptr); + } + } + finish_fence(); + return; + } + if (gen_block_wait) { + VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "fence (blocking)", ctx->device); + finish_fence(); + return; } // Spin (w/pause) waiting for the graph to finish executing. @@ -377,7 +637,14 @@ void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) { YIELD(); } } - ctx->device->device.resetFences({ ctx->fence }); + finish_fence(); +} + +static void ggml_vk_ensure_fence_free(ggml_backend_vk_context * ctx) { + if (ctx->fence_submitted) { + ggml_vk_wait_for_fence(ctx); + ctx->submit_pending = false; + } } static bool ggml_vk_strip_decode_vector(const uint32_t * code, size_t word_count, std::vector & out) { @@ -672,10 +939,11 @@ static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipelin #if VK_HEADER_VERSION >= 287 // Roll the mul_mm BK loop on Asahi Linux. Skip bf16 and the mul_mmq pipelines. - if (device->driver_id == vk::DriverId::eMesaHoneykrisp && + if ((device->driver_id == vk::DriverId::eMesaHoneykrisp || device->borealis_roll_bk) && pipeline->name.rfind("matmul", 0) == 0 && pipeline->name.find("bf16") == std::string::npos && - pipeline->name.find("q8_1") == std::string::npos) { + pipeline->name.find("q8_1") == std::string::npos && + (!device->coopmat_support || (getenv("GGML_VK_CM1_ROLL_BK") && atoi(getenv("GGML_VK_CM1_ROLL_BK")) != 0))) { const uint32_t * src = spirv.empty() ? reinterpret_cast(spv_data) : spirv.data(); size_t src_n = spirv.empty() ? spv_size / sizeof(uint32_t) : spirv.size(); std::vector rolled; @@ -1157,6 +1425,12 @@ void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) { if (ctx) { ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false; + ctx->prealloc_mask_opt_need_sync = false; + for (uint32_t s = 0; s < VK_PREALLOC_RING; ++s) { + ctx->prealloc_y_slot_need_sync[s] = false; + ctx->prealloc_split_k_slot_need_sync[s] = false; + } + ctx->stat_syncs++; } subctx->s->buffer->buf.pipelineBarrier( @@ -1206,6 +1480,106 @@ void ggml_vk_wait_events(vk_context& ctx, std::vector&& events) { ); } +// gen: GGML_VK_BATCH_INVARIANT=1 makes small batches (speculative verification) compute each token exactly as n=1: +// the KV split of flash attention is sized as for one token, and the n=1-only ADD+RMS_NORM partials fusion is off. +static bool gen_batch_invariant() { + static const bool v = getenv("GGML_VK_BATCH_INVARIANT") != nullptr && atoi(getenv("GGML_VK_BATCH_INVARIANT")) != 0; + return v; +} + +// Series 13: Speculative verification batches are small (k <= 8); prompts with n > 8 tokens do not need +// single-token bit-identity and can use full coopmat8x8 FA, mul_mv_mma, mul_mv_mma_id, and cm1 fusions. +static bool gen_batch_invariant_for_n(int64_t n) { + return gen_batch_invariant() && n <= 8; +} + +static bool ggml_vk_fast_fp16_enabled() { + static const bool v = getenv("GGML_VK_FAST_FP16") != nullptr && atoi(getenv("GGML_VK_FAST_FP16")) != 0; + return v; +} + +static bool ggml_vk_exact_s8_enabled() { + static const bool v = getenv("GGML_VK_EXACT_S8") != nullptr && atoi(getenv("GGML_VK_EXACT_S8")) != 0; + return v; +} + +static bool ggml_vk_is_apple_agx_coopmat(const vk_device& device); + +static const char * ggml_backend_vk_repack_buffer_type_name(ggml_backend_buffer_type_t buft) { + return GGML_VK_NAME "_Repack"; + UNUSED(buft); +} + +static inline int ggml_vk_repack_type_idx(ggml_type type) { + switch (type) { + case GGML_TYPE_Q4_K: return 0; + case GGML_TYPE_Q5_K: return 1; + case GGML_TYPE_Q6_K: return 2; + case GGML_TYPE_NVFP4: return 3; + default: return -1; + } +} + +static inline size_t ggml_vk_repack_sb_bytes(ggml_type type) { + switch (type) { + case GGML_TYPE_Q4_K: return 144u; + case GGML_TYPE_Q5_K: return 176u; + case GGML_TYPE_Q6_K: return 224u; + default: return 0u; + } +} + +static inline size_t ggml_vk_repack_alloc_bytes(const ggml_tensor * tensor) { + if (!tensor) { + return 0; + } + if (tensor->type == GGML_TYPE_NVFP4) { + static const bool disable_nvfp4_repack = getenv("GGML_VK_DISABLE_NVFP4_REPACK") != nullptr; + if (disable_nvfp4_repack || tensor->ne[0] <= 0 || tensor->ne[0] % 64 != 0) { + return 0; + } + const size_t s_blks = ((size_t)tensor->ne[0] / 64u) * (size_t)tensor->ne[1]; + if (s_blks == 0 || (s_blks % 4u) != 0u) { + return 0; + } + const size_t n_slices = (size_t)tensor->ne[2] * (size_t)tensor->ne[3]; + return s_blks * n_slices * 36u; + } + if (tensor->ne[0] % 256 != 0) { + return 0; + } + const size_t sb_bytes = ggml_vk_repack_sb_bytes(tensor->type); + if (sb_bytes == 0) { + return 0; + } + const size_t n_sb = (size_t)tensor->ne[0] / 256u; + const size_t n_rows = (size_t)tensor->ne[1] * (size_t)tensor->ne[2] * (size_t)tensor->ne[3]; + return n_rows * n_sb * sb_bytes; +} + +static inline bool ggml_vk_tensor_is_repack(const ggml_tensor * t) { + if (!t) { + return false; + } + ggml_backend_buffer_t buf = t->view_src ? t->view_src->buffer : t->buffer; + return buf && buf->buft && buf->buft->iface.get_name == ggml_backend_vk_repack_buffer_type_name; +} + +static ggml_backend_buffer_type_t * ggml_backend_vk_dev_get_extra_bufts(ggml_backend_dev_t dev); +static ggml_backend_buffer_t ggml_backend_vk_repack_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size); +static size_t ggml_backend_vk_repack_buffer_type_get_alignment(ggml_backend_buffer_type_t buft); +static size_t ggml_backend_vk_repack_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor); +static const ggml_backend_buffer_type_i ggml_backend_vk_repack_buffer_type_interface = { + /* .get_name = */ ggml_backend_vk_repack_buffer_type_name, + /* .alloc_buffer = */ ggml_backend_vk_repack_buffer_type_alloc_buffer, + /* .alloc_buffer_n = */ NULL, + /* .get_alignment = */ ggml_backend_vk_repack_buffer_type_get_alignment, + /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size, + /* .get_alloc_size = */ ggml_backend_vk_repack_buffer_type_get_alloc_size, + /* .get_alloc_size_n = */ NULL, + /* .is_host = */ NULL, +}; + static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc) { vk_fa_tuning_params result{}; @@ -1245,6 +1619,8 @@ static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device, // row_split 1 means higher register use per row, so block size has to be adjusted if (result.row_split == 1) { result.block_rows = n_rows == 2 ? 2 : ((n_rows <= 4 || reduce_block_rows) ? 4 : 8); + } else if (ggml_vk_fast_fp16_enabled() && ggml_vk_is_apple_agx_coopmat(device) && hsv >= 256 && n_rows > 8 && n_rows <= 64) { + result.block_rows = 4; } else { result.block_rows = n_rows <= 4 ? 4 : ((n_rows <= 8 || reduce_block_rows) ? 8 : 16); } @@ -1299,19 +1675,36 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device const uint32_t D = hsk | hsv; - const uint32_t coopmat_block_rows = 16; - const uint32_t coopmat_block_cols = 16; + static const int env_fa_wg256 = getenv("GGML_VK_FA_WG256") ? atoi(getenv("GGML_VK_FA_WG256")) : 1; + const bool kv_f16_or_q8 = (k_type == GGML_TYPE_F16 || k_type == GGML_TYPE_Q8_0) && + (v_type == GGML_TYPE_F16 || v_type == GGML_TYPE_Q8_0); + const bool use_agx_wg256 = !device->coopmat_support_16x16x16_f32acc && + device->coopmat_support_8x8x8_f32acc && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(n_rows) && + kv_f16_or_q8 && + hsv >= 128 && + env_fa_wg256 != 0; + + const uint32_t coopmat_block_rows = 16u; + const uint32_t coopmat_block_cols = 16u; - const uint32_t num_subgroups = 4; + const uint32_t num_subgroups = 4u; + const uint32_t wg_subgroups = use_agx_wg256 ? 8u : 4u; + + static const bool disable_fa_br24 = getenv("GGML_VK_DISABLE_FA_BR24") != nullptr; + const bool use_agx_br24 = use_agx_wg256 && !disable_fa_br24 && + hsk == 128u && hsv == 128u && f32acc && + n_rows > 16u && n_rows <= 24u; // Halves K/V re-reads; only wins on UMA, regresses on discrete RDNA4 const bool double_block_rows = device->uma && (device->architecture == AMD_RDNA3 || device->architecture == AMD_RDNA4) && n_rows >= 64; - result.block_rows = double_block_rows ? 2 * coopmat_block_rows : coopmat_block_rows; + result.block_rows = use_agx_br24 ? 24u : (double_block_rows ? 2 * coopmat_block_rows : coopmat_block_rows); result.block_cols = coopmat_block_cols * num_subgroups; result.row_split = num_subgroups; result.subgroup_size = device->subgroup_size; - result.workgroup_size = num_subgroups * result.subgroup_size; + result.workgroup_size = wg_subgroups * result.subgroup_size; const uint32_t D_lsb = D ^ (D & (D-1)); // extract lowest set bit result.d_split = std::min(std::min(result.subgroup_size, 8u), D_lsb / 4); @@ -1408,7 +1801,7 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, } if (path == FA_COOPMAT1) { - bool shape_ok = (f32acc && device->coopmat_support_16x16x16_f32acc) || + bool shape_ok = (f32acc && (device->coopmat_support_16x16x16_f32acc || device->coopmat_support_8x8x8_f32acc)) || (!f32acc && device->coopmat_support_16x16x16_f16acc); vk_fa_tuning_params params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, allow_flip); bool shmem_ok = ggml_vk_flash_attn_coopmat_shmem_support(device, params, hsk, hsv, f32acc, k_type, v_type); @@ -1420,6 +1813,17 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, if (!shape_ok || !shmem_ok) { path = FA_SCALAR; + } else if (!device->coopmat_support_16x16x16_f32acc && device->coopmat_support_8x8x8_f32acc) { + static const int fa_8x8_min_rows = getenv("GGML_VK_FA_8X8_MIN_ROWS") ? atoi(getenv("GGML_VK_FA_8X8_MIN_ROWS")) : -1; + const int eff_fa_min_rows = (fa_8x8_min_rows >= 0) ? fa_8x8_min_rows : (n_kv >= 64 ? 4 : 8); + const bool kv_8x8_ok = (k_type == GGML_TYPE_BF16 && v_type == GGML_TYPE_BF16) || + ((k_type == GGML_TYPE_F16 || k_type == GGML_TYPE_Q8_0) && + (v_type == GGML_TYPE_F16 || v_type == GGML_TYPE_Q8_0)); + if (ggml_vk_exact_s8_enabled() || gen_batch_invariant_for_n(n_rows) || + !kv_8x8_ok || (hsk % 16 != 0) || (hsv % 16 != 0) || + (int)n_rows < eff_fa_min_rows) { + path = FA_SCALAR; + } } } @@ -1441,18 +1845,32 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, } vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool aligned, bool f32acc, - bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type) { + bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type, + uint32_t extra_flags) { const bool old_amd_windows = device->vendor_id == VK_VENDOR_ID_AMD && device->driver_id == vk::DriverId::eAmdProprietary && (device->architecture == AMD_GCN || device->architecture == AMD_RDNA1 || device->architecture == AMD_RDNA2); - uint32_t flags = (use_mask_opt ? 1 : 0) | - (use_mask ? 2 : 0) | - (use_logit_softcap ? 4 : 0) | - (old_amd_windows ? 8 : 0) | - (use_sparse ? 16 : 0) | - (params.q_in_regs ? 32 : 0) | - (params.flip ? 64 : 0) | - (params.flip_direct ? 128 : 0); + static const int env_fa_swizzle = getenv("GGML_VK_FA_SWIZZLE") ? atoi(getenv("GGML_VK_FA_SWIZZLE")) : 1; + const bool use_lpt_gqa_swizzle = (env_fa_swizzle != 0) && + (extra_flags & 512u) == 0u && + params.path == FA_COOPMAT1 && + !device->coopmat_support_16x16x16_f32acc && + device->coopmat_support_8x8x8_f32acc && + (k_type == GGML_TYPE_F16 || k_type == GGML_TYPE_Q8_0) && + (v_type == GGML_TYPE_F16 || v_type == GGML_TYPE_Q8_0) && + !use_sparse && + !ggml_vk_exact_s8_enabled(); + + uint32_t flags = (use_mask_opt ? 1 : 0) | + (use_mask ? 2 : 0) | + (use_logit_softcap ? 4 : 0) | + (old_amd_windows ? 8 : 0) | + (use_sparse ? 16 : 0) | + (params.q_in_regs ? 32 : 0) | + (params.flip ? 64 : 0) | + (params.flip_direct ? 128 : 0) | + (use_lpt_gqa_swizzle ? 256 : 0) | + extra_flags; const uint32_t subgroup_size = params.disable_subgroups ? 0 : params.subgroup_size; @@ -1669,7 +2087,7 @@ static vk_xe_fa_tuning_params get_xe_fa_tuning_params(const vk_device_struct * d // CM2 uses narrow tiles for 5 <= N <= 32; CM1 uses them for 9 <= N <= 32. static uint32_t ggml_vk_mul_mat_vec_max_cols(const vk_device & device) { - return device->coopmat2 && !device->disable_narrow_mul_mat ? 4u : mul_mat_vec_max_cols; + return device->coopmat2 && !device->disable_narrow_mul_mat ? 4u : device->mmv_max_cols; } static uint32_t ggml_vk_gated_delta_net_shmem_size(uint32_t v, bool coopmat2, bool replay = false) { @@ -1717,12 +2135,11 @@ static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vec break; case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS: - case GGML_TYPE_MXFP4: lut_size = 4*16; break; + case GGML_TYPE_MXFP4: case GGML_TYPE_NVFP4: - // Same kvalues budget as MXFP4 plus ue4m3_fp32_lut[256] (types.glsl, DATA_A_NVFP4). - lut_size = 4*16 + 256u * (uint32_t)sizeof(float); + lut_size = 0; break; default: break; @@ -1732,13 +2149,16 @@ static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vec // Needs to stay aligned with ggml_vk_mul_mm_spec. const bool intel_shmem_stride_pad_zero = device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support && device->driver_id == vk::DriverId::eIntelProprietaryWindows; - const uint32_t bank_conflict_offset = intel_shmem_stride_pad_zero ? 0 : (device->coopmat_support ? 8 : 1); + const bool agx_reshaped_dense = ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled() && !mul_mat_id && !getenv("GGML_VK_NO_SLM_RESHAPE"); + const uint32_t bank_conflict_offset = (intel_shmem_stride_pad_zero || agx_reshaped_dense) ? 0 : (device->coopmat_support ? 8 : 1); const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float); const uint32_t warps = warptile[0] / warptile[10]; const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size; const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0; - const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] * warps * sizeof(float) : 0; + const uint32_t coopmat_stage = device->coopmat_support + ? (ggml_vk_is_apple_agx_coopmat(device) ? (ggml_vk_exact_s8_enabled() ? (uint32_t)sizeof(float) : 0u) : warptile[7] * warptile[8] * warps * (uint32_t)sizeof(float)) + : 0; const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size; const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize; @@ -1754,6 +2174,19 @@ static bool ggml_vk_mmq_use_sudot(const vk_device& device) { return device->integer_dot_mixed && !device->integer_dot_signed; } +static bool ggml_vk_is_apple_agx_coopmat(const vk_device& device) { + if (!device->coopmat_support || device->coopmat_m != 8 || device->coopmat_n != 8 || device->coopmat_k != 8) { + return false; + } +#if VK_HEADER_VERSION >= 287 + if (device->driver_id == vk::DriverId::eMesaHoneykrisp) { + return true; + } +#endif + return device->borealis_medium_tiles || device->borealis_roll_bk || + (device->vendor_id == 0x10005 && device->properties.deviceID == 0x6041); +} + static bool ggml_vk_matmul_int_shmem_support(const vk_device& device, const std::vector& warptile, bool mul_mat_id, ggml_type src0_type) { // FLOAT_TYPE in the shader is float16_t with fp16 support, otherwise float. @@ -1865,9 +2298,7 @@ static bool ggml_vk_matmul_cm1_int_shmem_support(const vk_device& device, const if (has_kvalues) { total += 16u * (uint32_t)sizeof(int8_t); // cm1_kvalues[16] } - if (src0_type == GGML_TYPE_NVFP4 && !device->ocp_fp4) { - total += 256u * (uint32_t)sizeof(float); // ue4m3_fp32_lut[256] - } + // Series 17: MXFP4 and NVFP4 decode via branchless ALU (0 LUT shared memory) if (mul_mat_id) { total += BN * 2u * (uint32_t)sizeof(uint16_t); // row_ids[BN] (u16vec2) } @@ -2010,7 +2441,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms, l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k, l_mmq_cm1_wg_denoms_k, m_mmq_cm1_wg_denoms_k, s_mmq_cm1_wg_denoms_k, - l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms; + l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms, gen_s_mmqid_denoms; uint32_t l_align, m_align, s_align; @@ -2166,6 +2597,80 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } } + if (ggml_vk_is_apple_agx_coopmat(device)) { + if (ggml_vk_exact_s8_enabled()) { + s_warptile = { 32, 32, 16, 32, 32, 16, 2, tm_s, tn_s, tk_s, 32 }; + m_warptile = { 128, 64, 64, 16, 32, 32, 2, tm_m, tn_m, tk_m, 32 }; + l_warptile = { 256, 128, 64, 16, 32, 32, 2, tm_l, tn_l, tk_l, 32 }; + s_warptile_mmq = { 32, 32, 16, 32, 32, 16, 2, tm_s, tn_s, tk_s, 32 }; + m_warptile_mmq = { 128, 64, 64, 32, 32, 32, 2, tm_m, tn_m, tk_m, 32 }; + l_warptile_mmq = { 256, 128, 64, 32, 32, 32, 2, tm_l, tn_l, tk_l, 32 }; + s_warptile_id = s_warptile; + m_warptile_id = m_warptile; + l_warptile_id = l_warptile; + s_warptile_mmqid = { 128, 128, 16, 32, 64, 8, 2, tm_s, tn_s, tk_s, 32 }; + m_warptile_mmqid = m_warptile_mmq; + l_warptile_mmqid = l_warptile_mmq; + l_mmq_wg_denoms = l_wg_denoms = { 128, 64, 1 }; + m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 }; + s_mmq_wg_denoms = s_wg_denoms = { 32, 16, 1 }; + l_mmqid_wg_denoms = { 128, 64, 1 }; + m_mmqid_wg_denoms = { 64, 64, 1 }; + s_mmqid_wg_denoms = { 128, 16, 1 }; + } else { + // AGX G17P 8x8x8 simdgroup_matrix (f32matmad8x8): keep <=16 8x8 accumulators (64 half-regs) per subgroup + // with reshaped 8x8 buf_a + buf_b (zero bank-pad waste) and BK=32 alignment. + s_warptile = { 64, 32, 32, 32, 32, 16, 2, tm_s, tn_s, tk_s, 32 }; + m_warptile = { 128, 64, 64, 32, 32, 32, 2, tm_m, tn_m, tk_m, 32 }; + l_warptile = { 256, 128, 64, 32, 32, 32, 2, tm_l, tn_l, tk_l, 32 }; + s_warptile_mmq = { 32, 32, 16, 32, 32, 16, 2, tm_s, tn_s, tk_s, 32 }; + m_warptile_mmq = { 128, 64, 64, 32, 32, 32, 2, tm_m, tn_m, tk_m, 32 }; + l_warptile_mmq = { 256, 128, 64, 32, 32, 32, 2, tm_l, tn_l, tk_l, 32 }; + s_warptile_id = s_warptile; + m_warptile_id = m_warptile; + l_warptile_id = l_warptile; + s_warptile_mmqid = { 128, 64, 32, 32, 32, 16, 2, tm_s, tn_s, tk_s, 32 }; + m_warptile_mmqid = { 128, 64, 64, 32, 32, 32, 2, tm_m, tn_m, tk_m, 32 }; + l_warptile_mmqid = l_warptile_mmq; + l_mmq_wg_denoms = l_wg_denoms = { 128, 64, 1 }; + m_wg_denoms = { 64, 64, 1 }; + m_mmq_wg_denoms = { 64, 64, 1 }; + s_wg_denoms = { 32, 32, 1 }; + s_mmq_wg_denoms = { 32, 16, 1 }; + l_mmqid_wg_denoms = { 128, 64, 1 }; + m_mmqid_wg_denoms = { 64, 64, 1 }; + s_mmqid_wg_denoms = { 64, 32, 1 }; + l_align = 32; + m_align = 32; + s_align = 32; + } + } + auto gen_parse_warptile = [](const char * env_name, std::vector& wt, std::array& denoms) { + if (const char * gs = getenv(env_name)) { + std::vector v; + for (const char * c = gs; *c; ) { char * end = nullptr; v.push_back((uint32_t) strtoul(c, &end, 10)); c = end; if (*c == ',') c++; else if (*c) break; } + GGML_ASSERT(v.size() == 11 && "warptile override needs 11 values"); + wt = v; + denoms = { v[1], v[2], 1 }; + } + }; + gen_parse_warptile("GGML_VK_MMQ_S", s_warptile_mmq, s_mmq_wg_denoms); + gen_parse_warptile("GGML_VK_MMQ_M", m_warptile_mmq, m_mmq_wg_denoms); + gen_parse_warptile("GGML_VK_MMQ_L", l_warptile_mmq, l_mmq_wg_denoms); + + // gen: GGML_VK_MMQID_S="BLOCK,BM,BN,BK,WM,WN,WMITER,TM,TN,TK,WARP" replaces the small quantized MUL_MAT_ID tile + // (and enables it on Borealis, which otherwise runs only the medium 64x64 tile): an expert with ~8 rows in a + // 64-column tile computes 56 empty columns. Each output's sum over K is unchanged. + if (const char * gs = getenv("GGML_VK_MMQID_S")) { + std::vector v; + for (const char * c = gs; *c; ) { char * end = nullptr; v.push_back((uint32_t) strtoul(c, &end, 10)); c = end; if (*c == ',') c++; else if (*c) break; } + GGML_ASSERT(v.size() == 11 && "GGML_VK_MMQID_S needs 11 values"); + s_warptile_mmqid = v; + gen_s_mmqid_denoms = { v[1], v[2], 1 }; + } else { + gen_s_mmqid_denoms = { s_warptile_mmqid[1], s_warptile_mmqid[2], 1 }; + } + const bool use_cm1_int = device->coopmat_int_support && (device->architecture == AMD_RDNA3 || device->architecture == AMD_RDNA4); @@ -2308,6 +2813,176 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { has_claimed_task = true; } } + + // gen: mat-vec / mul_mv_mma twins (mode: 1 = single-op epilogue, 2 = PAIR_MM, 3 = PAIR_GLU), compiled lazily when requested + const bool is_mmv_twin = strncmp(name, "mul_mat_vec", 11) == 0 && strstr(name, "p021") == nullptr && strstr(name, "_nc_") == nullptr; + const bool is_mma_twin = strncmp(name, "mul_mv_mma", 10) == 0; + const bool is_mma_id_twin = strncmp(name, "mul_mv_mma_id", 13) == 0; + if (is_mmv_twin || is_mma_twin) { + const size_t mode_idx = is_mma_twin ? 4u : 3u; + for (vk_pipeline * b = &base_pipeline; *b; b = &(*b)->next) { + const struct { vk_pipeline * slot; const char * sfx; uint32_t mode; uint32_t kp_cap; } twins[5] = { + { &(*b)->gen_glu, "_glu", 1u, 0u }, + { &(*b)->gen_pair_mm, "_pairmm", 2u, 0u }, + { &(*b)->gen_pair_glu, "_pairglu", 3u, 0u }, + { &(*b)->gen_fast_ep, "_fastep", 4u, 0u }, + { &(*b)->gen_fast_ep_kp2, "_fastepkp2", 4u, 2u }, + }; + for (const auto & tw : twins) { + if ((is_mma_id_twin && tw.mode == 2u) || (!is_mma_twin && tw.mode == 4u) || (!is_mma_id_twin && tw.kp_cap != 0u)) { + continue; + } + static const int env_pglu_nt1 = getenv("GGML_VK_MMA_ID_PGLU_NT1") ? atoi(getenv("GGML_VK_MMA_ID_PGLU_NT1")) : 1; + static const int env_fep_nt1 = getenv("GGML_VK_MMA_ID_FEP_NT1") ? atoi(getenv("GGML_VK_MMA_ID_FEP_NT1")) : 0; + static const int env_fep_nt = getenv("GGML_VK_MMA_ID_FEP_NT") ? atoi(getenv("GGML_VK_MMA_ID_FEP_NT")) : 2; + static const int env_fep_nt4_min_rt = getenv("GGML_VK_MMA_ID_FEP_NT4_MIN_RT") ? atoi(getenv("GGML_VK_MMA_ID_FEP_NT4_MIN_RT")) : 1; + static const int env_fep_nt4_max_rt = getenv("GGML_VK_MMA_ID_FEP_NT4_MAX_RT") ? atoi(getenv("GGML_VK_MMA_ID_FEP_NT4_MAX_RT")) : 3; + const bool mma_id_twin_nt1 = is_mma_twin && + specialization_constants.size() >= 4 && + specialization_constants[1] == 2u && + specialization_constants[3] == 1u && + ((tw.mode == 3u && ((env_pglu_nt1 == 1 && specialization_constants[2] >= 4u) || + (env_pglu_nt1 >= 2 && specialization_constants[2] >= 2u))) || + (is_mma_id_twin && tw.mode == 4u && ((env_fep_nt1 == 1 && specialization_constants[2] >= 4u) || + (env_fep_nt1 >= 2 && specialization_constants[2] >= 2u)))); + const bool mma_id_twin_nt4 = is_mma_id_twin && !mma_id_twin_nt1 && + tw.mode == 4u && env_fep_nt == 4 && + specialization_constants.size() >= 3 && + specialization_constants[0] == 4u && + specialization_constants[1] == 2u && + (int)specialization_constants[2] >= env_fep_nt4_min_rt && + (int)specialization_constants[2] <= env_fep_nt4_max_rt; + const std::array twin_denoms = mma_id_twin_nt1 + ? std::array{ wg_denoms[0] / 2u, wg_denoms[1], wg_denoms[2] } + : (mma_id_twin_nt4 + ? std::array{ wg_denoms[0] * 2u, wg_denoms[1], wg_denoms[2] } + : wg_denoms); + vk_pipeline & twin = *tw.slot; + if (!twin) { + twin = std::make_shared(); + } + if (!twin->initialized) { + twin->name = std::string(name) + tw.sfx; + twin->parameter_count = parameter_count; + twin->push_constant_size = push_constant_size; + twin->wg_denoms = twin_denoms; + twin->align = align; + twin->initialized = true; +#if defined(VK_EXT_shader_64bit_indexing) + twin->is_64b_indexing = (*b)->is_64b_indexing; +#endif + } + const bool can_lora_twin = !is_mma_id_twin && strncmp(name, "mul_mat_vec_id", 14) != 0 && parameter_count == 7u; + if (can_lora_twin) { + vk_pipeline & ltwin = twin->gen_lora_twin; + if (!ltwin) { + ltwin = std::make_shared(); + } + if (!ltwin->initialized) { + ltwin->name = twin->name + "_lora"; + ltwin->parameter_count = 11u; + ltwin->push_constant_size = push_constant_size; + ltwin->wg_denoms = twin_denoms; + ltwin->align = align; + ltwin->initialized = true; +#if defined(VK_EXT_shader_64bit_indexing) + ltwin->is_64b_indexing = (*b)->is_64b_indexing; +#endif + } + } + auto make_twin_sc = [&](bool with_lora) { + std::vector sc = specialization_constants; + if (mma_id_twin_nt1) { + sc[1] = 1u; + } else if (mma_id_twin_nt4) { + sc[1] = 4u; + } + if (!is_mma_id_twin && is_mma_twin && sc.size() >= 7 && sc[5] != 0u && sc[2] >= 4u && tw.mode == 3u) { + static const uint32_t env_twin_shb = getenv("GGML_VK_MMA_TWIN_SHB") ? (uint32_t)atoi(getenv("GGML_VK_MMA_TWIN_SHB")) : 12u; + sc[5] = env_twin_shb; + } + if (is_mma_id_twin && sc.size() >= 7 && sc[5] != 0u) { + const uint32_t wg_sg_val = sc[0]; + const uint32_t id_rt_val = sc[2]; + if (tw.mode == 3u) { + const uint32_t def_shb = (id_rt_val >= 4u) ? 6u : ((id_rt_val == 3u) ? 7u : 8u); + const uint32_t def_kp = (id_rt_val == 3u || id_rt_val == 4u || (wg_sg_val >= 8u && id_rt_val >= 3u)) ? 2u : 1u; + sc[5] = getenv("GGML_VK_MMA_PGLU_SHB") ? (uint32_t)atoi(getenv("GGML_VK_MMA_PGLU_SHB")) : def_shb; + sc[6] = getenv("GGML_VK_MMA_PGLU_KP") ? (uint32_t)atoi(getenv("GGML_VK_MMA_PGLU_KP")) : def_kp; + } else if (tw.mode == 4u) { + const uint32_t def_shb = (id_rt_val >= 4u) ? 6u : 7u; + uint32_t def_kp = (id_rt_val >= 5u) ? ((wg_sg_val >= 8u) ? 2u : 1u) : ((id_rt_val >= 3u) ? 2u : 4u); + if (tw.kp_cap != 0u && def_kp > tw.kp_cap) { + def_kp = tw.kp_cap; + } + sc[5] = getenv("GGML_VK_MMA_FASTEP_SHB") ? (uint32_t)atoi(getenv("GGML_VK_MMA_FASTEP_SHB")) : def_shb; + sc[6] = getenv("GGML_VK_MMA_FASTEP_KP") ? (uint32_t)atoi(getenv("GGML_VK_MMA_FASTEP_KP")) : def_kp; + } + } + while (sc.size() < mode_idx) { + sc.push_back(1); + } + if (sc.size() == mode_idx) { + sc.push_back(tw.mode); + } else { + sc[mode_idx] = tw.mode; + } + if (with_lora) { + static constexpr uint32_t k_mmv_defs[7] = { 32u, 1u, 1u, 0u, 1u, 0u, 0u }; + static constexpr uint32_t k_mma_defs[10] = { 1u, 2u, 1u, 1u, 0u, 1u, 1u, 1u, 0u, 0u }; + const size_t lora_idx = is_mma_twin ? 9u : 6u; + const uint32_t * defs = is_mma_twin ? k_mma_defs : k_mmv_defs; + while (sc.size() < lora_idx) { + sc.push_back(defs[sc.size()]); + } + if (sc.size() == lora_idx) { + sc.push_back(1u); + } else { + sc[lora_idx] = 1u; + } + } + return sc; + }; + if (can_lora_twin && twin->gen_lora_twin.get() == requested.get() && !twin->gen_lora_twin->compiled) { + vk_pipeline & ltwin = twin->gen_lora_twin; + wait_pipeline = ltwin; + if (!ltwin->compile_pending) { + ltwin->compile_pending = true; + claimed_task.pipeline = ltwin; + claimed_task.spv_size = spv_size; + claimed_task.spv_data = spv_data; + claimed_task.entrypoint = entrypoint; + claimed_task.parameter_count = 11u; + claimed_task.wg_denoms = twin_denoms; + claimed_task.specialization_constants = make_twin_sc(true); + claimed_task.disable_robustness = disable_robustness; + claimed_task.require_full_subgroups = require_full_subgroups; + claimed_task.required_subgroup_size = required_subgroup_size; + has_claimed_task = true; + } + continue; + } + if (twin.get() != requested.get() || twin->compiled) { + continue; + } + wait_pipeline = twin; + if (!twin->compile_pending) { + twin->compile_pending = true; + claimed_task.pipeline = twin; + claimed_task.spv_size = spv_size; + claimed_task.spv_data = spv_data; + claimed_task.entrypoint = entrypoint; + claimed_task.parameter_count = parameter_count; + claimed_task.wg_denoms = twin_denoms; + claimed_task.specialization_constants = make_twin_sc(false); + claimed_task.disable_robustness = disable_robustness; + claimed_task.require_full_subgroups = require_full_subgroups; + claimed_task.required_subgroup_size = required_subgroup_size; + has_claimed_task = true; + } + } + } + } }; auto const &ggml_vk_create_pipeline2 = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const char *entrypoint, @@ -2339,6 +3014,15 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { spv_data = flash_attn_f32_f16_fp32_data; spv_size = flash_attn_f32_f16_fp32_len; name = aligned ? "flash_attn_f32_bf16_aligned" : "flash_attn_f32_bf16"; + } else if ((fa.first.flags & 1024u) != 0u) { + if (device->dot2_f16) { + spv_data = flash_attn_vec_mhm_f32_f16_dot2_data; + spv_size = flash_attn_vec_mhm_f32_f16_dot2_len; + } else { + spv_data = flash_attn_vec_mhm_f32_f16_data; + spv_size = flash_attn_vec_mhm_f32_f16_len; + } + name = aligned ? "flash_attn_vec_mhm_f32_f16_aligned" : "flash_attn_vec_mhm_f32_f16"; } else if (use_mmq) { #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) if (device->fp16) { @@ -2365,7 +3049,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } name = aligned ? "flash_attn_f32_f16_aligned" : "flash_attn_f32_f16"; } - ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8, + ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 10, sizeof(vk_flash_attn_push_constants), {Br, 1, 1}, get_fa_spec_constants(fa.first), aligned ? Bc : 1, true, !fa_ds, !fa_ds ? fa_sgs : 0); @@ -2388,6 +3072,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const void * spv_data; size_t spv_size; const char *name; + const bool use_8x8_fa = !device->coopmat_support_16x16x16_f32acc && device->coopmat_support_8x8x8_f32acc; + if (use_8x8_fa && !f32acc) continue; if (bf16_kv) { #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) if (!device->coopmat_bf16_support) continue; @@ -2396,8 +3082,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { spv_size = flash_attn_f32_f16_bf16_flip_cm1_len; name = aligned ? "flash_attn_f32_bf16_aligned_flip_cm1" : "flash_attn_f32_bf16_flip_cm1"; } else { - spv_data = flash_attn_f32_f16_bf16_cm1_data; - spv_size = flash_attn_f32_f16_bf16_cm1_len; + spv_data = use_8x8_fa ? flash_attn_f32_f16_bf16_8x8_cm1_data : flash_attn_f32_f16_bf16_cm1_data; + spv_size = use_8x8_fa ? flash_attn_f32_f16_bf16_8x8_cm1_len : flash_attn_f32_f16_bf16_cm1_len; name = aligned ? "flash_attn_f32_bf16_aligned_cm1" : "flash_attn_f32_bf16_cm1"; } #else @@ -2408,11 +3094,19 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { else { spv_data = flash_attn_f32_f16_flip_f16acc_cm1_data; spv_size = flash_attn_f32_f16_flip_f16acc_cm1_len; } name = aligned ? "flash_attn_f32_f16_aligned_flip_cm1" : "flash_attn_f32_f16_flip_cm1"; } else { - if (f32acc) { spv_data = flash_attn_f32_f16_cm1_data; spv_size = flash_attn_f32_f16_cm1_len; } - else { spv_data = flash_attn_f32_f16_f16acc_cm1_data; spv_size = flash_attn_f32_f16_f16acc_cm1_len; } + if (use_8x8_fa) { + spv_data = flash_attn_f32_f16_8x8_cm1_data; + spv_size = flash_attn_f32_f16_8x8_cm1_len; + } else if (f32acc) { + spv_data = flash_attn_f32_f16_cm1_data; + spv_size = flash_attn_f32_f16_cm1_len; + } else { + spv_data = flash_attn_f32_f16_f16acc_cm1_data; + spv_size = flash_attn_f32_f16_f16acc_cm1_len; + } name = aligned ? "flash_attn_f32_f16_aligned_cm1" : "flash_attn_f32_f16_cm1"; } - ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8, + ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 10, sizeof(vk_flash_attn_push_constants), {Br, 1, 1}, get_fa_spec_constants(fa.first), aligned ? Bc : 1, true, !fa_ds, !fa_ds ? fa_sgs : 0); @@ -2449,30 +3143,46 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { if (f32acc) { spv_data = flash_attn_f32_f16_cm2_data; spv_size = flash_attn_f32_f16_cm2_len; name = "flash_attn_f32_f16_f32acc_cm2"; } else { spv_data = flash_attn_f32_f16_f16acc_cm2_data; spv_size = flash_attn_f32_f16_f16acc_cm2_len; name = "flash_attn_f32_f16_f16acc_cm2"; } } - ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8, + ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 10, sizeof(vk_flash_attn_push_constants), {Br, 1, 1}, get_fa_spec_constants(fa.first), aligned ? Bc : 1, true, false, 0); } } #endif - auto const &ggml_vk_mul_mm_spec = [&device](std::vector spec, bool aligned) { + static const uint32_t agx_slm_reshape = (getenv("GGML_VK_NO_SLM_RESHAPE") || ggml_vk_exact_s8_enabled()) ? 0u : 1u; + const uint32_t agx_shmem_pad = ggml_vk_exact_s8_enabled() ? 4u : 2u; + const uint32_t env_mm_kunroll = getenv("GGML_VK_MM_KUNROLL") ? (uint32_t)atoi(getenv("GGML_VK_MM_KUNROLL")) : 9u; + const uint32_t agx_direct_mode = ggml_vk_exact_s8_enabled() ? 1u + : (env_mm_kunroll == 9u) ? 5u + : (env_mm_kunroll == 8u) ? 4u + : (env_mm_kunroll == 1u) ? 3u + : (env_mm_kunroll == 2u) ? 2u : 1u; + auto const &ggml_vk_mul_mm_spec = [&device, agx_shmem_pad, agx_direct_mode](std::vector spec, bool aligned) { spec.push_back(aligned ? 1u : 0u); // constantID=11: ALIGNED if (device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support && device->driver_id == vk::DriverId::eIntelProprietaryWindows) { spec.push_back(0u); // constantID=12: SHMEM_STRIDE_PAD = 0 spec.push_back(1u); // constantID=13: APPLY_SLM_A_RESHAPE = true + } else if (ggml_vk_is_apple_agx_coopmat(device)) { + spec.push_back(agx_shmem_pad); // constantID=12: SHMEM_STRIDE_PAD + spec.push_back(agx_slm_reshape); // constantID=13: APPLY_SLM_A_RESHAPE + spec.push_back(agx_direct_mode); // constantID=14: AGX_DIRECT_STORE } return spec; }; - auto const &ggml_vk_mul_mm_spec_quant = [&device](std::vector spec, bool aligned, uint32_t type) { + auto const &ggml_vk_mul_mm_spec_quant = [&device, agx_shmem_pad, agx_direct_mode](std::vector spec, bool aligned, uint32_t type) { spec.push_back(aligned ? 1u : 0u); // constantID=11: ALIGNED spec.push_back(type); // constantID=12: MmTypeA if (device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support && device->driver_id == vk::DriverId::eIntelProprietaryWindows) { spec.push_back(0u); // constantID=13: SHMEM_STRIDE_PAD = 0 spec.push_back(1u); // constantID=14: APPLY_SLM_A_RESHAPE = true + } else if (ggml_vk_is_apple_agx_coopmat(device)) { + spec.push_back(agx_shmem_pad); // constantID=13: SHMEM_STRIDE_PAD + spec.push_back(agx_slm_reshape); // constantID=14: APPLY_SLM_A_RESHAPE + spec.push_back(agx_direct_mode); // constantID=15: AGX_DIRECT_STORE } return spec; }; @@ -2510,7 +3220,9 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { uint32_t push_constant_size, uint32_t param_count, const spec_fn_t& spec_fn, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0, - bool create_aligned = true, bool pin_subgroup_to_warp = false + bool create_aligned = true, bool pin_subgroup_to_warp = false, + size_t fused_spv_len = 0, const void* fused_spv_data = nullptr, + uint32_t fused_pc_size = 0, uint32_t fused_param_count = 0, uint32_t fused_mode_const_id = 15 ) { GGML_ASSERT(!key.stream_k || (!key.mul_mat_id && param_count == 3 && push_constant_size == sizeof(vk_mat_mat_push_constants) && create_aligned)); // Non-ID matmul shaders declare the Stream-K scratch binding in all specializations. @@ -2570,6 +3282,74 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { tc.wg_denoms, spec, tc.align, disable_robustness, rfs, rsgs); } + + if (fused_spv_data != nullptr) { + const bool can_pair_glu = tc.warptile.size() >= 8 && + tc.warptile[1] >= 16 && (tc.warptile[1] % 2 == 0) && + (tc.warptile[4] % 2 == 0) && + ((tc.warptile[4] / tc.warptile[7]) % 2 == 0); + auto attach_mm_twins = [&](vk_pipeline & base_pl, bool is_aligned) { + for (vk_pipeline * b = &base_pl; *b; b = &(*b)->next) { + const struct { + vk_pipeline * slot; + const char * sfx; + uint32_t mode; + std::array denoms; + bool enabled; + } twins[4] = { + { &(*b)->gen_glu, "_mmep", 1u, tc.wg_denoms, true }, + { &(*b)->gen_pair_glu, "_mmpairglu", 2u, { tc.wg_denoms[0] / 2u, tc.wg_denoms[1], tc.wg_denoms[2] }, can_pair_glu }, + { &(*b)->gen_pair_mm, "_mmpairmm", 3u, tc.wg_denoms, !key.mul_mat_id }, + { &(*b)->gen_fast_ep, key.mul_mat_id ? "_mmfastep" : "_mmbias", 4u, tc.wg_denoms, true }, + }; + for (const auto & tw : twins) { + if (!tw.enabled) continue; + vk_pipeline & twin = *tw.slot; + if (!twin) { + twin = std::make_shared(); + } + if (!twin->initialized) { + twin->name = (*b)->name + tw.sfx; + twin->parameter_count = fused_param_count; + twin->push_constant_size = fused_pc_size; + twin->wg_denoms = tw.denoms; + twin->align = (*b)->align; + twin->initialized = true; +#if defined(VK_EXT_shader_64bit_indexing) + twin->is_64b_indexing = (*b)->is_64b_indexing; +#endif + } + if (twin.get() != requested.get() || twin->compiled) { + continue; + } + wait_pipeline = twin; + if (!twin->compile_pending) { + twin->compile_pending = true; + std::vector sc = spec_fn(tc.warptile, is_aligned); + if (sc.size() == fused_mode_const_id - 3) sc.push_back(4u); // SHMEM_STRIDE_PAD + if (sc.size() == fused_mode_const_id - 2) sc.push_back(0u); // APPLY_SLM_A_RESHAPE + if (sc.size() == fused_mode_const_id - 1) sc.push_back(0u); // AGX_DIRECT_STORE + sc.push_back(tw.mode); // MM_FUSE_MODE + claimed_task.pipeline = twin; + claimed_task.spv_size = fused_spv_len; + claimed_task.spv_data = fused_spv_data; + claimed_task.entrypoint = "main"; + claimed_task.parameter_count = fused_param_count; + claimed_task.wg_denoms = tw.denoms; + claimed_task.specialization_constants = std::move(sc); + claimed_task.disable_robustness = disable_robustness; + claimed_task.require_full_subgroups = rfs; + claimed_task.required_subgroup_size = rsgs; + has_claimed_task = true; + } + } + } + }; + attach_mm_twins(vec[i].unaligned, false); + if (vec[i].aligned) { + attach_mm_twins(vec[i].aligned, true); + } + } } }; @@ -2632,7 +3412,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } }; auto add_narrow_n_cm1 = [&](std::vector& configs, ggml_type type, bool is_id) { - if (is_id || configs.empty()) { + if (is_id || configs.empty() || (ggml_vk_is_apple_agx_coopmat(device) && ggml_vk_exact_s8_enabled())) { return; } add_narrow_n_cm1_tile(configs, type, 16); @@ -2640,7 +3420,17 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { }; std::vector tc_mm = {{s_warptile, s_wg_denoms, s_align}, {m_warptile, m_wg_denoms, m_align}, {l_warptile, l_wg_denoms, l_align}}; - std::vector tc_mmq = {{s_warptile_mmq, s_mmq_wg_denoms, s_align}, {m_warptile_mmq, m_mmq_wg_denoms, m_align}, {l_warptile_mmq, l_mmq_wg_denoms, l_align}}; + // gen: GGML_VK_MMQ_M="BLOCK,BM,BN,BK,WM,WN,WMITER,TM,TN,TK,WARP" replaces the medium quantized matmul tile (the only + // one Borealis runs), for a register/shared-memory tile sweep on the M4 Max + std::array gen_m_mmq_denoms = m_mmq_wg_denoms; + if (const char * gs = getenv("GGML_VK_MMQ_M")) { + std::vector v; + for (const char * c = gs; *c; ) { char * end = nullptr; v.push_back((uint32_t) strtoul(c, &end, 10)); c = end; if (*c == ',') c++; else if (*c) break; } + GGML_ASSERT(v.size() == 11 && "GGML_VK_MMQ_M needs 11 values"); + m_warptile_mmq = v; + gen_m_mmq_denoms = { v[1], v[2], 1 }; + } + std::vector tc_mmq = {{s_warptile_mmq, s_mmq_wg_denoms, s_align}, {m_warptile_mmq, gen_m_mmq_denoms, m_align}, {l_warptile_mmq, l_mmq_wg_denoms, l_align}}; #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) if (device->coopmat2) { @@ -2772,23 +3562,35 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const bool cm1_pin = device->vendor_id == VK_VENDOR_ID_INTEL; // Intel coopmat1 uses a dedicated large-tile config for quant matmul_id. - std::vector tc_mmq_id = tc_mmq; + const uint32_t s_mmqid_align = std::max(s_align, s_warptile_mmqid[1]); + std::vector tc_id = {{s_warptile_id, s_wg_denoms, s_align}, {m_warptile_id, m_wg_denoms, m_align}, {l_warptile_id, l_wg_denoms, l_align}}; + std::vector tc_mmq_id = { + {s_warptile_mmqid, gen_s_mmqid_denoms, s_mmqid_align}, + {m_warptile_mmqid, m_mmqid_wg_denoms, m_align}, + {l_warptile_mmqid, l_mmqid_wg_denoms, l_align}, + }; if (cm1_pin) { tc_mmq_id[2] = { { 512, 128, 128, 32, 32, 32, 2, device->coopmat_m, device->coopmat_n, device->coopmat_k, 32 }, { 128, 128, 1 }, 32 }; } auto cm1_create = [&](vk_matmul_pipeline_key key, const std::vector& tc_base, - const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc) { + const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc, + size_t flen = 0, const void* fdata = nullptr) { auto tc = filter_tc(tc_base, key.type_a, key.mul_mat_id); add_narrow_n_cm1(tc, key.type_a, key.mul_mat_id); - if (!tc.empty()) create_mm_pipelines(key, tc, name, len, data, pc_size, pc, cm1_spec, false, true, 0, true, cm1_pin); + const uint32_t fpc_size = key.mul_mat_id ? sizeof(vk_mat_mat_id_fused_push_constants) : sizeof(vk_mat_mat_fused_push_constants); + const uint32_t fpc = key.mul_mat_id ? 8u : 6u; + if (!tc.empty()) create_mm_pipelines(key, tc, name, len, data, pc_size, pc, cm1_spec, true, true, 0, true, cm1_pin, flen, fdata, fpc_size, fpc, 15); }; auto cm1_create_quant = [&](vk_matmul_pipeline_key key, const std::vector& tc_base, - const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc) { + const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc, + size_t flen = 0, const void* fdata = nullptr) { spec_fn_t qs = [&, type_a=key.type_a](const std::vector& wt, bool a) { return ggml_vk_mul_mm_spec_quant(wt, a, (uint32_t)type_a); }; auto tc = filter_tc(tc_base, key.type_a, key.mul_mat_id); add_narrow_n_cm1(tc, key.type_a, key.mul_mat_id); - if (!tc.empty()) create_mm_pipelines(key, tc, name, len, data, pc_size, pc, qs, false, true, 0, true, cm1_pin); + const uint32_t fpc_size = key.mul_mat_id ? sizeof(vk_mat_mat_id_fused_push_constants) : sizeof(vk_mat_mat_fused_push_constants); + const uint32_t fpc = key.mul_mat_id ? 8u : 6u; + if (!tc.empty()) create_mm_pipelines(key, tc, name, len, data, pc_size, pc, qs, true, true, 0, true, cm1_pin, flen, fdata, fpc_size, fpc, 16); }; // int8 MMQ helper: per-type cm1 shader, warptile passed as-is (carries DEVICE_ARCH in // spec constant WARP_SIZE_IDX+1), subgroup size pinned to the warptile WARP element, no aligned variant. @@ -2814,15 +3616,15 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const bool rdna3 = device->architecture == AMD_RDNA3; const bool rdna4 = device->architecture == AMD_RDNA4; - cm1_create({GGML_TYPE_F32, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f32_f32", matmul_f32_f32_cm1_len, matmul_f32_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3); - cm1_create({GGML_TYPE_F32, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f32_f16", matmul_f32_f16_cm1_len, matmul_f32_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3); + cm1_create({GGML_TYPE_F32, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f32_f32", matmul_f32_f32_cm1_len, matmul_f32_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_f32_f32_fused_cm1_len, matmul_f32_f32_fused_cm1_data); + cm1_create({GGML_TYPE_F32, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f32_f16", matmul_f32_f16_cm1_len, matmul_f32_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_f32_f16_fused_cm1_len, matmul_f32_f16_fused_cm1_data); if (device->coopmat_acc_f16_support) { cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, false, true}, tc_mm, "matmul_f16_f16acc", matmul_f16_f16acc_cm1_len, matmul_f16_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, false, true}, tc_mm, "matmul_f16_f32_f16acc", matmul_f16_f32_f16acc_cm1_len, matmul_f16_f32_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); } if (device->coopmat_acc_f32_support) { - cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f16", matmul_f16_cm1_len, matmul_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3); - cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f16_f32", matmul_f16_f32_cm1_len, matmul_f16_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3); + cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f16", matmul_f16_cm1_len, matmul_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_f16_fused_cm1_len, matmul_f16_fused_cm1_data); + cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f16_f32", matmul_f16_f32_cm1_len, matmul_f16_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_f16_f32_fused_cm1_len, matmul_f16_f32_fused_cm1_data); } #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) if (device->coopmat_bf16_support) { @@ -2835,8 +3637,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { cm1_create_quant({type, GGML_TYPE_F16, false, true}, tc_mmq, "matmul_quant_f16_f16acc", matmul_quant_f16_f16acc_cm1_len, matmul_quant_f16_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); } if (device->coopmat_acc_f32_support) { - cm1_create_quant({type, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_quant_f32", matmul_quant_f32_cm1_len, matmul_quant_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3); - cm1_create_quant({type, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_quant_f16", matmul_quant_f16_cm1_len, matmul_quant_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3); + cm1_create_quant({type, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_quant_f32", matmul_quant_f32_cm1_len, matmul_quant_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_quant_f32_fused_cm1_len, matmul_quant_f32_fused_cm1_data); + cm1_create_quant({type, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_quant_f16", matmul_quant_f16_cm1_len, matmul_quant_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_quant_f16_fused_cm1_len, matmul_quant_f16_fused_cm1_data); } } // The _f16 variants provide the f16 B-type pipeline used when y_non_contig converts f32->f16. @@ -2845,11 +3647,17 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { cm1_create({TYPE, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_" #tstr "_f32_f16acc", matmul_##tstr##_f32_f16acc_cm1_len, matmul_##tstr##_f32_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ cm1_create({TYPE, GGML_TYPE_F16, false, true}, tc_mmq, "matmul_" #tstr "_f16_f16acc", matmul_##tstr##_f16_f16acc_cm1_len, matmul_##tstr##_f16_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ } \ - if (device->coopmat_acc_f32_support) { \ + if (device->coopmat_acc_f32_support && (TYPE) != GGML_TYPE_IQ4_XS && (TYPE) != GGML_TYPE_IQ4_NL) { \ cm1_create({TYPE, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_" #tstr "_f32", matmul_##tstr##_f32_cm1_len, matmul_##tstr##_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ cm1_create({TYPE, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_" #tstr "_f16", matmul_##tstr##_f16_cm1_len, matmul_##tstr##_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ } FOR_EACH_LUT_TYPE_NONFP4(X_CM1) + if (device->coopmat_acc_f32_support) { + cm1_create({GGML_TYPE_IQ4_XS, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_iq4_xs_f32", matmul_iq4_xs_f32_cm1_len, matmul_iq4_xs_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_iq4_xs_f32_fused_cm1_len, matmul_iq4_xs_f32_fused_cm1_data); + cm1_create({GGML_TYPE_IQ4_XS, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_iq4_xs_f16", matmul_iq4_xs_f16_cm1_len, matmul_iq4_xs_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_iq4_xs_f16_fused_cm1_len, matmul_iq4_xs_f16_fused_cm1_data); + cm1_create({GGML_TYPE_IQ4_NL, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_iq4_nl_f32", matmul_iq4_nl_f32_cm1_len, matmul_iq4_nl_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_iq4_nl_f32_fused_cm1_len, matmul_iq4_nl_f32_fused_cm1_data); + cm1_create({GGML_TYPE_IQ4_NL, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_iq4_nl_f16", matmul_iq4_nl_f16_cm1_len, matmul_iq4_nl_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3, matmul_iq4_nl_f16_fused_cm1_len, matmul_iq4_nl_f16_fused_cm1_data); + } #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) if (device->ocp_fp4) { #define X_CM1_OCP(TYPE, tstr) \ @@ -2888,18 +3696,18 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { GGML_ASSERT(device->subgroup_ballot); - cm1_create({GGML_TYPE_F32, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_subgroup_f32_f32", matmul_id_subgroup_f32_f32_cm1_len, matmul_id_subgroup_f32_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); + cm1_create({GGML_TYPE_F32, GGML_TYPE_F32, true, false}, tc_id, "matmul_id_subgroup_f32_f32", matmul_id_subgroup_f32_f32_cm1_len, matmul_id_subgroup_f32_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, matmul_id_subgroup_f32_f32_fused_cm1_len, matmul_id_subgroup_f32_f32_fused_cm1_data); if (device->coopmat_acc_f16_support) { - cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, true, true}, tc_mm, "matmul_id_subgroup_f16_f16acc", matmul_id_subgroup_f16_f16acc_cm1_len, matmul_id_subgroup_f16_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); - cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, true, true}, tc_mm, "matmul_id_subgroup_f16_f32_f16acc", matmul_id_subgroup_f16_f32_f16acc_cm1_len, matmul_id_subgroup_f16_f32_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); + cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, true, true}, tc_id, "matmul_id_subgroup_f16_f16acc", matmul_id_subgroup_f16_f16acc_cm1_len, matmul_id_subgroup_f16_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); + cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, true, true}, tc_id, "matmul_id_subgroup_f16_f32_f16acc", matmul_id_subgroup_f16_f32_f16acc_cm1_len, matmul_id_subgroup_f16_f32_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); } if (device->coopmat_acc_f32_support) { - cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_mm, "matmul_id_subgroup_f16", matmul_id_subgroup_f16_cm1_len, matmul_id_subgroup_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); - cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_subgroup_f16_f32", matmul_id_subgroup_f16_f32_cm1_len, matmul_id_subgroup_f16_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); + cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_id, "matmul_id_subgroup_f16", matmul_id_subgroup_f16_cm1_len, matmul_id_subgroup_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, matmul_id_subgroup_f16_fused_cm1_len, matmul_id_subgroup_f16_fused_cm1_data); + cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, true, false}, tc_id, "matmul_id_subgroup_f16_f32", matmul_id_subgroup_f16_f32_cm1_len, matmul_id_subgroup_f16_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, matmul_id_subgroup_f16_f32_fused_cm1_len, matmul_id_subgroup_f16_f32_fused_cm1_data); } #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) if (device->coopmat_bf16_support) { - cm1_create({GGML_TYPE_BF16, GGML_TYPE_BF16, true, false}, tc_mm, "matmul_id_subgroup_bf16", matmul_id_subgroup_bf16_cm1_len, matmul_id_subgroup_bf16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); + cm1_create({GGML_TYPE_BF16, GGML_TYPE_BF16, true, false}, tc_id, "matmul_id_subgroup_bf16", matmul_id_subgroup_bf16_cm1_len, matmul_id_subgroup_bf16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); } #endif for (const auto type : non_lut_quant_types) { @@ -2908,8 +3716,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { cm1_create_quant({type, GGML_TYPE_F16, true, true}, tc_mmq_id, "matmul_id_subgroup_quant_f16_f16acc", matmul_id_subgroup_quant_f16_f16acc_cm1_len, matmul_id_subgroup_quant_f16_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); } if (device->coopmat_acc_f32_support) { - cm1_create_quant({type, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_quant_f32", matmul_id_subgroup_quant_f32_cm1_len, matmul_id_subgroup_quant_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); - cm1_create_quant({type, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_quant_f16", matmul_id_subgroup_quant_f16_cm1_len, matmul_id_subgroup_quant_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); + cm1_create_quant({type, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_quant_f32", matmul_id_subgroup_quant_f32_cm1_len, matmul_id_subgroup_quant_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, matmul_id_subgroup_quant_f32_fused_cm1_len, matmul_id_subgroup_quant_f32_fused_cm1_data); + cm1_create_quant({type, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_quant_f16", matmul_id_subgroup_quant_f16_cm1_len, matmul_id_subgroup_quant_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, matmul_id_subgroup_quant_f16_fused_cm1_len, matmul_id_subgroup_quant_f16_fused_cm1_data); } } // The _f16 variants provide the f16 B-type pipeline used when y_non_contig converts f32->f16. @@ -2918,11 +3726,17 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { cm1_create({TYPE, GGML_TYPE_F32, true, true}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f32_f16acc", matmul_id_subgroup_##tstr##_f32_f16acc_cm1_len, matmul_id_subgroup_##tstr##_f32_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ cm1_create({TYPE, GGML_TYPE_F16, true, true}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f16_f16acc", matmul_id_subgroup_##tstr##_f16_f16acc_cm1_len, matmul_id_subgroup_##tstr##_f16_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ } \ - if (device->coopmat_acc_f32_support) { \ + if (device->coopmat_acc_f32_support && (TYPE) != GGML_TYPE_IQ4_XS && (TYPE) != GGML_TYPE_IQ4_NL) { \ cm1_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f32", matmul_id_subgroup_##tstr##_f32_cm1_len, matmul_id_subgroup_##tstr##_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ cm1_create({TYPE, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f16", matmul_id_subgroup_##tstr##_f16_cm1_len, matmul_id_subgroup_##tstr##_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ } FOR_EACH_LUT_TYPE_NONFP4(X_CM1_ID) + if (device->coopmat_acc_f32_support) { + cm1_create({GGML_TYPE_IQ4_XS, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_iq4_xs_f32", matmul_id_subgroup_iq4_xs_f32_cm1_len, matmul_id_subgroup_iq4_xs_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, matmul_id_subgroup_iq4_xs_f32_fused_cm1_len, matmul_id_subgroup_iq4_xs_f32_fused_cm1_data); + cm1_create({GGML_TYPE_IQ4_XS, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_iq4_xs_f16", matmul_id_subgroup_iq4_xs_f16_cm1_len, matmul_id_subgroup_iq4_xs_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, matmul_id_subgroup_iq4_xs_f16_fused_cm1_len, matmul_id_subgroup_iq4_xs_f16_fused_cm1_data); + cm1_create({GGML_TYPE_IQ4_NL, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_iq4_nl_f32", matmul_id_subgroup_iq4_nl_f32_cm1_len, matmul_id_subgroup_iq4_nl_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, matmul_id_subgroup_iq4_nl_f32_fused_cm1_len, matmul_id_subgroup_iq4_nl_f32_fused_cm1_data); + cm1_create({GGML_TYPE_IQ4_NL, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_iq4_nl_f16", matmul_id_subgroup_iq4_nl_f16_cm1_len, matmul_id_subgroup_iq4_nl_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, matmul_id_subgroup_iq4_nl_f16_fused_cm1_len, matmul_id_subgroup_iq4_nl_f16_fused_cm1_data); + } #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) if (device->ocp_fp4) { #define X_CM1_ID_OCP(TYPE, tstr) \ @@ -2958,6 +3772,158 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { cm1_create_mmq({GGML_TYPE_Q6_K, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int_k, "matmul_id_subgroup_q6_k_q8_1", matmul_id_subgroup_q6_k_q8_1_cm1_len, matmul_id_subgroup_q6_k_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); if (!rdna4) { cm1_create_mmq({GGML_TYPE_NVFP4, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int_k, "matmul_id_subgroup_nvfp4_q8_1", matmul_id_subgroup_nvfp4_q8_1_cm1_len, matmul_id_subgroup_nvfp4_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); } } + + if (ggml_vk_is_apple_agx_coopmat(device) && !getenv("GGML_VK_DISABLE_MMA")) { + struct mma_spv_entry { + ggml_type type; + const char * tstr; + size_t dense_len; const void * dense_data; + size_t id_len; const void * id_data; + }; + const mma_spv_entry mma_spvs[] = { + { GGML_TYPE_F32, "f32", mul_mv_mma_f32_cm1_len, mul_mv_mma_f32_cm1_data, mul_mv_mma_id_f32_cm1_len, mul_mv_mma_id_f32_cm1_data }, + { GGML_TYPE_F16, "f16", mul_mv_mma_f16_cm1_len, mul_mv_mma_f16_cm1_data, mul_mv_mma_id_f16_cm1_len, mul_mv_mma_id_f16_cm1_data }, + { GGML_TYPE_Q4_0, "q4_0", mul_mv_mma_q4_0_cm1_len, mul_mv_mma_q4_0_cm1_data, mul_mv_mma_id_q4_0_cm1_len, mul_mv_mma_id_q4_0_cm1_data }, + { GGML_TYPE_Q4_1, "q4_1", mul_mv_mma_q4_1_cm1_len, mul_mv_mma_q4_1_cm1_data, mul_mv_mma_id_q4_1_cm1_len, mul_mv_mma_id_q4_1_cm1_data }, + { GGML_TYPE_Q5_0, "q5_0", mul_mv_mma_q5_0_cm1_len, mul_mv_mma_q5_0_cm1_data, mul_mv_mma_id_q5_0_cm1_len, mul_mv_mma_id_q5_0_cm1_data }, + { GGML_TYPE_Q5_1, "q5_1", mul_mv_mma_q5_1_cm1_len, mul_mv_mma_q5_1_cm1_data, mul_mv_mma_id_q5_1_cm1_len, mul_mv_mma_id_q5_1_cm1_data }, + { GGML_TYPE_Q8_0, "q8_0", mul_mv_mma_q8_0_cm1_len, mul_mv_mma_q8_0_cm1_data, mul_mv_mma_id_q8_0_cm1_len, mul_mv_mma_id_q8_0_cm1_data }, + { GGML_TYPE_Q4_K, "q4_k", mul_mv_mma_q4_k_cm1_len, mul_mv_mma_q4_k_cm1_data, mul_mv_mma_id_q4_k_cm1_len, mul_mv_mma_id_q4_k_cm1_data }, + { GGML_TYPE_Q5_K, "q5_k", mul_mv_mma_q5_k_cm1_len, mul_mv_mma_q5_k_cm1_data, mul_mv_mma_id_q5_k_cm1_len, mul_mv_mma_id_q5_k_cm1_data }, + { GGML_TYPE_Q6_K, "q6_k", mul_mv_mma_q6_k_cm1_len, mul_mv_mma_q6_k_cm1_data, mul_mv_mma_id_q6_k_cm1_len, mul_mv_mma_id_q6_k_cm1_data }, + { GGML_TYPE_IQ4_XS, "iq4_xs", mul_mv_mma_iq4_xs_cm1_len, mul_mv_mma_iq4_xs_cm1_data, mul_mv_mma_id_iq4_xs_cm1_len, mul_mv_mma_id_iq4_xs_cm1_data }, + { GGML_TYPE_IQ4_NL, "iq4_nl", mul_mv_mma_iq4_nl_cm1_len, mul_mv_mma_iq4_nl_cm1_data, mul_mv_mma_id_iq4_nl_cm1_len, mul_mv_mma_id_iq4_nl_cm1_data }, + { GGML_TYPE_NVFP4, "nvfp4", mul_mv_mma_nvfp4_cm1_len, mul_mv_mma_nvfp4_cm1_data, mul_mv_mma_id_nvfp4_cm1_len, mul_mv_mma_id_nvfp4_cm1_data }, + }; + const uint32_t mma_use_shb = getenv("GGML_VK_MMA_SHB") ? (uint32_t)atoi(getenv("GGML_VK_MMA_SHB")) : 1u; + const uint32_t mma_id_kp = getenv("GGML_VK_MMA_ID_KP") ? (uint32_t)atoi(getenv("GGML_VK_MMA_ID_KP")) : 1u; + const uint32_t mma_id_wgsg0 = getenv("GGML_VK_MMA_ID_WGSG") ? (uint32_t)atoi(getenv("GGML_VK_MMA_ID_WGSG")) : 4u; + const uint32_t mma_id_nt0 = getenv("GGML_VK_MMA_ID_NT") ? (uint32_t)atoi(getenv("GGML_VK_MMA_ID_NT")) : 2u; + static constexpr struct { uint32_t wg_sg; uint32_t nt; uint32_t nsg; } mma_cfgs[8] = { + { 8u, 1u, 8u }, // ci=0: NSG=8, MSG=1, BM=8 + { 4u, 1u, 4u }, // ci=1: NSG=4, MSG=1, BM=8 + { 4u, 2u, 4u }, // ci=2: NSG=4, MSG=1, BM=16 + { 2u, 2u, 1u }, // ci=3: NSG=1, MSG=2, BM=32 (64 threads/WG, fills all 40 cores at m=2048!) + { 1u, 2u, 1u }, // ci=4: NSG=1, MSG=1, BM=16 (0 shmem, 0 barriers) + { 4u, 2u, 1u }, // ci=5: NSG=1, MSG=4, BM=64 (128 threads/WG, hoisted sh_b!) + { 8u, 1u, 1u }, // ci=6: NSG=1, MSG=8, BM=64 (256 threads/WG, 100% occupancy at RT=8!) + { 8u, 2u, 1u }, // ci=7: NSG=1, MSG=8, BM=128 (256 threads/WG, NT=1 BM=64 on _pairglu!) + }; + static constexpr uint32_t mma_rts[5] = { 1u, 2u, 4u, 6u, 8u }; + const uint32_t mma_f32_f16_shb = getenv("GGML_VK_MMA_F32_SHB") ? (uint32_t)atoi(getenv("GGML_VK_MMA_F32_SHB")) : 7u; + const uint32_t mma_bf16_shb = getenv("GGML_VK_MMA_BF16_SHB") ? (uint32_t)atoi(getenv("GGML_VK_MMA_BF16_SHB")) : 12u; + const uint32_t mma_bf16_kp = getenv("GGML_VK_MMA_BF16_KP") ? (uint32_t)atoi(getenv("GGML_VK_MMA_BF16_KP")) : 2u; + for (uint32_t rt_i = 0; rt_i < 5; ++rt_i) { + const uint32_t rt = mma_rts[rt_i]; + for (uint32_t ci = 0; ci < 8; ++ci) { + const uint32_t wg_sg = mma_cfgs[ci].wg_sg; + const uint32_t nt = mma_cfgs[ci].nt; + const uint32_t nsg = mma_cfgs[ci].nsg; + const uint32_t msg = wg_sg / nsg; + for (uint32_t bf16_i = 0; bf16_i < 2; ++bf16_i) { + const uint32_t shb = bf16_i ? mma_bf16_shb : ((rt >= 6u && !getenv("GGML_VK_MMA_F32_SHB")) ? 1u : mma_f32_f16_shb); + const uint32_t kp = bf16_i ? mma_bf16_kp : 1u; + const std::string pname = std::string("mul_mv_mma_f32_f16_rt") + std::to_string(rt) + "_c" + std::to_string(ci) + (bf16_i ? "_bf16" : ""); + ggml_vk_create_pipeline(device, device->pipeline_mul_mv_mma_f32_f16[rt_i][ci][bf16_i], + pname.c_str(), mul_mv_mma_f32_f16_cm1_len, mul_mv_mma_f32_f16_cm1_data, "main", + 7u, sizeof(vk_mat_mv_mma_push_constants), + { 8u * nt * msg, 8u * rt, 1u }, { wg_sg, nt, rt, nsg, 0u, shb, kp, 1u, bf16_i }, + 1u, true, true, 32u); + } + } + } + for (const auto & e : mma_spvs) { + for (uint32_t rt_i = 0; rt_i < 5; ++rt_i) { + const uint32_t rt = mma_rts[rt_i]; + if (rt >= 6u && e.type == GGML_TYPE_F32) { + continue; + } + for (uint32_t ci = 0; ci < 8; ++ci) { + const uint32_t wg_sg = mma_cfgs[ci].wg_sg; + const uint32_t nt = mma_cfgs[ci].nt; + const uint32_t nsg = mma_cfgs[ci].nsg; + const uint32_t msg = wg_sg / nsg; + for (uint32_t bf16_i = 0; bf16_i < 2; ++bf16_i) { + const uint32_t shb = bf16_i ? mma_bf16_shb : mma_use_shb; + const uint32_t kp = (bf16_i && e.type != GGML_TYPE_F32) ? mma_bf16_kp : 1u; + const std::string pname = std::string("mul_mv_mma_") + e.tstr + "_rt" + std::to_string(rt) + "_c" + std::to_string(ci) + (bf16_i ? "_bf16" : ""); + ggml_vk_create_pipeline(device, device->pipeline_mul_mv_mma[e.type][rt_i][ci][bf16_i], + pname.c_str(), e.dense_len, e.dense_data, "main", + 7u, sizeof(vk_mat_mv_mma_push_constants), + { 8u * nt * msg, 8u * rt, 1u }, { wg_sg, nt, rt, nsg, 0u, shb, kp, 1u, bf16_i }, + 1u, true, true, 32u); + } + } + } + static constexpr uint32_t mma_id_rts[7] = { 1u, 2u, 3u, 4u, 5u, 6u, 8u }; + for (uint32_t id_rt_i = 0; id_rt_i < 7; ++id_rt_i) { + const uint32_t id_rt = mma_id_rts[id_rt_i]; + if (id_rt >= 5u && e.type == GGML_TYPE_F32) { + continue; + } + for (uint32_t ici = 0; ici < 5; ++ici) { + const uint32_t wg_sg = (ici == 1u) ? 1u : ((ici == 2u) ? 2u : ((ici >= 3u) ? 8u : mma_id_wgsg0)); + const uint32_t id_nt = (ici == 4u) ? 1u : ((ici == 0u) ? mma_id_nt0 : 2u); + const uint32_t msg = wg_sg; + for (uint32_t bf16_i = 0; bf16_i < 2; ++bf16_i) { + const std::string id_pname = std::string("mul_mv_mma_id_") + e.tstr + "_rt" + std::to_string(id_rt) + + "_m" + std::to_string(msg) + "_nt" + std::to_string(id_nt) + (bf16_i ? "_bf16" : ""); + ggml_vk_create_pipeline(device, device->pipeline_mul_mv_mma_id[e.type][id_rt_i][ici][bf16_i], + id_pname.c_str(), e.id_len, e.id_data, "main", + 8u, sizeof(vk_mat_mat_id_fused_push_constants), + { 8u * id_nt * msg, 8u * id_rt, 1u }, { wg_sg, id_nt, id_rt, 1u, 0u, mma_use_shb, mma_id_kp, 1u, bf16_i }, + 1u, true, true, 32u); + } + } + } + } + static const struct { ggml_type type; const char * tstr; uint64_t dense_len; const void * dense_data; uint64_t id_len; const void * id_data; } mma_repack_spvs[] = { + { GGML_TYPE_Q4_K, "q4_k", mul_mv_mma_q4_k_repack_cm1_len, mul_mv_mma_q4_k_repack_cm1_data, mul_mv_mma_id_q4_k_repack_cm1_len, mul_mv_mma_id_q4_k_repack_cm1_data }, + { GGML_TYPE_Q5_K, "q5_k", mul_mv_mma_q5_k_repack_cm1_len, mul_mv_mma_q5_k_repack_cm1_data, mul_mv_mma_id_q5_k_repack_cm1_len, mul_mv_mma_id_q5_k_repack_cm1_data }, + { GGML_TYPE_Q6_K, "q6_k", mul_mv_mma_q6_k_repack_cm1_len, mul_mv_mma_q6_k_repack_cm1_data, mul_mv_mma_id_q6_k_repack_cm1_len, mul_mv_mma_id_q6_k_repack_cm1_data }, + { GGML_TYPE_NVFP4, "nvfp4", mul_mv_mma_nvfp4_repack_cm1_len, mul_mv_mma_nvfp4_repack_cm1_data, mul_mv_mma_id_nvfp4_repack_cm1_len, mul_mv_mma_id_nvfp4_repack_cm1_data }, + }; + for (const auto & e : mma_repack_spvs) { + const int ri = ggml_vk_repack_type_idx(e.type); + for (uint32_t rt_i = 0; rt_i < 5; ++rt_i) { + const uint32_t rt = mma_rts[rt_i]; + for (uint32_t ci = 0; ci < 8; ++ci) { + const uint32_t wg_sg = mma_cfgs[ci].wg_sg; + const uint32_t nt = mma_cfgs[ci].nt; + const uint32_t nsg = mma_cfgs[ci].nsg; + const uint32_t msg = wg_sg / nsg; + for (uint32_t bf16_i = 0; bf16_i < 2; ++bf16_i) { + const uint32_t shb = bf16_i ? mma_bf16_shb : mma_use_shb; + const uint32_t kp = bf16_i ? mma_bf16_kp : 1u; + const std::string pname = std::string("mul_mv_mma_") + e.tstr + "_repack_rt" + std::to_string(rt) + "_c" + std::to_string(ci) + (bf16_i ? "_bf16" : ""); + ggml_vk_create_pipeline(device, device->pipeline_mul_mv_mma_repack[ri][rt_i][ci][bf16_i], + pname.c_str(), e.dense_len, e.dense_data, "main", + 7u, sizeof(vk_mat_mv_mma_push_constants), + { 8u * nt * msg, 8u * rt, 1u }, { wg_sg, nt, rt, nsg, 0u, shb, kp, 1u, bf16_i }, + 1u, true, true, 32u); + } + } + } + static constexpr uint32_t mma_id_rts[7] = { 1u, 2u, 3u, 4u, 5u, 6u, 8u }; + for (uint32_t id_rt_i = 0; id_rt_i < 7; ++id_rt_i) { + const uint32_t id_rt = mma_id_rts[id_rt_i]; + for (uint32_t ici = 0; ici < 5; ++ici) { + const uint32_t wg_sg = (ici == 1u) ? 1u : ((ici == 2u) ? 2u : ((ici >= 3u) ? 8u : mma_id_wgsg0)); + const uint32_t id_nt = (ici == 4u) ? 1u : ((ici == 0u) ? mma_id_nt0 : 2u); + const uint32_t msg = wg_sg; + for (uint32_t bf16_i = 0; bf16_i < 2; ++bf16_i) { + const std::string id_pname = std::string("mul_mv_mma_id_") + e.tstr + "_repack_rt" + std::to_string(id_rt) + + "_m" + std::to_string(msg) + "_nt" + std::to_string(id_nt) + (bf16_i ? "_bf16" : ""); + ggml_vk_create_pipeline(device, device->pipeline_mul_mv_mma_id_repack[ri][id_rt_i][ici][bf16_i], + id_pname.c_str(), e.id_len, e.id_data, "main", + 8u, sizeof(vk_mat_mat_id_fused_push_constants), + { 8u * id_nt * msg, 8u * id_rt, 1u }, { wg_sg, id_nt, id_rt, 1u, 0u, mma_use_shb, mma_id_kp, 1u, bf16_i }, + 1u, true, true, 32u); + } + } + } + } + } } else #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) { @@ -2997,7 +3963,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { #endif std::vector tc_id = {{s_warptile_id, s_wg_denoms, s_align}, {m_warptile_id, m_wg_denoms, m_align}, {l_warptile_id, l_wg_denoms, l_align}}; - std::vector tc_mmqid = {{s_warptile_mmqid, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid, l_mmq_wg_denoms, l_align}}; + std::vector tc_mmqid = {{s_warptile_mmqid, gen_s_mmqid_denoms, s_align}, {m_warptile_mmqid, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid, l_mmq_wg_denoms, l_align}}; if (device->fp16) { // FP16 subgroup path - with dot2 runtime selection @@ -3250,6 +4216,34 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { if (n > crossover_medium) return 1; return 0; }; + } else if (ggml_vk_is_apple_agx_coopmat(device)) { + device->matmul_tile_selector = [](uint32_t m, uint32_t n, uint32_t /*k*/, uint32_t shader_core_count, + const std::vector& configs) -> uint32_t { + if (configs.size() <= 1) return 0; + const uint32_t cores = std::max(shader_core_count, 40u); + if (m <= 32 || n <= (ggml_vk_exact_s8_enabled() ? 24u : 16u)) return 0; + const uint32_t tiles_m = CEIL_DIV(m, configs[1].unaligned->wg_denoms[0]) * CEIL_DIV(n, configs[1].unaligned->wg_denoms[1]); + if (tiles_m < cores) return 0; + if (configs.size() == 2) return 1; + if (m < 128 || n < 64) return 1; + const uint32_t last = (uint32_t)configs.size() - 1; + const uint32_t tiles_l = CEIL_DIV(m, configs[last].unaligned->wg_denoms[0]) * CEIL_DIV(n, configs[last].unaligned->wg_denoms[1]); + static const uint32_t env_l_min = getenv("GGML_VK_CM1_L_MIN_TILES") ? (uint32_t)atoi(getenv("GGML_VK_CM1_L_MIN_TILES")) : 0u; + const uint32_t min_tiles_l = env_l_min > 0 ? env_l_min : (ggml_vk_exact_s8_enabled() ? (cores / 2u) : 140u); + if (tiles_l < min_tiles_l) return 1; + return last; + }; + device->matmul_id_tile_selector = [](uint32_t m, uint32_t n, uint32_t /*k*/, uint32_t /*shader_core_count*/, + const std::vector& configs) -> uint32_t { + if (configs.size() <= 1) return 0; + const uint32_t bn0 = configs[0].unaligned->wg_denoms[1]; + const uint32_t bn1 = configs[1].unaligned->wg_denoms[1]; + const uint32_t cross0 = std::min(3 * bn0, std::max(bn0, bn1 / 2)); + if (m <= 64 || n <= cross0) return 0; + if (configs.size() == 2) return 1; + if (m <= 128 || n <= bn1) return 1; + return (uint32_t)configs.size() - 1; + }; } else { device->matmul_tile_selector = [](uint32_t m, uint32_t n, uint32_t /*k*/, uint32_t /*shader_core_count*/, const std::vector& configs) -> uint32_t { @@ -3262,9 +4256,21 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { if (last == 0 || m <= 32 || n <= 32) return 0; if (last == 1) return 1; if (m <= 64 || n <= 64) return 1; + const uint32_t tiles_l = CEIL_DIV(m, configs[last].unaligned->wg_denoms[0]) * CEIL_DIV(n, configs[last].unaligned->wg_denoms[1]); + if (tiles_l < 64) return 1; return last; }; - device->matmul_id_tile_selector = device->matmul_tile_selector; + device->matmul_id_tile_selector = [](uint32_t m, uint32_t n, uint32_t /*k*/, uint32_t /*shader_core_count*/, + const std::vector& configs) -> uint32_t { + if (configs.size() <= 1) return 0; + const uint32_t bn0 = configs[0].unaligned->wg_denoms[1]; + const uint32_t bn1 = configs[1].unaligned->wg_denoms[1]; + const uint32_t cross0 = std::min(2 * bn0, std::max(bn0, bn1 / 2)); + if (m <= 32 || n <= cross0) return 0; + if (configs.size() == 2) return 1; + if (m <= 64 || n <= bn1) return 1; + return (uint32_t)configs.size() - 1; + }; } // mul mat vec @@ -3284,7 +4290,26 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } else if (device->vendor_id == VK_VENDOR_ID_INTEL) { rm_stdq = 2; rm_stdq_int = 2; - } + } else if (ggml_vk_is_apple_agx_coopmat(device)) { + rm_stdq = 2; + rm_kq = 2; + } + // gen: GGML_VK_RM_STDQ / GGML_VK_RM_KQ override the rows each mat-vec workgroup computes (q8_0 etc. / K-quants); + // each row's arithmetic is unchanged, only the grouping (Metal uses 8 rows per threadgroup for q8_0, 4 for q4_K) + if (getenv("GGML_VK_RM_STDQ")) { rm_stdq = std::max(1, atoi(getenv("GGML_VK_RM_STDQ"))); } + if (getenv("GGML_VK_RM_KQ")) { rm_kq = std::max(1, atoi(getenv("GGML_VK_RM_KQ"))); } + uint32_t rm_stdq_id = rm_stdq; + uint32_t rm_kq_id = rm_kq; + if (getenv("GGML_VK_RM_STDQ_ID")) { rm_stdq_id = std::max(1, atoi(getenv("GGML_VK_RM_STDQ_ID"))); } + if (getenv("GGML_VK_RM_KQ_ID")) { rm_kq_id = std::max(1, atoi(getenv("GGML_VK_RM_KQ_ID"))); } + uint32_t dmmv_nsg = 1; + uint32_t dmmv_id_nsg = 1; + uint32_t fast_kq = (ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled()) ? 2u : 0u; + if (getenv("GGML_VK_DMMV_NSG")) { dmmv_nsg = std::max(1, atoi(getenv("GGML_VK_DMMV_NSG"))); } + if (getenv("GGML_VK_DMMV_ID_NSG")) { dmmv_id_nsg = std::max(1, atoi(getenv("GGML_VK_DMMV_ID_NSG"))); } + if (getenv("GGML_VK_FAST_KQ")) { fast_kq = std::max(0, atoi(getenv("GGML_VK_FAST_KQ"))); } + const uint32_t fast_kq_id_56 = (ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled() && !getenv("GGML_VK_FAST_KQ")) ? 1u : fast_kq; + // 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); // RDNA3/4 and NVIDIA except pre-Turing: use 4 rows for MUL_MAT_ID MMVQ. auto const &rm_id = [&](uint32_t rows) { @@ -3294,7 +4319,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } return is_rdna3_or_4 ? 4u : rows; }; - uint32_t rm_iq = 2 * rm_kq; + uint32_t rm_iq_id = 2 * rm_kq_id; const bool use_subgroups = device->subgroup_arithmetic; // The Imagination proprietary compiler rejects the subgroup-only dequant mul_mat_vec @@ -3309,8 +4334,10 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0; const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0; - static constexpr uint32_t mul_mat_vec_num_bindings = 5; + const uint32_t dmmv_max_wg_inv = std::min(device->properties.limits.maxComputeWorkGroupInvocations, device->properties.limits.maxComputeWorkGroupSize[1]); + static constexpr uint32_t mul_mat_vec_num_bindings = 7; static constexpr uint32_t mul_mat_vec_id_num_bindings = 6; + const bool agx_no_robust = ggml_vk_is_apple_agx_coopmat(device); #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) #define OCP_DMMV_LEN(NAME, REDUC) (device->ocp_fp4 ? NAME ## _ocp_len[REDUC] : NAME ## _len[REDUC]) @@ -3332,64 +4359,82 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID : SHADER_REDUCTION_MODE_SHMEM; - for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) { - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q1_0][i], "mul_mat_vec_q1_0_f32_f32", arr_dmmv_q1_0_f32_f32_len[reduc], arr_dmmv_q1_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_f32_f32", arr_dmmv_q2_0_f32_f32_len[reduc], arr_dmmv_q2_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_TQ1_0][i], "mul_mat_vec_tq1_0_f32_f32", arr_dmmv_tq1_0_f32_f32_len[reduc16], arr_dmmv_tq1_0_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_TQ2_0][i], "mul_mat_vec_tq2_0_f32_f32", arr_dmmv_tq2_0_f32_f32_len[reduc16], arr_dmmv_tq2_0_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_mxfp4_f32_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_nvfp4_f32_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q1_0][i], "mul_mat_vec_q1_0_f16_f32", arr_dmmv_q1_0_f16_f32_len[reduc], arr_dmmv_q1_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_f16_f32", arr_dmmv_q2_0_f16_f32_len[reduc], arr_dmmv_q2_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_TQ1_0][i], "mul_mat_vec_tq1_0_f16_f32", arr_dmmv_tq1_0_f16_f32_len[reduc16], arr_dmmv_tq1_0_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_TQ2_0][i], "mul_mat_vec_tq2_0_f16_f32", arr_dmmv_tq2_0_f16_f32_len[reduc16], arr_dmmv_tq2_0_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f16_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_mxfp4_f16_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f16_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_nvfp4_f16_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + const uint32_t nsg_sub = (reduc == SHADER_REDUCTION_MODE_SUBGROUP) ? std::max(1u, std::min(dmmv_nsg, dmmv_max_wg_inv / wg_size_subgroup)) : 1u; + const uint32_t nsg_sub16 = (reduc16 == SHADER_REDUCTION_MODE_SUBGROUP) ? std::max(1u, std::min(dmmv_nsg, dmmv_max_wg_inv / wg_size_subgroup16)) : 1u; + const uint32_t nsg_id = (reduc == SHADER_REDUCTION_MODE_SUBGROUP) ? std::max(1u, std::min(dmmv_id_nsg, dmmv_max_wg_inv / wg_size_subgroup)) : 1u; + const uint32_t nsg_id16 = (reduc16 == SHADER_REDUCTION_MODE_SUBGROUP) ? std::max(1u, std::min(dmmv_id_nsg, dmmv_max_wg_inv / wg_size_subgroup16)) : 1u; + + const uint32_t mmv_pipe_cols = std::min(device->mmv_max_cols, mul_mat_vec_max_cols_limit); + for (uint32_t i = 0; i < mmv_pipe_cols; ++i) { + static const bool s18_rm_q8 = getenv("S19_S18_RM_Q8") != nullptr; + const uint32_t rm_stdq_c = (ggml_vk_is_apple_agx_coopmat(device) && i >= 4 && !getenv("GGML_VK_RM_STDQ")) ? 1u : rm_stdq; + const uint32_t rm_q8_c = (w == DMMV_WG_SIZE_LARGE && ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled() && !getenv("GGML_VK_RM_STDQ")) + ? 1u + : ((!s18_rm_q8 && ggml_vk_is_apple_agx_coopmat(device) && i < 8 && !getenv("GGML_VK_RM_STDQ")) ? rm_stdq : rm_stdq_c); + const uint32_t rm_kq_c = (ggml_vk_is_apple_agx_coopmat(device) && i >= 4 && !getenv("GGML_VK_RM_KQ")) ? 1u : rm_kq; + const uint32_t rm_iq_c = 2u * rm_kq_c; + const uint32_t rm_f32_c = getenv("GGML_VK_RM_F32") ? (uint32_t)std::max(1, atoi(getenv("GGML_VK_RM_F32"))) : 1u; + const uint32_t rm_f16_c = getenv("GGML_VK_RM_F16") + ? (uint32_t)std::max(1, atoi(getenv("GGML_VK_RM_F16"))) + : ((!s18_rm_q8 && w == DMMV_WG_SIZE_SUBGROUP && ggml_vk_is_apple_agx_coopmat(device) && i == 0) ? 4u : 2u); + const uint32_t fast_kq_c = (ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled() && !getenv("GGML_VK_FAST_KQ") && i >= 1) ? 2u : fast_kq; + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_f32_c*nsg_sub, 1, 1}, {wg_size_subgroup, rm_f32_c, i+1, 0, nsg_sub}, 1, agx_no_robust, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_f16_c*nsg_sub, 1, 1}, {wg_size_subgroup, rm_f16_c, i+1, 0, nsg_sub}, 1, agx_no_robust, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*nsg_sub, 1, 1}, {wg_size_subgroup, 2, i+1, 0, nsg_sub}, 1, agx_no_robust, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q1_0][i], "mul_mat_vec_q1_0_f32_f32", arr_dmmv_q1_0_f32_f32_len[reduc], arr_dmmv_q1_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_f32_f32", arr_dmmv_q2_0_f32_f32_len[reduc], arr_dmmv_q2_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_q8_c*nsg_sub, 1, 1}, {wg_size_subgroup, 1*rm_q8_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub16, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1, 0, nsg_sub16, fast_kq_c}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub16, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1, 0, nsg_sub16, fast_kq_c}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub16, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1, 0, nsg_sub16, fast_kq_c}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_TQ1_0][i], "mul_mat_vec_tq1_0_f32_f32", arr_dmmv_tq1_0_f32_f32_len[reduc16], arr_dmmv_tq1_0_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_TQ2_0][i], "mul_mat_vec_tq2_0_f32_f32", arr_dmmv_tq2_0_f32_f32_len[reduc16], arr_dmmv_tq2_0_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f32_f32, reduc), OCP_DMMV_DATA(arr_dmmv_mxfp4_f32_f32, reduc), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub, 1, 1}, {wg_size_subgroup, rm_kq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f32_f32, reduc), OCP_DMMV_DATA(arr_dmmv_nvfp4_f32_f32, reduc), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub, 1, 1}, {wg_size_subgroup, rm_kq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_f32_c*nsg_sub, 1, 1}, {wg_size_subgroup, rm_f32_c, i+1, 0, nsg_sub}, 1, false, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*nsg_sub, 1, 1}, {wg_size_subgroup, 2, i+1, 0, nsg_sub}, 1, false, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*nsg_sub, 1, 1}, {wg_size_subgroup, 2, i+1, 0, nsg_sub}, 1, agx_no_robust, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q1_0][i], "mul_mat_vec_q1_0_f16_f32", arr_dmmv_q1_0_f16_f32_len[reduc], arr_dmmv_q1_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_f16_f32", arr_dmmv_q2_0_f16_f32_len[reduc], arr_dmmv_q2_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_c*nsg_sub, 1, 1}, {wg_size_subgroup, 2*rm_stdq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_q8_c*nsg_sub, 1, 1}, {wg_size_subgroup, 1*rm_q8_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub16, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1, 0, nsg_sub16, fast_kq_c}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub16, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1, 0, nsg_sub16, fast_kq_c}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub16, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1, 0, nsg_sub16, fast_kq_c}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_TQ1_0][i], "mul_mat_vec_tq1_0_f16_f32", arr_dmmv_tq1_0_f16_f32_len[reduc16], arr_dmmv_tq1_0_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_TQ2_0][i], "mul_mat_vec_tq2_0_f16_f32", arr_dmmv_tq2_0_f16_f32_len[reduc16], arr_dmmv_tq2_0_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c, 1, 1}, {wg_size_subgroup16, rm_kq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq_c, 1, 1}, {wg_size_subgroup16, rm_iq_c, i+1}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f16_f32, reduc), OCP_DMMV_DATA(arr_dmmv_mxfp4_f16_f32, reduc), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub, 1, 1}, {wg_size_subgroup, rm_kq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f16_f32, reduc), OCP_DMMV_DATA(arr_dmmv_nvfp4_f16_f32, reduc), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq_c*nsg_sub, 1, 1}, {wg_size_subgroup, rm_kq_c, i+1, 0, nsg_sub}, 1, true, use_subgroups, force_subgroup_size); #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) if (device->integer_dot_product) { @@ -3437,34 +4482,35 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT } - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", arr_dmmv_id_f32_f32_f32_len[reduc], arr_dmmv_id_f32_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {wg_size_subgroup, 1}, 1, false, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", arr_dmmv_id_f16_f32_f32_len[reduc], arr_dmmv_id_f16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", arr_dmmv_id_bf16_f32_f32_len[reduc], arr_dmmv_id_bf16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q1_0], "mul_mat_vec_id_q1_0_f32", arr_dmmv_id_q1_0_f32_f32_len[reduc], arr_dmmv_id_q1_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q2_0], "mul_mat_vec_id_q2_0_f32", arr_dmmv_id_q2_0_f32_f32_len[reduc], arr_dmmv_id_q2_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", arr_dmmv_id_q4_0_f32_f32_len[reduc], arr_dmmv_id_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", arr_dmmv_id_q4_1_f32_f32_len[reduc], arr_dmmv_id_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", arr_dmmv_id_q5_0_f32_f32_len[reduc], arr_dmmv_id_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", arr_dmmv_id_q5_1_f32_f32_len[reduc], arr_dmmv_id_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", arr_dmmv_id_q8_0_f32_f32_len[reduc], arr_dmmv_id_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", arr_dmmv_id_q2_k_f32_f32_len[reduc16], arr_dmmv_id_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", arr_dmmv_id_q3_k_f32_f32_len[reduc16], arr_dmmv_id_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", arr_dmmv_id_q4_k_f32_f32_len[reduc16], arr_dmmv_id_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", arr_dmmv_id_q5_k_f32_f32_len[reduc16], arr_dmmv_id_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", arr_dmmv_id_q6_k_f32_f32_len[reduc16], arr_dmmv_id_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_TQ1_0], "mul_mat_vec_id_tq1_0_f32", arr_dmmv_id_tq1_0_f32_f32_len[reduc16], arr_dmmv_id_tq1_0_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_TQ2_0], "mul_mat_vec_id_tq2_0_f32", arr_dmmv_id_tq2_0_f32_f32_len[reduc16], arr_dmmv_id_tq2_0_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", arr_dmmv_id_iq1_s_f32_f32_len[reduc16], arr_dmmv_id_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", arr_dmmv_id_iq1_m_f32_f32_len[reduc16], arr_dmmv_id_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", arr_dmmv_id_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", arr_dmmv_id_iq2_xs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", arr_dmmv_id_iq2_s_f32_f32_len[reduc16], arr_dmmv_id_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", arr_dmmv_id_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", arr_dmmv_id_iq3_s_f32_f32_len[reduc16], arr_dmmv_id_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", arr_dmmv_id_iq4_xs_f32_f32_len[reduc16], arr_dmmv_id_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", arr_dmmv_id_iq4_nl_f32_f32_len[reduc16], arr_dmmv_id_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_mxfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_id_mxfp4_f32_f32, reduc16), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_NVFP4], "mul_mat_vec_id_nvfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_nvfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_id_nvfp4_f32_f32, reduc16), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", arr_dmmv_id_f32_f32_f32_len[reduc], arr_dmmv_id_f32_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*nsg_id, 1, 1}, {wg_size_subgroup, 1, 1, 0, nsg_id}, 1, false, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", arr_dmmv_id_f16_f32_f32_len[reduc], arr_dmmv_id_f16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*nsg_id, 1, 1}, {wg_size_subgroup, 2, 1, 0, nsg_id}, 1, false, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", arr_dmmv_id_bf16_f32_f32_len[reduc], arr_dmmv_id_bf16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*nsg_id, 1, 1}, {wg_size_subgroup, 2, 1, 0, nsg_id}, 1, agx_no_robust, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q1_0], "mul_mat_vec_id_q1_0_f32", arr_dmmv_id_q1_0_f32_f32_len[reduc], arr_dmmv_id_q1_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq_id*nsg_id, 1, 1}, {wg_size_subgroup, 2*rm_stdq_id, 1, 0, nsg_id}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q2_0], "mul_mat_vec_id_q2_0_f32", arr_dmmv_id_q2_0_f32_f32_len[reduc], arr_dmmv_id_q2_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq_id*nsg_id, 1, 1}, {wg_size_subgroup, 2*rm_stdq_id, 1, 0, nsg_id}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", arr_dmmv_id_q4_0_f32_f32_len[reduc], arr_dmmv_id_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq_id*nsg_id, 1, 1}, {wg_size_subgroup, 2*rm_stdq_id, 1, 0, nsg_id}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", arr_dmmv_id_q4_1_f32_f32_len[reduc], arr_dmmv_id_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq_id*nsg_id, 1, 1}, {wg_size_subgroup, 2*rm_stdq_id, 1, 0, nsg_id}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", arr_dmmv_id_q5_0_f32_f32_len[reduc], arr_dmmv_id_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq_id*nsg_id, 1, 1}, {wg_size_subgroup, 2*rm_stdq_id, 1, 0, nsg_id}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", arr_dmmv_id_q5_1_f32_f32_len[reduc], arr_dmmv_id_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq_id*nsg_id, 1, 1}, {wg_size_subgroup, 2*rm_stdq_id, 1, 0, nsg_id}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", arr_dmmv_id_q8_0_f32_f32_len[reduc], arr_dmmv_id_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq_id*nsg_id, 1, 1}, {wg_size_subgroup, 1*rm_stdq_id, 1, 0, nsg_id}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", arr_dmmv_id_q2_k_f32_f32_len[reduc16], arr_dmmv_id_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq_id, 1, 1}, {wg_size_subgroup16, rm_kq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", arr_dmmv_id_q3_k_f32_f32_len[reduc16], arr_dmmv_id_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq_id, 1, 1}, {wg_size_subgroup16, rm_kq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", arr_dmmv_id_q4_k_f32_f32_len[reduc16], arr_dmmv_id_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq_id*nsg_id16, 1, 1}, {wg_size_subgroup16, rm_kq_id, 1, 0, nsg_id16, fast_kq}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", arr_dmmv_id_q5_k_f32_f32_len[reduc16], arr_dmmv_id_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq_id*nsg_id16, 1, 1}, {wg_size_subgroup16, rm_kq_id, 1, 0, nsg_id16, fast_kq_id_56}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", arr_dmmv_id_q6_k_f32_f32_len[reduc16], arr_dmmv_id_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq_id*nsg_id16, 1, 1}, {wg_size_subgroup16, rm_kq_id, 1, 0, nsg_id16, fast_kq_id_56}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_TQ1_0], "mul_mat_vec_id_tq1_0_f32", arr_dmmv_id_tq1_0_f32_f32_len[reduc16], arr_dmmv_id_tq1_0_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq_id, 1, 1}, {wg_size_subgroup16, rm_kq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_TQ2_0], "mul_mat_vec_id_tq2_0_f32", arr_dmmv_id_tq2_0_f32_f32_len[reduc16], arr_dmmv_id_tq2_0_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq_id, 1, 1}, {wg_size_subgroup16, rm_kq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", arr_dmmv_id_iq1_s_f32_f32_len[reduc16], arr_dmmv_id_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq_id, 1, 1}, {wg_size_subgroup16, rm_iq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", arr_dmmv_id_iq1_m_f32_f32_len[reduc16], arr_dmmv_id_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq_id, 1, 1}, {wg_size_subgroup16, rm_iq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", arr_dmmv_id_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq_id, 1, 1}, {wg_size_subgroup16, rm_iq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", arr_dmmv_id_iq2_xs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq_id, 1, 1}, {wg_size_subgroup16, rm_iq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", arr_dmmv_id_iq2_s_f32_f32_len[reduc16], arr_dmmv_id_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq_id, 1, 1}, {wg_size_subgroup16, rm_iq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", arr_dmmv_id_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq_id, 1, 1}, {wg_size_subgroup16, rm_iq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", arr_dmmv_id_iq3_s_f32_f32_len[reduc16], arr_dmmv_id_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq_id, 1, 1}, {wg_size_subgroup16, rm_iq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", arr_dmmv_id_iq4_xs_f32_f32_len[reduc16], arr_dmmv_id_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq_id, 1, 1}, {wg_size_subgroup16, rm_iq_id}, 1, true, use_subgroups16, force_subgroup_size16); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", arr_dmmv_id_iq4_nl_f32_f32_len[reduc16], arr_dmmv_id_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq_id, 1, 1}, {wg_size_subgroup16, rm_iq_id}, 1, true, use_subgroups16, force_subgroup_size16); + const uint32_t rm_nvfp4_id = getenv("GGML_VK_RM_NVFP4_ID") ? (uint32_t)std::max(1, atoi(getenv("GGML_VK_RM_NVFP4_ID"))) : rm_kq_id; + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_mxfp4_f32_f32, reduc), OCP_DMMV_DATA(arr_dmmv_id_mxfp4_f32_f32, reduc), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_nvfp4_id*nsg_id, 1, 1}, {wg_size_subgroup, rm_nvfp4_id, 1, 0, nsg_id}, 1, true, use_subgroups, force_subgroup_size); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_NVFP4], "mul_mat_vec_id_nvfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_nvfp4_f32_f32, reduc), OCP_DMMV_DATA(arr_dmmv_id_nvfp4_f32_f32, reduc), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_nvfp4_id*nsg_id, 1, 1}, {wg_size_subgroup, rm_nvfp4_id, 1, 0, nsg_id}, 1, true, use_subgroups, force_subgroup_size); #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) if (device->integer_dot_product) { @@ -3496,6 +4542,60 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { #undef OCP_DMMV_DATA #undef OCP_DMMV_LEN + if (use_subgroups16 && device->subgroup_size == 32) { + static const struct { + ggml_type type; + const char * tstr; + uint64_t f32_len; const void * f32_data; + uint64_t f16_len; const void * f16_data; + uint64_t id_len; const void * id_data; + } repack_mmv_spvs[4] = { + { GGML_TYPE_Q4_K, "q4_k", + mul_mat_vec_q4_k_repack_f32_f32_subgroup_no_shmem_len, mul_mat_vec_q4_k_repack_f32_f32_subgroup_no_shmem_data, + mul_mat_vec_q4_k_repack_f16_f32_subgroup_no_shmem_len, mul_mat_vec_q4_k_repack_f16_f32_subgroup_no_shmem_data, + mul_mat_vec_id_q4_k_repack_f32_f32_subgroup_no_shmem_len, mul_mat_vec_id_q4_k_repack_f32_f32_subgroup_no_shmem_data }, + { GGML_TYPE_Q5_K, "q5_k", + mul_mat_vec_q5_k_repack_f32_f32_subgroup_no_shmem_len, mul_mat_vec_q5_k_repack_f32_f32_subgroup_no_shmem_data, + mul_mat_vec_q5_k_repack_f16_f32_subgroup_no_shmem_len, mul_mat_vec_q5_k_repack_f16_f32_subgroup_no_shmem_data, + mul_mat_vec_id_q5_k_repack_f32_f32_subgroup_no_shmem_len, mul_mat_vec_id_q5_k_repack_f32_f32_subgroup_no_shmem_data }, + { GGML_TYPE_Q6_K, "q6_k", + mul_mat_vec_q6_k_repack_f32_f32_subgroup_no_shmem_len, mul_mat_vec_q6_k_repack_f32_f32_subgroup_no_shmem_data, + mul_mat_vec_q6_k_repack_f16_f32_subgroup_no_shmem_len, mul_mat_vec_q6_k_repack_f16_f32_subgroup_no_shmem_data, + mul_mat_vec_id_q6_k_repack_f32_f32_subgroup_no_shmem_len, mul_mat_vec_id_q6_k_repack_f32_f32_subgroup_no_shmem_data }, + { GGML_TYPE_NVFP4, "nvfp4", + mul_mat_vec_nvfp4_repack_f32_f32_subgroup_no_shmem_len, mul_mat_vec_nvfp4_repack_f32_f32_subgroup_no_shmem_data, + mul_mat_vec_nvfp4_repack_f16_f32_subgroup_no_shmem_len, mul_mat_vec_nvfp4_repack_f16_f32_subgroup_no_shmem_data, + mul_mat_vec_id_nvfp4_repack_f32_f32_subgroup_no_shmem_len, mul_mat_vec_id_nvfp4_repack_f32_f32_subgroup_no_shmem_data }, + }; + const uint32_t rm_nvfp4_id_repack = getenv("GGML_VK_RM_NVFP4_ID") ? (uint32_t)std::max(1, atoi(getenv("GGML_VK_RM_NVFP4_ID"))) : rm_kq_id; + const uint32_t nsg_sub_repack = getenv("GGML_VK_MMV_NSG") ? (uint32_t)std::clamp(atoi(getenv("GGML_VK_MMV_NSG")), 1, 8) : (ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled() ? 2u : 1u); + const uint32_t nsg_id_repack = getenv("GGML_VK_MMVID_NSG") ? (uint32_t)std::clamp(atoi(getenv("GGML_VK_MMVID_NSG")), 1, 8) : (ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled() ? 2u : 1u); + for (uint32_t ri = 0; ri < 4; ++ri) { + const auto & e = repack_mmv_spvs[ri]; + const bool is_nvfp4_r = (e.type == GGML_TYPE_NVFP4); + const uint32_t nsg_d = is_nvfp4_r ? nsg_sub_repack : 1u; + const uint32_t f_kq = is_nvfp4_r ? 0u : fast_kq; + const uint32_t max_repack_cols = is_nvfp4_r ? std::min(8u, mul_mat_vec_max_cols_limit) : 4u; + for (uint32_t i = 0; i < max_repack_cols; ++i) { + const std::string name_f32 = std::string("mul_mat_vec_") + e.tstr + "_repack_f32_f32"; + const std::string name_f16 = std::string("mul_mat_vec_") + e.tstr + "_repack_f16_f32"; + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_repack_f32_f32[ri][i], name_f32.c_str(), + e.f32_len, e.f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), + {rm_kq * nsg_d, 1u, 1u}, {32u, rm_kq, i + 1u, 0u, nsg_d, f_kq}, 1, true, true, 32u); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_repack_f16_f32[ri][i], name_f16.c_str(), + e.f16_len, e.f16_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), + {rm_kq * nsg_d, 1u, 1u}, {32u, rm_kq, i + 1u, 0u, nsg_d, f_kq}, 1, true, true, 32u); + } + const std::string name_id = std::string("mul_mat_vec_id_") + e.tstr + "_repack_f32"; + const uint32_t rm_id_r = is_nvfp4_r ? rm_nvfp4_id_repack : rm_kq_id; + const uint32_t nsg_i_r = is_nvfp4_r ? nsg_id_repack : 1u; + const uint32_t fast_kq_id = is_nvfp4_r ? 0u : ((e.type == GGML_TYPE_Q4_K) ? fast_kq : fast_kq_id_56); + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_repack_f32[ri], name_id.c_str(), + e.id_len, e.id_data, "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), + {rm_id_r * nsg_i_r, 1u, 1u}, {32u, rm_id_r, 1u, 0u, nsg_i_r, fast_kq_id}, 1, true, true, 32u); + } + } + #if !defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) GGML_UNUSED(rm_stdq_int); GGML_UNUSED(rm_kq_int); @@ -3519,6 +4619,10 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_K], "dequant_q4_k", dequant_q4_k_len, dequant_q4_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_K], "dequant_q5_k", dequant_q5_k_len, dequant_q5_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q6_K], "dequant_q6_k", dequant_q6_k_len, dequant_q6_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1); + ggml_vk_create_pipeline(device, device->pipeline_dequant_repack[0], "dequant_q4_k_repack", dequant_q4_k_repack_len, dequant_q4_k_repack_data, "main", 2, 5 * sizeof(uint32_t), {256 * 256, 1, 1}, {}, 1); + ggml_vk_create_pipeline(device, device->pipeline_dequant_repack[1], "dequant_q5_k_repack", dequant_q5_k_repack_len, dequant_q5_k_repack_data, "main", 2, 5 * sizeof(uint32_t), {256 * 256, 1, 1}, {}, 1); + ggml_vk_create_pipeline(device, device->pipeline_dequant_repack[2], "dequant_q6_k_repack", dequant_q6_k_repack_len, dequant_q6_k_repack_data, "main", 2, 5 * sizeof(uint32_t), {256 * 256, 1, 1}, {}, 1); + ggml_vk_create_pipeline(device, device->pipeline_dequant_repack[3], "dequant_nvfp4_repack", dequant_nvfp4_repack_len, dequant_nvfp4_repack_data, "main", 2, 5 * sizeof(uint32_t), {256 * 256, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_TQ1_0], "dequant_tq1_0", dequant_tq1_0_len, dequant_tq1_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_TQ2_0], "dequant_tq2_0", dequant_tq2_0_len, dequant_tq2_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_S], "dequant_iq1_s", dequant_iq1_s_len, dequant_iq1_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); @@ -3662,27 +4766,31 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) { if (device->subgroup_arithmetic && device->subgroup_require_full_support) { - ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_subgroup_add_len, mul_mat_vec_p021_f16_f32_subgroup_add_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true); + ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_subgroup_add_len, mul_mat_vec_p021_f16_f32_subgroup_add_data, "main", 5, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true); } else { - ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true); + ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", 5, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true); } } - ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_nc_f16_f32, "mul_mat_vec_nc_f16_f32", mul_mat_vec_nc_f16_f32_len, mul_mat_vec_nc_f16_f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_nc_push_constants), {1, 1, 1}, {}, 1); + ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_nc_f16_f32, "mul_mat_vec_nc_f16_f32", mul_mat_vec_nc_f16_f32_len, mul_mat_vec_nc_f16_f32_data, "main", 5, sizeof(vk_mat_vec_nc_push_constants), {1, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_norm_f32, "norm_f32", norm_f32_len, norm_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1, true); ggml_vk_create_pipeline(device, device->pipeline_group_norm_f32, "group_norm_f32", group_norm_f32_len, group_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1); - const bool rms_subgroups = (device->vendor_id == VK_VENDOR_ID_INTEL || device->vendor_id == VK_VENDOR_ID_NVIDIA || device->vendor_id == VK_VENDOR_ID_AMD) && device->subgroup_arithmetic && device->subgroup_require_full_support; + const bool rms_subgroups = (device->vendor_id == VK_VENDOR_ID_INTEL || device->vendor_id == VK_VENDOR_ID_NVIDIA || device->vendor_id == VK_VENDOR_ID_AMD || + (ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled())) && + device->subgroup_arithmetic && device->subgroup_require_full_support; const uint32_t rms_set_rows_block_size = 128; // the unrolled fixed-count loop variants miscompile on Qualcomm's driver const uint32_t rms_unroll = device->driver_id != vk::DriverId::eQualcommProprietary; #define RMS_SHADER(name) (rms_subgroups ? name##_subgroup_len : name##_len), (rms_subgroups ? name##_subgroup_data : name##_data) - // 128/256/512 block sizes, picked by row length - for (uint32_t i = 0; i < 3; ++i) { - const uint32_t block_size = 128u << i; + // 128/256/512 block sizes (+ 32 single-subgroup block size in slot 3 when subgroups are enabled), picked by row length + for (uint32_t i = 0; i < (rms_subgroups ? 4u : 3u); ++i) { + const uint32_t block_size = (i == 3u) ? 32u : (128u << i); const std::string suffix = "_" + std::to_string(block_size); ggml_vk_create_pipeline2(device, device->pipeline_rms_norm[0][0][i], "rms_norm_f32" + suffix, RMS_SHADER(rms_norm_f32), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, block_size, rms_unroll}, 1, true, rms_subgroups); ggml_vk_create_pipeline2(device, device->pipeline_rms_norm[0][1][i], "rms_norm_mul_f32" + suffix, RMS_SHADER(rms_norm_f32), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1, 0, block_size, rms_unroll}, 1, true, rms_subgroups); + ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_scale_f32[i], "rms_norm_scale_f32" + suffix, RMS_SHADER(rms_norm_scale_f32), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, block_size, rms_unroll}, 1, true, rms_subgroups); + ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_mul_silu_f32[i], "rms_norm_mul_silu_f32" + suffix, RMS_SHADER(rms_norm_mul_silu_f32), "main", rms_subgroups ? 5u : 4u, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1, 0, block_size, rms_unroll}, 1, true, rms_subgroups); ggml_vk_create_pipeline2(device, device->pipeline_rms_norm[1][0][i], "rms_norm_bf16" + suffix, RMS_SHADER(rms_norm_bf16), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, block_size, rms_unroll}, 1, true, rms_subgroups); ggml_vk_create_pipeline2(device, device->pipeline_rms_norm[1][1][i], "rms_norm_mul_bf16" + suffix, RMS_SHADER(rms_norm_bf16), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1, 0, block_size, rms_unroll}, 1, true, rms_subgroups); for (uint32_t pm : {0, 1}) { @@ -3696,6 +4804,13 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_add_mul_partials_f32, "rms_norm_mul_add_mul_partials_f32", rms_norm_mul_add_partials_f32_len, rms_norm_mul_add_partials_f32_data, "main", 6, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1, 1}, 1, true); ggml_vk_create_pipeline(device, device->pipeline_rms_norm_set_rows_f32_f32, "rms_norm_set_rows_f32_f32", RMS_SHADER(rms_norm_set_rows_f32_f32), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, rms_set_rows_block_size, rms_unroll}, 1, true, rms_subgroups); ggml_vk_create_pipeline(device, device->pipeline_rms_norm_set_rows_f32_f16, "rms_norm_set_rows_f32_f16", RMS_SHADER(rms_norm_set_rows_f32_f16), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, rms_set_rows_block_size, rms_unroll}, 1, true, rms_subgroups); + if (rms_subgroups) { + ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_set_rows_f32_f32_32, "rms_norm_set_rows_f32_f32_32", RMS_SHADER(rms_norm_set_rows_f32_f32), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, 32u, rms_unroll}, 1, true, true); + ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_set_rows_f32_f16_32, "rms_norm_set_rows_f32_f16_32", RMS_SHADER(rms_norm_set_rows_f32_f16), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, 32u, rms_unroll}, 1, true, true); + if (device->subgroup_shuffle && device->subgroup_size == 32 && device->fp16) { + ggml_vk_create_pipeline(device, device->pipeline_rms_norm_set_rows_f32_q8_0_32, "rms_norm_set_rows_f32_q8_0_32", rms_norm_set_rows_q8_0_len, rms_norm_set_rows_q8_0_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {}, 1, true, true, 32); + } + } ggml_vk_create_pipeline(device, device->pipeline_rms_norm_partials_f32, "rms_norm_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true); ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_partials_f32, "rms_norm_mul_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true); @@ -3712,25 +4827,25 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_rms_norm_back_f32, "rms_norm_back_f32", rms_norm_back_f32_len, rms_norm_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_l2_norm_f32, "l2_norm_f32", l2_norm_f32_len, l2_norm_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1, true); - ggml_vk_create_pipeline(device, device->pipeline_cpy_32, "cpy_32", cpy_32_len, cpy_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_f16, "cpy_f32_f16", cpy_f32_f16_len, cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_cpy_16, "cpy_16", cpy_16_len, cpy_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f32, "cpy_f16_f32", cpy_f16_f32_len, cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_bf16,"cpy_f32_bf16",cpy_f32_bf16_len,cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f32,"cpy_bf16_f32",cpy_bf16_f32_len,cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f16,"cpy_bf16_f16",cpy_bf16_f16_len,cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - - ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_32, "contig_cpy_32", contig_cpy_32_len, contig_cpy_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_f16, "contig_cpy_f32_f16", contig_cpy_f32_f16_len, contig_cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_16, "contig_cpy_16", contig_cpy_16_len, contig_cpy_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f32, "contig_cpy_f16_f32", contig_cpy_f16_f32_len, contig_cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_bf16,"contig_cpy_f32_bf16",contig_cpy_f32_bf16_len,contig_cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f32,"contig_cpy_bf16_f32",contig_cpy_bf16_f32_len,contig_cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f16,"contig_cpy_bf16_f16",contig_cpy_bf16_f16_len,contig_cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); + ggml_vk_create_pipeline(device, device->pipeline_cpy_32, "cpy_32", cpy_32_len, cpy_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_f16, "cpy_f32_f16", cpy_f32_f16_len, cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_cpy_16, "cpy_16", cpy_16_len, cpy_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f32, "cpy_f16_f32", cpy_f16_f32_len, cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_bf16,"cpy_f32_bf16",cpy_f32_bf16_len,cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f32,"cpy_bf16_f32",cpy_bf16_f32_len,cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f16,"cpy_bf16_f16",cpy_bf16_f16_len,cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + + ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_32, "contig_cpy_32", contig_cpy_32_len, contig_cpy_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_f16, "contig_cpy_f32_f16", contig_cpy_f32_f16_len, contig_cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_16, "contig_cpy_16", contig_cpy_16_len, contig_cpy_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f32, "contig_cpy_f16_f32", contig_cpy_f16_f32_len, contig_cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_bf16,"contig_cpy_f32_bf16",contig_cpy_f32_bf16_len,contig_cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f32,"contig_cpy_bf16_f32",contig_cpy_bf16_f32_len,contig_cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f16,"contig_cpy_bf16_f16",contig_cpy_bf16_f16_len,contig_cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1, agx_no_robust); ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_32, "cpy_transpose_32", cpy_transpose_32_len, cpy_transpose_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_16, "cpy_transpose_16", cpy_transpose_16_len, cpy_transpose_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1); @@ -3819,8 +4934,19 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { if (device->multi_add) { for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) { - ggml_vk_create_pipeline2(device, device->pipeline_multi_add[i], "multi_add_f32_" + std::to_string(i+1), multi_add_f32_len, multi_add_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1); - ggml_vk_create_pipeline2(device, device->pipeline_multi_add_rms[i], "multi_add_rms_f32_" + std::to_string(i+1), multi_add_rms_f32_len, multi_add_rms_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1); + ggml_vk_create_pipeline2(device, device->pipeline_multi_add[i], "multi_add_f32_" + std::to_string(i+1), multi_add_f32_len, multi_add_f32_data, "main", 12, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1, agx_no_robust); + ggml_vk_create_pipeline2(device, device->pipeline_multi_add_rms[i], "multi_add_rms_f32_" + std::to_string(i+1), multi_add_rms_f32_len, multi_add_rms_f32_data, "main", 12, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1, agx_no_robust); + if (device->subgroup_basic && device->subgroup_arithmetic && device->subgroup_shuffle && device->subgroup_require_full_support) { + for (uint32_t tm = 0; tm < 3; ++tm) { + const uint32_t block_size = (tm == 2u) ? 128u : 512u; + for (uint32_t dm = 0; dm < 2; ++dm) { + ggml_vk_create_pipeline2(device, device->pipeline_multi_add_rms_mul[i][tm][dm], + "multi_add_rms_mul_f32_" + std::to_string(i+1) + "_tm" + std::to_string(tm) + "_dm" + std::to_string(dm), + multi_add_rms_mul_f32_len, multi_add_rms_mul_f32_data, "main", + 14, sizeof(vk_op_multi_add_rms_push_constants), {1, 1, 1}, {i+2, tm, dm, block_size}, 1, true, true); + } + } + } } } @@ -3858,6 +4984,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_ ## name [2], #name "_bf16", name ## _bf16_len, name ## _bf16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); CREATE_UNARY(scale) + ggml_vk_create_pipeline(device, device->pipeline_scale_zero_f32, "scale_zero_f32", scale_f32_len, scale_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {1}, 1); CREATE_UNARY(log) CREATE_UNARY(sqr) CREATE_UNARY(sqrt) @@ -3916,7 +5043,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_unary_mul[(idx)][dt][nr][ob], \ (#name "_mul" + std::string(ob ? "_b" : "") + "_" + dts_ + (nr ? "_norepeat" : "")).c_str(), \ len_, data_, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, \ - { (uint32_t) nr, (uint32_t) ob }, 1); \ + { (uint32_t) nr, (uint32_t) ob }, 1, agx_no_robust); \ } CREATE_UNARY_MUL(gelu, 0) @@ -3944,6 +5071,25 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { CREATE_GLU(swiglu, SWIGLU) CREATE_GLU(swiglu_oai, SWIGLU_OAI) CREATE_GLU(swiglu_clamp, SWIGLU_CLAMP) + CREATE_GLU(situ, SITU) + if (device->subgroup_arithmetic && device->subgroup_require_full_support && device->subgroup_size == 32) { + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[0], "inkling_l2_clip", inkling_l2_clip_len, inkling_l2_clip_data, "main", 5, 48, {1, 1, 1}, {}, 1, true, true, 32); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[1], "inkling_conv", inkling_conv_len, inkling_conv_data, "main", 7, 76, {1, 1, 1}, {}, 1, true); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[14], "inkling_conv_scopy", inkling_conv_scopy_len, inkling_conv_scopy_data, "main", 8, 92, {1, 1, 1}, {}, 1, true); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[2], "inkling_rel_gather", inkling_rel_gather_len, inkling_rel_gather_data, "main", 5, 84, {1, 1, 1}, {}, 1, true); + // S19_WAVE3/4: pure 16B [3] depth_mix, [13] depth_mix_rms, [4] rms2_concat, [11] ctrl_apply_rms_mul, [12] l2_clip_qr + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[3], "inkling_depth_mix", inkling_depth_mix_len, inkling_depth_mix_data, "main", 8, 56, {1, 1, 1}, {}, 1, true, true, 32); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[13], "inkling_depth_mix_rms", inkling_depth_mix_rms_len, inkling_depth_mix_rms_data, "main", 10, 72, {1, 1, 1}, {}, 1, true, true, 32); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[4], "inkling_rms2_concat", inkling_rms2_concat_len, inkling_rms2_concat_data, "main", 3, 36, {1, 1, 1}, {}, 1, true, true, 32); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[5], "inkling_ctrl_apply", inkling_ctrl_apply_len, inkling_ctrl_apply_data, "main", 5, 24, {1, 1, 1}, {}, 1, true); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[11], "inkling_ctrl_apply_rms_mul", inkling_ctrl_apply_rms_mul_len, inkling_ctrl_apply_rms_mul_data, "main", 6, 44, {1, 1, 1}, {}, 1, true, true, 32); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[12], "inkling_l2_clip_qr", inkling_l2_clip_qr_len, inkling_l2_clip_qr_data, "main", 6, 64, {1, 1, 1}, {}, 1, true, true, 32); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[6], "inkling_dspark_concat4", inkling_dspark_concat4_len, inkling_dspark_concat4_data, "main", 5, 40, {256, 1, 1}, {}, 1, true); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[7], "inkling_dspark_gru", inkling_dspark_gru_len, inkling_dspark_gru_data, "main", 3, 20, {256, 1, 1}, {}, 1, true); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[8], "inkling_softcap", inkling_softcap_len, inkling_softcap_data, "main", 2, 24, {1, 1, 1}, {}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[9], "inkling_dspark_joint_gru", inkling_dspark_joint_gru_len, inkling_dspark_joint_gru_data, "main", 8, 48, {1, 1, 1}, {}, 1, true, true, 32); + ggml_vk_create_pipeline(device, device->pipeline_inkling_fused[10], "inkling_dspark_inject_mix", inkling_dspark_inject_mix_len, inkling_dspark_inject_mix_data, "main", 9, 60, {1, 1, 1}, {}, 1, true, true, 32); + } CREATE_GLU(geglu_erf, GEGLU_ERF) CREATE_GLU(geglu_quick, GEGLU_QUICK) #undef CREATE_GLU @@ -4022,7 +5168,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } } - ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); + ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { ggml_vk_is_apple_agx_coopmat(device) ? 512u : device->subgroup_size }, 1, agx_no_robust); ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true); ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_f32, "cross_entropy_loss_f32", cross_entropy_loss_f32_len, cross_entropy_loss_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); @@ -4164,9 +5310,11 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } const bool gdn_packed_rows = S_V == 128u && device->vendor_id == VK_VENDOR_ID_NVIDIA && gdn_subgroup_size == 32u && device->subgroup_arithmetic && device->subgroup_clustered; + static const bool gen_exact_s8 = getenv("GGML_VK_EXACT_S8") != nullptr && atoi(getenv("GGML_VK_EXACT_S8")) != 0; uint32_t lanes_per_column; - if (device->vendor_id == VK_VENDOR_ID_INTEL) { - // Intel Xe: full-width reduction (min rows/lane) ~10x over the COLS_PER_WG=8 rule. + if (device->vendor_id == VK_VENDOR_ID_INTEL || + (ggml_vk_is_apple_agx_coopmat(device) && !gen_exact_s8)) { + // Intel Xe & Apple AGX: full-width reduction (ROWS_PER_LANE=4 on sg32) eliminates 128+ reg pressure and multiplies occupancy 8x. lanes_per_column = std::min(gdn_subgroup_size, S_V); } else if (S_V >= 128u && device->subgroup_clustered) { lanes_per_column = gdn_packed_rows ? 8u : std::max(1u, gdn_subgroup_size / 8u); @@ -4197,29 +5345,61 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const bool use_clustered_reduce = device->subgroup_arithmetic && device->subgroup_clustered && need_partial_subgroup_reduce; const bool use_subgroup_reduce = device->subgroup_arithmetic && !need_partial_subgroup_reduce; const bool use_subgroup_ops = use_clustered_reduce || use_subgroup_reduce; - size_t gdn_len; + size_t gdn_len, gdn_sout_len; const void * gdn_data; + const void * gdn_sout_data; if (use_clustered_reduce) { gdn_len = gated_delta_net_f32_len; gdn_data = (const void *)gated_delta_net_f32_data; + gdn_sout_len = gated_delta_net_f32_sout_len; + gdn_sout_data = (const void *)gated_delta_net_f32_sout_data; } else if (use_subgroup_reduce) { gdn_len = gated_delta_net_f32_nocluster_len; gdn_data = (const void *)gated_delta_net_f32_nocluster_data; + gdn_sout_len = gated_delta_net_f32_nocluster_sout_len; + gdn_sout_data = (const void *)gated_delta_net_f32_nocluster_sout_data; } else { gdn_len = gated_delta_net_f32_shmem_len; gdn_data = (const void *)gated_delta_net_f32_shmem_data; + gdn_sout_len = gated_delta_net_f32_shmem_sout_len; + gdn_sout_data = (const void *)gated_delta_net_f32_shmem_sout_data; } - const uint32_t cols_per_wg = gdn_subgroup_size / lanes_per_column; - const std::array wg_denoms = {1u, 1u, cols_per_wg}; + uint32_t cols_per_sub = (ggml_vk_is_apple_agx_coopmat(device) && !gen_exact_s8) ? 4u : 1u; + if (const char * env_cps = getenv("GGML_VK_GDN_COLS_PER_SUB")) { + cols_per_sub = (uint32_t)std::max(1, atoi(env_cps)); + } + const uint32_t cols_per_sub_step = gdn_subgroup_size / lanes_per_column; + if ((S_V % (cols_per_sub_step * cols_per_sub)) != 0) { + cols_per_sub = 1u; + } + uint32_t subgroups_per_wg = 1u; + if (const char * env_nsg = getenv("GGML_VK_GDN_NSG")) { + subgroups_per_wg = (uint32_t)std::max(1, atoi(env_nsg)); + } + while (subgroups_per_wg > 1u && (S_V % (cols_per_sub_step * subgroups_per_wg * cols_per_sub)) != 0) { + subgroups_per_wg >>= 1u; + } + const uint32_t cols_per_wg = cols_per_sub_step * subgroups_per_wg; + const std::array wg_denoms = {1u, 1u, cols_per_wg * cols_per_sub}; + const uint32_t gdn_contig_v4 = (ggml_vk_is_apple_agx_coopmat(device) && !gen_exact_s8 && + S_V == 128u && lanes_per_column == 32u && + (cols_per_sub == 4u || cols_per_sub == 2u) && + !getenv("GGML_VK_DISABLE_GDN_VEC4")) + ? (getenv("GGML_VK_DISABLE_GDN_FAST_READOUT") ? 1u : 2u) + : 0u; for (uint32_t kda = 0; kda < 2; kda++) { for (uint32_t rep = 0; rep < 2; rep++) { const std::string name = std::string(gdn_names[si][kda]) + (rep ? "_rep" : ""); ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda][rep], name.c_str(), gdn_len, gdn_data, "main", 11, sizeof(vk_op_gated_delta_net_push_constants), - wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows), rep}, 1, true, use_subgroup_ops, gdn_subgroup_size); + wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows), rep, cols_per_sub, subgroups_per_wg, gdn_contig_v4}, 1, true, use_subgroup_ops, gdn_subgroup_size); } + const std::string sout_name = std::string(gdn_names[si][kda]) + "_sout"; + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_sout[si][kda], + sout_name.c_str(), gdn_sout_len, gdn_sout_data, "main", 12, sizeof(vk_op_gated_delta_net_push_constants), + wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows), 0u, cols_per_sub, subgroups_per_wg, gdn_contig_v4}, 1, true, use_subgroup_ops, gdn_subgroup_size); } } @@ -4295,9 +5475,23 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true); } - ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 0}, 1); - ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_silu_f32, "ssm_conv_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 1}, 1); - ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_bias_silu_f32, "ssm_conv_bias_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 1, 1}, 1); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), { 32, 16, 1}, { 32, 16, 0, 0, 0, 0}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_silu_f32, "ssm_conv_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), { 32, 16, 1}, { 32, 16, 0, 1, 0, 0}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_bias_silu_f32, "ssm_conv_bias_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), { 32, 16, 1}, { 32, 16, 1, 1, 0, 0}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_1t_f32, "ssm_conv_1t_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), {128, 1, 1}, {128, 1, 0, 0, 0, 0}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_silu_1t_f32, "ssm_conv_silu_1t_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), {128, 1, 1}, {128, 1, 0, 1, 0, 0}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_sout_f32, "ssm_conv_sout_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), { 32, 16, 1}, { 32, 16, 0, 0, 1, 0}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_silu_sout_f32, "ssm_conv_silu_sout_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), { 32, 16, 1}, { 32, 16, 0, 1, 1, 0}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_concat_cpy_f32, "ssm_conv_concat_cpy_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), {128, 1, 1}, {128, 1, 0, 0, 0, 1}, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_concat_cpy_silu_f32, "ssm_conv_concat_cpy_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), {128, 1, 1}, {128, 1, 0, 1, 0, 1}, 1, agx_no_robust); + { + const bool ssm_slide_8 = ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled() && !getenv("GGML_VK_DISABLE_SSM_SLIDE8"); + const uint32_t mt_t_wg = ssm_slide_8 ? 4u : 8u; + const uint32_t mt_t_pt = ssm_slide_8 ? 8u : 1u; + const std::array mt_denoms = { 32u, mt_t_wg * mt_t_pt, 1u }; + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_concat_cpy_mt_f32, "ssm_conv_concat_cpy_mt_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), mt_denoms, { 32, mt_t_wg, 0, 0, 0, 1, mt_t_pt }, 1, agx_no_robust); + ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_concat_cpy_mt_silu_f32, "ssm_conv_concat_cpy_mt_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 5, sizeof(vk_op_ssm_conv_push_constants), mt_denoms, { 32, mt_t_wg, 0, 1, 0, 1, mt_t_pt }, 1, agx_no_robust); + } ggml_vk_create_pipeline(device, device->pipeline_opt_step_adamw_f32, "opt_step_adamw_f32", opt_step_adamw_f32_len, opt_step_adamw_f32_data, "main", 5, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); @@ -4517,6 +5711,17 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { for (uint32_t use_push = 0; use_push < 2; ++use_push) { for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) { ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][use_push], "topk_moe_f32_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 4, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<subgroup_size); + if (device->subgroup_size == 32 && i <= 8) { + for (uint32_t wg16 = 0; wg16 < 2; ++wg16) { + const uint32_t rows_wg = wg16 ? 16u : 8u; + ggml_vk_create_pipeline2(device, device->pipeline_topk_moe_count[i][use_push][wg16], + "topk_moe_count_f32_" + std::to_string(i) + "_r" + std::to_string(rows_wg), + topk_moe_count_f32_len, topk_moe_count_f32_data, "main", + 5, sizeof(vk_op_topk_moe_push_constants) + 2 * sizeof(uint32_t), + {1, 1, 1}, {device->subgroup_size, 1u<subgroup_size); + } + } } } @@ -4610,7 +5815,8 @@ vk_device ggml_vk_get_device(size_t idx) { const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE"); device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr; - device->disable_narrow_mul_mat = getenv("GGML_VK_DISABLE_NARROW_MUL_MAT") != nullptr; + const char* GGML_VK_DISABLE_NARROW_MUL_MAT = getenv("GGML_VK_DISABLE_NARROW_MUL_MAT"); + device->disable_narrow_mul_mat = GGML_VK_DISABLE_NARROW_MUL_MAT != nullptr && strcmp(GGML_VK_DISABLE_NARROW_MUL_MAT, "0") != 0; bool fp16_storage = false; bool fp16_compute = false; @@ -4777,10 +5983,31 @@ vk_device ggml_vk_get_device(size_t idx) { device->vendor_id = device->properties.vendorID; device->driver_id = driver_props.driverID; - device->external_memory_host = device->external_memory_host && ggml_vk_external_memory_host_usable(device->driver_id); - - // Implementing the async backend interfaces seems broken on older Intel HW, - // see https://github.com/ggml-org/llama.cpp/issues/17302. +#if VK_HEADER_VERSION >= 287 + // Private M4 Max experiment: Borealis currently reports Mesa's vendor ID + // and a driver ID not named by the installed Vulkan headers. Match its + // advertised name and this device instead of guessing a new enum value. + if (device->vendor_id == 0x10005 && device->properties.deviceID == 0x6041 && + strcmp(driver_props.driverName.data(), "Borealis") == 0) { + const char * mode = getenv("GGML_VK_BOREALIS_TUNING"); + if (mode == nullptr) { + mode = "all"; + } + if (strcmp(mode, "off") != 0 && strcmp(mode, "tiles") != 0 && + strcmp(mode, "roll") != 0 && strcmp(mode, "all") != 0) { + throw std::invalid_argument("GGML_VK_BOREALIS_TUNING must be off, tiles, roll, or all"); + } + device->borealis_medium_tiles = strcmp(mode, "tiles") == 0 || strcmp(mode, "all") == 0; + device->borealis_roll_bk = strcmp(mode, "roll") == 0 || strcmp(mode, "all") == 0; + GGML_LOG_INFO("ggml_vulkan: Borealis M4 tuning=%s (medium_tiles=%d, roll_bk=%d)\n", + mode, device->borealis_medium_tiles, device->borealis_roll_bk); + } +#endif + + device->external_memory_host = device->external_memory_host && ggml_vk_external_memory_host_usable(device->driver_id); + + // Implementing the async backend interfaces seems broken on older Intel HW, + // see https://github.com/ggml-org/llama.cpp/issues/17302. device->support_async = (device->vendor_id != VK_VENDOR_ID_INTEL || std::string(device->properties.deviceName.data()).find("(DG1)") == std::string::npos) && getenv("GGML_VK_DISABLE_ASYNC") == nullptr; @@ -4829,6 +6056,8 @@ vk_device ggml_vk_get_device(size_t idx) { device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount; } else if (device->vendor_id == VK_VENDOR_ID_INTEL) { device->shader_core_count = ggml_vk_intel_shader_core_count(device->physical_device); + } else if (strstr(device->name.c_str(), "M4 Max") != nullptr && !ggml_vk_exact_s8_enabled()) { + device->shader_core_count = 40; } else { device->shader_core_count = 0; } @@ -5370,6 +6599,9 @@ vk_device ggml_vk_get_device(size_t idx) { if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) { device->coopmat_support_16x16x16_f32acc = true; } + if (prop.MSize == 8 && prop.NSize == 8 && prop.KSize == 8) { + device->coopmat_support_8x8x8_f32acc = true; + } } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 && (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) { // coopmat sizes not set yet @@ -5439,8 +6671,31 @@ vk_device ggml_vk_get_device(size_t idx) { } } + if (device->driver_id == vk::DriverId::eMesaHoneykrisp || + (device->vendor_id == 0x10005 && strcmp(driver_props.driverName.data(), "Borealis") == 0)) { + device->mmv_max_cols = getenv("GGML_VK_MMV_MAX_COLS") + ? (uint32_t) std::clamp(atoi(getenv("GGML_VK_MMV_MAX_COLS")), 1, (int) mul_mat_vec_max_cols_limit) + : 32u; + device->mmv_id_max_tokens = getenv("GGML_VK_MMVID_MAX") + ? (uint32_t) std::max(1, atoi(getenv("GGML_VK_MMVID_MAX"))) + : 48u; + } + if (device->coopmat_support) { device_extensions.push_back("VK_KHR_cooperative_matrix"); + if (ggml_vk_is_apple_agx_coopmat(device) && !ggml_vk_exact_s8_enabled() && !getenv("GGML_VK_MMVID_MAX")) { + device->mmv_id_max_tokens = gen_batch_invariant() ? 8u : 4u; + } + } +#else + if (device->driver_id == vk::DriverId::eMesaHoneykrisp || + (device->vendor_id == 0x10005 && strcmp(driver_props.driverName.data(), "Borealis") == 0)) { + device->mmv_max_cols = getenv("GGML_VK_MMV_MAX_COLS") + ? (uint32_t) std::clamp(atoi(getenv("GGML_VK_MMV_MAX_COLS")), 1, (int) mul_mat_vec_max_cols_limit) + : 32u; + device->mmv_id_max_tokens = getenv("GGML_VK_MMVID_MAX") + ? (uint32_t) std::max(1, atoi(getenv("GGML_VK_MMVID_MAX"))) + : 48u; } #endif device->name = GGML_VK_NAME + std::to_string(idx); @@ -5521,15 +6776,15 @@ vk_device ggml_vk_get_device(size_t idx) { } #if VK_HEADER_VERSION >= 287 - // Honeykrisp driver for Asahi Linux doesn't report VK_VENDOR_ID_APPLE. - // Check for Honeykrisp driver and force same configuration as the VK_VENDOR_ID_APPLE case. - if (device->driver_id == vk::DriverId::eMesaHoneykrisp) { + // Mesa's Apple drivers do not report VK_VENDOR_ID_APPLE. Reuse the + // Apple tile configuration for Honeykrisp and opted-in Borealis. + if (device->driver_id == vk::DriverId::eMesaHoneykrisp || device->borealis_medium_tiles) { device->mul_mat_l[i] = false; device->mul_mat_m[i] = true; device->mul_mat_s[i] = false; device->mul_mat_id_l[i] = false; device->mul_mat_id_m[i] = true; - device->mul_mat_id_s[i] = false; + device->mul_mat_id_s[i] = getenv("GGML_VK_MMQID_S") != nullptr; // gen } #endif @@ -5539,6 +6794,29 @@ vk_device ggml_vk_get_device(size_t idx) { device->mul_mat_id_l_int[i] = device->mul_mat_id_l[i]; device->mul_mat_id_m_int[i] = device->mul_mat_id_m[i]; device->mul_mat_id_s_int[i] = device->mul_mat_id_s[i]; + if (ggml_vk_is_apple_agx_coopmat(device)) { + const char * cm1_t = getenv("GGML_VK_CM1_TILES"); + const char * cm1_id_t = getenv("GGML_VK_CM1_ID_TILES"); + if (!cm1_t || !*cm1_t) cm1_t = "sml"; + if (!cm1_id_t || !*cm1_id_t) cm1_id_t = "sm"; + device->mul_mat_s[i] = strchr(cm1_t, 's') != nullptr; + device->mul_mat_m[i] = strchr(cm1_t, 'm') != nullptr; + device->mul_mat_l[i] = strchr(cm1_t, 'l') != nullptr; + device->mul_mat_id_s[i] = strchr(cm1_id_t, 's') != nullptr; + device->mul_mat_id_m[i] = strchr(cm1_id_t, 'm') != nullptr; + device->mul_mat_id_l[i] = strchr(cm1_id_t, 'l') != nullptr; + } + } + + // Upstream narrow-N CM1 tiles ({BM, 16/32, 32, WM=16, WN=16}) and shader_core_count==0 split_k=8 + // target AMD/Intel 16x16 coopmat1; keep Apple AGX's tuned 8x8x8 s/m/l tiles and split_k=1 unless overridden. + if (GGML_VK_DISABLE_NARROW_MUL_MAT == nullptr && + (ggml_vk_is_apple_agx_coopmat(device) || device->borealis_medium_tiles +#if VK_HEADER_VERSION >= 287 + || device->driver_id == vk::DriverId::eMesaHoneykrisp +#endif + )) { + device->disable_narrow_mul_mat = true; } @@ -5591,6 +6869,18 @@ vk_device ggml_vk_get_device(size_t idx) { /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx), /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device }, }; + const bool enable_repack = ggml_vk_is_apple_agx_coopmat(device) && device->uma && !ggml_vk_exact_s8_enabled() && + device->subgroup_arithmetic && device->subgroup_size == 32 && !getenv("GGML_VK_DISABLE_REPACK"); + if (enable_repack) { + device->repack_buffer_type = { + /* .iface = */ ggml_backend_vk_repack_buffer_type_interface, + /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx), + /* .context = */ new ggml_backend_vk_buffer_type_context{ GGML_VK_NAME "_Repack", device }, + }; + device->extra_bufts = { &device->repack_buffer_type, nullptr }; + } else { + device->extra_bufts = { nullptr, nullptr }; + } device->idx = idx; @@ -5603,7 +6893,8 @@ vk_device ggml_vk_get_device(size_t idx) { device->disable_descriptor_reuse = getenv("GGML_VK_DISABLE_DESCRIPTOR_REUSE") != nullptr; device->add_rms_fusion = device->subgroup_arithmetic && - device->vendor_id != VK_VENDOR_ID_INTEL; + device->vendor_id != VK_VENDOR_ID_INTEL && + getenv("GGML_VK_DISABLE_ADD_RMS") == nullptr; device->partials_binding_alignment = std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment); @@ -5832,6 +7123,7 @@ static void ggml_vk_print_gpu_info(size_t idx) { const bool rebar = ggml_vk_has_rebar(physical_device); integer_dot_product = integer_dot_product + && getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT") == nullptr && (shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated || shader_integer_dot_product_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) && shader_integer_dot_product_features.shaderIntegerDotProduct; @@ -6191,8 +7483,9 @@ void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) { ctx->prealloc_size_x = 0; ctx->prealloc_size_y = 0; ctx->prealloc_size_split_k = 0; - // Fixed size of 1KB, for deterministic behavior - ctx->prealloc_size_add_rms_partials = 1024; + // Fixed size of 1KB, for deterministic behavior (gen: 1 MiB in batch-invariant mode, where the 1 KB budget is + // still applied per row so the same pairs fuse as at n=1) + ctx->prealloc_size_add_rms_partials = gen_batch_invariant() ? (1u << 20) : 1024; ctx->fence = ctx->device->device.createFence({}); ctx->almost_ready_fence = ctx->device->device.createFence({}); @@ -6257,10 +7550,21 @@ vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) { return ctx->device->pipeline_dequant[type]; } -static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t num_cols, uint32_t m, uint32_t k) { +static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t num_cols, uint32_t m, uint32_t k, bool is_repack = false) { VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()"); GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1); - GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols); + GGML_ASSERT(num_cols >= 1 && num_cols <= ggml_vk_mul_mat_vec_max_cols(ctx->device)); + + if (is_repack) { + const int ri = ggml_vk_repack_type_idx(a_type); + const uint32_t max_r_cols = (a_type == GGML_TYPE_NVFP4) ? 8u : 4u; + if (ri < 0 || b_type == GGML_TYPE_Q8_1 || num_cols > max_r_cols) { + return nullptr; + } + return b_type == GGML_TYPE_F32 + ? ctx->device->pipeline_dequant_mul_mat_vec_repack_f32_f32[ri][num_cols - 1] + : ctx->device->pipeline_dequant_mul_mat_vec_repack_f16_f32[ri][num_cols - 1]; + } if (b_type == GGML_TYPE_Q8_1) { switch (a_type) { @@ -6321,7 +7625,23 @@ static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * // heuristic to choose workgroup size uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP; - if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) { + static const int gen_dmmv_large = getenv("GGML_VK_DMMV_LARGE") ? atoi(getenv("GGML_VK_DMMV_LARGE")) : 0; + if (gen_dmmv_large < 0) { + dmmv_wg = DMMV_WG_SIZE_SUBGROUP; + } else if (gen_dmmv_large > 0) { + const uint32_t max_m = gen_dmmv_large == 1 ? 8192u : (uint32_t)gen_dmmv_large; + if (a_type == GGML_TYPE_Q6_K) { + if (m < std::min(4096u, max_m) && k >= 1024) { + dmmv_wg = DMMV_WG_SIZE_LARGE; + } + } else if (m <= max_m && k >= 1024) { + dmmv_wg = DMMV_WG_SIZE_LARGE; + } + } else if (ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled() && a_type == GGML_TYPE_Q8_0) { + if (m <= 262144 && (k >= 4096 || (m < 2048 && k >= 1024))) { + dmmv_wg = DMMV_WG_SIZE_LARGE; + } + } else if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) { // Prefer larger workgroups when M is small, to spread the work out more // and keep more SMs busy. // q6_k seems to prefer small workgroup size even for "medium" values of M. @@ -6346,10 +7666,18 @@ static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[dmmv_wg][a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[dmmv_wg][a_type][num_cols-1]; } -static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t m, uint32_t k) { +static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t m, uint32_t k, bool is_repack = false) { VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()"); GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_Q8_1); + if (is_repack) { + const int ri = ggml_vk_repack_type_idx(a_type); + if (ri < 0 || b_type == GGML_TYPE_Q8_1) { + return nullptr; + } + return ctx->device->pipeline_dequant_mul_mat_vec_id_repack_f32[ri]; + } + if (b_type == GGML_TYPE_Q8_1) { switch (a_type) { case GGML_TYPE_Q2_0: @@ -6409,7 +7737,19 @@ static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context // heuristic to choose workgroup size uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP; - if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) { + static const int gen_dmmv_id_large = getenv("GGML_VK_DMMV_ID_LARGE") ? atoi(getenv("GGML_VK_DMMV_ID_LARGE")) : 0; + if (gen_dmmv_id_large < 0) { + dmmv_wg = DMMV_WG_SIZE_SUBGROUP; + } else if (gen_dmmv_id_large > 0) { + const uint32_t max_m = gen_dmmv_id_large == 1 ? 8192u : (uint32_t)gen_dmmv_id_large; + if (a_type == GGML_TYPE_Q6_K) { + if (m < std::min(4096u, max_m) && k >= 1024) { + dmmv_wg = DMMV_WG_SIZE_LARGE; + } + } else if (m <= max_m && k >= 1024) { + dmmv_wg = DMMV_WG_SIZE_LARGE; + } + } else if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) { // Prefer larger workgroups when M is small, to spread the work out more // and keep more SMs busy. // q6_k seems to prefer small workgroup size even for "medium" values of M. @@ -6434,6 +7774,19 @@ static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[dmmv_wg][a_type]; } +static size_t ggml_vk_tensor_byte_span(const ggml_tensor * t) { + if (!t || ggml_nelements(t) == 0) { + return 0; + } + size_t span = ggml_row_size(t->type, t->ne[0]); + for (int d = 1; d < GGML_MAX_DIMS; ++d) { + if (t->ne[d] > 1) { + span += (size_t)(t->ne[d] - 1) * t->nb[d]; + } + } + return span; +} + vk_subbuffer ggml_vk_tensor_subbuffer( const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign) { @@ -6449,7 +7802,9 @@ vk_subbuffer ggml_vk_tensor_subbuffer( } GGML_ASSERT(buffer != nullptr); - size_t size = ggml_nbytes(tensor); + size_t size = ggml_vk_tensor_is_repack(tensor) + ? ggml_vk_repack_alloc_bytes(tensor) + : std::max(ggml_nbytes(tensor), ggml_vk_tensor_byte_span(tensor)); const size_t descriptor_offset = ggml_vk_descriptor_offset( offset, ctx->device->properties.limits.minStorageBufferOffsetAlignment, ggml_type_size(tensor->type)); @@ -6458,10 +7813,32 @@ vk_subbuffer ggml_vk_tensor_subbuffer( GGML_ASSERT(allow_misalign || misalign_bytes == 0); offset = descriptor_offset; size += misalign_bytes; + if (offset < buffer->size && size > buffer->size - offset) { + size = buffer->size - offset; + } return vk_subbuffer{buffer, offset, size}; } +static vk_subbuffer ggml_vk_strided_subbuffer( + const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) { + vk_subbuffer sb = ggml_vk_tensor_subbuffer(ctx, tensor, allow_misalign); + size_t raw_offset = 0; + vk_buffer host_buf = nullptr; + if (ctx->device->uma) { + ggml_vk_host_get(ctx->device, tensor->data, host_buf, raw_offset); + } + if (!host_buf) { + raw_offset = vk_tensor_offset(tensor) + tensor->view_offs; + } + const size_t misalign_bytes = raw_offset - sb.offset; + const size_t span_bytes = ggml_vk_tensor_byte_span(tensor) + misalign_bytes; + if (span_bytes > sb.size) { + sb.size = span_bytes; + } + return sb; +} + static vk_command_buffer* ggml_vk_get_or_create_cmd_buffer(vk_device& device, vk_command_pool& pool) { for (auto& cmd_buffer : pool.cmd_buffers) { if (!cmd_buffer.in_use) { @@ -6532,10 +7909,22 @@ void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) { } } +static void ggml_vk_ctx_begin_reusable(vk_device& device, vk_context& subctx) { + if (subctx->s != nullptr) { + ggml_vk_ctx_end(subctx); + } + subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p, false) }); + subctx->s = subctx->seqs[subctx->seqs.size() - 1].data(); +} + vk_context ggml_vk_get_compute_ctx(ggml_backend_vk_context * ctx) { vk_context result; if (!ctx->compute_ctx.expired()) { result = ctx->compute_ctx.lock(); + } else if (ctx->recording_replay && ctx->active_replay_cmd_pool != nullptr) { + result = ggml_vk_create_context(ctx, *ctx->active_replay_cmd_pool); + ctx->compute_ctx = result; + ggml_vk_ctx_begin_reusable(ctx->device, result); } else { result = ggml_vk_create_context(ctx, ctx->compute_cmd_pool); @@ -6606,6 +7995,99 @@ void deferred_memset(void * dst, uint32_t val, size_t size, std::vectorview_src && t->view_offs == 0 && + t->type == t->view_src->type && + ggml_is_contiguous(t) && ggml_is_contiguous(t->view_src) && + ggml_nelements(t) == ggml_nelements(t->view_src)) { + t = t->view_src; + } + return t; +} + +static uint32_t ggml_vk_acquire_prealloc_y_slot( + ggml_backend_vk_context * ctx, vk_context & subctx, + vk_pipeline_struct * pipe, const ggml_tensor * src1, bool k_padded, + bool & out_cached, int avoid_slot = -1) { + const ggml_tensor * key_src1 = k_padded ? src1 : ggml_vk_prealloc_y_equiv_root(src1); + if (pipe != nullptr && key_src1 != nullptr) { + for (uint32_t s = 0; s < ctx->prealloc_y_ring_count; ++s) { + if (ctx->prealloc_y_last_pipeline_ring[s] == pipe && + ctx->prealloc_y_last_tensor_ring[s] == key_src1 && + ctx->prealloc_y_last_k_padded_ring[s] == k_padded) { + out_cached = true; + return s; + } + } + } + out_cached = false; + uint32_t slot = ctx->prealloc_y_ring_count > 1 + ? ((ctx->prealloc_y_ring_idx++) % ctx->prealloc_y_ring_count) + : 0u; + if ((int)slot == avoid_slot && ctx->prealloc_y_ring_count > 1) { + slot = (ctx->prealloc_y_ring_idx++) % ctx->prealloc_y_ring_count; + } + if (ctx->prealloc_y_slot_need_sync[slot] || (ctx->prealloc_y_ring_count == 1 && ctx->prealloc_y_need_sync)) { + ggml_vk_sync_buffers(ctx, subctx); + } + ctx->prealloc_y_last_pipeline_ring[slot] = pipe; + ctx->prealloc_y_last_tensor_ring[slot] = key_src1; + ctx->prealloc_y_last_k_padded_ring[slot] = k_padded; + ctx->prealloc_y_last_pipeline_used = pipe; + ctx->prealloc_y_last_tensor_used = key_src1; + ctx->prealloc_y_last_k_padded = k_padded; + return slot; +} + +static void ggml_vk_reserve_prealloc_y(ggml_backend_vk_context * ctx, vk_context & subctx, size_t req_bytes) { + if (req_bytes > ctx->device->properties.limits.maxStorageBufferRange) { + GGML_ABORT("Requested preallocation size is too large"); + } + if (ctx->prealloc_size_y < req_bytes || ctx->prealloc_y == nullptr) { + ctx->prealloc_size_y = std::max(ctx->prealloc_size_y, req_bytes); + ggml_vk_preallocate_buffers(ctx, subctx); + } +} + +static vk_subbuffer ggml_vk_produce_prealloc_y_f16( + ggml_backend_vk_context * ctx, vk_context & subctx, + const ggml_tensor * dst_tensor, size_t write_bytes, + bool keep_post_dispatch = false, int avoid_slot = -1) { + vk_pipeline_struct * cpy_pipe = ctx->device->pipeline_contig_cpy_f32_f16.get(); + const ggml_tensor * key_t = ggml_vk_prealloc_y_equiv_root(dst_tensor); + for (uint32_t s = 0; s < ctx->prealloc_y_ring_count; ++s) { + if (ctx->prealloc_y_last_tensor_ring[s] == key_t) { + ctx->prealloc_y_last_tensor_ring[s] = nullptr; + ctx->prealloc_y_last_pipeline_ring[s] = nullptr; + } + } + bool dummy_cached = false; + const uint32_t slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, cpy_pipe, key_t, false, dummy_cached, avoid_slot); + GGML_ASSERT(!dummy_cached); + const size_t y_off = (size_t)slot * ctx->prealloc_y_ring_stride; + ctx->prealloc_y_need_sync = true; + ctx->prealloc_y_slot_need_sync[slot] = true; + if (keep_post_dispatch) { + ctx->prealloc_y_keep_slot = (int)slot; + } + return vk_subbuffer{ ctx->prealloc_y, y_off, write_bytes }; +} + +static uint32_t ggml_vk_acquire_prealloc_split_k_slot( + ggml_backend_vk_context * ctx, vk_context & subctx, size_t req_bytes) { + if (ctx->prealloc_split_k_ring_count > 1 && req_bytes <= ctx->prealloc_split_k_ring_stride) { + const uint32_t slot = (ctx->prealloc_split_k_ring_idx++) % ctx->prealloc_split_k_ring_count; + if (ctx->prealloc_split_k_slot_need_sync[slot]) { + ggml_vk_sync_buffers(ctx, subctx); + } + return slot; + } + if (ctx->prealloc_split_k_need_sync) { + ggml_vk_sync_buffers(ctx, subctx); + } + return 0u; +} + static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, uint32_t n, uint32_t k, bool disable_split_k, const vk_pipeline& pipeline, bool narrow_n) { VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")"); @@ -6613,6 +8095,15 @@ static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, return 1; } + // Series 9 (S9.3): On Apple AGX coopmat, split_k > 1 forces two full 40-core GPU pipeline drains + a + // split_k_reduce dispatch per matmul (32 ms bubble across 100 alpha/beta/router projections at pp256). + if (ggml_vk_is_apple_agx_coopmat(ctx->device)) { + const uint32_t tiles = CEIL_DIV(m, pipeline->wg_denoms[0]) * CEIL_DIV(n, pipeline->wg_denoms[1]); + if (k <= 8192 || tiles >= 8) { + return 1; + } + } + const bool rdna = ctx->device->architecture == AMD_RDNA3 || ctx->device->architecture == AMD_RDNA4; uint32_t split_k = narrow_n && ctx->device->shader_core_count == 0 ? 8u : 1u; if ((narrow_n || rdna) && ctx->device->shader_core_count != 0 && k >= 2048 && n <= 32) { @@ -6624,19 +8115,21 @@ static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, } // On RDNA, also split when n <= 64 only partly fills one tile column. - if (!narrow_n && split_k == 1 && ctx->device->shader_core_count != 0 && (n >= pipeline->wg_denoms[1] || (rdna && n <= 64))) { + const uint32_t eff_cores = (ggml_vk_fast_fp16_enabled() && ggml_vk_is_apple_agx_coopmat(ctx->device) && ctx->device->shader_core_count == 0) + ? 40u : ctx->device->shader_core_count; + if (!narrow_n && split_k == 1 && eff_cores != 0 && (n >= pipeline->wg_denoms[1] || (rdna && n <= 64))) { // If k is 'large' and the SMs will fill less than halfway, use split_k. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]); uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]); if (k >= 2048) { - if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) { - split_k = ctx->device->shader_core_count / (m_tiles * n_tiles); - } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) { + if (m_tiles * n_tiles <= eff_cores / 2) { + split_k = eff_cores / (m_tiles * n_tiles); + } else if (m_tiles * n_tiles <= eff_cores * 2 / 3) { split_k = 3; } else if ((ctx->device->architecture == AMD_RDNA3 || ctx->device->architecture == AMD_RDNA4) && - m_tiles * n_tiles > ctx->device->shader_core_count && - m_tiles * n_tiles <= ctx->device->shader_core_count * 4 / 3) { + m_tiles * n_tiles > eff_cores && + m_tiles * n_tiles <= eff_cores * 4 / 3) { // two waves, the second one at most 1/3 full split_k = 3; } @@ -6822,6 +8315,61 @@ void ggml_vk_matmul( const std::array pc2 = { (uint32_t)(m * n * batch), split_k }; ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 }); ctx->prealloc_split_k_need_sync = true; + for (uint32_t s = 0; s < VK_PREALLOC_RING; ++s) { + ctx->prealloc_split_k_slot_need_sync[s] = true; + } + ctx->last_expert_count_valid = false; +} + +static void ggml_vk_matmul_fused( + ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline, + const vk_subbuffer& a, const vk_subbuffer& b, const vk_subbuffer& d, + const vk_subbuffer& u, const vk_subbuffer& aux0, const vk_subbuffer& aux1, + uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d, + uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d, + uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3, + uint32_t padded_n, uint64_t b_col_bytes, uint64_t d_col_bytes, + uint64_t aux0_col_bytes, uint64_t aux1_col_bytes, uint32_t fusion_flags, + uint32_t pair_m0 = 0, uint32_t stride_d2 = 0, uint32_t batch_stride_d2 = 0) { + const uint64_t max_n = (uint64_t)ctx->device->properties.limits.maxComputeWorkGroupCount[1] * pipeline->wg_denoms[1]; + const uint64_t n_chunks = CEIL_DIV(n, max_n); + ggml_pipeline_request_descriptor_sets(ctx, pipeline, n_chunks * CEIL_DIV(batch, ctx->device->properties.limits.maxComputeWorkGroupCount[2])); + + for (uint64_t n_base = 0; n_base < n; n_base += max_n) { + const uint32_t n_chunk = (uint32_t) std::min(n - n_base, max_n); + GGML_ASSERT(n_base * b_col_bytes < b.size && n_base * d_col_bytes < d.size); + vk_subbuffer b_chunk = b; + vk_subbuffer d_chunk = d; + vk_subbuffer aux0_chunk = aux0; + vk_subbuffer aux1_chunk = aux1; + b_chunk.offset += n_base * b_col_bytes; + b_chunk.size -= n_base * b_col_bytes; + d_chunk.offset += n_base * d_col_bytes; + d_chunk.size -= n_base * d_col_bytes; + if (aux0_col_bytes != 0) { + aux0_chunk.offset += n_base * aux0_col_bytes; + aux0_chunk.size -= n_base * aux0_col_bytes; + } + if (aux1_col_bytes != 0) { + aux1_chunk.offset += n_base * aux1_col_bytes; + aux1_chunk.size -= n_base * aux1_col_bytes; + } + + uint32_t base_work_group_z = 0; + while (base_work_group_z < batch) { + uint32_t groups_z = std::min(batch - base_work_group_z, ctx->device->properties.limits.maxComputeWorkGroupCount[2]); + const vk_mat_mat_fused_push_constants pc = { + m, n_chunk, k, stride_a, stride_b, stride_d, + batch_stride_a, batch_stride_b, batch_stride_d, + base_work_group_z, batch, k, ne02, ne12, broadcast2, broadcast3, + uint32_t(padded_n - n_base), fusion_flags, + pair_m0, stride_d2, batch_stride_d2 + }; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { a, b_chunk, d_chunk, u, aux0_chunk, aux1_chunk }, pc, { m, n_chunk, groups_z }); + base_work_group_z += groups_z; + } + } } static bool ggml_vk_src1_prec_allows_q8(const ggml_tensor * dst) { @@ -6852,7 +8400,7 @@ static bool ggml_vk_prec_allows_f16acc(ggml_prec prec) { return false; } -static bool ggml_vk_get_mul_mat_mat_f16acc(ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec acc_prec) { +static bool ggml_vk_get_mul_mat_mat_f16acc(const ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec acc_prec) { if (src0_type == GGML_TYPE_F32 || src0_type == GGML_TYPE_BF16) return false; if (src1_type == GGML_TYPE_Q8_1) return false; const bool prec_allows_f16 = ggml_vk_prec_allows_f16acc(acc_prec); @@ -6870,7 +8418,7 @@ static bool ggml_vk_get_mul_mat_mat_f16acc(ggml_backend_vk_context * ctx, ggml_t } static const std::vector * ggml_vk_get_mul_mat_mat_pipeline_map( - ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec, + const ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec, bool mul_mat_id = false, bool stream_k = false) { bool f16acc = ggml_vk_get_mul_mat_mat_f16acc(ctx, src0_type, src1_type, prec); vk_matmul_pipeline_key key{src0_type, src1_type, mul_mat_id, f16acc, stream_k}; @@ -6928,6 +8476,27 @@ static void ggml_vk_matmul_id( ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids, expert_count_buf }, pc, elements); } +static void ggml_vk_matmul_id_fused( + ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline, + const vk_subbuffer& a, const vk_subbuffer& b, const vk_subbuffer& d, + const vk_subbuffer& ids, const vk_subbuffer& expert_count_buf, + const vk_subbuffer& u, const vk_subbuffer& aux0, const vk_subbuffer& aux1, + uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d, + uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d, + uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11, + uint32_t row_ids_offset, uint32_t max_tiles, uint32_t fusion_flags, + float glu_alpha = 0.0f, float glu_limit = 0.0f) { + const vk_mat_mat_id_fused_push_constants pc = { + m, n, k, stride_a, stride_b, stride_d, + batch_stride_a, batch_stride_b, batch_stride_d, + nei0, nei1, nbi1, ne11, n_as, row_ids_offset, fusion_flags, glu_alpha, glu_limit + }; + const uint32_t tiles_y = std::min(max_tiles, ctx->device->properties.limits.maxComputeWorkGroupCount[1]); + const std::array elements = { m, tiles_y * pipeline->wg_denoms[1], uint32_t(CEIL_DIV(max_tiles, tiles_y)) }; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { a, b, d, ids, expert_count_buf, u, aux0, aux1 }, pc, elements); +} + bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) { return tensor->nb[0] == ggml_type_size(tensor->type) && @@ -7184,10 +8753,72 @@ static ggml_type ggml_vk_mul_mat_b_type( return f16_type; } -static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool disable_split_k) { +static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool disable_split_k, const struct ggml_cgraph * cgraph = nullptr, int node_idx = -1) { + const bool has_pair_mm = ctx->gen_pair_mm1 != nullptr; + const bool has_pair_glu = !has_pair_mm && cgraph != nullptr && ctx->num_additional_fused_ops == 2 && + cgraph->nodes[node_idx + 2]->op == GGML_OP_GLU; + const ggml_tensor * src0_up = nullptr; + if (has_pair_glu) { + const ggml_tensor * glu = cgraph->nodes[node_idx + 2]; + src0 = glu->src[0]->src[0]; + src0_up = glu->src[1]->src[0]; + } else if (has_pair_mm) { + src0_up = ctx->gen_pair_mm1->src[0]; + } + const ggml_tensor * out_dst = has_pair_mm + ? (ctx->gen_mm_dst ? ctx->gen_mm_dst : dst) + : (ctx->gen_mm_dst ? ctx->gen_mm_dst + : ((cgraph != nullptr && ctx->num_additional_fused_ops > 0) + ? cgraph->nodes[node_idx + ctx->num_additional_fused_ops] + : dst)); + const ggml_tensor * out_dst2 = has_pair_mm ? ctx->gen_pair_dst1 : nullptr; + uint32_t fusion_flags = 0; + const ggml_tensor * aux0_t = nullptr; + const ggml_tensor * aux1_t = nullptr; + uint64_t aux0_col_bytes = 0; + uint64_t aux1_col_bytes = 0; + if (has_pair_mm) { + fusion_flags |= ctx->gen_mm_flags; + aux1_t = out_dst2; + aux1_col_bytes = (uint64_t)out_dst2->nb[1]; + } else if (!has_pair_glu) { + if (ctx->gen_mm_dst != nullptr) { + fusion_flags |= ctx->gen_mm_flags; + aux0_t = ctx->gen_mm_f0; + aux1_t = ctx->gen_mm_f1; + if ((fusion_flags & MAT_VEC_FUSION_FLAGS_ROW_SCALE0) != 0) { + aux0_col_bytes = sizeof(float); + } + } else if (cgraph != nullptr && ctx->num_additional_fused_ops == 1 && + cgraph->nodes[node_idx + 1]->op == GGML_OP_GLU) { + const ggml_tensor * glu = cgraph->nodes[node_idx + 1]; + const bool is_gate = (glu->src[0] == dst); + aux0_t = is_gate ? glu->src[1] : glu->src[0]; + fusion_flags |= is_gate ? MAT_VEC_FUSION_FLAGS_GLU_A : MAT_VEC_FUSION_FLAGS_GLU_B; + aux0_col_bytes = (uint64_t)out_dst->nb[1]; + } else if (cgraph != nullptr && ctx->num_additional_fused_ops > 0) { + const ggml_tensor * add0 = cgraph->nodes[node_idx + 1]; + GGML_ASSERT(add0->op == GGML_OP_ADD); + aux0_t = (add0->src[0] == dst) ? add0->src[1] : add0->src[0]; + fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0; + aux0_col_bytes = (uint64_t)out_dst->nb[1]; + if (ctx->num_additional_fused_ops > 1) { + const ggml_tensor * add1 = cgraph->nodes[node_idx + 2]; + GGML_ASSERT(add1->op == GGML_OP_ADD); + aux1_t = (add1->src[0] == add0) ? add1->src[1] : add1->src[0]; + fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1; + aux1_col_bytes = (uint64_t)out_dst->nb[1]; + } + } + } + const bool use_mm_fused = has_pair_glu || (fusion_flags != 0); + if (use_mm_fused) { + disable_split_k = true; + } + VK_LOG_DEBUG("ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << ggml_type_name(src0->type) << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << ggml_type_name(src1->type) << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; - std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << ggml_type_name(dst->type) << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3]; + std::cerr << "), (" << out_dst << ", name=" << out_dst->name << ", type=" << ggml_type_name(out_dst->type) << ", ne0=" << out_dst->ne[0] << ", ne1=" << out_dst->ne[1] << ", ne2=" << out_dst->ne[2] << ", ne3=" << out_dst->ne[3] << ", nb0=" << out_dst->nb[0] << ", nb1=" << out_dst->nb[1] << ", nb2=" << out_dst->nb[2] << ", nb3=" << out_dst->nb[3]; std::cerr << "))"); GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT @@ -7202,14 +8833,13 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub const uint64_t ne12 = src1->ne[2]; const uint64_t ne13 = src1->ne[3]; - const uint64_t ne21 = dst->ne[1]; - const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type); + const uint64_t ne21 = out_dst->ne[1]; + const uint32_t stride_d = out_dst->nb[1] / ggml_type_size(out_dst->type); const uint32_t stride_batch_d = stride_d*ne21; const uint64_t r2 = ne12 / ne02; const uint64_t r3 = ne13 / ne03; - ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context; ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context; @@ -7234,10 +8864,16 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16; const bool is_coopmat = ctx->device->coopmat_support || ctx->device->coopmat2; - const bool can_quantize_y = (ctx->device->integer_dot_product || ctx->device->coopmat_int_support) && + const bool can_quantize_y = !use_mm_fused && (ctx->device->integer_dot_product || ctx->device->coopmat_int_support) && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0 && ggml_vk_src1_prec_allows_q8(dst); - // coopmat shaders are fast enough that memory bandwidth reduction from f16 activations helps - const bool prefer_f16_b = is_coopmat && ggml_is_quantized(src0->type) && src1->type == GGML_TYPE_F32; + // coopmat shaders are fast enough that memory bandwidth reduction from f16 activations helps on PCIe GPUs; + // on unified-memory Apple AGX, direct F32 vec4/mat2x4 reads avoid an extra cpy_f32_f16 dispatch + barrier. + static const int gen_mm_f16_b = getenv("GGML_VK_MM_F16_B") ? atoi(getenv("GGML_VK_MM_F16_B")) : -1; + const bool allow_f32_f16_b = src0->type == GGML_TYPE_F32 && ggml_vk_is_apple_agx_coopmat(ctx->device) && + !ggml_vk_exact_s8_enabled() && !gen_batch_invariant_for_n(ne11) && ne11 >= 128; + const bool prefer_f16_b = is_coopmat && (ggml_is_quantized(src0->type) || allow_f32_f16_b) && src1->type == GGML_TYPE_F32 && + (ggml_vk_exact_s8_enabled() || gen_mm_f16_b > 0 || (gen_mm_f16_b < 0 && + (!ggml_vk_is_apple_agx_coopmat(ctx->device) || get_misalign_bytes(ctx, src1) != 0 || ne11 >= 128))); const ggml_type y_kernel_type = ggml_vk_mul_mat_b_type(ctx, src0->type, src1, f16_type, ggml_prec_get_acc(dst), false, can_quantize_y, prefer_f16_b); @@ -7246,12 +8882,13 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub const bool y_f32_kernel = y_kernel_type == GGML_TYPE_F32; const bool y_needs_reformat = !quantize_y && (!ggml_vk_dim01_contiguous(src1) || y_kernel_type != src1->type); + const bool is_repack = ggml_vk_tensor_is_repack(src0); ggml_type mmp_type_a = src0->type; const ggml_type mmp_type_b = y_kernel_type; - const std::vector * mmp_map = + const std::vector * mmp_map = is_repack ? nullptr : ggml_vk_get_mul_mat_mat_pipeline_map(ctx, mmp_type_a, mmp_type_b, ggml_prec_get_acc(dst)); - const bool qx_needs_dequant = mmp_map == nullptr || x_non_contig; + const bool qx_needs_dequant = mmp_map == nullptr || x_non_contig || is_repack; const bool qy_needs_dequant = y_needs_reformat; if (qx_needs_dequant) { @@ -7263,7 +8900,7 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub GGML_ASSERT(mmp_map != nullptr); const std::vector * regular_mmp_map = mmp_map; - bool use_stream_k = ctx->device->coopmat2 && !ctx->device->disable_stream_k && !disable_split_k; + bool use_stream_k = !use_mm_fused && ctx->device->coopmat2 && !ctx->device->disable_stream_k && !disable_split_k; if (use_stream_k) { mmp_map = ggml_vk_get_mul_mat_mat_pipeline_map(ctx, mmp_type_a, mmp_type_b, ggml_prec_get_acc(dst), false, true); if (mmp_map == nullptr) { @@ -7272,35 +8909,63 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub } } - const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align_map(ctx, *mmp_map, ne01, ne11, false)); - const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8; - const bool needs_64b_indexing = ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange; + const vk_subbuffer d_U_opt = (has_pair_glu || has_pair_mm) ? ggml_vk_tensor_subbuffer(ctx, src0_up) : vk_subbuffer{}; + const size_t raw_x_offs = src0_uma ? qx_buf_offset : (vk_tensor_offset(src0) + src0->view_offs); + const size_t raw_y_offs = src1_uma ? qy_buf_offset : (vk_tensor_offset(src1) + src1->view_offs); + const bool offsets_vec8_aligned = + (qx_needs_dequant || ggml_is_quantized(src0->type) || ((raw_x_offs % 32 == 0) && (!(has_pair_glu || has_pair_mm) || (d_U_opt.offset % 32 == 0)))) && + (qy_needs_dequant || quantize_y || (raw_y_offs % 32 == 0)); + + const uint64_t total_m = has_pair_mm ? (ne01 + (uint64_t)ctx->gen_pair_mm1->ne[0]) : ne01; + const uint32_t sel_m = has_pair_glu ? (uint32_t)(2 * ne01) : (uint32_t)total_m; + const uint32_t map_align = ggml_vk_guess_matmul_pipeline_align_map(ctx, *mmp_map, sel_m, ne11, false); + const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, map_align); + const bool aligned = !quantize_y && ne10 == kpad && offsets_vec8_aligned && + ((ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled()) || (ne01 > 8 && ne11 > 8)); if (use_stream_k && !aligned) { mmp_map = regular_mmp_map; use_stream_k = false; } - vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *mmp_map, ne01, ne11, aligned, false); + vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *mmp_map, sel_m, ne11, aligned, false); const bool narrow_n = mmp_map->back().narrow_n_max != 0 && ne11 <= mmp_map->back().narrow_n_max; const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline, narrow_n); const uint32_t stream_k_groups = use_stream_k ? ggml_vk_guess_stream_k_groups(ctx, pipeline, ne01, ne11, ne10, stride_d, ne12 * ne13, split_k, disable_split_k) : 0; if (use_stream_k && stream_k_groups == 0) { - pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *regular_mmp_map, ne01, ne11, aligned, false); + pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *regular_mmp_map, sel_m, ne11, aligned, false); } - if (needs_64b_indexing) { + auto tensor_alloc_bytes = [](const ggml_tensor * t) -> uint64_t { + return t ? (ggml_vk_tensor_is_repack(t) ? ggml_vk_repack_alloc_bytes(t) : ggml_nbytes(t)) : 0; + }; + const uint64_t max_a_nbytes = std::max(tensor_alloc_bytes(src0), tensor_alloc_bytes(src0_up)); + if (max_a_nbytes > ctx->device->properties.limits.maxStorageBufferRange) { pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline); } + if (has_pair_glu) { + GGML_ASSERT(pipeline && pipeline->gen_pair_glu); + pipeline = pipeline->gen_pair_glu; + } else if (has_pair_mm) { + GGML_ASSERT(pipeline && pipeline->gen_pair_mm); + pipeline = pipeline->gen_pair_mm; + } else if (use_mm_fused) { + if ((fusion_flags & ~(MAT_VEC_FUSION_FLAGS_BIAS0 | MAT_VEC_FUSION_FLAGS_BIAS1 | MAT_VEC_FUSION_FLAGS_ROW_SCALE0)) == 0u && pipeline && pipeline->gen_fast_ep) { + pipeline = pipeline->gen_fast_ep; + } else { + GGML_ASSERT(pipeline && pipeline->gen_glu); + pipeline = pipeline->gen_glu; + } + } // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11; const uint64_t x_ne = ggml_nelements(src0); // 128 elements per Q8_1 x4 block const uint64_t y_ne = padded_n * ne10 * ne12 * ne13; - const uint64_t d_ne = ggml_nelements(dst); + const uint64_t d_ne = ggml_nelements(out_dst); - const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type); + const uint64_t qx_sz = is_repack ? ggml_vk_repack_alloc_bytes(src0) : (ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type)); const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type); const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne; const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne); @@ -7310,7 +8975,10 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub vk_pipeline to_fp16_vk_1 = nullptr; vk_pipeline to_q8_1 = nullptr; - if (x_non_contig) { + if (is_repack) { + GGML_ASSERT(!x_non_contig); + to_fp16_vk_0 = ctx->device->pipeline_dequant_repack[ggml_vk_repack_type_idx(src0->type)]; + } else if (x_non_contig) { to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type); } else { to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type); @@ -7364,8 +9032,9 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub } } - vk_buffer d_D = dst_buf_ctx->dev_buffer; - const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs; + const vk_subbuffer out_d_sub = ggml_vk_tensor_subbuffer(ctx, out_dst); + vk_buffer d_D = out_d_sub.buffer; + const uint64_t d_buf_offset = out_d_sub.offset; GGML_ASSERT(d_D != nullptr); GGML_ASSERT(d_D->size >= d_buf_offset + d_sz); vk_buffer d_X; @@ -7415,30 +9084,21 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)(x_ne), 1, 1}); ggml_vk_sync_buffers(ctx, subctx); } + uint32_t y_ring_slot = 0; if (y_needs_reformat) { - if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() || - ctx->prealloc_y_last_tensor_used != src1 || - ctx->prealloc_y_last_k_padded) { - if (ctx->prealloc_y_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } - ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0)); - ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get(); - ctx->prealloc_y_last_tensor_used = src1; - ctx->prealloc_y_last_k_padded = false; + bool cached = false; + y_ring_slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, to_fp16_vk_1.get(), src1, false, cached); + y_buf_offset = y_ring_slot * ctx->prealloc_y_ring_stride; + if (!cached) { + ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), vk_subbuffer{ d_Y, y_buf_offset, y_sz }); } } if (quantize_y) { - if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() || - ctx->prealloc_y_last_tensor_used != src1 || - ctx->prealloc_y_last_k_padded) { - if (ctx->prealloc_y_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } - ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne); - ctx->prealloc_y_last_pipeline_used = to_q8_1.get(); - ctx->prealloc_y_last_tensor_used = src1; - ctx->prealloc_y_last_k_padded = false; + bool cached = false; + y_ring_slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, to_q8_1.get(), src1, false, cached); + y_buf_offset = y_ring_slot * ctx->prealloc_y_ring_stride; + if (!cached) { + ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), vk_subbuffer{ d_Y, y_buf_offset, CEIL_DIV(y_sz, 144) * 144 }, y_ne); } } @@ -7464,21 +9124,43 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub : (uint64_t)src1->nb[1]; // compute - ggml_vk_matmul( - ctx, subctx, pipeline, - { d_X, x_buf_offset, x_range }, { d_Y, y_buf_offset, y_range }, - ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, split_k_size }, - ne01, ne11, ne10, - ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d, - split_k, stream_k_groups, ne12*ne13, ne02, ne12, r2, r3, padded_n, - b_col_bytes, (uint64_t)dst->nb[1] - ); // NOLINT + if (use_mm_fused) { + const vk_subbuffer d_sub = ggml_vk_subbuffer(ctx, d_D, d_buf_offset); + const vk_subbuffer x_sub = { d_X, x_buf_offset, x_range }; + const vk_subbuffer y_sub = { d_Y, y_buf_offset, y_range }; + const vk_subbuffer u_sub = (has_pair_glu || has_pair_mm) ? d_U_opt : x_sub; + const vk_subbuffer aux0_sub = aux0_t ? ggml_vk_tensor_subbuffer(ctx, aux0_t) : d_sub; + const vk_subbuffer aux1_sub = aux1_t ? ggml_vk_tensor_subbuffer(ctx, aux1_t) : d_sub; + const uint32_t stride_d2 = has_pair_mm ? (uint32_t)(out_dst2->nb[1] / ggml_type_size(out_dst2->type)) : 0u; + const uint32_t stride_batch_d2 = has_pair_mm ? (uint32_t)(stride_d2 * out_dst2->ne[1]) : 0u; + ggml_vk_matmul_fused( + ctx, subctx, pipeline, + x_sub, y_sub, d_sub, u_sub, aux0_sub, aux1_sub, + (uint32_t)total_m, ne11, ne10, + ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d, + ne12*ne13, ne02, ne12, r2, r3, padded_n, + b_col_bytes, (uint64_t)out_dst->nb[1], + aux0_col_bytes, aux1_col_bytes, fusion_flags, + has_pair_mm ? (uint32_t)ne01 : 0u, stride_d2, stride_batch_d2 + ); + } else { + ggml_vk_matmul( + ctx, subctx, pipeline, + { d_X, x_buf_offset, x_range }, { d_Y, y_buf_offset, y_range }, + ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, split_k_size }, + ne01, ne11, ne10, + ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d, + split_k, stream_k_groups, ne12*ne13, ne02, ne12, r2, r3, padded_n, + b_col_bytes, (uint64_t)out_dst->nb[1] + ); // NOLINT + } if (x_non_contig || qx_needs_dequant) { ctx->prealloc_x_need_sync = true; } if (y_needs_reformat || quantize_y) { ctx->prealloc_y_need_sync = true; + ctx->prealloc_y_slot_need_sync[y_ring_slot] = true; } } @@ -7568,8 +9250,23 @@ static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, bool swap_inputs = false) { ggml_tensor * dst = cgraph->nodes[node_idx]; + const bool has_pair_mm = !swap_inputs && ctx->gen_pair_mm1 != nullptr; + const bool has_pair_glu = !swap_inputs && !has_pair_mm && + ((ctx->num_additional_fused_ops == 2 && cgraph->nodes[node_idx + 2]->op == GGML_OP_GLU) || + ctx->gen_lora_gate_src0 != nullptr); const ggml_tensor * src0 = dst->src[swap_inputs ? 1 : 0]; - const ggml_tensor * src1 = dst->src[swap_inputs ? 0 : 1]; + const ggml_tensor * src1 = (!swap_inputs && ctx->gen_mm_src1_override != nullptr) ? ctx->gen_mm_src1_override : dst->src[swap_inputs ? 0 : 1]; + const ggml_tensor * src0_up = nullptr; + if (has_pair_glu) { + if (ctx->gen_lora_gate_src0 != nullptr) { + src0 = ctx->gen_lora_gate_src0; + src0_up = ctx->gen_lora_up_src0; + } else { + const ggml_tensor * glu = cgraph->nodes[node_idx + 2]; + src0 = glu->src[0]->src[0]; + src0_up = glu->src[1]->src[0]; + } + } VK_LOG_DEBUG("ggml_vk_mul_mat_vec_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; @@ -7592,15 +9289,23 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& const uint64_t ne21 = dst->ne[swap_inputs ? 0 : 1]; // const uint64_t ne22 = dst->ne[2]; // const uint64_t ne23 = dst->ne[3]; + const uint64_t pair_m1 = has_pair_mm ? (uint64_t)ctx->gen_pair_mm1->ne[0] : 0; + const uint64_t total_m = has_pair_mm ? (ne01 + pair_m1) : ne20; const uint64_t r2 = ne12 / ne02; const uint64_t r3 = ne13 / ne03; // batch_n indicates that we need to compute a few vector results, and this assumes // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides. - GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1); + const bool s19_batched_dmmv = ne11 > 1 && ne12 * ne13 > 1 && ne12 * ne13 <= 4 && ne11 <= 8 && + !ggml_vk_tensor_is_repack(src0) && + (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_Q8_0) && + src1->type == GGML_TYPE_F32; + GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1 || s19_batched_dmmv); bool batch_n = ne11 > 1; + const bool is_repack = ggml_vk_tensor_is_repack(src0); + const int repack_ri = is_repack ? ggml_vk_repack_type_idx(src0->type) : -1; const bool x_non_contig = !ggml_vk_dim01_contiguous(src0); // BF16 src1 has no mul_mat_vec B-type; widen to F32 @@ -7609,7 +9314,7 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& const ggml_type y_kernel_type = widen_bf16 ? GGML_TYPE_F32 : src1->type; const bool f16_f32_kernel = y_kernel_type == GGML_TYPE_F32; - bool quantize_y = ctx->device->integer_dot_signed && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && (swap_inputs || ggml_vk_src1_prec_allows_q8(dst)) && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type); + bool quantize_y = !is_repack && !has_pair_glu && !has_pair_mm && !s19_batched_dmmv && ctx->gen_mm_src1_override == nullptr && ctx->gen_lora_r == 0 && ctx->device->integer_dot_signed && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && (swap_inputs || ggml_vk_src1_prec_allows_q8(dst)) && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type); vk_pipeline to_fp16_vk_0 = nullptr; vk_pipeline to_fp16_vk_1 = nullptr; @@ -7622,23 +9327,187 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type); } + static const bool mma_disabled = getenv("GGML_VK_DISABLE_MMA") != nullptr; + static const int env_mma_min_n = getenv("GGML_VK_MMA_MIN_N") ? atoi(getenv("GGML_VK_MMA_MIN_N")) : 8; + static const int env_mma_max_n = getenv("GGML_VK_MMA_MAX_N") ? atoi(getenv("GGML_VK_MMA_MAX_N")) : 4096; + static const int env_mma_cfg = getenv("GGML_VK_MMA_CFG") ? atoi(getenv("GGML_VK_MMA_CFG")) : -1; + static const int env_mma_rt = getenv("GGML_VK_MMA_RT") ? atoi(getenv("GGML_VK_MMA_RT")) : -1; + static const int env_mma_f32_rt = getenv("GGML_VK_MMA_F32_RT") ? atoi(getenv("GGML_VK_MMA_F32_RT")) : -1; + static const int env_mma_f32_f16_min_n = getenv("GGML_VK_MMA_F32_F16_MIN_N") ? atoi(getenv("GGML_VK_MMA_F32_F16_MIN_N")) : 64; + static const int env_mma_bf16_min_n = getenv("GGML_VK_MMA_BF16_MIN_N") ? atoi(getenv("GGML_VK_MMA_BF16_MIN_N")) : 64; + static const uint32_t env_mma_bf16_kp = getenv("GGML_VK_MMA_BF16_KP") ? (uint32_t)atoi(getenv("GGML_VK_MMA_BF16_KP")) : 2u; + const bool use_f32_f16_mma = src0->type == GGML_TYPE_F32 && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(ne11) && + env_mma_f32_f16_min_n >= 0 && + (int64_t)ne11 >= env_mma_f32_f16_min_n; + const bool mma_can_bf16 = (use_f32_f16_mma || src0->type != GGML_TYPE_F32) && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(ne11) && + env_mma_bf16_min_n >= 0 && + (int64_t)ne11 >= env_mma_bf16_min_n && + (ne00 % (64u * env_mma_bf16_kp) == 0) && + !y_non_contig && ggml_is_contiguous(src1) && get_misalign_bytes(ctx, src1) == 0 && + (src1->type == GGML_TYPE_F16 || (src1->type == GGML_TYPE_F32 && ctx->device->pipeline_contig_cpy_f32_f16 != nullptr)); + const uint32_t mma_bf16_idx = mma_can_bf16 ? 1u : 0u; + const bool f32_force_rt2 = (src0->type == GGML_TYPE_F32) && + (env_mma_f32_rt == 2 || (env_mma_f32_rt < 0 && (!use_f32_f16_mma || total_m <= 128))); + const bool small_m_force_rt2 = (total_m <= 128 && ne11 >= 64 && ne11 <= 512); + uint32_t mma_rt_idx = 2u; + if (env_mma_rt == 1) { mma_rt_idx = 0u; } + else if (env_mma_rt == 2) { mma_rt_idx = 1u; } + else if (env_mma_rt == 4) { mma_rt_idx = 2u; } + else if (env_mma_rt == 6 && (use_f32_f16_mma || src0->type != GGML_TYPE_F32)) { mma_rt_idx = 3u; } + else if (env_mma_rt == 8 && (use_f32_f16_mma || src0->type != GGML_TYPE_F32)) { mma_rt_idx = 4u; } + else if (ne11 <= 8) { + mma_rt_idx = 0u; + } else if (ne11 <= 16 || f32_force_rt2 || small_m_force_rt2 || (total_m <= 2048 && ne11 <= 32)) { + mma_rt_idx = 1u; + } else { + mma_rt_idx = 2u; // RT=4 (BN=32, 8 accumulators = 32 half-regs, 8 KiB sh_b -> peak AGX occupancy) + } + static constexpr uint32_t k_mma_rts_sel[5] = { 1u, 2u, 4u, 6u, 8u }; + const uint32_t mma_rt = k_mma_rts_sel[mma_rt_idx]; + const uint32_t mma_k_step = ((src0->type == GGML_TYPE_Q8_0 && mma_rt_idx == 0u) || src0->type == GGML_TYPE_Q4_0) ? 32u : 64u; + const int eff_mma_min_n = ((total_m >= 32768 || + (src0->type == GGML_TYPE_Q8_0 && ne00 >= 2048 && (total_m >= 4096 || (total_m * ne02 >= 2048 && ne11 >= 6)))) && + env_mma_min_n == 8) + ? 4 : env_mma_min_n; + const bool use_mv_mma = !mma_disabled && + ggml_vk_is_apple_agx_coopmat(ctx->device) && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(ne11) && + !swap_inputs && + (!s19_batched_dmmv || (ne11 >= 6 && src0->type == GGML_TYPE_Q8_0 && ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst))) && + ctx->gen_mm_src1_override == nullptr && + (int64_t)ne11 >= eff_mma_min_n && (int64_t)ne11 <= env_mma_max_n && + total_m >= 4 && + (y_kernel_type == GGML_TYPE_F32 || (mma_bf16_idx == 1u && y_kernel_type == GGML_TYPE_F16)) && + dst->type == GGML_TYPE_F32 && + (ne00 % mma_k_step == 0) && + (!has_pair_mm || (ne01 % 8 == 0 && ctx->gen_pair_mm1->src[0]->type == src0->type && ggml_vk_tensor_is_repack(ctx->gen_pair_mm1->src[0]) == is_repack)) && + (use_f32_f16_mma ? ctx->device->pipeline_mul_mv_mma_f32_f16[mma_rt_idx][4][mma_bf16_idx] != nullptr + : (is_repack ? (repack_ri >= 0 && ctx->device->pipeline_mul_mv_mma_repack[repack_ri][mma_rt_idx][4][mma_bf16_idx] != nullptr) + : ctx->device->pipeline_mul_mv_mma[src0->type][mma_rt_idx][4][mma_bf16_idx] != nullptr)); + + static const int env_col_tile = getenv("GGML_VK_MMV_COL_TILE") ? atoi(getenv("GGML_VK_MMV_COL_TILE")) : -1; + static const bool s18_col_tile = getenv("S19_S18_RM_Q8") != nullptr; + const uint32_t max_repack_tile = (src0->type == GGML_TYPE_NVFP4) ? 8u : 4u; + const uint32_t def_repack_tile = (src0->type == GGML_TYPE_NVFP4 && ne11 <= 4) ? 4u : ((src0->type == GGML_TYPE_NVFP4 && ne11 <= 8) ? 3u : 4u); + const uint32_t col_tile = is_repack + ? (env_col_tile > 0 ? std::min(max_repack_tile, (uint32_t)env_col_tile) : def_repack_tile) + : (env_col_tile >= 0 ? (uint32_t)env_col_tile : (s18_col_tile ? (ne11 <= 8 ? 8u : 4u) : (ne11 <= 4 ? 4u : (ne11 <= 8 ? 3u : 4u)))); + const bool use_col_split = !use_mv_mma && col_tile > 0 && ggml_vk_is_apple_agx_coopmat(ctx->device) && + !swap_inputs && batch_n && ne12 * ne13 == 1 && ne11 > col_tile; + const uint32_t full_col_tiles = use_col_split ? (uint32_t)(ne11 / col_tile) : 0u; + const uint32_t rem_col_count = use_col_split ? (uint32_t)(ne11 % col_tile) : 0u; + const uint64_t eff_num_cols = use_col_split ? (uint64_t)col_tile : ne11; + // Check for mmq first - vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr; + vk_pipeline dmmv = nullptr; + vk_pipeline dmmv_rem = nullptr; vk_pipeline to_q8_1 = nullptr; + if (use_mv_mma) { + quantize_y = false; + const uint32_t n_steps = (uint32_t)(ne00 / mma_k_step); + const uint64_t n_col_tiles = CEIL_DIV(ne11, 8u * mma_rt) * (uint64_t)(ne12 * ne13); + const uint64_t wg_64 = CEIL_DIV(total_m, 64) * n_col_tiles; + const uint64_t wg_32 = CEIL_DIV(total_m, 32) * n_col_tiles; + uint32_t ci = 4u; + if (env_mma_cfg >= 0 && env_mma_cfg <= 7) { + ci = (uint32_t)env_mma_cfg; + if ((ci == 7u || ci == 6u || ci == 5u || ci == 3u) && (ne00 % 64 != 0)) { + ci = 4u; + } + } else if (small_m_force_rt2 && n_steps >= 8u) { + ci = (total_m >= 16) ? 2u : 1u; // NSG=4 K-split keeps all 40 cores saturated on small-M GDN/LoRA gates + } else if ((ne00 % 64 == 0) && total_m >= 64 && wg_64 >= 48) { + ci = 5u; // WG_SG=4 (128 threads), MSG=4, NT=2 (NT=1 BM=32 on _pairglu), zero barrier stragglers & peak occupancy + } else if ((ne00 % 64 == 0) && total_m >= 32 && wg_32 >= 32) { + ci = 3u; // MSG=2, NSG=1, NT=2 (BM=32 cooperative sh_b, 0 spills, fills all 40 cores!) + } else if (total_m <= 128 && n_steps >= 16u) { + ci = 0u; // NSG=8, NT=1 + } else if (total_m <= 512 && n_steps >= 8u) { + ci = 1u; // NSG=4, NT=1 + } else if (mma_rt_idx == 0u && total_m <= 2048 && n_steps >= 8u) { + ci = 2u; // NSG=4, NT=2 + } else { + ci = 4u; // NSG=1, NT=2 + } + dmmv = use_f32_f16_mma + ? ctx->device->pipeline_mul_mv_mma_f32_f16[mma_rt_idx][ci][mma_bf16_idx] + : (is_repack ? ctx->device->pipeline_mul_mv_mma_repack[repack_ri][mma_rt_idx][ci][mma_bf16_idx] + : ctx->device->pipeline_mul_mv_mma[src0->type][mma_rt_idx][ci][mma_bf16_idx]); + if (dmmv == nullptr) { + ci = 4u; + dmmv = use_f32_f16_mma + ? ctx->device->pipeline_mul_mv_mma_f32_f16[mma_rt_idx][ci][mma_bf16_idx] + : (is_repack ? ctx->device->pipeline_mul_mv_mma_repack[repack_ri][mma_rt_idx][ci][mma_bf16_idx] + : ctx->device->pipeline_mul_mv_mma[src0->type][mma_rt_idx][ci][mma_bf16_idx]); + } + } else { + dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, eff_num_cols, total_m, ne00, is_repack) : nullptr; + } + if (dmmv == nullptr) { // Fall back to f16 dequant mul mat - dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, y_kernel_type, ne11, ne20, ne00); + dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, y_kernel_type, eff_num_cols, total_m, ne00, is_repack); quantize_y = false; } + if (rem_col_count > 0) { + dmmv_rem = quantize_y + ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, rem_col_count, total_m, ne00, is_repack) + : ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, y_kernel_type, rem_col_count, total_m, ne00, is_repack); + if (dmmv_rem == nullptr && quantize_y) { + quantize_y = false; + dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, y_kernel_type, eff_num_cols, total_m, ne00, is_repack); + dmmv_rem = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, y_kernel_type, rem_col_count, total_m, ne00, is_repack); + } + } if (quantize_y) { to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1); } - if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { - dmmv = ggml_vk_get_64b_indexing_pipeline(ctx, dmmv); - } + auto tensor_alloc_bytes = [](const ggml_tensor * t) -> uint64_t { + return t ? (ggml_vk_tensor_is_repack(t) ? ggml_vk_repack_alloc_bytes(t) : ggml_nbytes(t)) : 0; + }; + const uint64_t max_a_nbytes = std::max(tensor_alloc_bytes(src0), + src0_up ? tensor_alloc_bytes(src0_up) : (has_pair_mm ? tensor_alloc_bytes(ctx->gen_pair_mm1->src[0]) : 0)); + const bool mv_mma_bias_only = use_mv_mma && + ((ctx->gen_mm_dst == nullptr && ctx->num_additional_fused_ops > 0 && + !(ctx->num_additional_fused_ops == 1 && cgraph->nodes[node_idx + 1]->op == GGML_OP_GLU)) || + (ctx->gen_mm_dst != nullptr && (ctx->gen_mm_flags & ~(uint32_t)MAT_VEC_FUSION_FLAGS_BIAS0) == 0)); + auto specialize_dmmv = [&](vk_pipeline p) -> vk_pipeline { + if (!p) { + return nullptr; + } + if (max_a_nbytes > ctx->device->properties.limits.maxStorageBufferRange) { + p = ggml_vk_get_64b_indexing_pipeline(ctx, p); + } + if (has_pair_glu) { + GGML_ASSERT(p && p->gen_pair_glu); + p = p->gen_pair_glu; + } else if (has_pair_mm) { + GGML_ASSERT(p && p->gen_pair_mm); + p = p->gen_pair_mm; + } else if (mv_mma_bias_only && p->gen_fast_ep) { + p = p->gen_fast_ep; + } else if ((use_mv_mma && ctx->num_additional_fused_ops > 0) || + (ctx->num_additional_fused_ops == 1 && cgraph->nodes[node_idx + 1]->op == GGML_OP_GLU) || + ctx->gen_mm_dst != nullptr) { + GGML_ASSERT(p && p->gen_glu); + p = p->gen_glu; // gen: single-op epilogue twin (GEN_GLU = 1 / FUSE_MODE = 1) + } + if (ctx->gen_lora_r > 0) { + GGML_ASSERT(p && p->gen_lora_twin); + p = p->gen_lora_twin; + } + return p; + }; + dmmv = specialize_dmmv(dmmv); + dmmv_rem = specialize_dmmv(dmmv_rem); const bool qx_needs_dequant = x_non_contig; const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig); @@ -7653,11 +9522,16 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& const uint64_t x_ne = ggml_nelements(src0); const uint64_t y_ne = ggml_nelements(src1); - const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment); + const uint64_t qx_sz = is_repack + ? ggml_vk_align_size(ggml_vk_repack_alloc_bytes(src0), ctx->device->properties.limits.minStorageBufferOffsetAlignment) + : ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment); const uint64_t x_sz = x_non_contig ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : qx_sz; const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne); + const bool mma_use_y_f16_ring = use_mv_mma && mma_bf16_idx == 1u && src1->type == GGML_TYPE_F32; + const uint64_t mma_y_f16_sz = sizeof(ggml_fp16_t) * y_ne; + { if ( (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) || @@ -7672,6 +9546,9 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& ctx->prealloc_size_y = y_sz; ggml_vk_preallocate_buffers(ctx, subctx); } + if (mma_use_y_f16_ring) { + ggml_vk_reserve_prealloc_y(ctx, subctx, mma_y_f16_sz); + } // Request descriptor sets if (qx_needs_dequant) { @@ -7683,9 +9560,13 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& if (quantize_y) { ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1); } + if (mma_use_y_f16_ring) { + ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_contig_cpy_f32_f16, 1); + } } - vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]); + vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, has_pair_mm ? (ctx->gen_mm_dst ? ctx->gen_mm_dst : dst) : (ctx->gen_mm_dst ? ctx->gen_mm_dst : cgraph->nodes[node_idx + ctx->num_additional_fused_ops])); + vk_subbuffer d_D2 = has_pair_mm ? ggml_vk_tensor_subbuffer(ctx, ctx->gen_pair_dst1) : d_D; vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0); vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1); vk_subbuffer d_X, d_Y; @@ -7710,36 +9591,35 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment)); ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X); } + uint32_t y_ring_slot = 0; if (y_non_contig) { GGML_ASSERT(y_sz == ggml_type_size(y_kernel_type) * y_ne); - if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() || - ctx->prealloc_y_last_tensor_used != src1 || - ctx->prealloc_y_last_k_padded) { - if (ctx->prealloc_y_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } + bool cached = false; + y_ring_slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, to_fp16_vk_1.get(), src1, false, cached); + d_Y = { ctx->prealloc_y, y_ring_slot * ctx->prealloc_y_ring_stride, y_sz }; + if (!cached) { ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y); - ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get(); - ctx->prealloc_y_last_tensor_used = src1; - ctx->prealloc_y_last_k_padded = false; + } + } + if (mma_use_y_f16_ring) { + bool cached = false; + y_ring_slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, ctx->device->pipeline_contig_cpy_f32_f16.get(), src1, false, cached); + d_Y = { ctx->prealloc_y, y_ring_slot * ctx->prealloc_y_ring_stride, mma_y_f16_sz }; + if (!cached) { + ggml_vk_cpy_to_contiguous(ctx, subctx, ctx->device->pipeline_contig_cpy_f32_f16, src1, d_Qy, d_Y); } } if (quantize_y) { - if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() || - ctx->prealloc_y_last_tensor_used != src1 || - ctx->prealloc_y_last_k_padded) { - if (ctx->prealloc_y_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } + bool cached = false; + y_ring_slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, to_q8_1.get(), src1, false, cached); + d_Y = { ctx->prealloc_y, y_ring_slot * ctx->prealloc_y_ring_stride, y_sz }; + if (!cached) { ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne); - ctx->prealloc_y_last_pipeline_used = to_q8_1.get(); - ctx->prealloc_y_last_tensor_used = src1; - ctx->prealloc_y_last_k_padded = false; } } // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride - uint32_t stride_batch_x = batch_n ? 0 : (qx_needs_dequant ? ne00*ne01 : ggml_vk_batch_stride(src0)); + uint32_t stride_batch_x = (batch_n && ne02 * ne03 == 1) ? 0 : (qx_needs_dequant ? ne00*ne01 : ggml_vk_batch_stride(src0)); uint32_t stride_batch_y = batch_n ? ne10 : ((qy_needs_dequant || quantize_y) ? ne10*ne11 : ggml_vk_batch_stride(src1)); uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21); @@ -7753,10 +9633,11 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0]; - uint32_t groups_x = ne01; + const uint64_t launch_m = has_pair_mm ? total_m : ne01; + uint32_t groups_x = (uint32_t)launch_m; uint32_t groups_z = 1; - if (ne01 > max_groups_x) { + if (launch_m > max_groups_x) { groups_z = 64; groups_x = CEIL_DIV(groups_x, groups_z); } @@ -7764,7 +9645,35 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& uint32_t fusion_flags = 0; vk_subbuffer d_F0 = d_D; - if (ctx->num_additional_fused_ops > 0) { + vk_subbuffer d_F1 = d_D; + vk_subbuffer d_F2 = d_D; + if (has_pair_glu) { + d_F0 = ggml_vk_tensor_subbuffer(ctx, src0_up); + fusion_flags |= MAT_VEC_FUSION_FLAGS_PAIR_GLU; + } else if (has_pair_mm) { + d_F0 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_pair_mm1->src[0]); + if (ctx->gen_mm_f0 != nullptr) { + d_F1 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_mm_f0); + } + if (ctx->gen_mm_f1 != nullptr) { + d_F2 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_mm_f1); + } + fusion_flags |= ctx->gen_mm_flags; + } else if (ctx->gen_mm_dst != nullptr) { + fusion_flags |= ctx->gen_mm_flags; + if (ctx->gen_mm_f0 != nullptr) { + d_F0 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_mm_f0); + } + if (ctx->gen_mm_f1 != nullptr) { + d_F1 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_mm_f1); + } + } else if (ctx->num_additional_fused_ops == 1 && cgraph->nodes[node_idx + 1]->op == GGML_OP_GLU) { + // gen: SWIGLU epilogue (GGML_GEN_FUSE=glu) + const ggml_tensor * glu = cgraph->nodes[node_idx + 1]; + const bool is_gate = glu->src[0] == dst; + d_F0 = ggml_vk_tensor_subbuffer(ctx, is_gate ? glu->src[1] : glu->src[0]); + fusion_flags |= is_gate ? MAT_VEC_FUSION_FLAGS_GLU_A : MAT_VEC_FUSION_FLAGS_GLU_B; + } else if (ctx->num_additional_fused_ops > 0) { const ggml_tensor * add = cgraph->nodes[node_idx + 1]; const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0]; @@ -7772,8 +9681,7 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0; } - vk_subbuffer d_F1 = d_D; - if (ctx->num_additional_fused_ops == 2) { + if (!has_pair_glu && !has_pair_mm && ctx->gen_mm_dst == nullptr && ctx->num_additional_fused_ops == 2) { const ggml_tensor * add = cgraph->nodes[node_idx + 2]; const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0]; @@ -7781,35 +9689,151 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1; } - ggml_pipeline_request_descriptor_sets(ctx, dmmv, CEIL_DIV(ne12 * ne13, ctx->device->properties.limits.maxComputeWorkGroupCount[1])); - - uint32_t base_work_group_y = 0; - while (base_work_group_y < ne12 * ne13) { - - uint32_t groups_y = std::min((uint32_t)(ne12 * ne13) - base_work_group_y, ctx->device->properties.limits.maxComputeWorkGroupCount[1]); - const vk_mat_vec_push_constants pc = { - (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01, - stride_batch_x, stride_batch_y, stride_batch_d, - fusion_flags, base_work_group_y, - (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3, - }; - ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, - { - d_X, - d_Y, - d_D, - d_F0, - d_F1, - }, - pc, { groups_x, groups_y, groups_z }); - base_work_group_y += groups_y; + vk_subbuffer d_LB0 = d_D; + vk_subbuffer d_LH0 = d_D; + vk_subbuffer d_LB1 = d_D; + vk_subbuffer d_LH1 = d_D; + const uint32_t lora_r = ctx->gen_lora_r; + const float lora_scale0 = ctx->gen_lora_scale0; + const float lora_scale1 = ctx->gen_lora_scale1; + if (lora_r > 0) { + if (ctx->gen_lora_b0 != nullptr && ctx->gen_lora_h0 != nullptr) { + d_LB0 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_lora_b0); + d_LH0 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_lora_h0); + fusion_flags |= MAT_VEC_FUSION_FLAGS_LORA0; + } + if (ctx->gen_lora_b1 != nullptr && ctx->gen_lora_h1 != nullptr) { + d_LB1 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_lora_b1); + d_LH1 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_lora_h1); + fusion_flags |= MAT_VEC_FUSION_FLAGS_LORA1; + } + } + + if (use_mv_mma) { + if (mma_bf16_idx == 1u) { + fusion_flags |= MAT_VEC_FUSION_FLAGS_B_F16; + } + const uint32_t max_wg_z = ctx->device->properties.limits.maxComputeWorkGroupCount[2]; + const uint32_t total_batches = (uint32_t)(ne12 * ne13); + const uint32_t mma_bstride_x = qx_needs_dequant ? (uint32_t)(ne00 * ne01) : (uint32_t)ggml_vk_batch_stride(src0); + const uint32_t mma_bstride_y = (y_non_contig || mma_use_y_f16_ring) ? (uint32_t)(ne10 * ne11) : (uint32_t)ggml_vk_batch_stride(src1); + const uint32_t mma_stride_d = has_pair_mm ? (uint32_t)ne01 : (uint32_t)ne20; + const uint32_t mma_bstride_d = (uint32_t)(mma_stride_d * ne21); + ggml_pipeline_request_descriptor_sets(ctx, dmmv, CEIL_DIV(total_batches, max_wg_z)); + uint32_t base_wg_z = 0; + while (base_wg_z < total_batches) { + const uint32_t cur_z = std::min(total_batches - base_wg_z, max_wg_z); + const vk_mat_mv_mma_push_constants pc = { + (uint32_t)launch_m, (uint32_t)ne11, (uint32_t)ne00, + (uint32_t)ne00, (uint32_t)ne10, mma_stride_d, + mma_bstride_x, mma_bstride_y, mma_bstride_d, + fusion_flags, base_wg_z, + (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3, + has_pair_mm ? (uint32_t)ne01 : 0u, + has_pair_mm ? (uint32_t)pair_m1 : 0u, + has_pair_mm ? (uint32_t)(pair_m1 * ne21) : 0u, + lora_r, lora_scale0, lora_scale1, + }; + if (lora_r > 0) { + ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, + { d_X, d_Y, d_D, d_F0, d_F1, d_D2, d_F2, d_LB0, d_LH0, d_LB1, d_LH1 }, + pc, { (uint32_t)launch_m, (uint32_t)ne11, cur_z }); + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, + { d_X, d_Y, d_D, d_F0, d_F1, d_D2, d_F2 }, + pc, { (uint32_t)launch_m, (uint32_t)ne11, cur_z }); + } + base_wg_z += cur_z; + } + } else if (use_col_split) { + fusion_flags |= MAT_VEC_FUSION_FLAGS_COL_SPLIT; + const uint32_t max_wg_y = ctx->device->properties.limits.maxComputeWorkGroupCount[1]; + ggml_pipeline_request_descriptor_sets(ctx, dmmv, CEIL_DIV(full_col_tiles, max_wg_y)); + if (rem_col_count > 0) { + GGML_ASSERT(dmmv_rem != nullptr); + ggml_pipeline_request_descriptor_sets(ctx, dmmv_rem, 1); + } + uint32_t base_tile = 0; + while (base_tile < full_col_tiles) { + const uint32_t groups_y = std::min(full_col_tiles - base_tile, max_wg_y); + const vk_mat_vec_push_constants pc = { + (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)launch_m, + stride_batch_x, stride_batch_y, stride_batch_d, + fusion_flags, base_tile * col_tile, + (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3, + has_pair_mm ? (uint32_t)ne01 : 0u, + has_pair_mm ? (uint32_t)pair_m1 : 0u, + has_pair_mm ? (uint32_t)(batch_n ? pair_m1 : pair_m1 * ne21) : 0u, + lora_r, lora_scale0, lora_scale1, + }; + if (lora_r > 0) { + ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, + { d_X, d_Y, d_D, d_F0, d_F1, d_D2, d_F2, d_LB0, d_LH0, d_LB1, d_LH1 }, + pc, { groups_x, groups_y, groups_z }); + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, + { d_X, d_Y, d_D, d_F0, d_F1, d_D2, d_F2 }, + pc, { groups_x, groups_y, groups_z }); + } + base_tile += groups_y; + } + if (rem_col_count > 0) { + const vk_mat_vec_push_constants pc = { + (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)launch_m, + stride_batch_x, stride_batch_y, stride_batch_d, + fusion_flags, full_col_tiles * col_tile, + (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3, + has_pair_mm ? (uint32_t)ne01 : 0u, + has_pair_mm ? (uint32_t)pair_m1 : 0u, + has_pair_mm ? (uint32_t)(batch_n ? pair_m1 : pair_m1 * ne21) : 0u, + lora_r, lora_scale0, lora_scale1, + }; + if (lora_r > 0) { + ggml_vk_dispatch_pipeline(ctx, subctx, dmmv_rem, + { d_X, d_Y, d_D, d_F0, d_F1, d_D2, d_F2, d_LB0, d_LH0, d_LB1, d_LH1 }, + pc, { groups_x, 1u, groups_z }); + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, dmmv_rem, + { d_X, d_Y, d_D, d_F0, d_F1, d_D2, d_F2 }, + pc, { groups_x, 1u, groups_z }); + } + } + } else { + ggml_pipeline_request_descriptor_sets(ctx, dmmv, CEIL_DIV(ne12 * ne13, ctx->device->properties.limits.maxComputeWorkGroupCount[1])); + + uint32_t base_work_group_y = 0; + while (base_work_group_y < ne12 * ne13) { + + uint32_t groups_y = std::min((uint32_t)(ne12 * ne13) - base_work_group_y, ctx->device->properties.limits.maxComputeWorkGroupCount[1]); + const vk_mat_vec_push_constants pc = { + (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)launch_m, + stride_batch_x, stride_batch_y, stride_batch_d, + fusion_flags, base_work_group_y, + (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3, + has_pair_mm ? (uint32_t)ne01 : 0u, + has_pair_mm ? (uint32_t)pair_m1 : 0u, + has_pair_mm ? (uint32_t)(batch_n ? pair_m1 : pair_m1 * ne21) : 0u, + lora_r, lora_scale0, lora_scale1, + }; + if (lora_r > 0) { + ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, + { d_X, d_Y, d_D, d_F0, d_F1, d_D2, d_F2, d_LB0, d_LH0, d_LB1, d_LH1 }, + pc, { groups_x, groups_y, groups_z }); + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, + { d_X, d_Y, d_D, d_F0, d_F1, d_D2, d_F2 }, + pc, { groups_x, groups_y, groups_z }); + } + base_work_group_y += groups_y; + } } if (x_non_contig) { ctx->prealloc_x_need_sync = true; } - if (y_non_contig || quantize_y) { + if (y_non_contig || quantize_y || mma_use_y_f16_ring) { ctx->prealloc_y_need_sync = true; + ctx->prealloc_y_slot_need_sync[y_ring_slot] = true; } } @@ -8076,31 +10100,951 @@ static uint32_t ggml_vk_nb_elem(const ggml_tensor * t, int i) { return (uint32_t)(t->nb[i] / ggml_type_size(t->type)); } -void ggml_vk_dsv4_hc_comb(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * mixes, const ggml_tensor * scale, const ggml_tensor * base, ggml_tensor * dst) { - VK_LOG_DEBUG("ggml_vk_dsv4_hc_comb(" << mixes << ", " << scale << ", " << base << ", " << dst << ")"); - - vk_pipeline pipeline = ctx->device->pipeline_dsv4_hc_comb_f32; - GGML_ASSERT(pipeline != nullptr); - - const uint32_t n_tokens = (uint32_t)mixes->ne[1]; +static bool ggml_vk_compute_mask_active_span( + ggml_backend_vk_context * ctx, + const ggml_tensor * kq_mask, + uint32_t mask_r0, + uint32_t nr, + uint32_t * out_kv_min, + uint32_t * out_kv_max) { + static const bool disable_span = getenv("GGML_VK_DISABLE_FA_ACTIVE_SPAN") != nullptr; + if (disable_span || !kq_mask || kq_mask->type != GGML_TYPE_F16 || + kq_mask->nb[0] != sizeof(ggml_fp16_t) || nr == 0) { + return false; + } + const uint32_t n_kv = (uint32_t)kq_mask->ne[0]; + const uint32_t mask_ne1 = (uint32_t)kq_mask->ne[1]; + const uint32_t mask_ne2 = (uint32_t)kq_mask->ne[2]; + const uint32_t mask_ne3 = (uint32_t)kq_mask->ne[3]; + if (n_kv < 128u || mask_r0 + nr > mask_ne1) { + return false; + } + const ggml_tensor * base_t = kq_mask->view_src ? kq_mask->view_src : kq_mask; + if (base_t->op != GGML_OP_NONE || !base_t->buffer || !ggml_backend_buffer_is_vk(base_t->buffer)) { + return false; + } + if (ctx && (!ctx->transfer_ctx.expired() || (!ctx->compute_ctx.expired() && !ctx->compute_ctx.lock()->in_memcpys.empty()))) { + return false; + } + if (ctx) { + for (int i = 0; i < 4; ++i) { + const auto & ce = ctx->mask_span_cache[i]; + if (ce.valid && ce.mask == kq_mask && ce.mask_r0 == mask_r0 && ce.nr == nr) { + *out_kv_min = ce.kv_min; + *out_kv_max = ce.kv_max; + return true; + } + } + } + ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)base_t->buffer->context; + vk_buffer dev_buf = buf_ctx ? buf_ctx->dev_buffer : nullptr; + if (!dev_buf || dev_buf->ptr == nullptr || + !(dev_buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent)) { + return false; + } + const uint8_t * base_ptr = (const uint8_t *)dev_buf->ptr + vk_tensor_offset(kq_mask) + kq_mask->view_offs; + uint32_t cur_min = n_kv; + uint32_t cur_max = 0u; + for (uint32_t m3 = 0; m3 < mask_ne3; ++m3) { + for (uint32_t m2 = 0; m2 < mask_ne2; ++m2) { + for (uint32_t r = 0; r < nr; ++r) { + const uint16_t * row = (const uint16_t *)(base_ptr + + (size_t)m3 * kq_mask->nb[3] + + (size_t)m2 * kq_mask->nb[2] + + (size_t)(mask_r0 + r) * kq_mask->nb[1]); + uint32_t c = 0u; + while (c < cur_min && (((uintptr_t)(row + c)) & 7u) != 0u) { + if (row[c] != 0xFC00u) { cur_min = c; break; } + ++c; + } + while (c + 4u <= cur_min) { + uint64_t w64; + memcpy(&w64, row + c, sizeof(w64)); + if (w64 != 0xFC00FC00FC00FC00ULL) { + for (uint32_t k = 0; k < 4u; ++k) { + if (row[c + k] != 0xFC00u) { cur_min = c + k; break; } + } + break; + } + c += 4u; + } + while (c < cur_min) { + if (row[c] != 0xFC00u) { cur_min = c; break; } + ++c; + } - ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + uint32_t e = n_kv; + while (e > cur_max && (((uintptr_t)(row + e)) & 7u) != 0u) { + if (row[e - 1u] != 0xFC00u) { cur_max = e; break; } + --e; + } + while (e >= cur_max + 4u) { + uint64_t w64; + memcpy(&w64, row + (e - 4u), sizeof(w64)); + if (w64 != 0xFC00FC00FC00FC00ULL) { + for (uint32_t k = 0; k < 4u; ++k) { + if (row[e - 1u - k] != 0xFC00u) { cur_max = e - k; break; } + } + break; + } + e -= 4u; + } + while (e > cur_max) { + if (row[e - 1u] != 0xFC00u) { cur_max = e; break; } + --e; + } - const vk_subbuffer mixes_buf = ggml_vk_tensor_subbuffer(ctx, mixes, true); - const vk_subbuffer scale_buf = ggml_vk_tensor_subbuffer(ctx, scale, true); - const vk_subbuffer base_buf = ggml_vk_tensor_subbuffer(ctx, base, true); - const vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); + if (cur_min == 0u && cur_max == n_kv) { + break; + } + } + if (cur_min == 0u && cur_max == n_kv) { + break; + } + } + if (cur_min == 0u && cur_max == n_kv) { + break; + } + } + if (cur_min >= cur_max) { + cur_min = 0u; + cur_max = 0u; + } + if (ctx) { + for (int i = 0; i < 4; ++i) { + if (!ctx->mask_span_cache[i].valid) { + ctx->mask_span_cache[i] = { kq_mask, nullptr, mask_r0, nr, 0u, cur_min, cur_max, 0u, true }; + break; + } + } + } + *out_kv_min = cur_min; + *out_kv_max = cur_max; + return true; +} - vk_op_dsv4_hc_comb_push_constants pc = { - n_tokens, - ggml_vk_nb_elem(mixes, 0), ggml_vk_nb_elem(mixes, 1), - ggml_vk_nb_elem(scale, 0), - ggml_vk_nb_elem(base, 0), - ggml_vk_nb_elem(dst, 0), ggml_vk_nb_elem(dst, 1), ggml_vk_nb_elem(dst, 2), - 0, 0, 0, 0, - ggml_get_op_params_f32(dst, 0), - (uint32_t)ggml_get_op_params_i32(dst, 1), - }; +static uint32_t ggml_vk_compute_rel_const_prefix_end( + ggml_backend_vk_context * ctx, + const ggml_tensor * kq_mask, + const ggml_tensor * rel_pos_in, + uint32_t mask_r0, + uint32_t r0, + uint32_t nr, + uint32_t n_seq_tokens, + uint32_t n_stream, + uint32_t extent, + uint32_t blk_min, + uint32_t blk_max) { + static const bool disable_const_pfx = getenv("GGML_VK_DISABLE_REL_CONST_PREFIX") != nullptr; + static const bool force_disable_vrow = getenv("GGML_VK_DISABLE_FA_VROW_PACK") != nullptr; + static const bool fa_exact_split3 = getenv("GGML_VK_FA_EXACT_SPLIT3") != nullptr; + static const int min_kv_env = getenv("GGML_VK_FA_LONG_CTX_MIN_KV") ? atoi(getenv("GGML_VK_FA_LONG_CTX_MIN_KV")) : -1; + const int eff_min_kv = min_kv_env >= 0 ? min_kv_env : ((ctx && ggml_vk_is_apple_agx_coopmat(ctx->device)) ? 256 : 4096); + // Activate CONST_PREFIX strictly on multi-token (nr >= 2..8) FA_COOPMAT1 long-context queries + // so N=1 flash_attn_vec_mhm.comp and FA_SCALAR remain 100% untouched at peak s20 occupancy. + const uint32_t min_nr_cpfx = (force_disable_vrow || fa_exact_split3) ? 4u : 2u; + if (disable_const_pfx || !kq_mask || nr < min_nr_cpfx || nr > 8u || + gen_batch_invariant_for_n(nr) || + !ctx || !ctx->device->coopmat1_fa_support || !ctx->device->coopmat_support_8x8x8_f32acc || + (int64_t)kq_mask->ne[0] < (int64_t)eff_min_kv || blk_max < blk_min + 256u) { + return blk_min; + } + const ggml_tensor * rp = rel_pos_in + ? ((rel_pos_in->op == GGML_OP_CONT && rel_pos_in->src[0]) ? rel_pos_in->src[0] : rel_pos_in) + : nullptr; + const uint32_t cache_extent = rp ? extent : UINT32_MAX; + if (ctx) { + for (int i = 0; i < 4; ++i) { + const auto & ce = ctx->mask_span_cache[i]; + if (ce.valid && ce.mask == kq_mask && ce.mask_r0 == mask_r0 && ce.nr == nr && + ce.rel_pos == rp && ce.extent == cache_extent) { + return ce.kv_const_end; + } + } + } + const ggml_tensor * mk_base = kq_mask->view_src ? kq_mask->view_src : kq_mask; + if (!mk_base->buffer || !ggml_backend_buffer_is_vk(mk_base->buffer)) { + return blk_min; + } + ggml_backend_vk_buffer_context * mk_bctx = (ggml_backend_vk_buffer_context *)mk_base->buffer->context; + vk_buffer mk_dev = mk_bctx ? mk_bctx->dev_buffer : nullptr; + if (!mk_dev || !mk_dev->ptr || !(mk_dev->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent)) { + return blk_min; + } + const uint32_t n_kv = (uint32_t)kq_mask->ne[0]; + const int32_t * rp_ptr = nullptr; + if (rp) { + const ggml_tensor * rp_base = rp->view_src ? rp->view_src : rp; + if (rp_base->op != GGML_OP_NONE || !rp_base->buffer || !ggml_backend_buffer_is_vk(rp_base->buffer) || + rp->type != GGML_TYPE_I32 || rp->nb[0] != sizeof(int32_t) || + rp->ne[0] != kq_mask->ne[0] || rp->nb[1] != (size_t)rp->ne[0] * sizeof(int32_t) || + (uint64_t)n_stream * n_seq_tokens > (uint64_t)rp->ne[1]) { + return blk_min; + } + ggml_backend_vk_buffer_context * rp_bctx = (ggml_backend_vk_buffer_context *)rp_base->buffer->context; + vk_buffer rp_dev = rp_bctx ? rp_bctx->dev_buffer : nullptr; + if (!rp_dev || !rp_dev->ptr || !(rp_dev->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent)) { + return blk_min; + } + rp_ptr = (const int32_t *)((const uint8_t *)rp_dev->ptr + vk_tensor_offset(rp) + rp->view_offs); + } + const uint8_t * mk_ptr = (const uint8_t *)mk_dev->ptr + vk_tensor_offset(kq_mask) + kq_mask->view_offs; + + uint32_t const_limit = blk_max; + const uint32_t m_ne2 = (uint32_t)kq_mask->ne[2]; + const uint32_t m_ne3 = (uint32_t)kq_mask->ne[3]; + for (uint32_t m3 = 0; m3 < m_ne3 && const_limit >= blk_min + 256u; ++m3) { + for (uint32_t m2 = 0; m2 < m_ne2 && const_limit >= blk_min + 256u; ++m2) { + for (uint32_t r = 0; r < nr && const_limit >= blk_min + 256u; ++r) { + const uint16_t * row = (const uint16_t *)(mk_ptr + + (size_t)m3 * kq_mask->nb[3] + (size_t)m2 * kq_mask->nb[2] + (size_t)(mask_r0 + r) * kq_mask->nb[1]); + uint32_t c = blk_min; + while (c + 4u <= const_limit) { + uint64_t w64; + memcpy(&w64, row + c, sizeof(w64)); + if (w64 != 0ULL) { + for (uint32_t k = 0; k < 4u; ++k) { + if (row[c + k] != 0x0000u) { const_limit = c + k; break; } + } + break; + } + c += 4u; + } + while (c < const_limit) { + if (row[c] != 0x0000u) { const_limit = c; break; } + ++c; + } + } + } + } + if (rp_ptr) { + for (uint32_t s = 0; s < n_stream && const_limit >= blk_min + 256u; ++s) { + for (uint32_t r = 0; r < nr && const_limit >= blk_min + 256u; ++r) { + const int32_t * rrow = rp_ptr + (size_t)(s * n_seq_tokens + r0 + r) * n_kv; + uint32_t c = blk_min; + while (c + 2u <= const_limit) { + const int32_t v0 = rrow[c + 0u]; + const int32_t v1 = rrow[c + 1u]; + if ((v0 >= 0 && (uint32_t)v0 < extent) || (v1 >= 0 && (uint32_t)v1 < extent)) { + const_limit = (v0 >= 0 && (uint32_t)v0 < extent) ? c : (c + 1u); + break; + } + c += 2u; + } + while (c < const_limit) { + if (rrow[c] >= 0 && (uint32_t)rrow[c] < extent) { const_limit = c; break; } + ++c; + } + } + } + } + const uint32_t kv_const_end = (const_limit >= blk_min + 256u) + ? (blk_min + ((const_limit - blk_min) & ~255u)) + : blk_min; + if (ctx) { + for (int i = 0; i < 4; ++i) { + auto & ce = ctx->mask_span_cache[i]; + if (ce.valid && ce.mask == kq_mask && ce.mask_r0 == mask_r0 && ce.nr == nr && ce.rel_pos == nullptr && ce.extent == 0u) { + ce.rel_pos = rp; + ce.extent = cache_extent; + ce.kv_const_end = kv_const_end; + break; + } + } + } + return kv_const_end; +} + +static bool ggml_vk_get_node_active_kv_span( + ggml_backend_vk_context * ctx, + const ggml_tensor * n, + uint32_t * out_blk_min, + uint32_t * out_blk_max, + uint32_t * out_const_end = nullptr) { + if (out_const_end) { + *out_const_end = 0u; + } + if (!n) { + return false; + } + const ggml_tensor * kq_mask = nullptr; + const ggml_tensor * rg_node = nullptr; + uint32_t mask_r0 = 0u; + uint32_t nr = 0u; + uint32_t n_kv = 0u; + if (n->op == GGML_OP_INKLING_FUSED && ggml_get_op_params_i32(n, 0) == 2) { + rg_node = n; + kq_mask = n->src[3]; + mask_r0 = (uint32_t)ggml_get_op_params_i32(n, 4); + nr = (uint32_t)n->ne[1]; + n_kv = (uint32_t)n->ne[0]; + } else if (n->op == GGML_OP_FLASH_ATTN_EXT && n->src[3] != nullptr) { + const ggml_tensor * mask = n->src[3]; + if (mask->op == GGML_OP_INKLING_FUSED && ggml_get_op_params_i32(mask, 0) == 2) { + rg_node = mask; + kq_mask = mask->src[3]; + mask_r0 = (uint32_t)ggml_get_op_params_i32(mask, 4); + nr = (uint32_t)mask->ne[1]; + n_kv = (uint32_t)mask->ne[0]; + } else { + kq_mask = mask; + mask_r0 = 0u; + nr = (uint32_t)mask->ne[1]; + n_kv = (uint32_t)mask->ne[0]; + } + } + if (!kq_mask || n_kv == 0u || kq_mask->ne[0] != (int64_t)n_kv) { + return false; + } + uint32_t kv_min = 0u, kv_max = n_kv; + if (!ggml_vk_compute_mask_active_span(ctx, kq_mask, mask_r0, nr, &kv_min, &kv_max)) { + return false; + } + if (kv_max == 0u) { + *out_blk_min = 0u; + *out_blk_max = 0u; + return true; + } + *out_blk_min = (kv_min / 64u) * 64u; + *out_blk_max = std::min(n_kv, CEIL_DIV(kv_max, 64u) * 64u); + if (out_const_end && *out_blk_max >= *out_blk_min + 256u) { + if (rg_node && rg_node->type == GGML_TYPE_F16) { + *out_const_end = ggml_vk_compute_rel_const_prefix_end( + ctx, kq_mask, rg_node->src[2], mask_r0, + (uint32_t)ggml_get_op_params_i32(rg_node, 2), nr, + (uint32_t)ggml_get_op_params_i32(rg_node, 1), (uint32_t)rg_node->ne[3], + (uint32_t)ggml_get_op_params_i32(rg_node, 3), *out_blk_min, *out_blk_max); + } else if (!rg_node && kq_mask->type == GGML_TYPE_F16) { + *out_const_end = ggml_vk_compute_rel_const_prefix_end( + ctx, kq_mask, nullptr, mask_r0, 0u, nr, + (uint32_t)kq_mask->ne[1], (uint32_t)kq_mask->ne[3], 0u, + *out_blk_min, *out_blk_max); + } + } + return true; +} + +static void ggml_vk_inkling_fused(ggml_backend_vk_context * ctx, vk_context & subctx, ggml_tensor * dst, + const ggml_cgraph * cgraph = nullptr, int node_idx = -1) { + const int32_t mode = ggml_get_op_params_i32(dst, 0); + GGML_ASSERT(mode >= 0 && mode < 16); + int32_t pipe_idx = mode; + if (mode == 1) { + const uint32_t n_seq_t = (uint32_t)ggml_get_op_params_i32(dst, 2); + const uint32_t n_sq = (uint32_t)ggml_get_op_params_i32(dst, 3); + const ggml_tensor * c0 = dst->src[0]; + const bool has_n_exp = c0 && (c0->ne[2] > 1 || c0->ne[1] != (int64_t)(n_seq_t * n_sq)); + if (dst->src[6] != nullptr || has_n_exp) { + pipe_idx = 14; + } + } else if (mode == 3 && dst->src[ggml_get_op_params_i32(dst, 1) + 1] != nullptr) { + pipe_idx = 13; + } + vk_pipeline pipeline = ctx->device->pipeline_inkling_fused[pipe_idx]; + GGML_ASSERT(pipeline != nullptr); + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + + auto f32_off = [&](const ggml_tensor * t) -> uint32_t { + return t ? (uint32_t)(get_misalign_bytes(ctx, t) / sizeof(float)) : 0u; + }; + const vk_subbuffer d_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); + const uint32_t off_d = dst->type == GGML_TYPE_F16 + ? (uint32_t)(get_misalign_bytes(ctx, dst) / sizeof(ggml_fp16_t)) + : f32_off(dst); + + if (mode == 0) { + const ggml_tensor * cur = dst->src[0]; + const ggml_tensor * scale = dst->src[1]; + const ggml_tensor * tau = dst->src[2]; + const vk_subbuffer c_buf = ggml_vk_tensor_subbuffer(ctx, cur, true); + const vk_subbuffer s_buf = scale ? ggml_vk_tensor_subbuffer(ctx, scale, true) : c_buf; + const vk_subbuffer t_buf = tau ? ggml_vk_tensor_subbuffer(ctx, tau, true) : c_buf; + vk_subbuffer out_buf = d_buf; + vk_subbuffer idx_buf = c_buf; + uint32_t out_off = off_d; + uint32_t off_idx = 0u; + uint32_t sr_nb1 = 0u; + uint32_t flags = (scale ? 1u : 0u) | (tau ? 2u : 0u); + if (ctx->fused_inkling_clip_set_rows && cgraph != nullptr && node_idx >= 0) { + ggml_tensor * set_rows = cgraph->nodes[node_idx + 2]; + const ggml_tensor * indices = set_rows->src[1]; + out_buf = ggml_vk_tensor_subbuffer(ctx, set_rows, true); + idx_buf = ggml_vk_tensor_subbuffer(ctx, indices, true); + const size_t el_sz = ggml_type_size(set_rows->type); + out_off = (uint32_t)(get_misalign_bytes(ctx, set_rows) / el_sz); + off_idx = (uint32_t)(get_misalign_bytes(ctx, indices) / sizeof(int64_t)); + sr_nb1 = (uint32_t)(set_rows->nb[1] / el_sz); + flags |= 4u | (set_rows->type == GGML_TYPE_F16 ? 8u : 0u) | (set_rows->type == GGML_TYPE_Q8_0 ? 16u : 0u); + } + struct { + uint32_t ne0, ne1, ne2, flags; + uint32_t off_cur, off_scale, off_tau, off_dst; + float threshold, eps; + uint32_t off_idx, set_rows_nb1; + } pc = { + (uint32_t)cur->ne[0], (uint32_t)cur->ne[1], (uint32_t)cur->ne[2], + flags, + f32_off(cur), f32_off(scale), f32_off(tau), out_off, + ggml_get_op_params_f32(dst, 1), ggml_get_op_params_f32(dst, 2), + off_idx, sr_nb1, + }; + const uint32_t rows = (uint32_t)(cur->ne[1] * cur->ne[2]); + const uint32_t wg_y = CEIL_DIV(rows, 65535u); + const uint32_t wg_x = wg_y > 1u ? 65535u : rows; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { c_buf, s_buf, t_buf, out_buf, idx_buf }, pc, { wg_x, wg_y, 1u }); + return; + } + + if (mode == 6) { + const ggml_tensor * s0 = dst->src[0]; + const ggml_tensor * s1 = dst->src[1]; + const ggml_tensor * s2 = dst->src[2]; + const ggml_tensor * s3 = dst->src[3]; + const vk_subbuffer b0 = ggml_vk_tensor_subbuffer(ctx, s0, true); + const vk_subbuffer b1 = ggml_vk_tensor_subbuffer(ctx, s1, true); + const vk_subbuffer b2 = ggml_vk_tensor_subbuffer(ctx, s2, true); + const vk_subbuffer b3 = ggml_vk_tensor_subbuffer(ctx, s3, true); + struct { + uint32_t n0, n1, n2, n3; + uint32_t nb; + uint32_t off0, off1, off2, off3, off_dst; + } pc = { + (uint32_t)s0->ne[0], (uint32_t)s1->ne[0], (uint32_t)s2->ne[0], (uint32_t)s3->ne[0], + (uint32_t)dst->ne[1], + f32_off(s0), f32_off(s1), f32_off(s2), f32_off(s3), off_d, + }; + const uint32_t total = (uint32_t)ggml_nelements(dst); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { b0, b1, b2, b3, d_buf }, pc, { total, 1u, 1u }); + return; + } + + if (mode == 7) { + const ggml_tensor * joint = dst->src[0]; + const ggml_tensor * st_in = dst->src[1]; + const vk_subbuffer bj = ggml_vk_tensor_subbuffer(ctx, joint, true); + const vk_subbuffer bs = ggml_vk_tensor_subbuffer(ctx, st_in, true); + struct { + uint32_t rank, nb; + uint32_t off_joint, off_state, off_dst; + } pc = { + (uint32_t)st_in->ne[0], (uint32_t)st_in->ne[1], + f32_off(joint), f32_off(st_in), off_d, + }; + const uint32_t slice_elems = (uint32_t)(st_in->ne[0] * st_in->ne[1]); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { bj, bs, d_buf }, pc, { slice_elems, 1u, 1u }); + return; + } + + if (mode == 8) { + const ggml_tensor * src0 = dst->src[0]; + const vk_subbuffer s0_buf = ggml_vk_tensor_subbuffer(ctx, src0, true); + const uint32_t total = (uint32_t)ggml_nelements(dst); + struct { + uint32_t total, off_src, off_dst; + float inv_cap, cap; + uint32_t pad; + } pc = { + total, f32_off(src0), off_d, + ggml_get_op_params_f32(dst, 1), ggml_get_op_params_f32(dst, 2), 0u, + }; + const bool v4_ok = ((pc.off_src & 3u) == 0u) && ((pc.off_dst & 3u) == 0u); + const uint32_t thr = v4_ok ? (CEIL_DIV(total, 4u) + (total & 3u)) : total; + const uint32_t wgs = CEIL_DIV(thr, 256u); + const uint32_t wgy = CEIL_DIV(wgs, 65535u); + const uint32_t wgx = wgy > 1u ? 65535u : wgs; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { s0_buf, d_buf }, pc, { wgx, wgy, 1u }); + return; + } + + if (mode == 9) { + const ggml_tensor * prev = dst->src[0]; + const ggml_tensor * w1 = dst->src[1]; + const ggml_tensor * st_in = dst->src[2]; + const ggml_tensor * hid = dst->src[3]; + const ggml_tensor * ctx_in = dst->src[4]; + const ggml_tensor * jp = dst->src[5]; + const ggml_tensor * jpb = dst->src[6]; + const vk_subbuffer b_prev = ggml_vk_tensor_subbuffer(ctx, prev, true); + const vk_subbuffer b_w1 = ggml_vk_tensor_subbuffer(ctx, w1, true); + const vk_subbuffer b_st = ggml_vk_tensor_subbuffer(ctx, st_in, true); + const vk_subbuffer b_hid = ggml_vk_tensor_subbuffer(ctx, hid, true); + const vk_subbuffer b_ctx = ggml_vk_tensor_subbuffer(ctx, ctx_in, true); + const vk_subbuffer b_jp = ggml_vk_tensor_subbuffer(ctx, jp, true); + const vk_subbuffer b_jpb = jpb ? ggml_vk_tensor_subbuffer(ctx, jpb, true) : b_st; + const uint32_t rank = (uint32_t)dst->ne[0]; + const uint32_t nb = (uint32_t)dst->ne[1]; + const uint32_t n_embd = (uint32_t)hid->ne[0]; + const uint32_t flags = (w1->type == GGML_TYPE_BF16 ? 1u : 0u) | + (jp->type == GGML_TYPE_BF16 ? 2u : 0u) | + (jpb ? 4u : 0u); + struct { + uint32_t rank, n_embd, nb, flags; + uint32_t off_prev, off_w1, off_state, off_hid, off_ctx, off_jp, off_bias, off_dst; + } pc = { + rank, n_embd, nb, flags, + (uint32_t)(get_misalign_bytes(ctx, prev) / sizeof(int32_t)), + (uint32_t)(get_misalign_bytes(ctx, w1) / ggml_type_size(w1->type)), + f32_off(st_in), f32_off(hid), f32_off(ctx_in), + (uint32_t)(get_misalign_bytes(ctx, jp) / ggml_type_size(jp->type)), + f32_off(jpb), off_d, + }; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { b_prev, b_w1, b_st, b_hid, b_ctx, b_jp, b_jpb, d_buf }, + pc, { CEIL_DIV(rank, 4u), nb, 1u }); + return; + } + + if (mode == 10) { + const ggml_tensor * feat = dst->src[0]; + const ggml_tensor * fuse = dst->src[1]; + const ggml_tensor * n0 = dst->src[2]; + const ggml_tensor * n1 = dst->src[3]; + const ggml_tensor * n2 = dst->src[4]; + const ggml_tensor * n3 = dst->src[5]; + const ggml_tensor * pos = dst->src[6]; + ggml_tensor * ring = dst->src[7]; + const vk_subbuffer b_feat = ggml_vk_tensor_subbuffer(ctx, feat, true); + const vk_subbuffer b_fuse = ggml_vk_tensor_subbuffer(ctx, fuse, true); + const vk_subbuffer b_n0 = ggml_vk_tensor_subbuffer(ctx, n0, true); + const vk_subbuffer b_n1 = ggml_vk_tensor_subbuffer(ctx, n1, true); + const vk_subbuffer b_n2 = ggml_vk_tensor_subbuffer(ctx, n2, true); + const vk_subbuffer b_n3 = ggml_vk_tensor_subbuffer(ctx, n3, true); + const vk_subbuffer b_pos = pos ? ggml_vk_tensor_subbuffer(ctx, pos, true) : b_fuse; + const vk_subbuffer b_ring = ring ? ggml_vk_tensor_subbuffer(ctx, ring, true) : d_buf; + const uint32_t n_embd = (uint32_t)dst->ne[0]; + const uint32_t n_tokens = (uint32_t)dst->ne[1]; + struct { + uint32_t n_embd, n_tokens, has_ring, ring_seq_offset, ring_rows; + float eps; + uint32_t off_feat, off_fuse; + uint32_t off_n0, off_n1, off_n2, off_n3; + uint32_t off_pos, off_ring, off_dst; + } pc = { + n_embd, n_tokens, (pos && ring) ? 1u : 0u, + (uint32_t)ggml_get_op_params_i32(dst, 1), + (uint32_t)ggml_get_op_params_i32(dst, 2), + ggml_get_op_params_f32(dst, 3), + f32_off(feat), f32_off(fuse), + f32_off(n0), f32_off(n1), f32_off(n2), f32_off(n3), + pos ? (uint32_t)(get_misalign_bytes(ctx, pos) / sizeof(int32_t)) : 0u, + f32_off(ring), off_d, + }; + const uint32_t wgz = CEIL_DIV(n_tokens, 65535u); + const uint32_t wgx = wgz > 1u ? 65535u : n_tokens; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { b_feat, b_fuse, b_n0, b_n1, b_n2, b_n3, b_pos, b_ring, d_buf }, + pc, { wgx, 4u, wgz }); + if (ring) { + ctx->unsynced_nodes_written.push_back(ring); + } + return; + } + + if (mode == 1) { + const ggml_tensor * cur = dst->src[0]; + const ggml_tensor * history = dst->src[1]; + const ggml_tensor * weight = dst->src[2]; + const ggml_tensor * dynamic = dst->src[3]; + ggml_tensor * state = dst->src[4]; + const ggml_tensor * residual = dst->src[5]; + const ggml_tensor * scopy = dst->src[6]; + const vk_subbuffer c_buf = ggml_vk_strided_subbuffer(ctx, cur, true); + const vk_subbuffer h_buf = ggml_vk_tensor_subbuffer(ctx, history, true); + const vk_subbuffer w_buf = ggml_vk_tensor_subbuffer(ctx, weight, true); + const vk_subbuffer dyn_buf = dynamic ? ggml_vk_tensor_subbuffer(ctx, dynamic, true) : c_buf; + const vk_subbuffer st_buf = ggml_vk_tensor_subbuffer(ctx, state, true); + const vk_subbuffer res_buf = residual ? ggml_vk_tensor_subbuffer(ctx, residual, true) : c_buf; + const uint32_t n_channels = (uint32_t)cur->ne[0]; + const uint32_t cur_s1 = (uint32_t)(cur->nb[1] / sizeof(float)); + const uint32_t n_seq_tokens = (uint32_t)ggml_get_op_params_i32(dst, 2); + const uint32_t n_seqs = (uint32_t)ggml_get_op_params_i32(dst, 3); + const uint32_t off_st = f32_off(state); + const uint32_t n_exp = (cur->ne[2] > 1 || cur->ne[1] != (int64_t)(n_seq_tokens * n_seqs)) ? (uint32_t)cur->ne[1] : 1u; + if (scopy != nullptr || n_exp > 1u) { + const vk_subbuffer sc_buf = scopy ? ggml_vk_tensor_subbuffer(ctx, scopy, true) : c_buf; + struct { + uint32_t n_channels, n_seq_tokens, n_seqs, n_exp; + uint32_t ch_offset, n_heads, st_base_f32, st_seq_stride; + uint32_t st_slot_stride, st_kw; + uint32_t off_cur, off_w, off_dyn, off_dst; + float scale_out; + uint32_t has_res, off_res; + uint32_t off_state, off_scopy; + uint32_t use_hist, off_hist, hist_sconv_ch; + uint32_t cur_s1; + } pc_sc = { + n_channels, n_seq_tokens, n_seqs, n_exp, + (uint32_t)ggml_get_op_params_i32(dst, 1), + (uint32_t)ggml_get_op_params_i32(dst, 4), + (uint32_t)ggml_get_op_params_i32(dst, 5) + off_st, + (uint32_t)ggml_get_op_params_i32(dst, 6), + (uint32_t)ggml_get_op_params_i32(dst, 7), + (uint32_t)ggml_get_op_params_i32(dst, 8), + f32_off(cur), f32_off(weight), f32_off(dynamic), off_d, + ggml_get_op_params_f32(dst, 9), + residual ? 1u : 0u, + f32_off(residual), + off_st, + scopy ? (uint32_t)(get_misalign_bytes(ctx, scopy) / sizeof(int32_t)) : 0u, + scopy ? 0u : 1u, + f32_off(history), + (uint32_t)history->ne[1], + cur_s1, + }; + static_assert(sizeof(pc_sc) == 92, "inkling_conv_scopy pc size"); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { c_buf, h_buf, w_buf, dyn_buf, st_buf, d_buf, res_buf, sc_buf }, pc_sc, + { CEIL_DIV(n_channels, 64u), 1u, n_seqs }); + } else { + struct { + uint32_t n_channels, n_seq_tokens, n_seqs, hist_sconv_ch; + uint32_t ch_offset, n_heads, st_base_f32, st_seq_stride; + uint32_t st_slot_stride, st_kw; + uint32_t off_cur, off_hist, off_w, off_dyn, off_dst; + float scale_out; + uint32_t has_res, off_res; + uint32_t cur_s1; + } pc_c = { + n_channels, n_seq_tokens, n_seqs, (uint32_t)history->ne[1], + (uint32_t)ggml_get_op_params_i32(dst, 1), + (uint32_t)ggml_get_op_params_i32(dst, 4), + (uint32_t)ggml_get_op_params_i32(dst, 5) + off_st, + (uint32_t)ggml_get_op_params_i32(dst, 6), + (uint32_t)ggml_get_op_params_i32(dst, 7), + (uint32_t)ggml_get_op_params_i32(dst, 8), + f32_off(cur), f32_off(history), f32_off(weight), f32_off(dynamic), off_d, + ggml_get_op_params_f32(dst, 9), + residual ? 1u : 0u, + f32_off(residual), + cur_s1, + }; + static_assert(sizeof(pc_c) == 76, "inkling_conv pc size"); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { c_buf, h_buf, w_buf, dyn_buf, st_buf, d_buf, res_buf }, pc_c, + { CEIL_DIV(n_channels, 64u), n_seq_tokens, n_seqs }); + } + ctx->unsynced_nodes_written.push_back(state); + return; + } + + if (mode == 2) { + const ggml_tensor * table = dst->src[0]; + const ggml_tensor * sinks = dst->src[1]; + const ggml_tensor * rel_pos = dst->src[2]; + const ggml_tensor * kq_mask = dst->src[3]; + const vk_subbuffer t_buf = ggml_vk_tensor_subbuffer(ctx, table, true); + const vk_subbuffer s_buf = ggml_vk_tensor_subbuffer(ctx, sinks, true); + const vk_subbuffer r_buf = ggml_vk_tensor_subbuffer(ctx, rel_pos, true); + const vk_subbuffer m_buf = kq_mask ? ggml_vk_tensor_subbuffer(ctx, kq_mask, true) : t_buf; + const bool out_f16 = (dst->type == GGML_TYPE_F16); + const uint32_t dst_off_elem = out_f16 + ? (uint32_t)(get_misalign_bytes(ctx, dst) / sizeof(ggml_fp16_t)) + : off_d; + const uint32_t mask_off_elem = kq_mask + ? (uint32_t)(get_misalign_bytes(ctx, kq_mask) / sizeof(ggml_fp16_t)) + : 0u; + const uint32_t n_kv_u = (uint32_t)dst->ne[0]; + const uint32_t nr_u = (uint32_t)dst->ne[1]; + const uint32_t mask_r0u = (uint32_t)ggml_get_op_params_i32(dst, 4); + uint32_t rg_flags = (out_f16 ? 1u : 0u) | (kq_mask ? 2u : 0u); + uint32_t kv_blk_min = 0u; + uint32_t kv_blk_max = n_kv_u; + uint32_t kv_const_end = 0u; + uint32_t disp_kv = n_kv_u; + const bool has_span = kq_mask && ggml_vk_get_node_active_kv_span(ctx, dst, &kv_blk_min, &kv_blk_max, &kv_const_end); + const bool has_cpfx = has_span && out_f16 && (kv_const_end >= kv_blk_min + 256u) && ((kv_blk_max / 64u) <= 0xFFFFu); + if (has_span && (kv_blk_min > 0u || kv_blk_max < n_kv_u || has_cpfx)) { + bool sole_fa_span_consumer = false; + if (nr_u <= 8u && kv_blk_max > 0u && cgraph != nullptr && node_idx >= 0 && + !ctx->device->xe_fa_support && !ggml_vk_exact_s8_enabled() && + !(dst->flags & GGML_TENSOR_FLAG_OUTPUT) && + ggml_node_get_use_count(cgraph, node_idx) == 1) { + const ggml_tensor * fa_cons = nullptr; + for (int k = node_idx + 1; k < std::min(cgraph->n_nodes, node_idx + 64); ++k) { + const ggml_tensor * cn = cgraph->nodes[k]; + if (cn->op == GGML_OP_FLASH_ATTN_EXT && cn->src[3] == dst && + cn->src[0] != dst && cn->src[1] != dst && cn->src[2] != dst && cn->src[4] != dst) { + fa_cons = cn; + break; + } + } + if (fa_cons != nullptr) { + float fa_max_bias = 0.0f; + memcpy(&fa_max_bias, (const float *)fa_cons->op_params + 1, sizeof(float)); + const int32_t fa_n_kv_max = ggml_get_op_params_i32(fa_cons, 4); + if (fa_max_bias == 0.0f && fa_n_kv_max <= 0) { + sole_fa_span_consumer = true; + } + } + } + if (sole_fa_span_consumer) { + if (has_cpfx) { + rg_flags |= 16u; + disp_kv = 1u + (kv_blk_max - kv_const_end); + } else { + rg_flags |= 4u; + disp_kv = kv_blk_max - kv_blk_min; + } + } else if (kv_blk_min > 0u || kv_blk_max < n_kv_u) { + rg_flags |= 8u; + } + } + struct { + uint32_t n_kv, nr, n_head, n_stream; + uint32_t n_seq_tokens, r0, table_len, extent; + uint32_t off_table, off_sinks, off_rel, off_dst; + uint32_t flags, off_mask, mask_r0, mask_ne1, mask_ne2, mask_ne3; + uint32_t kv_min, kv_limit, kv_const_end; + } pc = { + n_kv_u, nr_u, (uint32_t)dst->ne[2], (uint32_t)dst->ne[3], + (uint32_t)ggml_get_op_params_i32(dst, 1), + (uint32_t)ggml_get_op_params_i32(dst, 2), + (uint32_t)table->ne[0], + (uint32_t)ggml_get_op_params_i32(dst, 3), + f32_off(table), f32_off(sinks), (uint32_t)(get_misalign_bytes(ctx, rel_pos) / sizeof(int32_t)), dst_off_elem, + rg_flags, + mask_off_elem, + mask_r0u, + kq_mask ? (uint32_t)kq_mask->ne[1] : 1u, + kq_mask ? (uint32_t)kq_mask->ne[2] : 1u, + kq_mask ? (uint32_t)kq_mask->ne[3] : 1u, + kv_blk_min, kv_blk_max, kv_const_end, + }; + const uint64_t total = (uint64_t)disp_kv * dst->ne[1] * dst->ne[2] * dst->ne[3]; + const uint64_t wgs = CEIL_DIV(total, 256ull); + const uint32_t wg_y = (uint32_t)CEIL_DIV(wgs, 65535ull); + const uint32_t wg_x = wg_y > 1u ? 65535u : (uint32_t)wgs; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { t_buf, s_buf, r_buf, m_buf, d_buf }, pc, { wg_x, wg_y, 1u }); + return; + } + + if (mode == 3) { + const uint32_t K = (uint32_t)ggml_get_op_params_i32(dst, 1); + const ggml_tensor * query = dst->src[K]; + const ggml_tensor * rms_w = dst->src[K + 1]; + const vk_subbuffer s0_buf = ggml_vk_tensor_subbuffer(ctx, dst->src[0], true); + vk_subbuffer sb[6] = { s0_buf, s0_buf, s0_buf, s0_buf, s0_buf, s0_buf }; + uint32_t offs[6] = {}; + for (uint32_t b = 0; b < K; ++b) { + sb[b] = ggml_vk_tensor_subbuffer(ctx, dst->src[b], true); + offs[b] = f32_off(dst->src[b]); + } + const vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, query, true); + const uint32_t n_tokens = (uint32_t)dst->ne[1]; + const uint32_t Q = (uint32_t)dst->ne[2]; + const uint32_t wg_y = CEIL_DIV(n_tokens, 65535u); + const uint32_t wg_x = wg_y > 1u ? 65535u : n_tokens; + if (rms_w != nullptr) { + static const bool disable_f16_dual = getenv("GGML_VK_DISABLE_F16_DUAL") != nullptr; + const uint32_t n_embd = (uint32_t)dst->ne[0]; + const bool want_f16_dual = !disable_f16_dual && + Q == 1u && dst->ne[3] == 1 && n_tokens >= 2u && + ggml_vk_is_apple_agx_coopmat(ctx->device) && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(n_tokens) && + ctx->device->pipeline_contig_cpy_f32_f16 != nullptr && + ggml_is_contiguous(dst) && + get_misalign_bytes(ctx, dst) == 0; + const size_t req_y_bytes = sizeof(ggml_fp16_t) * (size_t)ROUNDUP_POW2(n_tokens, 128u) * (size_t)n_embd; + const size_t wr_y_bytes = sizeof(ggml_fp16_t) * (size_t)n_tokens * (size_t)n_embd; + if (want_f16_dual) { + ggml_vk_reserve_prealloc_y(ctx, subctx, req_y_bytes); + } + vk_subbuffer f16_buf = want_f16_dual + ? ggml_vk_produce_prealloc_y_f16(ctx, subctx, dst, wr_y_bytes, false) + : d_buf; + const vk_subbuffer w_buf = ggml_vk_tensor_subbuffer(ctx, rms_w, true); + struct { + uint32_t n_embd, n_tokens, K, Q; + uint32_t off_s[6]; + uint32_t off_q, off_dst; + float eps, sm_scale; + uint32_t has_rms_w, off_w, w_s1; + float rms_eps; + } pc_r = { + n_embd, n_tokens, K, Q, + { offs[0], offs[1], offs[2], offs[3], offs[4], offs[5] }, + f32_off(query), off_d, + ggml_get_op_params_f32(dst, 2), + 1.0f / sqrtf((float)n_embd), + want_f16_dual ? 3u : 1u, f32_off(rms_w), + (rms_w->ne[1] > 1) ? n_embd : 0u, + ggml_get_op_params_f32(dst, 3), + }; + static_assert(sizeof(pc_r) == 72, "inkling_depth_mix_rms pc size"); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { sb[0], sb[1], sb[2], sb[3], sb[4], sb[5], q_buf, d_buf, w_buf, f16_buf }, pc_r, { wg_x, wg_y, Q }); + } else { + static const bool s18_dm = getenv("S19_S18_DEPTH_MIX") != nullptr; + struct { + uint32_t n_embd, n_tokens, K, Q; + uint32_t off_s[6]; + uint32_t off_q, off_dst; + float eps, sm_scale; + } pc_p = { + ((uint32_t)dst->ne[0]) | (s18_dm ? 0x80000000u : 0u), n_tokens, K, Q, + { offs[0], offs[1], offs[2], offs[3], offs[4], offs[5] }, + f32_off(query), off_d, + ggml_get_op_params_f32(dst, 2), + 1.0f / sqrtf((float)dst->ne[0]), + }; + static_assert(sizeof(pc_p) == 56, "inkling_depth_mix pc size"); + const uint32_t wg_z = (!s18_dm && n_tokens <= 16u) ? Q : 1u; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { sb[0], sb[1], sb[2], sb[3], sb[4], sb[5], q_buf, d_buf }, pc_p, { wg_x, wg_y, wg_z }); + } + return; + } + + if (mode == 4) { + const ggml_tensor * cur = dst->src[0]; + const ggml_tensor * msg = dst->src[1]; + const vk_subbuffer c_buf = ggml_vk_tensor_subbuffer(ctx, cur, true); + const vk_subbuffer m_buf = ggml_vk_tensor_subbuffer(ctx, msg, true); + const uint32_t n_embd = (uint32_t)cur->ne[0]; + const uint32_t n_tokens = (uint32_t)cur->ne[1]; + const uint32_t C = (uint32_t)dst->ne[2]; + struct { + uint32_t n_embd, n_tokens, off_cur, off_msg, off_dst; + float eps; + uint32_t C, cur_s2, msg_s2; + } pc = { + n_embd, n_tokens, f32_off(cur), f32_off(msg), off_d, + ggml_get_op_params_f32(dst, 1), + C, + cur->ne[2] > 1 ? n_tokens * n_embd : 0u, + msg->ne[2] > 1 ? n_tokens * n_embd : 0u, + }; + static_assert(sizeof(pc) == 36, "inkling_rms2_concat pc size"); + const uint32_t wg_y = CEIL_DIV(n_tokens, 65535u); + const uint32_t wg_x = wg_y > 1u ? 65535u : n_tokens; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { c_buf, m_buf, d_buf }, pc, { wg_x, wg_y, C }); + return; + } + + if (mode == 11) { + static const bool disable_f16_dual = getenv("GGML_VK_DISABLE_F16_DUAL") != nullptr; + const ggml_tensor * cur = dst->src[0]; + const ggml_tensor * msg = dst->src[1]; + const ggml_tensor * up = dst->src[2]; + const ggml_tensor * w = dst->src[3]; + const vk_subbuffer c_buf = ggml_vk_tensor_subbuffer(ctx, cur, true); + const vk_subbuffer m_buf = ggml_vk_tensor_subbuffer(ctx, msg, true); + const vk_subbuffer u_buf = ggml_vk_tensor_subbuffer(ctx, up, true); + const vk_subbuffer w_buf = ggml_vk_tensor_subbuffer(ctx, w, true); + const uint32_t n_embd = (uint32_t)dst->ne[0]; + const uint32_t n_tokens = (uint32_t)dst->ne[1]; + const uint32_t C = (uint32_t)dst->ne[2]; + const bool want_f16_dual = !disable_f16_dual && + C == 1u && dst->ne[3] == 1 && n_tokens >= 2u && + ggml_vk_is_apple_agx_coopmat(ctx->device) && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(n_tokens) && + ctx->device->pipeline_contig_cpy_f32_f16 != nullptr && + ggml_is_contiguous(dst) && + get_misalign_bytes(ctx, dst) == 0; + const size_t req_y_bytes = sizeof(ggml_fp16_t) * (size_t)ROUNDUP_POW2(n_tokens, 128u) * (size_t)n_embd; + const size_t wr_y_bytes = sizeof(ggml_fp16_t) * (size_t)n_tokens * (size_t)n_embd; + if (want_f16_dual) { + ggml_vk_reserve_prealloc_y(ctx, subctx, req_y_bytes); + } + vk_subbuffer f16_buf = want_f16_dual + ? ggml_vk_produce_prealloc_y_f16(ctx, subctx, dst, wr_y_bytes, false) + : d_buf; + struct { + uint32_t n_embd, n_tokens, C; + uint32_t off_cur, off_msg, off_up, off_w, off_dst; + uint32_t cur_s2, w_s1; + float eps; + } pc = { + n_embd, n_tokens, C | (want_f16_dual ? 0x80000000u : 0u), + f32_off(cur), f32_off(msg), f32_off(up), f32_off(w), off_d, + cur->ne[2] > 1 ? n_tokens * n_embd : 0u, + w->ne[1] > 1 ? n_embd : 0u, + ggml_get_op_params_f32(dst, 1), + }; + static_assert(sizeof(pc) == 44, "inkling_ctrl_apply_rms_mul pc size"); + const uint32_t wg_y = CEIL_DIV(n_tokens, 65535u); + const uint32_t wg_x = wg_y > 1u ? 65535u : n_tokens; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { c_buf, m_buf, u_buf, w_buf, d_buf, f16_buf }, pc, { wg_x, wg_y, C }); + return; + } + + if (mode == 12) { + const ggml_tensor * q_cur = dst->src[0]; + const ggml_tensor * r_cur = dst->src[1]; + const ggml_tensor * q_sc = dst->src[2]; + const ggml_tensor * r_sc = dst->src[3]; + const ggml_tensor * tau = dst->src[4]; + const vk_subbuffer q_buf = ggml_vk_strided_subbuffer(ctx, q_cur, true); + const vk_subbuffer r_buf = ggml_vk_strided_subbuffer(ctx, r_cur, true); + const vk_subbuffer qs_buf = q_sc ? ggml_vk_tensor_subbuffer(ctx, q_sc, true) : q_buf; + const vk_subbuffer rs_buf = r_sc ? ggml_vk_tensor_subbuffer(ctx, r_sc, true) : r_buf; + const vk_subbuffer t_buf = tau ? ggml_vk_tensor_subbuffer(ctx, tau, true) : q_buf; + const uint32_t flags = (q_sc ? 1u : 0u) | (r_sc ? 2u : 0u) | (tau ? 4u : 0u); + struct { + uint32_t q_ne0, r_ne0, n_head, n_tokens, flags; + uint32_t off_q, off_r, off_qs, off_rs, off_tau, off_dst; + float q_threshold, r_threshold, eps; + uint32_t q_tok_s, r_tok_s; + } pc = { + (uint32_t)q_cur->ne[0], (uint32_t)r_cur->ne[0], (uint32_t)q_cur->ne[1], (uint32_t)q_cur->ne[2], flags, + f32_off(q_cur), f32_off(r_cur), f32_off(q_sc), f32_off(r_sc), f32_off(tau), off_d, + ggml_get_op_params_f32(dst, 1), ggml_get_op_params_f32(dst, 2), ggml_get_op_params_f32(dst, 3), + (uint32_t)(q_cur->nb[2] / sizeof(float)), (uint32_t)(r_cur->nb[2] / sizeof(float)), + }; + static_assert(sizeof(pc) == 64, "inkling_l2_clip_qr pc size"); + const uint32_t rows = 2u * (uint32_t)(q_cur->ne[1] * q_cur->ne[2]); + const uint32_t wg_y = CEIL_DIV(rows, 65535u); + const uint32_t wg_x = wg_y > 1u ? 65535u : rows; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { q_buf, r_buf, qs_buf, rs_buf, t_buf, d_buf }, pc, { wg_x, wg_y, 1u }); + return; + } + + if (mode == 5) { + const vk_subbuffer c_buf = ggml_vk_tensor_subbuffer(ctx, dst->src[0], true); + const vk_subbuffer m_buf = ggml_vk_tensor_subbuffer(ctx, dst->src[1], true); + const vk_subbuffer gn_buf = ggml_vk_tensor_subbuffer(ctx, dst->src[2], true); + const vk_subbuffer fg_buf = ggml_vk_tensor_subbuffer(ctx, dst->src[3], true); + const uint32_t ne = (uint32_t)ggml_nelements(dst); + struct { + uint32_t ne, off_cur, off_msg, off_gn, off_fg, off_dst; + } pc = { + ne, f32_off(dst->src[0]), f32_off(dst->src[1]), f32_off(dst->src[2]), f32_off(dst->src[3]), off_d, + }; + const uint32_t wgs = CEIL_DIV(ne, 1024u); + const uint32_t wg_y = CEIL_DIV(wgs, 65535u); + const uint32_t wg_x = wg_y > 1u ? 65535u : wgs; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { c_buf, m_buf, gn_buf, fg_buf, d_buf }, pc, { wg_x, wg_y, 1u }); + return; + } +} + +void ggml_vk_dsv4_hc_comb(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * mixes, const ggml_tensor * scale, const ggml_tensor * base, ggml_tensor * dst) { + VK_LOG_DEBUG("ggml_vk_dsv4_hc_comb(" << mixes << ", " << scale << ", " << base << ", " << dst << ")"); + + vk_pipeline pipeline = ctx->device->pipeline_dsv4_hc_comb_f32; + GGML_ASSERT(pipeline != nullptr); + + const uint32_t n_tokens = (uint32_t)mixes->ne[1]; + + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + + const vk_subbuffer mixes_buf = ggml_vk_tensor_subbuffer(ctx, mixes, true); + const vk_subbuffer scale_buf = ggml_vk_tensor_subbuffer(ctx, scale, true); + const vk_subbuffer base_buf = ggml_vk_tensor_subbuffer(ctx, base, true); + const vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); + + vk_op_dsv4_hc_comb_push_constants pc = { + n_tokens, + ggml_vk_nb_elem(mixes, 0), ggml_vk_nb_elem(mixes, 1), + ggml_vk_nb_elem(scale, 0), + ggml_vk_nb_elem(base, 0), + ggml_vk_nb_elem(dst, 0), ggml_vk_nb_elem(dst, 1), ggml_vk_nb_elem(dst, 2), + 0, 0, 0, 0, + ggml_get_op_params_f32(dst, 0), + (uint32_t)ggml_get_op_params_i32(dst, 1), + }; init_pushconst_tensor_offsets(ctx, pc, mixes, scale, base, nullptr, dst); ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { mixes_buf, scale_buf, base_buf, dst_buf }, pc, { n_tokens, 1, 1 }); @@ -8224,7 +11168,7 @@ void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const st // Split_k doesn't work with M splitting. // This only supports batchsize == 1. const size_t nbytes = ggml_nbytes(src0); - const bool needs_split = dst->ne[2] == 1 && dst->ne[3] == 1 && nbytes > ctx->device->properties.limits.maxStorageBufferRange; + const bool needs_split = ctx->gen_pair_mm1 == nullptr && dst->ne[2] == 1 && dst->ne[3] == 1 && nbytes > ctx->device->properties.limits.maxStorageBufferRange; if (needs_split) { // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets) const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]); @@ -8267,31 +11211,101 @@ void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const st src0->ne[1] <= ctx->device->properties.limits.maxComputeWorkGroupCount[1] && src1->ne[2] <= ctx->device->properties.limits.maxComputeWorkGroupCount[2]) { ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx); - // With one output row, B^T*A has the same flat output as A^T*B. + } else if ((dst->ne[1] == 1 || + ((dst->ne[1] <= (int64_t) ggml_vk_mul_mat_vec_max_cols(ctx->device) || + (ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled() && !gen_batch_invariant_for_n(dst->ne[1]) && + dst->ne[1] <= 4096 && + ((src0->type == GGML_TYPE_F32 && dst->ne[0] <= (dst->ne[1] <= 32 ? 256 : ([]() { static const int vf = getenv("GGML_VK_MMA_F32_MAX_M") ? atoi(getenv("GGML_VK_MMA_F32_MAX_M")) : 256; return vf; })())) || + (src0->type == GGML_TYPE_Q8_0 && + (dst->ne[1] <= 32 + ? dst->ne[0] <= ([]() { static const int v = getenv("GGML_VK_MMA_Q8_MAX_M") ? atoi(getenv("GGML_VK_MMA_Q8_MAX_M")) : 65536; return v; })() + : (dst->ne[1] >= ([]() { static const int qminn = getenv("GGML_VK_MMA_Q8_MIN_N") ? atoi(getenv("GGML_VK_MMA_Q8_MIN_N")) : 8; return qminn; })() && + dst->ne[0] >= ([]() { static const int vmin = getenv("GGML_VK_MMA_Q8_MIN_M") ? atoi(getenv("GGML_VK_MMA_Q8_MIN_M")) : 0; return vmin; })() && + dst->ne[0] <= ([]() { static const int vmax = getenv("GGML_VK_MMA_Q8_MAX_M") ? atoi(getenv("GGML_VK_MMA_Q8_MAX_M")) : 65536; return vmax; })()))) || + (src0->type == GGML_TYPE_NVFP4 && dst->ne[0] <= 65536) || + (ggml_vk_tensor_is_repack(src0) && dst->ne[1] >= 8 && dst->ne[0] >= 4)))) && + (src1->ne[2] * src1->ne[3] == 1 || + (dst->ne[1] <= 8 && src1->ne[2] * src1->ne[3] <= 4 && !ggml_vk_tensor_is_repack(src0) && + (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_Q8_0) && + src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 && + ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst))))) && + (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) { + ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx); + // With one output row, B^T*A has the same flat output as A^T*B (including elementwise SIGMOID epilogue). } else if (ctx->num_additional_fused_ops == 0 && + (ctx->gen_mm_dst == nullptr || + (ctx->gen_mm_flags == MAT_VEC_FUSION_FLAGS_SIGMOID && ctx->gen_mm_f0 == nullptr && ctx->gen_mm_f1 == nullptr && + ggml_is_contiguous(ctx->gen_mm_dst) && get_misalign_bytes(ctx, ctx->gen_mm_dst) == 0)) && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) && (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16 || ggml_is_quantized(src1->type)) && - dst->ne[0] == 1 && dst->ne[1] > mul_mat_vec_max_cols && + dst->ne[0] == 1 && dst->ne[1] > (int64_t) ggml_vk_mul_mat_vec_max_cols(ctx->device) && src0->ne[2] == 1 && src0->ne[3] == 1 && src1->ne[2] == 1 && src1->ne[3] == 1 && ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) && get_misalign_bytes(ctx, src0) == 0 && get_misalign_bytes(ctx, src1) == 0 && get_misalign_bytes(ctx, dst) == 0) { ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx, true); - // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four) - // when ne12 and ne13 are one. - } else if ((dst->ne[1] == 1 || (dst->ne[1] <= ggml_vk_mul_mat_vec_max_cols(ctx->device) && src1->ne[2] * src1->ne[3] == 1)) && - (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) { - ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx); } else { - ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false); + ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false, cgraph, node_idx); } } -static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) { +static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const struct ggml_cgraph * cgraph = nullptr, int node_idx = -1) { + const bool has_pair_glu = cgraph != nullptr && ctx->num_additional_fused_ops == 2 && + cgraph->nodes[node_idx + 2]->op == GGML_OP_GLU; + const ggml_tensor * src0_up = nullptr; + if (has_pair_glu) { + const ggml_tensor * glu = cgraph->nodes[node_idx + 2]; + src0 = glu->src[0]->src[0]; + src0_up = glu->src[1]->src[0]; + } + const ggml_tensor * out_dst = ctx->gen_mm_dst ? ctx->gen_mm_dst + : ((cgraph != nullptr && ctx->num_additional_fused_ops > 0) + ? cgraph->nodes[node_idx + ctx->num_additional_fused_ops] + : dst); + uint32_t fusion_flags = 0; + const ggml_tensor * aux0_t = nullptr; + const ggml_tensor * aux1_t = nullptr; + if (ctx->gen_mm_dst != nullptr) { + fusion_flags |= ctx->gen_mm_flags; + aux0_t = ctx->gen_mm_f0; + aux1_t = ctx->gen_mm_f1; + } else if (!has_pair_glu && cgraph != nullptr && ctx->num_additional_fused_ops > 0) { + const ggml_tensor * op1 = cgraph->nodes[node_idx + 1]; + if (ctx->num_additional_fused_ops == 1 && op1->op == GGML_OP_GLU) { + const bool is_gate = (op1->src[0] == dst); + aux0_t = is_gate ? op1->src[1] : op1->src[0]; + fusion_flags |= is_gate ? MAT_VEC_FUSION_FLAGS_GLU_A : MAT_VEC_FUSION_FLAGS_GLU_B; + } else { + aux0_t = op1->src[1]; + if (op1->op == GGML_OP_MUL) { + fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0; + if (aux0_t->ne[2] == ids->ne[1] && ids->ne[1] > 1) { + fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0_TOK; + } + } else { + GGML_ASSERT(op1->op == GGML_OP_ADD_ID); + fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0; + } + if (ctx->num_additional_fused_ops > 1) { + const ggml_tensor * op2 = cgraph->nodes[node_idx + 2]; + GGML_ASSERT(op2->op == GGML_OP_MUL); + aux1_t = op2->src[1]; + fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1; + if (aux1_t->ne[2] == ids->ne[1] && ids->ne[1] > 1) { + fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1_TOK; + } + } + } + } + const bool has_situ_merged = (fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u; + const float situ_alpha = has_situ_merged ? ctx->gen_glu_alpha : 0.0f; + const float situ_limit = has_situ_merged ? ctx->gen_glu_limit : 0.0f; + const bool use_mmid_fused = has_pair_glu || (fusion_flags != 0); + VK_LOG_DEBUG("ggml_vk_mul_mat_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3]; - std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3] << "),)"); + std::cerr << "), (" << out_dst << ", name=" << out_dst->name << ", type=" << out_dst->type << ", ne0=" << out_dst->ne[0] << ", ne1=" << out_dst->ne[1] << ", ne2=" << out_dst->ne[2] << ", ne3=" << out_dst->ne[3] << ", nb0=" << out_dst->nb[0] << ", nb1=" << out_dst->nb[1] << ", nb2=" << out_dst->nb[2] << ", nb3=" << out_dst->nb[3] << "),)"); GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT GGML_ASSERT(ids->type == GGML_TYPE_I32); @@ -8311,14 +11325,13 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& const uint32_t nbi0 = ids->nb[0]; const uint32_t nbi1 = ids->nb[1]; - const uint64_t ne20 = dst->ne[0]; - const uint64_t ne21 = dst->ne[1]; - // const uint64_t ne22 = dst->ne[2]; - // const uint64_t ne23 = dst->ne[3]; + const uint64_t ne20 = out_dst->ne[0]; + const uint64_t ne21 = out_dst->ne[1]; + // const uint64_t ne22 = out_dst->ne[2]; + // const uint64_t ne23 = out_dst->ne[3]; const uint64_t n_as = ne02; - ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context; ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context; @@ -8338,6 +11351,8 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& } // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf + const bool is_repack = ggml_vk_tensor_is_repack(src0); + const int repack_ri = is_repack ? ggml_vk_repack_type_idx(src0->type) : -1; const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) || !ggml_vk_dim01_contiguous(src0); // If src0 is BF16, try to use a BF16 x BF16 multiply @@ -8358,57 +11373,221 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& #else const bool y_decode_vector_staging = false; #endif - const bool can_quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && + const bool can_quantize_y = !use_mmid_fused && ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0 && ggml_vk_src1_prec_allows_q8(dst); - // Intel coopmat1 matrix cores prefer f16 activations for quantized weights - const bool prefer_f16_b = ctx->device->coopmat_support && !ctx->device->coopmat2 && - ctx->device->vendor_id == VK_VENDOR_ID_INTEL && - ggml_is_quantized(src0->type) && src1->type == GGML_TYPE_F32; - - const ggml_type y_kernel_type = ggml_vk_mul_mat_b_type(ctx, src0->type, src1, f16_type, - ggml_prec_get_acc(dst), true, can_quantize_y, prefer_f16_b); + static const bool mma_id_disabled = getenv("GGML_VK_DISABLE_MMA_ID") != nullptr; + static const int env_mma_id_max_n = getenv("GGML_VK_MMA_ID_MAX_N") ? atoi(getenv("GGML_VK_MMA_ID_MAX_N")) : 2048; + static const int env_mma_id_pglu_max_n = getenv("GGML_VK_MMA_ID_PGLU_MAX_N") ? atoi(getenv("GGML_VK_MMA_ID_PGLU_MAX_N")) : -1; + static const int env_mma_id_fep_max_n = getenv("GGML_VK_MMA_ID_FASTEP_MAX_N") ? atoi(getenv("GGML_VK_MMA_ID_FASTEP_MAX_N")) : -1; + static const bool has_mma_id_rt1_n = getenv("GGML_VK_MMA_ID_RT1_MAX_N") != nullptr; + static const int env_mma_id_rt1_n = has_mma_id_rt1_n ? atoi(getenv("GGML_VK_MMA_ID_RT1_MAX_N")) : 32; + static const int env_mma_id_rt3_tok = getenv("GGML_VK_MMA_ID_RT3_MIN_TOK") ? atoi(getenv("GGML_VK_MMA_ID_RT3_MIN_TOK")) : 12; + static const int env_mma_id_rt4_tok = getenv("GGML_VK_MMA_ID_RT4_MIN_TOK") ? atoi(getenv("GGML_VK_MMA_ID_RT4_MIN_TOK")) : 21; + static const int env_mma_id_rt5_tok = getenv("GGML_VK_MMA_ID_RT5_MIN_TOK") ? atoi(getenv("GGML_VK_MMA_ID_RT5_MIN_TOK")) : 9999; + static const int env_mma_id_rt6_tok = getenv("GGML_VK_MMA_ID_RT6_MIN_TOK") ? atoi(getenv("GGML_VK_MMA_ID_RT6_MIN_TOK")) : 26; + static const int env_mma_id_rt8_tok = getenv("GGML_VK_MMA_ID_RT8_MIN_TOK") ? atoi(getenv("GGML_VK_MMA_ID_RT8_MIN_TOK")) : 9999; + static const int env_mma_id_msg = getenv("GGML_VK_MMA_ID_MSG") ? atoi(getenv("GGML_VK_MMA_ID_MSG")) : -1; + static const int env_mma_id_pglu_msg = getenv("GGML_VK_MMA_ID_PGLU_MSG") ? atoi(getenv("GGML_VK_MMA_ID_PGLU_MSG")) : 0; + static const int env_mma_id_fep_msg = getenv("GGML_VK_MMA_ID_FEP_MSG") ? atoi(getenv("GGML_VK_MMA_ID_FEP_MSG")) : 0; + static const int env_mma_id_rt = getenv("GGML_VK_MMA_ID_RT") ? atoi(getenv("GGML_VK_MMA_ID_RT")) : 0; + static const int env_mma_id_pglu_rt = getenv("GGML_VK_MMA_ID_PGLU_RT") ? atoi(getenv("GGML_VK_MMA_ID_PGLU_RT")) : 0; + static const int env_mma_id_fep_rt = getenv("GGML_VK_MMA_ID_FEP_RT") ? atoi(getenv("GGML_VK_MMA_ID_FEP_RT")) : 0; + static const int env_mma_id_f16_b = getenv("GGML_VK_MMA_ID_F16_B") ? atoi(getenv("GGML_VK_MMA_ID_F16_B") ) : 1; + static const uint32_t env_mma_id_kp = getenv("GGML_VK_MMA_ID_KP") ? (uint32_t)atoi(getenv("GGML_VK_MMA_ID_KP")) : 1u; + const bool has_pglu_twin = has_pair_glu || has_situ_merged; + const uint32_t eff_m_rows = has_situ_merged ? (uint32_t)(ne01 / 2) : (uint32_t)ne01; + const bool is_fastep_cand = !has_pglu_twin && use_mmid_fused && + ((fusion_flags & ~(MAT_VEC_FUSION_FLAGS_SCALE0 | MAT_VEC_FUSION_FLAGS_SCALE0_TOK)) == 0u || + (ggml_vk_is_apple_agx_coopmat(ctx->device) && !mma_id_disabled && + (fusion_flags & ~(MAT_VEC_FUSION_FLAGS_EXP_SCALE0 | MAT_VEC_FUSION_FLAGS_SCALE1 | MAT_VEC_FUSION_FLAGS_SCALE1_TOK)) == 0u)); + const int eff_mma_id_max_n = has_pglu_twin ? (env_mma_id_pglu_max_n >= 0 ? env_mma_id_pglu_max_n : env_mma_id_max_n) + : is_fastep_cand ? (env_mma_id_fep_max_n >= 0 ? env_mma_id_fep_max_n : env_mma_id_max_n) + : env_mma_id_max_n; + const uint32_t mma_id_k_step = (src0->type == GGML_TYPE_Q4_0) ? 32u : 64u; + const uint32_t avg_tok_per_exp = (uint32_t)CEIL_DIV(nei0 * nei1, n_as); + const int def_mma_id_msg = env_mma_id_msg >= 0 ? env_mma_id_msg : ((nei1 >= 1024) ? 8 : -1); + const int req_msg = has_pglu_twin ? (env_mma_id_pglu_msg > 0 ? env_mma_id_pglu_msg : def_mma_id_msg) + : is_fastep_cand ? (env_mma_id_fep_msg > 0 ? env_mma_id_fep_msg : def_mma_id_msg) + : def_mma_id_msg; + const bool want_msg8 = (req_msg == 8 || req_msg == 81) && eff_m_rows >= (req_msg == 81 ? 64u : 128u) && (ne10 % 128u == 0); + const bool want_msg8_pglu = (req_msg == 8 || req_msg == 81) && has_pglu_twin && eff_m_rows >= 64u && (ne10 % 128u == 0); + const bool use_msg8_cfg = want_msg8 || want_msg8_pglu; + const int req_rt = has_pglu_twin ? (env_mma_id_pglu_rt > 0 ? env_mma_id_pglu_rt : env_mma_id_rt) + : is_fastep_cand ? (env_mma_id_fep_rt > 0 ? env_mma_id_fep_rt : env_mma_id_rt) + : env_mma_id_rt; + const bool can_wide_rt = src0->type != GGML_TYPE_F32 && (ne10 % 64u == 0) && eff_m_rows >= 32u; + const uint32_t id_rt_i = (req_rt == 8 && can_wide_rt) ? 6u + : (req_rt == 6 && can_wide_rt) ? 5u + : (req_rt == 5 && can_wide_rt) ? 4u + : (req_rt == 4) ? 3u + : (req_rt == 3) ? 2u + : (req_rt == 2) ? 1u + : (req_rt == 1) ? 0u + : ((has_mma_id_rt1_n ? ((int64_t)nei1 <= env_mma_id_rt1_n) : (avg_tok_per_exp <= 4u)) ? 0u + : (can_wide_rt && (int)avg_tok_per_exp >= env_mma_id_rt8_tok) ? 6u + : (can_wide_rt && (int)avg_tok_per_exp >= env_mma_id_rt6_tok) ? 5u + : (can_wide_rt && (int)avg_tok_per_exp >= env_mma_id_rt5_tok) ? 4u + : ((int)avg_tok_per_exp >= env_mma_id_rt4_tok) ? 3u + : ((int)avg_tok_per_exp >= env_mma_id_rt3_tok) ? 2u : 1u); + static constexpr uint32_t sel_id_rt_map[7] = { 1u, 2u, 3u, 4u, 5u, 6u, 8u }; + const uint32_t sel_id_rt = sel_id_rt_map[id_rt_i]; + const uint32_t def_pglu_kp = (sel_id_rt == 3u || sel_id_rt == 4u || (use_msg8_cfg && sel_id_rt >= 3u)) ? 2u : 1u; + uint32_t def_fep_kp = (sel_id_rt >= 5u) ? (use_msg8_cfg ? 2u : 1u) : ((sel_id_rt >= 3u) ? 2u : 4u); + if (def_fep_kp == 4u && (ne10 % 256u != 0u) && (ne10 % 128u == 0u)) { + def_fep_kp = 2u; + } + const uint32_t eff_pglu_kp = getenv("GGML_VK_MMA_PGLU_KP") ? (uint32_t)atoi(getenv("GGML_VK_MMA_PGLU_KP")) : def_pglu_kp; + const uint32_t eff_fep_kp = getenv("GGML_VK_MMA_FASTEP_KP") ? (uint32_t)atoi(getenv("GGML_VK_MMA_FASTEP_KP")) : def_fep_kp; + const uint32_t eff_shb_kp = has_pglu_twin ? eff_pglu_kp : (is_fastep_cand ? eff_fep_kp : env_mma_id_kp); + const bool mma_id_candidate = !mma_id_disabled && + ggml_vk_is_apple_agx_coopmat(ctx->device) && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(nei1) && + !x_non_contig && + src1->type == GGML_TYPE_F32 && + out_dst->type == GGML_TYPE_F32 && + (ne11 == 1 || ne11 >= nei0) && + (int64_t)nei1 <= eff_mma_id_max_n && + (ne10 % mma_id_k_step == 0) && + (get_misalign_bytes(ctx, src1) % 4 == 0) && + (is_repack + ? (repack_ri >= 0 && ctx->device->pipeline_mul_mv_mma_id_repack[repack_ri][id_rt_i][0][0] != nullptr) + : (ctx->device->pipeline_mul_mv_mma_id[src0->type][id_rt_i][0][0] != nullptr)); + auto has_cached_y_f16 = [&]() -> bool { + if (!ggml_is_contiguous(src1) || ctx->device->pipeline_contig_cpy_f32_f16 == nullptr) { + return false; + } + vk_pipeline_struct * cpy_p = ctx->device->pipeline_contig_cpy_f32_f16.get(); + const ggml_tensor * key_s1 = ggml_vk_prealloc_y_equiv_root(src1); + for (uint32_t s = 0; s < ctx->prealloc_y_ring_count; ++s) { + if (ctx->prealloc_y_last_pipeline_ring[s] == cpy_p && + ctx->prealloc_y_last_tensor_ring[s] == key_s1 && + !ctx->prealloc_y_last_k_padded_ring[s]) { + return true; + } + } + return false; + }; + const bool mma_id_f16_b = mma_id_candidate && src0->type != GGML_TYPE_F32 && + ((env_mma_id_f16_b == 1 && ((has_pglu_twin && nei1 >= 4) || nei1 >= 32 || has_cached_y_f16())) || + (env_mma_id_f16_b == 2 && has_pglu_twin && nei1 >= 32) || + (env_mma_id_f16_b >= 3)); + + // Intel coopmat1 prefers f16 activations; for large batches on Apple AGX, pre-staged FP16 B (cached for _pairglu!) halves scattered MoE B bandwidth. + static const int gen_mmid_f16_b = getenv("GGML_VK_MMID_F16_B") ? atoi(getenv("GGML_VK_MMID_F16_B")) : -1; + const bool prefer_f16_b = mma_id_f16_b || + (!mma_id_candidate && ctx->device->coopmat_support && !ctx->device->coopmat2 && + (gen_mmid_f16_b > 0 || (gen_mmid_f16_b < 0 && + (ctx->device->vendor_id == VK_VENDOR_ID_INTEL || + (ggml_vk_is_apple_agx_coopmat(ctx->device) && + (ggml_vk_exact_s8_enabled() ? (nei1 > 32) : (get_misalign_bytes(ctx, src1) != 0)))))) && + ggml_is_quantized(src0->type) && src1->type == GGML_TYPE_F32); + + const ggml_type y_kernel_type = mma_id_candidate + ? (mma_id_f16_b ? f16_type : GGML_TYPE_F32) + : ggml_vk_mul_mat_b_type(ctx, src0->type, src1, f16_type, + ggml_prec_get_acc(dst), true, can_quantize_y, prefer_f16_b); const bool quantize_y = y_kernel_type == GGML_TYPE_Q8_1; const bool y_f32_kernel = y_kernel_type == GGML_TYPE_F32; - const std::vector* mmp_map = + const std::vector* mmp_map = is_repack ? nullptr : ggml_vk_get_mul_mat_mat_pipeline_map(ctx, src0->type, y_kernel_type, ggml_prec_get_acc(dst), true); - const bool qx_needs_dequant = mmp_map == nullptr || x_non_contig; + // Coopmat2 MUL_MAT_ID BK specialization constants in ggml_vk_load_shaders are at most 64. + const uint32_t y_staged_row_stride = ctx->device->coopmat2 && !quantize_y ? ggml_vk_align_size(ne10, 64) : ne10; + const bool y_needs_k_padding = ne10 != y_staged_row_stride; + + const bool mma_id_direct = is_repack || (mma_id_candidate && mmp_map == nullptr); + const bool use_mma_id_raw = mma_id_candidate && !x_non_contig && (mma_id_direct || mmp_map != nullptr) && + (y_f32_kernel || (mma_id_f16_b && y_kernel_type == GGML_TYPE_F16)) && + !y_needs_k_padding; + const bool qx_needs_dequant = mma_id_direct ? !use_mma_id_raw : (mmp_map == nullptr || x_non_contig); - if (qx_needs_dequant) { + if (qx_needs_dequant || mmp_map == nullptr) { // dequant src0 to f16 mmp_map = ggml_vk_get_mul_mat_mat_pipeline_map(ctx, f16_type, y_kernel_type, ggml_prec_get_acc(dst), true); } GGML_ASSERT(mmp_map != nullptr); - // Coopmat2 MUL_MAT_ID BK specialization constants in ggml_vk_load_shaders are at most 64. - const uint32_t y_staged_row_stride = ctx->device->coopmat2 && !quantize_y ? ggml_vk_align_size(ne10, 64) : ne10; - const bool y_needs_k_padding = ne10 != y_staged_row_stride; - const bool y_needs_reformat = !quantize_y && (!ggml_vk_dim01_contiguous(src1) || y_kernel_type != src1->type || y_decode_vector_staging || y_needs_k_padding); const bool qy_needs_dequant = y_needs_reformat; - const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align_map(ctx, *mmp_map, ne01, nei1, true)); - const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8; + // gen: GGML_VK_MMID_SELECT=pairs sizes the tile by the rows an expert gets on average (tokens x used / experts), + // not by the token count: each nonempty expert gets its own tiles, so a 128-column tile for an expert with 8 rows + // computes 120 empty columns. Each output's sum over K is the same for every tile size. + static const int gen_mmid_sel_mode = []() { + const char * s = getenv("GGML_VK_MMID_SELECT"); + if (!s || !*s) return -1; + if (!strcmp(s, "pairs")) return 1; + if (!strcmp(s, "tokens")) return 0; + return -1; + }(); + const bool gen_mmid_pairs = gen_mmid_sel_mode >= 0 ? (gen_mmid_sel_mode > 0) : ggml_vk_is_apple_agx_coopmat(ctx->device); + const uint32_t gen_n_sel = gen_mmid_pairs ? (uint32_t) std::max(1, CEIL_DIV(nei0 * nei1, n_as)) : (uint32_t) (nei1); + const vk_subbuffer d_id_U_opt = has_pair_glu ? ggml_vk_tensor_subbuffer(ctx, src0_up) : vk_subbuffer{}; + const size_t raw_id_x_offs = src0_uma ? qx_buf_offset : (vk_tensor_offset(src0) + src0->view_offs); + const size_t raw_id_y_offs = src1_uma ? qy_buf_offset : (vk_tensor_offset(src1) + src1->view_offs); + const bool id_offsets_vec8_aligned = + (qx_needs_dequant || ggml_is_quantized(src0->type) || ((raw_id_x_offs % 32 == 0) && (!has_pair_glu || (d_id_U_opt.offset % 32 == 0)))) && + (qy_needs_dequant || quantize_y || (raw_id_y_offs % 32 == 0)); + const uint32_t id_sel_m = has_pair_glu ? (uint32_t)(2 * ne01) : (uint32_t)ne01; + const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align_map(ctx, *mmp_map, id_sel_m, gen_n_sel, true)); + const bool aligned = !quantize_y && ne10 == kpad && id_offsets_vec8_aligned && + ((ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled()) || (ne01 > 8 && nei1 > 8)); + + const bool use_mma_id = mma_id_candidate && !qx_needs_dequant && + (y_f32_kernel || (mma_id_f16_b && y_kernel_type == GGML_TYPE_F16)) && + !y_needs_k_padding; + vk_pipeline pipeline = nullptr; + if (use_mma_id) { + static const bool dis_s23_moe_msg2 = getenv("GGML_VK_DISABLE_S23_MOE_MSG2") != nullptr; + const uint32_t id_ci = (req_msg == 1 || (ne10 % (64u * eff_shb_kp) != 0) || eff_m_rows < 32u) + ? 1u + : ((req_msg == 2 || (req_msg < 0 && (eff_m_rows < 64u || (!dis_s23_moe_msg2 && nei1 <= 8)))) + ? 2u + : (use_msg8_cfg ? ((req_msg == 81 && !has_pglu_twin) ? 4u : 3u) : 0u)); + const uint32_t bf16_i = y_f32_kernel ? 0u : 1u; + pipeline = is_repack + ? ctx->device->pipeline_mul_mv_mma_id_repack[repack_ri][id_rt_i][id_ci][bf16_i] + : ctx->device->pipeline_mul_mv_mma_id[src0->type][id_rt_i][id_ci][bf16_i]; + } else { + pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *mmp_map, id_sel_m, gen_n_sel, aligned, true); + } - vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *mmp_map, ne01, nei1, aligned, true); + const uint64_t max_id_a_nbytes = is_repack + ? std::max(ggml_vk_repack_alloc_bytes(src0), src0_up ? ggml_vk_repack_alloc_bytes(src0_up) : 0) + : std::max(ggml_nbytes(src0), src0_up ? ggml_nbytes(src0_up) : 0); + if (max_id_a_nbytes > ctx->device->properties.limits.maxStorageBufferRange) { + pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline); + } + if (has_pglu_twin) { + GGML_ASSERT(pipeline && pipeline->gen_pair_glu); + pipeline = pipeline->gen_pair_glu; + } else if (use_mmid_fused) { + if (((fusion_flags & ~(MAT_VEC_FUSION_FLAGS_SCALE0 | MAT_VEC_FUSION_FLAGS_SCALE0_TOK)) == 0u || + (use_mma_id && (fusion_flags & ~(MAT_VEC_FUSION_FLAGS_EXP_SCALE0 | MAT_VEC_FUSION_FLAGS_SCALE1 | MAT_VEC_FUSION_FLAGS_SCALE1_TOK)) == 0u)) && + pipeline && pipeline->gen_fast_ep) { + const bool need_kp2_twin = use_mma_id && (eff_fep_kp == 2u) && (sel_id_rt < 3u) && + !getenv("GGML_VK_MMA_FASTEP_KP") && pipeline->gen_fast_ep_kp2; + pipeline = need_kp2_twin ? pipeline->gen_fast_ep_kp2 : pipeline->gen_fast_ep; + } else { + GGML_ASSERT(pipeline && pipeline->gen_glu); + pipeline = pipeline->gen_glu; + } + } const uint32_t bn = pipeline->wg_denoms[1]; const uint64_t max_tiles = ggml_vk_mul_mat_id_max_tiles(n_as, nei0 * nei1, bn); const uint64_t row_ids_offset = 1 + 2 * max_tiles; const uint64_t row_map_words = row_ids_offset + max_tiles * bn; - - if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { - pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline); - } const uint64_t x_ne = ggml_nelements(src0); const uint64_t y_ne = (uint64_t)y_staged_row_stride * ne11 * ne12 * ne13; - const uint64_t d_ne = ggml_nelements(dst); + const uint64_t d_ne = ggml_nelements(out_dst); - const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type); + const uint64_t qx_sz = is_repack ? ggml_vk_repack_alloc_bytes(src0) : (ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type)); const uint64_t qy_sz = ggml_type_size(src1->type) * ggml_nelements(src1) / ggml_blck_size(src1->type); const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne; const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne); @@ -8430,6 +11609,9 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& if (x_non_contig) { to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type); + } else if (is_repack) { + GGML_ASSERT(repack_ri >= 0); + to_fp16_vk_0 = ctx->device->pipeline_dequant_repack[repack_ri]; } else { to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type); } @@ -8455,6 +11637,21 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& const size_t expert_data_size = sizeof(uint32_t) * row_map_words; + static const bool disable_pglu_f16_out = getenv("GGML_VK_DISABLE_PGLU_F16_OUT") != nullptr; + static const bool keep_pglu_f32 = getenv("GGML_VK_KEEP_PGLU_F32") != nullptr; + const bool next_mmid_wants_f16 = ctx->gen_pair_glu_sole_mmid_next || + (cgraph != nullptr && has_pair_glu && + (node_idx + 3 < cgraph->n_nodes) && + cgraph->nodes[node_idx + 3]->op == GGML_OP_MUL_MAT_ID && + cgraph->nodes[node_idx + 3]->src[1] == out_dst && + cgraph->nodes[node_idx + 3]->src[0]->type != GGML_TYPE_F32 && + cgraph->nodes[node_idx + 3]->src[0]->ne[1] >= 32 && + (out_dst->ne[0] % ((cgraph->nodes[node_idx + 3]->src[0]->type == GGML_TYPE_Q4_0) ? 32 : 64) == 0)); + const bool want_pglu_f16_out = !disable_pglu_f16_out && has_pglu_twin && use_mma_id && + (mma_id_f16_b || env_mma_id_f16_b == 1) && next_mmid_wants_f16 && ggml_is_contiguous(out_dst) && + get_misalign_bytes(ctx, out_dst) == 0; + const size_t pglu_f16_bytes = sizeof(ggml_fp16_t) * d_ne; + { if ( (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) || @@ -8469,6 +11666,9 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& ctx->prealloc_size_y = y_sz; ggml_vk_preallocate_buffers(ctx, subctx); } + if (want_pglu_f16_out) { + ggml_vk_reserve_prealloc_y(ctx, subctx, pglu_f16_bytes); + } if (ctx->prealloc_size_split_k < expert_data_size) { ctx->prealloc_size_split_k = expert_data_size; ggml_vk_preallocate_buffers(ctx, subctx); @@ -8488,8 +11688,9 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& ggml_pipeline_request_descriptor_sets(ctx, count_experts, 1); } - vk_buffer d_D = dst_buf_ctx->dev_buffer; - const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs; + const vk_subbuffer out_id_d_sub = ggml_vk_tensor_subbuffer(ctx, out_dst); + vk_buffer d_D = out_id_d_sub.buffer; + const uint64_t d_buf_offset = out_id_d_sub.offset; GGML_ASSERT(d_D != nullptr); vk_buffer d_X; uint64_t x_buf_offset = 0; @@ -8532,12 +11733,25 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& } vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids, true); - // Count how many times each expert is used - vk_subbuffer expert_count_buf = { ctx->prealloc_split_k, 0, expert_data_size }; - if (ctx->prealloc_split_k_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } - { + // Count how many times each expert is used (Series 9 S9.2: reuse across gate/up/down when ids come from ARGSORT >= 0) + const bool ids_non_negative = (ids->op == GGML_OP_ARGSORT) || (ids->view_src && ids->view_src->op == GGML_OP_ARGSORT); + const bool skip_f32_d_pre = want_pglu_f16_out && + (!(y_needs_reformat || quantize_y) || ctx->prealloc_y_ring_count >= 2) && + ctx->gen_pair_glu_sole_mmid_next && ids_non_negative && !keep_pglu_f32; + uint32_t sk_ring_slot = 0; + vk_subbuffer expert_count_buf; + bool unbarred_stage_writes = false; + if (ids_non_negative && ctx->last_expert_count_valid && + ctx->last_expert_ids_tensor == ids && + ctx->last_expert_bn == bn && + ctx->last_expert_row_ids_offset == (uint32_t) row_ids_offset && + ctx->last_expert_n_as == (uint32_t) n_as && + ctx->last_expert_count_buf.size >= expert_data_size) { + expert_count_buf = ctx->last_expert_count_buf; + sk_ring_slot = ctx->last_expert_slot; + } else { + sk_ring_slot = ggml_vk_acquire_prealloc_split_k_slot(ctx, subctx, expert_data_size); + expert_count_buf = { ctx->prealloc_split_k, sk_ring_slot * ctx->prealloc_split_k_ring_stride, expert_data_size }; // this also zeroes the dst rows of the skipped slots (negative ids) vk_op_count_experts_push_constants pc = { (uint32_t)nei0, (uint32_t)nei1, @@ -8546,67 +11760,74 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& (uint32_t)(get_misalign_bytes(ctx, ids) / ggml_type_size(ids->type)), (uint32_t)n_as, 0, 0, bn, (uint32_t)row_ids_offset, - (uint32_t)ne01, - (uint32_t)(dst->nb[1] / sizeof(float)), - (uint32_t)(dst->nb[2] / sizeof(float)) }; + (skip_f32_d_pre || ids_non_negative) ? 0u : (uint32_t)(has_situ_merged ? (ne01 / 2) : ne01), + (uint32_t)(out_dst->nb[1] / sizeof(float)), + (uint32_t)(out_dst->nb[2] / sizeof(float)) }; init_pushconst_fastdiv(pc); ggml_vk_dispatch_pipeline(ctx, subctx, count_experts, { d_ids, expert_count_buf, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, { 1, 1, 1 }); + unbarred_stage_writes = true; + if (ids_non_negative) { + ctx->last_expert_ids_tensor = ids; + ctx->last_expert_bn = bn; + ctx->last_expert_row_ids_offset = (uint32_t) row_ids_offset; + ctx->last_expert_n_as = (uint32_t) n_as; + ctx->last_expert_slot = sk_ring_slot; + ctx->last_expert_count_buf = expert_count_buf; + ctx->last_expert_count_valid = true; + } } if (x_non_contig) { ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0)); + unbarred_stage_writes = false; } else if (qx_needs_dequant) { const std::vector pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) }; ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1}); + unbarred_stage_writes = true; } + uint32_t y_ring_slot = 0; if (y_needs_reformat) { - if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() || - ctx->prealloc_y_last_tensor_used != src1 || - ctx->prealloc_y_last_k_padded != y_needs_k_padding) { - if (ctx->prealloc_y_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } + bool cached = false; + y_ring_slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, to_fp16_vk_1.get(), src1, y_needs_k_padding, cached); + y_buf_offset = y_ring_slot * ctx->prealloc_y_ring_stride; + if (!cached) { if (y_needs_k_padding) { GGML_ASSERT(y_sz % 4 == 0); // Zero B padding because clamping only A can produce 0 * Inf or NaN. - subctx->s->buffer->buf.fillBuffer(d_Y->buffer, 0, y_sz, 0); + subctx->s->buffer->buf.fillBuffer(d_Y->buffer, y_buf_offset, y_sz, 0); ggml_vk_sync_buffers(ctx, subctx); const ggml_tensor y_staged_dst = make_y_staged_dst(); const uint32_t y_staged_dst_type_size = ggml_type_size(y_staged_dst.type); ggml_vk_cpy_to_strided( ctx, subctx, to_fp16_vk_1, src1, - ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), + ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), vk_subbuffer{ d_Y, y_buf_offset, y_sz }, (uint32_t)(y_staged_dst.nb[0] / y_staged_dst_type_size), (uint32_t)(y_staged_dst.nb[1] / y_staged_dst_type_size), (uint32_t)(y_staged_dst.nb[2] / y_staged_dst_type_size), (uint32_t)(y_staged_dst.nb[3] / y_staged_dst_type_size)); } else { - ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0)); + ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), vk_subbuffer{ d_Y, y_buf_offset, y_sz }); } - ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get(); - ctx->prealloc_y_last_tensor_used = src1; - ctx->prealloc_y_last_k_padded = y_needs_k_padding; + unbarred_stage_writes = false; } } if (quantize_y) { - if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() || - ctx->prealloc_y_last_tensor_used != src1 || - ctx->prealloc_y_last_k_padded) { - if (ctx->prealloc_y_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } - ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne); - ctx->prealloc_y_last_pipeline_used = to_q8_1.get(); - ctx->prealloc_y_last_tensor_used = src1; - ctx->prealloc_y_last_k_padded = false; + bool cached = false; + y_ring_slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, to_q8_1.get(), src1, false, cached); + y_buf_offset = y_ring_slot * ctx->prealloc_y_ring_stride; + if (!cached) { + ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), vk_subbuffer{ d_Y, y_buf_offset, CEIL_DIV(y_sz, 144) * 144 }, y_ne); + unbarred_stage_writes = false; } } - ggml_vk_sync_buffers(ctx, subctx); + if (unbarred_stage_writes) { + ggml_vk_sync_buffers(ctx, subctx); + } - const uint64_t x_range = qx_needs_dequant ? x_sz : ggml_nbytes(src0); + const uint64_t x_range = qx_needs_dequant ? x_sz : (is_repack ? qx_sz : ggml_nbytes(src0)); const uint64_t y_range = (qy_needs_dequant || quantize_y) ? y_sz : ggml_nbytes(src1); uint32_t stride_batch_x = qx_needs_dequant ? ne00*ne01 : ggml_vk_batch_stride(src0); @@ -8622,29 +11843,71 @@ static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& } // compute - ggml_vk_matmul_id( - ctx, subctx, pipeline, - { d_X, x_buf_offset, x_range }, { d_Y, y_buf_offset, y_range }, - { d_D, d_buf_offset, d_sz }, std::move(d_ids), expert_count_buf, - ne01, ne21, ne10, ne10, stride_b_y, ne01, - stride_batch_x, stride_batch_y, ne20*ne21, - n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, row_ids_offset, max_tiles - ); // NOLINT + if (use_mmid_fused || use_mma_id) { + const int in_y_slot = (y_needs_reformat || quantize_y) ? (int)y_ring_slot : -1; + const bool do_pglu_f16_out = want_pglu_f16_out && (in_y_slot < 0 || ctx->prealloc_y_ring_count >= 2); + uint32_t mma_fusion_flags = fusion_flags | ((use_mma_id && !y_f32_kernel) ? MAT_VEC_FUSION_FLAGS_B_F16 : 0u); + const uint32_t mma_stride_b_y = (use_mma_id && ne11 == 1) ? 0u : stride_b_y; + const vk_subbuffer x_sub = { d_X, x_buf_offset, x_range }; + const vk_subbuffer y_sub = { d_Y, y_buf_offset, y_range }; + const vk_subbuffer d_sub = { d_D, d_buf_offset, d_sz }; + const vk_subbuffer u_sub = has_pair_glu ? d_id_U_opt : x_sub; + const vk_subbuffer aux0_sub = aux0_t ? ggml_vk_tensor_subbuffer(ctx, aux0_t) : d_sub; + vk_subbuffer aux1_sub = aux1_t ? ggml_vk_tensor_subbuffer(ctx, aux1_t) : d_sub; + if (do_pglu_f16_out) { + aux1_sub = ggml_vk_produce_prealloc_y_f16(ctx, subctx, out_dst, pglu_f16_bytes, true, in_y_slot); + GGML_ASSERT(in_y_slot < 0 || aux1_sub.offset != y_buf_offset); + mma_fusion_flags |= MAT_VEC_FUSION_FLAGS_D_F16_AUX1; + if (ctx->gen_pair_glu_sole_mmid_next && ids_non_negative && !keep_pglu_f32) { + mma_fusion_flags |= MAT_VEC_FUSION_FLAGS_SKIP_F32_D; + } + } + const uint32_t eff_m_id = has_situ_merged ? (uint32_t)(ne01 / 2) : (uint32_t)ne01; + ggml_vk_matmul_id_fused( + ctx, subctx, pipeline, + x_sub, y_sub, d_sub, d_ids, expert_count_buf, + u_sub, aux0_sub, aux1_sub, + eff_m_id, ne21, ne10, ne10, mma_stride_b_y, eff_m_id, + stride_batch_x, stride_batch_y, ne20*ne21, + n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, row_ids_offset, max_tiles, mma_fusion_flags, + situ_alpha, situ_limit + ); + } else { + ggml_vk_matmul_id( + ctx, subctx, pipeline, + { d_X, x_buf_offset, x_range }, { d_Y, y_buf_offset, y_range }, + { d_D, d_buf_offset, d_sz }, std::move(d_ids), expert_count_buf, + ne01, ne21, ne10, ne10, stride_b_y, ne01, + stride_batch_x, stride_batch_y, ne20*ne21, + n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, row_ids_offset, max_tiles + ); // NOLINT + } if (x_non_contig || qx_needs_dequant) { ctx->prealloc_x_need_sync = true; } if (y_needs_reformat || quantize_y) { ctx->prealloc_y_need_sync = true; + ctx->prealloc_y_slot_need_sync[y_ring_slot] = true; } ctx->prealloc_split_k_need_sync = true; + ctx->prealloc_split_k_slot_need_sync[sk_ring_slot] = true; } static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { ggml_tensor * dst = cgraph->nodes[node_idx]; + const bool has_pair_glu = ctx->num_additional_fused_ops == 2 && cgraph->nodes[node_idx + 2]->op == GGML_OP_GLU; + const bool has_situ_merged = ctx->gen_mm_dst != nullptr && (ctx->gen_mm_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u; + const ggml_tensor * out_dst = ctx->gen_mm_dst ? ctx->gen_mm_dst : cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; ggml_tensor * src0 = dst->src[0]; ggml_tensor * src1 = dst->src[1]; ggml_tensor * ids = dst->src[2]; + const ggml_tensor * src0_up = nullptr; + if (has_pair_glu) { + const ggml_tensor * glu = cgraph->nodes[node_idx + 2]; + src0 = glu->src[0]->src[0]; + src0_up = glu->src[1]->src[0]; + } VK_LOG_DEBUG("ggml_vk_mul_mat_vec_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3]; @@ -8668,16 +11931,18 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte const uint64_t nei1 = ids->ne[1]; const uint32_t nbi1 = (uint32_t)(ids->nb[1] / sizeof(int)); - const uint64_t ne20 = dst->ne[0]; - const uint64_t ne21 = dst->ne[1]; + const uint64_t ne20 = out_dst->ne[0]; + const uint64_t ne21 = out_dst->ne[1]; + const uint64_t eff_m_id = has_situ_merged ? (ne01 / 2) : ne01; // const uint64_t ne22 = dst->ne[2]; // const uint64_t ne23 = dst->ne[3]; + const bool is_repack = ggml_vk_tensor_is_repack(src0); const bool x_non_contig = !ggml_vk_dim01_contiguous(src0); const bool y_non_contig = !ggml_vk_dim01_contiguous(src1); const bool f16_f32_kernel = src1->type == GGML_TYPE_F32; - bool quantize_y = ctx->device->integer_dot_signed && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_src1_prec_allows_q8(dst) && ggml_vk_should_use_mmvq(ctx->device, ne01, ne12, ne10, src0->type); + bool quantize_y = !is_repack && !has_pair_glu && !has_situ_merged && ctx->device->integer_dot_signed && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_src1_prec_allows_q8(dst) && ggml_vk_should_use_mmvq(ctx->device, eff_m_id, ne12, ne10, src0->type); vk_pipeline to_fp16_vk_0 = nullptr; vk_pipeline to_fp16_vk_1 = nullptr; @@ -8691,12 +11956,12 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte } // Check for mmq first - vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, GGML_TYPE_Q8_1, ne20, ne00) : nullptr; + vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, GGML_TYPE_Q8_1, ne20, ne00, false) : nullptr; vk_pipeline to_q8_1 = nullptr; if (dmmv == nullptr) { // Fall back to f16 dequant mul mat - dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type, ne20, ne00); + dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type, ne20, ne00, is_repack); quantize_y = false; } @@ -8707,9 +11972,20 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte const bool qx_needs_dequant = x_non_contig; const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig); - if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { + const uint64_t max_a_nbytes = is_repack + ? std::max(ggml_vk_repack_alloc_bytes(src0), src0_up ? ggml_vk_repack_alloc_bytes(src0_up) : 0) + : std::max(ggml_nbytes(src0), src0_up ? ggml_nbytes(src0_up) : 0); + if (max_a_nbytes > ctx->device->properties.limits.maxStorageBufferRange) { dmmv = ggml_vk_get_64b_indexing_pipeline(ctx, dmmv); } + if (has_pair_glu || has_situ_merged) { + GGML_ASSERT(dmmv && dmmv->gen_pair_glu); + dmmv = dmmv->gen_pair_glu; + } else if ((ctx->num_additional_fused_ops == 1 && cgraph->nodes[node_idx + 1]->op == GGML_OP_GLU) || + (ctx->gen_mm_dst != nullptr && (ctx->gen_mm_flags & ~(uint32_t)(MAT_VEC_FUSION_FLAGS_EXP_SCALE0 | MAT_VEC_FUSION_FLAGS_SCALE0 | MAT_VEC_FUSION_FLAGS_SCALE1 | MAT_VEC_FUSION_FLAGS_SCALE0_TOK | MAT_VEC_FUSION_FLAGS_SCALE1_TOK)) != 0u)) { + GGML_ASSERT(dmmv && dmmv->gen_glu); + dmmv = dmmv->gen_glu; // gen: single-op epilogue twin (GEN_GLU = 1) + } // Not implemented GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT @@ -8720,11 +11996,19 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte const uint64_t x_ne = ggml_nelements(src0); const uint64_t y_ne = ggml_nelements(src1); - const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment); + const uint64_t qx_sz = is_repack + ? ggml_vk_align_size(ggml_vk_repack_alloc_bytes(src0), ctx->device->properties.limits.minStorageBufferOffsetAlignment) + : ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment); const uint64_t x_sz = x_non_contig ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : qx_sz; const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne); + static const bool mmvid_toky_enabled = + (!getenv("GGML_VK_DISABLE_MMVID_TOKY") || atoi(getenv("GGML_VK_DISABLE_MMVID_TOKY")) == 0) && + (!getenv("GGML_VK_MMVID_ONE") || atoi(getenv("GGML_VK_MMVID_ONE")) != 0); + const bool use_toky = mmvid_toky_enabled && nei1 > 1 && + (nei0 * nei1) <= ctx->device->properties.limits.maxComputeWorkGroupCount[1]; + { if ( (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) || @@ -8750,10 +12034,10 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte if (quantize_y) { ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1); } - ggml_pipeline_request_descriptor_sets(ctx, dmmv, nei1); + ggml_pipeline_request_descriptor_sets(ctx, dmmv, use_toky ? 1 : nei1); } - vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]); + vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, ctx->gen_mm_dst ? ctx->gen_mm_dst : cgraph->nodes[node_idx + ctx->num_additional_fused_ops]); vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0); vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1); vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids); @@ -8781,31 +12065,22 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment)); ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X); } + uint32_t y_ring_slot = 0; if (y_non_contig) { GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne); - if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() || - ctx->prealloc_y_last_tensor_used != src1 || - ctx->prealloc_y_last_k_padded) { - if (ctx->prealloc_y_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } + bool cached = false; + y_ring_slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, to_fp16_vk_1.get(), src1, false, cached); + d_Y = { ctx->prealloc_y, y_ring_slot * ctx->prealloc_y_ring_stride, y_sz }; + if (!cached) { ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y); - ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get(); - ctx->prealloc_y_last_tensor_used = src1; - ctx->prealloc_y_last_k_padded = false; } } if (quantize_y) { - if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() || - ctx->prealloc_y_last_tensor_used != src1 || - ctx->prealloc_y_last_k_padded) { - if (ctx->prealloc_y_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } + bool cached = false; + y_ring_slot = ggml_vk_acquire_prealloc_y_slot(ctx, subctx, to_q8_1.get(), src1, false, cached); + d_Y = { ctx->prealloc_y, y_ring_slot * ctx->prealloc_y_ring_stride, y_sz }; + if (!cached) { ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne); - ctx->prealloc_y_last_pipeline_used = to_q8_1.get(); - ctx->prealloc_y_last_tensor_used = src1; - ctx->prealloc_y_last_k_padded = false; } } @@ -8818,44 +12093,69 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0]; - uint32_t groups_x = ne01; + uint32_t groups_x = (uint32_t)eff_m_id; uint32_t groups_z = 1; - if (ne01 > max_groups_x) { + if (eff_m_id > max_groups_x) { groups_z = 64; groups_x = CEIL_DIV(groups_x, groups_z); } uint32_t fusion_flags = 0; - if (ctx->num_additional_fused_ops > 0) { + vk_subbuffer d_F1 = d_D; + if (ctx->gen_mm_dst != nullptr) { + fusion_flags |= ctx->gen_mm_flags; + if (ctx->gen_mm_f0 != nullptr) { + d_F0 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_mm_f0); + } + if (ctx->gen_mm_f1 != nullptr) { + d_F1 = ggml_vk_tensor_subbuffer(ctx, ctx->gen_mm_f1); + } + } else if (has_pair_glu) { + d_F0 = ggml_vk_tensor_subbuffer(ctx, src0_up); + fusion_flags |= MAT_VEC_FUSION_FLAGS_PAIR_GLU; + } else if (ctx->num_additional_fused_ops == 1 && cgraph->nodes[node_idx + 1]->op == GGML_OP_GLU) { + // gen: SWIGLU epilogue (GGML_GEN_FUSE=glu) + const ggml_tensor * glu = cgraph->nodes[node_idx + 1]; + const bool is_gate = glu->src[0] == dst; + d_F0 = ggml_vk_tensor_subbuffer(ctx, is_gate ? glu->src[1] : glu->src[0]); + fusion_flags |= is_gate ? MAT_VEC_FUSION_FLAGS_GLU_A : MAT_VEC_FUSION_FLAGS_GLU_B; + } else if (ctx->num_additional_fused_ops > 0) { const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1]; d_F0 = ggml_vk_tensor_subbuffer(ctx, bias); if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) { fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0; + if (bias->ne[2] == (int64_t) nei1 && nei1 > 1) { + fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0_TOK; + } } else { GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID); fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0; } } - vk_subbuffer d_F1 = d_D; - if (ctx->num_additional_fused_ops > 1) { + if (ctx->gen_mm_dst == nullptr && !has_pair_glu && ctx->num_additional_fused_ops > 1) { const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1]; d_F1 = ggml_vk_tensor_subbuffer(ctx, scale); fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1; + if (scale->ne[2] == (int64_t) nei1 && nei1 > 1) { + fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1_TOK; + } } - // Loop over the batch dimension - for (uint32_t expert_i1 = 0; expert_i1 < nei1; ++expert_i1) { + const float situ_alpha = has_situ_merged ? ctx->gen_glu_alpha : 0.0f; + const float situ_limit = has_situ_merged ? ctx->gen_glu_limit : 0.0f; + if (use_toky) { const vk_mat_vec_id_push_constants pc = { - (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01, + (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)eff_m_id, stride_batch_x, stride_batch_y, (uint32_t)(ne20 * ne21), - fusion_flags, - (uint32_t)nei0, (uint32_t)ne11, expert_i1, nbi1 + fusion_flags | MAT_VEC_FUSION_FLAGS_GEN_TOKY, + (uint32_t)nei0, (uint32_t)ne11, 0u, nbi1, + situ_alpha, situ_limit }; ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, { @@ -8866,7 +12166,28 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte d_F1, d_ids, }, - pc, { groups_x, (uint32_t)nei0, groups_z }); + pc, { groups_x, (uint32_t)(nei0 * nei1), groups_z }); + } else { + // Loop over the batch dimension + for (uint32_t expert_i1 = 0; expert_i1 < nei1; ++expert_i1) { + const vk_mat_vec_id_push_constants pc = { + (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)eff_m_id, + stride_batch_x, stride_batch_y, (uint32_t)(ne20 * ne21), + fusion_flags, + (uint32_t)nei0, (uint32_t)ne11, expert_i1, nbi1, + situ_alpha, situ_limit + }; + ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, + { + d_X, + d_Y, + d_D, + d_F0, + d_F1, + d_ids, + }, + pc, { groups_x, (uint32_t)nei0, groups_z }); + } } if (x_non_contig) { @@ -8874,17 +12195,18 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte } if (y_non_contig || quantize_y) { ctx->prealloc_y_need_sync = true; + ctx->prealloc_y_slot_need_sync[y_ring_slot] = true; } } -static bool ggml_vk_use_mul_mat_vec_id(const ggml_tensor * dst) { +static bool ggml_vk_use_mul_mat_vec_id(const ggml_tensor * dst, uint32_t max_tokens) { const ggml_tensor * src0 = dst->src[0]; const ggml_tensor * ids = dst->src[2]; - return ids->ne[1] <= 8 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)); + return ids->ne[1] <= (int64_t) max_tokens && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)); } -bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) { - return ggml_vk_use_mul_mat_vec_id(cgraph->nodes[node_idx]); +bool ggml_vk_use_mul_mat_vec_id(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) { + return ggml_vk_use_mul_mat_vec_id(cgraph->nodes[node_idx], ctx->device->mmv_id_max_tokens); } void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { @@ -8893,10 +12215,10 @@ void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src1 = dst->src[1]; ggml_tensor * src2 = dst->src[2]; VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")"); - if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) { + if (ggml_vk_use_mul_mat_vec_id(ctx, cgraph, node_idx)) { ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx); } else { - ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst); + ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst, cgraph, node_idx); } } @@ -8954,7 +12276,6 @@ bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const vk_f } bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool f32acc, ggml_type k_type, ggml_type v_type) { - GGML_UNUSED(v_type); // Needs to be kept up to date on shader changes const uint32_t Br = params.block_rows; const uint32_t Bc = params.block_cols; @@ -8969,6 +12290,28 @@ bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const vk_ const uint32_t acctype = f32acc ? 4 : 2; const uint32_t f16vec4 = 8; + if (!device->coopmat_support_16x16x16_f32acc && device->coopmat_support_8x8x8_f32acc && + (k_type == GGML_TYPE_F16 || k_type == GGML_TYPE_Q8_0) && + (v_type == GGML_TYPE_F16 || v_type == GGML_TYPE_Q8_0)) { + // Series 13/23A COOPMAT_8X8 F16/Q8_0 layout (no iq_shmem, no pvsh, compact 1 KB kvsh[128] only for F16 staging, WG=128 or WG=256) + const uint32_t num_sg = params.workgroup_size / params.subgroup_size; + const uint32_t tmpsh = num_sg * sizeof(float); + const uint32_t sh_eMf = Br * sizeof(float); + const uint32_t slope = Br * acctype; + const uint32_t Qf_T = hsk_pad * Br * sizeof(ggml_fp16_t); + const uint32_t Psh_s = Br * (Bc + 8) * sizeof(ggml_fp16_t); + const uint32_t sfstride = (Br == 16u && hsk <= 128u) ? (Br / 4u + 1u) : (Br / 4u); + const uint32_t ostride = 16u; + const uint32_t sfsh = std::max(Bc * sfstride, Br * ostride) * (4 * acctype); + const bool need_kvsh_k = (k_type != GGML_TYPE_Q8_0) && ((params.shmem_staging != 0) || ((hsk & 15u) != 0u)); + const bool need_kvsh_v = (v_type != GGML_TYPE_Q8_0) && ((params.shmem_staging != 0) || ((hsv % (16u * num_sg)) != 0u)); + const uint32_t kvsh = ((need_kvsh_k || need_kvsh_v) ? 128u : 1u) * f16vec4; + const uint32_t total_size = tmpsh + sh_eMf + slope + Qf_T + Psh_s + sfsh + kvsh; + const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize; + VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support_8x8(WG=" << params.workgroup_size << ", HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported); + return supported; + } + const uint32_t tmpsh = (Bc / MatBc) * sizeof(float); // DATA_A_IQ4_NL is compiled into the FA shaders unconditionally, so its shared table is always allocated. const uint32_t iq_shmem = 16 * sizeof(ggml_fp16_t); @@ -8991,7 +12334,8 @@ bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const vk_ uint32_t pvsh = 0; if (Br <= MatBr) { - const uint32_t pvsh_elem_size = (k_type == GGML_TYPE_BF16) ? 16u : f16vec4; + // BF16 / 8x8 PVMat accumulator is f32 (no f16/bf16 accumulator support), so pvsh is vec4 (16 bytes) + const uint32_t pvsh_elem_size = (k_type == GGML_TYPE_BF16 || (!device->coopmat_support_16x16x16_f32acc && device->coopmat_support_8x8x8_f32acc)) ? 16u : f16vec4; const uint32_t osh_stride = params.row_split * MatBr / 4; pvsh = Br * osh_stride * pvsh_elem_size; } @@ -9077,35 +12421,84 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const bool f32acc = !ctx->device->fp16 || !ggml_vk_prec_allows_f16acc(ggml_prec_get_acc(dst)) || k->type == GGML_TYPE_BF16; - // dequant K/V once into an f16 scratch, reordered KV layout so FA can read without a stride - auto is_dense_kv_cache = [](const ggml_tensor * t) { - return t->nb[0] == ggml_type_size(t->type) && - t->nb[2] == ggml_row_size(t->type, t->ne[0]) && - t->nb[1] == t->nb[2] * t->ne[2] && - (t->ne[3] == 1 || t->nb[3] == t->nb[1] * t->ne[1]); - }; - const bool k_quant = k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_BF16 && k->type != GGML_TYPE_F32; - const bool v_quant = v->type != GGML_TYPE_F16 && v->type != GGML_TYPE_BF16 && v->type != GGML_TYPE_F32; - const bool kv_raw = (k->type == GGML_TYPE_F16 || k->type == GGML_TYPE_BF16) && k->type == v->type; - // gated to AMD, except RDNA4, which regressed in benchmarks - const bool kv_raw_strided = ctx->device->vendor_id == VK_VENDOR_ID_AMD && - ctx->device->architecture != vk_device_architecture::AMD_RDNA4 && - neq1 >= 256 && + float scale = 1.0f; + float max_bias = 0.0f; + float logit_softcap = 0.0f; + + memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float)); + memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float)); + memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float)); + + if (logit_softcap != 0) { + scale /= logit_softcap; + } + + // Sparse mask hint (op_params[4]): compact the <= n_kv_max finite positions and gather only those. + const int32_t n_kv_max = mask ? ggml_get_op_params_i32(dst, 4) : 0; + const bool has_banded_bias = ggml_flash_attn_ext_has_banded_rel_bias(dst); + const ggml_tensor * rel_table = has_banded_bias ? dst->src[6] : nullptr; + const ggml_tensor * rel_pos = has_banded_bias ? dst->src[7] : nullptr; + const bool sinks_2d = sinks != nullptr && ggml_nrows(sinks) > 1; + + uint32_t span_blk_min = 0u, span_blk_max = KV, span_const_end = 0u; + const bool has_kv_span = !ctx->device->xe_fa_support && max_bias == 0.0f && mask != nullptr && n_kv_max <= 0 && + ggml_vk_get_node_active_kv_span(ctx, dst, &span_blk_min, &span_blk_max, &span_const_end); + + // dequant K/V once into an f16 scratch, reordered KV layout so FA can read without a stride + auto is_dense_kv_cache = [](const ggml_tensor * t) { + return t->nb[0] == ggml_type_size(t->type) && + t->nb[2] == ggml_row_size(t->type, t->ne[0]) && + t->nb[1] == t->nb[2] * t->ne[2] && + (t->ne[3] == 1 || t->nb[3] == t->nb[1] * t->ne[1]); + }; + const bool k_quant = k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_BF16 && k->type != GGML_TYPE_F32; + const bool v_quant = v->type != GGML_TYPE_F16 && v->type != GGML_TYPE_BF16 && v->type != GGML_TYPE_F32; + const bool kv_raw = (k->type == GGML_TYPE_F16 || k->type == GGML_TYPE_BF16) && k->type == v->type; + // gated to AMD, except RDNA4, which regressed in benchmarks + const bool kv_raw_strided = ctx->device->vendor_id == VK_VENDOR_ID_AMD && + ctx->device->architecture != vk_device_architecture::AMD_RDNA4 && + neq1 >= 256 && kv_raw && (k->nb[1] != (uint64_t)HSK * ggml_type_size(k->type) || v->nb[1] != (uint64_t)HSV * ggml_type_size(v->type)) && (HSK % 8) == 0 && (HSV % 8) == 0; const size_t kv_scratch_ts = kv_raw_strided ? ggml_type_size(k->type) : sizeof(ggml_fp16_t); + static const bool disable_fa_span_deq = getenv("GGML_VK_DISABLE_FA_SPAN_DEQ") != nullptr; + static const int env_fa_deq_small_n_max_kv = getenv("GGML_VK_FA_DEQ_SMALL_N_MAX_KV") ? atoi(getenv("GGML_VK_FA_DEQ_SMALL_N_MAX_KV")) : 65536; + // For single-stream dense KV caches ([HS, NH, KV, 1]), [0, KV_deq) is a contiguous prefix of K and V, + // so dequant_transpose only needs to convert up to the active mask span instead of the full allocated KV. + const bool can_trim_deq = !disable_fa_span_deq && has_kv_span && + nek3 == 1 && nev3 == 1 && span_blk_max < KV; + const uint32_t KV_deq = can_trim_deq + ? std::min(KV, ROUNDUP_POW2(std::max(span_blk_max, 256u), 256u)) + : KV; + const uint64_t k_deq_nel = (uint64_t)HSK * nek2 * KV_deq * nek3; + const uint64_t v_deq_nel = (uint64_t)HSV * nev2 * KV_deq * nev3; // K and V share one scratch buffer, so the sum must fit in one allocation - const uint64_t dequant_kv_sz = ((uint64_t)ggml_nelements(k) + (uint64_t)ggml_nelements(v)) * kv_scratch_ts; + const uint64_t dequant_kv_sz = (k_deq_nel + v_deq_nel) * kv_scratch_ts; const uint32_t cm2_min_queries = KV >= 8192 ? 512 : 1024; const uint32_t cm2_min_reuse = KV >= 8192 ? 4096 : 8192; // Query reuse must cover the conversion and synchronization cost. + // On Apple AGX 8x8 coopmat, N >= 2 GQA verify (can_vrow_pack) and N >= 16 prefill execute in a single + // CM1 pass over FP16 K/V, beating multi-workgroup scalar Q8_0 reads at both short and long context. const bool cm2_dequant_kv = KV >= 4096 && neq1 >= cm2_min_queries && (uint64_t) neq1 * qk_ratio >= cm2_min_reuse; - const bool use_dequant_kv = ((k_quant && v_quant) || kv_raw_strided) && neq1 >= 64 && + static const bool force_fa_q8_deq = getenv("GGML_VK_FORCE_FA_Q8_DEQ") != nullptr; + const bool agx_direct_q8_kv = !force_fa_q8_deq && f32acc && + (HSK % 16 == 0) && (HSV % 16 == 0) && + (k->type == GGML_TYPE_F16 || k->type == GGML_TYPE_Q8_0) && + (v->type == GGML_TYPE_F16 || v->type == GGML_TYPE_Q8_0); + const bool agx_small_n_deq = !disable_fa_span_deq && + !agx_direct_q8_kv && + ggml_vk_is_apple_agx_coopmat(ctx->device) && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(neq1) && + !kv_raw_strided && + (int64_t)KV_deq <= (int64_t)env_fa_deq_small_n_max_kv && + (neq1 >= 16 || (KV >= 256 && neq1 >= 2 && qk_ratio > 1 && neq1 * qk_ratio >= 4)); + const bool use_dequant_kv = ((k_quant && v_quant) || kv_raw_strided) && (neq1 >= 64 || agx_small_n_deq) && is_dense_kv_cache(k) && is_dense_kv_cache(v) && - (uint64_t)ggml_nelements(k) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && - (uint64_t)ggml_nelements(v) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && + k_deq_nel * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && + v_deq_nel * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && dequant_kv_sz <= ctx->device->max_buffer_size && dequant_kv_sz <= ctx->device->max_memory_allocation_size && (kv_raw_strided || @@ -9122,32 +12515,92 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_fa_tuning_params tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, 32, KV, k_type_eff, v_type_eff, f32acc, qk_ratio); const uint32_t max_gqa = std::min(tuning_params.block_rows, 32u); - if (N <= 8 && qk_ratio > 1 && qk_ratio <= max_gqa && - qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) { + const uint32_t N_orig = N; + static const bool disable_fa_vec_mhm = getenv("GGML_VK_DISABLE_FA_VEC_MHM") != nullptr; + static const bool force_disable_vrow = getenv("GGML_VK_DISABLE_FA_VROW_PACK") != nullptr; + static const bool force_enable_vrow = getenv("GGML_VK_ENABLE_FA_VROW_PACK") != nullptr; + static const bool fa_exact_split3 = getenv("GGML_VK_FA_EXACT_SPLIT3") != nullptr; + static const int fa_long_ctx_min_kv = getenv("GGML_VK_FA_LONG_CTX_MIN_KV") ? atoi(getenv("GGML_VK_FA_LONG_CTX_MIN_KV")) : -1; + static const int fa_8x8_min_rows_gqa = getenv("GGML_VK_FA_8X8_MIN_ROWS") ? atoi(getenv("GGML_VK_FA_8X8_MIN_ROWS")) : -1; + const int eff_fa_long_ctx_min_kv = (fa_long_ctx_min_kv >= 0) ? fa_long_ctx_min_kv : (ggml_vk_is_apple_agx_coopmat(ctx->device) ? 256 : 4096); + const int eff_fa_min_rows_gqa = (fa_8x8_min_rows_gqa >= 0) ? fa_8x8_min_rows_gqa : (KV >= 64 ? 4 : 8); + const bool long_ctx_fa = (int64_t)KV >= (int64_t)eff_fa_long_ctx_min_kv; + const bool allow_vrow_pack = !force_disable_vrow && (force_enable_vrow || long_ctx_fa); + const uint32_t vrow_check_n = (long_ctx_fa && !fa_exact_split3) ? (N_orig * qk_ratio) : N_orig; + + const bool kv_f16_or_q8_eff = (k_type_eff == GGML_TYPE_F16 || k_type_eff == GGML_TYPE_Q8_0) && + (v_type_eff == GGML_TYPE_F16 || v_type_eff == GGML_TYPE_Q8_0); + const bool can_vec_mhm = !disable_fa_vec_mhm && + !ggml_vk_exact_s8_enabled() && + !ctx->device->xe_fa_support && + ctx->device->fp16 && f32acc && + ctx->device->subgroup_size == 32 && + N_orig == 1 && qk_ratio == 3 && + qk_ratio * nek2 == neq2 && nek2 == nev2 && + (nem2 == 1 || nem2 == neq2) && mask != nullptr && mask->type == GGML_TYPE_F16 && nem0 == KV && + HSK == 128 && HSV == 128 && + kv_f16_or_q8_eff && + max_bias == 0.0f && logit_softcap == 0.0f && n_kv_max <= 0; + + const bool can_vrow_pack = allow_vrow_pack && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(N_orig) && + !ctx->device->xe_fa_support && + !ctx->device->coopmat2 && + ctx->device->coopmat1_fa_support && + !ctx->device->coopmat_support_16x16x16_f32acc && + ctx->device->coopmat_support_8x8x8_f32acc && + f32acc && + N_orig >= 2 && N_orig <= 8 && + (int)vrow_check_n >= eff_fa_min_rows_gqa && + qk_ratio > 1 && qk_ratio <= 16 && + qk_ratio * nek2 == neq2 && nek2 == nev2 && + (nem2 == 1 || nem2 == neq2) && mask != nullptr && mask->type == GGML_TYPE_F16 && nem0 == KV && + (HSK % 16 == 0) && (HSV % 16 == 0) && + kv_f16_or_q8_eff && + n_kv_max <= 0; + + bool gqa_multi_head_mask = false; + bool gqa_vrow_pack = false; + bool gqa_vec_mhm = false; + if (can_vrow_pack) { + gqa_multi_head_mask = (nem2 > 1); + gqa_vrow_pack = true; + gqa_ratio = qk_ratio; + N = N_orig * gqa_ratio; + workgroups_y /= gqa_ratio; + } else if (N <= 8 && qk_ratio > 1 && qk_ratio <= max_gqa && + qk_ratio * nek2 == neq2 && nek2 == nev2 && + (nem2 <= 1 || can_vec_mhm)) { // grouped query attention - make the N dimension equal to gqa_ratio, reduce // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1 // and change addressing calculations to index Q's dimension 2. - gqa_ratio = qk_ratio; - N = gqa_ratio; - workgroups_y /= gqa_ratio; - } - - tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio); - - float scale = 1.0f; - float max_bias = 0.0f; - float logit_softcap = 0.0f; - - memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float)); - memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float)); - memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float)); - - if (logit_softcap != 0) { - scale /= logit_softcap; + gqa_multi_head_mask = (nem2 > 1); + gqa_vec_mhm = can_vec_mhm; + gqa_ratio = qk_ratio; + N = gqa_ratio; + workgroups_y /= gqa_ratio; + } + + tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, !gqa_vrow_pack); + if (gen_batch_invariant_for_n(N_orig) && tuning_params.path != FA_SCALAR) { + tuning_params = get_fa_tuning_params_scalar(ctx->device, HSK, HSV, N_orig, KV, k_type_eff, v_type_eff, f32acc); + } + if (gqa_vec_mhm) { + tuning_params.path = FA_SCALAR; + tuning_params.subgroup_size = 32u; + tuning_params.workgroup_size = 128u; + tuning_params.block_rows = 3u; + tuning_params.block_cols = 64u; + tuning_params.d_split = 8u; + tuning_params.row_split = 1u; + tuning_params.shmem_staging = false; + tuning_params.disable_subgroups = false; + tuning_params.limit_occupancy_shmem = 0u; + } else if (gqa_multi_head_mask && tuning_params.path == FA_SCALAR) { + tuning_params.block_rows = gqa_ratio; + tuning_params.block_cols = 64u; } - - // Sparse mask hint (op_params[4]): compact the <= n_kv_max finite positions and gather only those. - const int32_t n_kv_max = mask ? ggml_get_op_params_i32(dst, 4) : 0; static const bool disable_sparse = getenv("GGML_VK_FA_SPARSE_DISABLE") != nullptr; const bool kv_f16 = k_type_eff == GGML_TYPE_F16 && v_type_eff == GGML_TYPE_F16; // cm2 dense is fast, so it needs a larger reduction to win. @@ -9159,6 +12612,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const (t->nb[1] | t->nb[2] | t->nb[3]) % (4 * sizeof(ggml_fp16_t)) == 0; }; const bool use_sparse = !disable_sparse && n_kv_max > 0 && mask && + !has_banded_bias && !sinks_2d && max_bias == 0.0f && logit_softcap == 0.0f && (tuning_params.path != FA_COOPMAT2 || (sparse_gather_aligned(k) && sparse_gather_aligned(v))) && nem0 == KV && @@ -9166,7 +12620,9 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const (gqa_ratio > 1 || (tuning_params.path == FA_SCALAR && N == 1)); const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type)); - const uint32_t q_stride_eff = gqa_ratio > 1 ? (uint32_t)(nbq2 / ggml_type_size(q->type)) : q_stride; + const uint32_t q_stride_eff = gqa_vrow_pack + ? (q_stride | (uint32_t)(nbq2 / ggml_type_size(q->type))) + : (gqa_ratio > 1 ? (uint32_t)(nbq2 / ggml_type_size(q->type)) : q_stride); uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type)); uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type)); @@ -9183,28 +12639,37 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const if (use_dequant_kv) { k_stride = HSK; v_stride = HSV; - nbk2_eff = (uint32_t)((uint64_t)HSK * KV * sizeof(ggml_fp16_t)); - nbk3_eff = (uint32_t)((uint64_t)HSK * KV * nek2 * sizeof(ggml_fp16_t)); - nbv2_eff = (uint32_t)((uint64_t)HSV * KV * sizeof(ggml_fp16_t)); - nbv3_eff = (uint32_t)((uint64_t)HSV * KV * nev2 * sizeof(ggml_fp16_t)); + nbk2_eff = (uint32_t)((uint64_t)HSK * KV_deq * kv_scratch_ts); + nbk3_eff = (uint32_t)((uint64_t)HSK * KV_deq * nek2 * kv_scratch_ts); + nbv2_eff = (uint32_t)((uint64_t)HSV * KV_deq * kv_scratch_ts); + nbv3_eff = (uint32_t)((uint64_t)HSV * KV_deq * nev2 * kv_scratch_ts); } auto fa_aligned = [&](const vk_fa_tuning_params & tp) { - // CM2 decoded K/V strides count whole blocks and do not need to be multiples of eight blocks. - const bool cm2_decode_k = tp.path == FA_COOPMAT2 && - k_type_eff != GGML_TYPE_F16 && k_type_eff != GGML_TYPE_BF16; - const bool cm2_decode_v = tp.path == FA_COOPMAT2 && - v_type_eff != GGML_TYPE_F16 && v_type_eff != GGML_TYPE_BF16; + // Decoded K/V strides count whole 32-element blocks and do not need to be multiples of eight blocks. + const bool cm1_8x8 = tp.path == FA_COOPMAT1 && + !ctx->device->coopmat_support_16x16x16_f32acc && + ctx->device->coopmat_support_8x8x8_f32acc; + const bool blk_decode_k = (tp.path == FA_COOPMAT2 && k_type_eff != GGML_TYPE_F16 && k_type_eff != GGML_TYPE_BF16) || + ((cm1_8x8 || gqa_vec_mhm) && k_type_eff == GGML_TYPE_Q8_0); + const bool blk_decode_v = (tp.path == FA_COOPMAT2 && v_type_eff != GGML_TYPE_F16 && v_type_eff != GGML_TYPE_BF16) || + ((cm1_8x8 || gqa_vec_mhm) && v_type_eff == GGML_TYPE_Q8_0); return (KV % tp.block_cols) == 0 && (q_stride_eff & 7) == 0 && - (cm2_decode_k || (k_stride & 7) == 0) && (cm2_decode_v || (v_stride & 7) == 0); + (blk_decode_k || (k_stride & 7) == 0) && (blk_decode_v || (v_stride & 7) == 0); }; uint32_t alignment = tuning_params.block_cols; bool aligned = fa_aligned(tuning_params); + if (!aligned && tuning_params.path == FA_COOPMAT1 && tuning_params.block_rows == 24u && + !(k_type_eff == GGML_TYPE_Q8_0 && v_type_eff == GGML_TYPE_Q8_0)) { + // Keep Br=24 strictly on aligned KV (need_kvsh == false) so shmem stays 15,976 B <= 16 KB + tuning_params.block_rows = 16u; + aligned = fa_aligned(tuning_params); + } if (tuning_params.flip) { // flipped coopmat1 path reads K/V rows with 16-byte loads const bool kv_16b = use_dequant_kv || (((uintptr_t)k->data | (uintptr_t)v->data | nbk2_eff | nbk3_eff | nbv2_eff | nbv3_eff) % 16) == 0; - if (!aligned || use_sparse || gqa_ratio != 1 || !kv_16b) { + if (!aligned || use_sparse || has_banded_bias || sinks_2d || gqa_ratio != 1 || !kv_16b) { tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, false); alignment = tuning_params.block_cols; aligned = fa_aligned(tuning_params); @@ -9216,11 +12681,24 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const aligned = false; } - // Only use mask opt when the mask is fairly large. This hasn't been tuned extensively. - bool use_mask_opt = mask && !use_sparse && nem1 >= 32 && nem0 * nem1 > 32768 && nem0 >= tuning_params.block_cols * 16 + // Only use mask opt when the mask is fairly large. On Apple AGX 8x8 coopmat (with graph-cached mask_opt), + // enable down to KV >= 128 (nem0 >= 2 * Bc) and nem1 >= 16 when gqa_ratio == 1. + static const int env_fa_mo_min_kv = getenv("GGML_VK_FA_MASK_OPT_MIN_KV") ? atoi(getenv("GGML_VK_FA_MASK_OPT_MIN_KV")) : 128; + const bool agx_fast_mask_opt = ggml_vk_is_apple_agx_coopmat(ctx->device) && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(N) && + env_fa_mo_min_kv > 0; + bool use_mask_opt = mask && !use_sparse && gqa_ratio == 1 && + (agx_fast_mask_opt + ? (nem1 >= 16 && (int64_t)nem0 * nem1 >= 4096 && (int)nem0 >= env_fa_mo_min_kv && nem0 >= tuning_params.block_cols * 2) + : (nem1 >= 32 && nem0 * nem1 > 32768 && nem0 >= tuning_params.block_cols * 16)) && (ctx->device->architecture != vk_device_architecture::AMD_GCN || HSK > 256 || HSV > 256); + const uint32_t fa_extra_flags = (gqa_vrow_pack ? 512u : 0u) | + (gqa_vec_mhm ? 1024u : 0u) | + (has_banded_bias ? 2048u : 0u); vk_fa_pipeline_state fa_pipeline_state = get_fa_pipeline_state(ctx->device, tuning_params, HSK, HSV, aligned, f32acc, - mask != nullptr, use_mask_opt, logit_softcap != 0, use_sparse, k_type_eff, v_type_eff); + mask != nullptr, use_mask_opt, logit_softcap != 0, use_sparse, k_type_eff, v_type_eff, + fa_extra_flags); vk_pipeline pipeline = nullptr; @@ -9232,7 +12710,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const bool xe_fa_opt = false; bool xe_fa_use_2phases = false; bool xe_fa_supported_platform = vk_dev->xe_fa_support && vk_dev->properties.deviceID != 0xFD80 && vk_dev->properties.deviceID != 0xFD81; - bool xe_fa_supported_usage = neq0 % 32 == 0 && nev0 % 16 == 0 && mask != nullptr && !use_sparse && max_bias == 0.0f && logit_softcap == 0.0f && + bool xe_fa_supported_usage = !has_banded_bias && !sinks_2d && neq0 % 32 == 0 && nev0 % 16 == 0 && mask != nullptr && !use_sparse && max_bias == 0.0f && logit_softcap == 0.0f && tensor_aligned_with(k, 16u) && tensor_aligned_with(v, 16u); bool xe_fa_supported_dtype = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16 && mask != nullptr && mask->type == GGML_TYPE_F16; @@ -9324,7 +12802,10 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const uint32_t shader_core_count_multiplier = (ctx->device->vendor_id == VK_VENDOR_ID_INTEL && ctx->device->architecture != INTEL_XE2) ? 2 : 1; // Use a placeholder core count if one isn't available. split_k is a big help for perf. - const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count * shader_core_count_multiplier : 16; + const uint32_t fa_default_cores = (ggml_vk_is_apple_agx_coopmat(ctx->device) && + strstr(ctx->device->properties.deviceName.data(), "M4 Max") != nullptr && + !ggml_vk_exact_s8_enabled()) ? 40u : 16u; + const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count * shader_core_count_multiplier : fa_default_cores; const uint32_t Br = fa_pipeline_state.Br; const uint32_t Bc = fa_pipeline_state.Bc; @@ -9347,20 +12828,48 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const // Match the shader's per-split block count so no split is empty. const uint32_t per_blocks = CEIL_DIV(total_blocks, split_k); split_k = CEIL_DIV(total_blocks, per_blocks); - } else if (gqa_ratio > 1 && workgroups_x <= Br) { - split_k = shader_core_count * 2 / (workgroups_x * workgroups_y * workgroups_z); + } else if (gqa_vrow_pack) { + if (long_ctx_fa && !fa_exact_split3 && !gen_batch_invariant()) { + const uint32_t actual_wgs = Tr * workgroups_y * workgroups_z; + if (actual_wgs < shader_core_count * 2) { + split_k = shader_core_count * 2 / actual_wgs; + } + } else { + const uint32_t tr_orig = gen_batch_invariant() && N_orig <= 8 ? 1u : CEIL_DIV(N_orig, 16u); + const uint32_t total_wgs_no_split = tr_orig * (uint32_t)neq2 * workgroups_z; + if (total_wgs_no_split < shader_core_count * 2) { + split_k = shader_core_count * 2 / total_wgs_no_split; + } + } + } else if (gqa_ratio > 1 && (workgroups_x <= Br || (gen_batch_invariant() && workgroups_x <= 8))) { + // gen: in batch-invariant mode also above Br query tokens (gqa ratio 2 has Br 2), so k <= 8 keeps n=1's split + // gen: GGML_VK_BATCH_INVARIANT=1 sizes the KV split as for one query token, so a token's attention sums in the + // same order whether it is evaluated alone or in a small verification batch + static const bool fa_old_vec_split = getenv("GGML_VK_FA_OLD_VEC_SPLIT") != nullptr; + const uint32_t wx_split = gen_batch_invariant() ? 1u : workgroups_x; + const bool keep_mhm_neq2 = fa_exact_split3 || gen_batch_invariant() || + ((!gqa_vec_mhm || fa_old_vec_split) && !long_ctx_fa); + const uint32_t wy_split = (gqa_multi_head_mask && keep_mhm_neq2) + ? (uint32_t)neq2 : workgroups_y; + split_k = shader_core_count * 2 / (wx_split * wy_split * workgroups_z); } else if (gqa_ratio <= 1) { - uint32_t total_wgs_no_split = Tr * workgroups_y * workgroups_z; + uint32_t total_wgs_no_split = (gen_batch_invariant() && N <= 8 ? 1u : Tr) * workgroups_y * workgroups_z; if (total_wgs_no_split < shader_core_count * 2) { split_k = shader_core_count * 2 / total_wgs_no_split; } } if (!use_sparse && split_k > 1) { - // Try to evenly split KV into split_k chunks, but it needs to be a multiple - // of "align", so recompute split_k based on that. - split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment); - split_k = CEIL_DIV(KV, split_kv); + // Try to evenly split KV (or the active [0, span_blk_max) prefix when known) into split_k chunks, + // aligned to "alignment" (Bc), and recompute split_k so trailing splits do not sit idle past span_blk_max. + static const bool disable_fa_span_split = getenv("GGML_VK_DISABLE_FA_SPAN_SPLIT") != nullptr; + const bool can_span_split = !disable_fa_span_split && !xe_fa_opt && has_kv_span && + !ggml_vk_exact_s8_enabled() && !gen_batch_invariant() && + span_blk_min == 0u && span_blk_max > 0u && span_blk_max < KV; + const uint32_t kv_for_split = can_span_split ? span_blk_max : KV; + const uint32_t min_split_kv = can_span_split ? std::max(alignment * 2u, 64u) : 1u; + split_kv = ROUNDUP_POW2(std::max(min_split_kv, kv_for_split / split_k), alignment); + split_k = CEIL_DIV(kv_for_split, split_kv); } if (xe_fa_opt) { @@ -9410,13 +12919,11 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const assert(pipeline_fa_mask_opt); ggml_pipeline_request_descriptor_sets(ctx, pipeline_fa_mask_opt, 1); - if (ctx->prealloc_size_y < mask_opt_size) { - ctx->prealloc_size_y = mask_opt_size; + const uint64_t req_mo_size = std::max(mask_opt_size, 65536ULL); + if (ctx->prealloc_mask_opt == nullptr || ctx->prealloc_size_mask_opt < req_mo_size) { + ctx->prealloc_size_mask_opt = req_mo_size; ggml_vk_preallocate_buffers(ctx, subctx); } - if (ctx->prealloc_y_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } } // Sparse index scratch reuses prealloc_y (mutually exclusive with mask opt). @@ -9439,8 +12946,31 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const uint32_t n_head_kv = neq2; const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv)); - const float m0 = powf(2.0f, -(max_bias ) / n_head_log2); - const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + float m0 = powf(2.0f, -(max_bias ) / n_head_log2); + float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + bool fa_has_active_span = false; + bool fa_has_const_prefix = false; + if (!xe_fa_opt && !use_sparse && has_kv_span) { + const uint32_t j_active_min = span_blk_min / Bc; + const uint32_t j_active_max = (span_blk_max == 0u) ? 0u : CEIL_DIV(span_blk_max, Bc); + const bool can_cpfx = !use_mask_opt && !ggml_vk_exact_s8_enabled() && + (tuning_params.path == FA_COOPMAT1) && !tuning_params.flip && + (span_const_end >= span_blk_min + 256u) && + (j_active_min <= 0xFFFFu) && ((span_const_end / Bc) <= 0xFFFFu); + if (can_cpfx) { + const uint32_t j_const_end = span_const_end / Bc; + const uint32_t packed_m0 = j_active_min | (j_const_end << 16); + memcpy(&m0, &packed_m0, sizeof(uint32_t)); + memcpy(&m1, &j_active_max, sizeof(uint32_t)); + fa_has_active_span = true; + fa_has_const_prefix = true; + } else if (span_blk_min > 0u || span_blk_max < KV) { + memcpy(&m0, &j_active_min, sizeof(uint32_t)); + memcpy(&m1, &j_active_max, sizeof(uint32_t)); + fa_has_active_span = true; + } + } + GGML_ASSERT(!use_dequant_kv || KV_deq == KV || fa_has_active_span); vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q); vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k); @@ -9448,25 +12978,27 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf; vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf; - vk_subbuffer mask_opt_buf = use_mask_opt ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf; + vk_subbuffer mask_opt_buf = use_mask_opt ? ggml_vk_subbuffer(ctx, ctx->prealloc_mask_opt, 0) : q_buf; vk_subbuffer sparse_buf = use_sparse ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf; - if (use_mask_opt || use_sparse) { - // the mask opt bits and the sparse index list overwrite a matmul input converted into prealloc_y - ctx->prealloc_y_last_pipeline_used = nullptr; - ctx->prealloc_y_last_tensor_used = nullptr; + vk_subbuffer rel_table_buf = rel_table ? ggml_vk_tensor_subbuffer(ctx, rel_table, true) : q_buf; + vk_subbuffer rel_pos_buf = rel_pos ? ggml_vk_tensor_subbuffer(ctx, rel_pos, true) : q_buf; + if (use_sparse) { + // the sparse index list overwrites a matmul input converted into prealloc_y + ggml_vk_invalidate_prealloc_y_ring(ctx); + ctx->prealloc_y_slot_need_sync[0] = true; } if (use_dequant_kv) { - const uint64_t k_sz = (uint64_t)ggml_nelements(k) * kv_scratch_ts; - const uint64_t v_sz = (uint64_t)ggml_nelements(v) * kv_scratch_ts; + const uint64_t k_sz = k_deq_nel * kv_scratch_ts; + const uint64_t v_sz = v_deq_nel * kv_scratch_ts; if (ctx->prealloc_size_x < k_sz + v_sz) { ctx->prealloc_size_x = k_sz + v_sz; ggml_vk_preallocate_buffers(ctx, subctx); } vk_subbuffer k_dst = vk_subbuffer{ ctx->prealloc_x, 0, k_sz }; vk_subbuffer v_dst = vk_subbuffer{ ctx->prealloc_x, k_sz, v_sz }; - const uint32_t k_nel = (uint32_t)ggml_nelements(k); - const uint32_t v_nel = (uint32_t)ggml_nelements(v); + const uint32_t k_nel = (uint32_t)k_deq_nel; + const uint32_t v_nel = (uint32_t)v_deq_nel; if (kv_raw_strided) { vk_pipeline cp_k = ggml_vk_get_cpy_pipeline(ctx, k, nullptr, k->type); vk_pipeline cp_v = ggml_vk_get_cpy_pipeline(ctx, v, nullptr, v->type); @@ -9491,9 +13023,9 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const return { ne, 1, 1 }; }; ggml_vk_dispatch_pipeline(ctx, subctx, cp_k, { k_buf, k_dst }, - make_pc((uint32_t)HSK, (uint32_t)nek2, (uint32_t)KV, k_nel), cpy_elems(k_nel)); + make_pc((uint32_t)HSK, (uint32_t)nek2, KV_deq, k_nel), cpy_elems(k_nel)); ggml_vk_dispatch_pipeline(ctx, subctx, cp_v, { v_buf, v_dst }, - make_pc((uint32_t)HSV, (uint32_t)nev2, (uint32_t)KV, v_nel), cpy_elems(v_nel)); + make_pc((uint32_t)HSV, (uint32_t)nev2, KV_deq, v_nel), cpy_elems(v_nel)); } else { vk_pipeline tr_k = ctx->device->pipeline_dequant_transpose[k->type]; vk_pipeline tr_v = ctx->device->pipeline_dequant_transpose[v->type]; @@ -9502,9 +13034,9 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const if (ctx->prealloc_x_need_sync) { ggml_vk_sync_buffers(ctx, subctx); } - { const std::vector pc = { (uint32_t)HSK, (uint32_t)nek2, (uint32_t)KV, 0, k_nel }; + { const std::vector pc = { (uint32_t)HSK, (uint32_t)nek2, KV_deq, 0, k_nel }; ggml_vk_dispatch_pipeline(ctx, subctx, tr_k, { k_buf, k_dst }, pc, { k_nel, 1, 1 }); } - { const std::vector pc = { (uint32_t)HSV, (uint32_t)nev2, (uint32_t)KV, 0, v_nel }; + { const std::vector pc = { (uint32_t)HSV, (uint32_t)nev2, KV_deq, 0, v_nel }; ggml_vk_dispatch_pipeline(ctx, subctx, tr_v, { v_buf, v_dst }, pc, { v_nel, 1, 1 }); } } ggml_vk_sync_buffers(ctx, subctx); @@ -9512,26 +13044,66 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const v_buf = v_dst; } - uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | n_head_log2; + uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | + (fa_has_active_span ? (1u << 25) : 0u) | + (fa_has_const_prefix ? (1u << 26) : 0u) | + (sinks_2d ? (1u << 27) : 0u) | + n_head_log2; if (use_mask_opt) { - const vk_op_flash_attn_mask_opt_push_constants opt_pc = { - nem0, - nem1, - nem2, - (uint32_t)(mask->nb[1] / sizeof(ggml_fp16_t)), - (uint32_t)(mask->nb[2] / sizeof(ggml_fp16_t)), - (uint32_t)(mask->nb[3] / sizeof(ggml_fp16_t)), - mask_opt_num_dwords, - mask_opt_num_dwords * CEIL_DIV(nem1, Br), - mask_opt_num_dwords * CEIL_DIV(nem1, Br) * nem2, - }; + static const int env_fa_mo_cache = getenv("GGML_VK_FA_MASK_OPT_CACHE") ? atoi(getenv("GGML_VK_FA_MASK_OPT_CACHE")) : 1; + const VkBuffer cur_m_vk_buf = mask_buf.buffer ? (VkBuffer)mask_buf.buffer->buffer : VK_NULL_HANDLE; + const bool can_reuse_mo = (env_fa_mo_cache != 0) && + !ggml_vk_exact_s8_enabled() && + ctx->last_mask_opt_valid && + ctx->last_mask_opt_tensor == mask && + ctx->last_mask_opt_vk_buf == cur_m_vk_buf && + ctx->last_mask_opt_offset == mask_buf.offset && + ctx->last_mask_opt_nem0 == nem0 && + ctx->last_mask_opt_nem1 == nem1 && + ctx->last_mask_opt_nem2 == nem2 && + ctx->last_mask_opt_nem3 == nem3 && + ctx->last_mask_opt_nb1 == mask->nb[1] && + ctx->last_mask_opt_nb2 == mask->nb[2] && + ctx->last_mask_opt_nb3 == mask->nb[3] && + ctx->last_mask_opt_br == Br && + ctx->last_mask_opt_bc == Bc; + if (!can_reuse_mo) { + if (ctx->prealloc_mask_opt_need_sync) { + ggml_vk_sync_buffers(ctx, subctx); + } + const vk_op_flash_attn_mask_opt_push_constants opt_pc = { + nem0, + nem1, + nem2, + (uint32_t)(mask->nb[1] / sizeof(ggml_fp16_t)), + (uint32_t)(mask->nb[2] / sizeof(ggml_fp16_t)), + (uint32_t)(mask->nb[3] / sizeof(ggml_fp16_t)), + mask_opt_num_dwords, + mask_opt_num_dwords * CEIL_DIV(nem1, Br), + mask_opt_num_dwords * CEIL_DIV(nem1, Br) * nem2, + }; - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline_fa_mask_opt, - { mask_buf, mask_opt_buf }, opt_pc, - { mask_opt_num_dwords, CEIL_DIV(nem1, Br), nem2 * nem3 }); - ggml_vk_sync_buffers(ctx, subctx); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline_fa_mask_opt, + { mask_buf, mask_opt_buf }, opt_pc, + { mask_opt_num_dwords, CEIL_DIV(nem1, Br), nem2 * nem3 }); + ggml_vk_sync_buffers(ctx, subctx); + + ctx->last_mask_opt_tensor = mask; + ctx->last_mask_opt_vk_buf = cur_m_vk_buf; + ctx->last_mask_opt_offset = mask_buf.offset; + ctx->last_mask_opt_nem0 = nem0; + ctx->last_mask_opt_nem1 = nem1; + ctx->last_mask_opt_nem2 = nem2; + ctx->last_mask_opt_nem3 = nem3; + ctx->last_mask_opt_nb1 = mask->nb[1]; + ctx->last_mask_opt_nb2 = mask->nb[2]; + ctx->last_mask_opt_nb3 = mask->nb[3]; + ctx->last_mask_opt_br = Br; + ctx->last_mask_opt_bc = Bc; + ctx->last_mask_opt_valid = true; + } } if (use_sparse) @@ -9552,6 +13124,15 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_vk_sync_buffers(ctx, subctx); } + if (has_banded_bias) { + GGML_ASSERT(max_bias == 0.0f && logit_softcap == 0.0f); + const uint32_t rel_params = (((uint32_t)rel_table->ne[0] & 0xFFFFu) | (((uint32_t)ggml_get_op_params_i32(dst, 6) & 0xFFFFu) << 16)); + const uint32_t rel_offsets = (((uint32_t)(get_misalign_bytes(ctx, rel_table) / sizeof(float)) & 0xFFFFu) | + (((uint32_t)(get_misalign_bytes(ctx, rel_pos) / sizeof(int32_t)) & 0xFFFFu) << 16)); + memcpy(&max_bias, &rel_params, sizeof(float)); + memcpy(&logit_softcap, &rel_offsets, sizeof(float)); + } + const vk_flash_attn_push_constants pc = { N, KV, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, (uint32_t)neq2, (uint32_t)neq3, @@ -9628,7 +13209,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const // We reuse workgroups_x to mean the number of splits, so we need to // cancel out the divide by wg_denoms[0]. uint32_t dispatch_x; - if (gqa_ratio > 1) { + if (gqa_ratio > 1 && !gqa_vrow_pack) { workgroups_x *= pipeline->wg_denoms[0]; dispatch_x = split_k * workgroups_x; } else { @@ -9637,30 +13218,43 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0); ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, - {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf, mask_opt_buf, sparse_buf}, + {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf, mask_opt_buf, sparse_buf, rel_table_buf, rel_pos_buf}, pc, { dispatch_x, workgroups_y, workgroups_z }); ggml_vk_sync_buffers(ctx, subctx); - const vk_op_flash_attn_split_k_reduce_push_constants pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, split_k, (sinks != nullptr) }; + const uint32_t sinks_mode = sinks ? (sinks_2d ? 2u : 1u) : 0u; + const vk_op_flash_attn_split_k_reduce_push_constants pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, split_k, sinks_mode }; ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce, {split_k_buf, sinks_buf, dst_buf}, pc2, { (uint32_t)ne1, HSV, (uint32_t)(ne2 * ne3) }); ctx->prealloc_split_k_need_sync = true; + for (uint32_t s = 0; s < VK_PREALLOC_RING; ++s) { + ctx->prealloc_split_k_slot_need_sync[s] = true; + } + ctx->last_expert_count_valid = false; } else { - if (gqa_ratio > 1) { + if (gqa_vrow_pack) { + workgroups_x = Tr * pipeline->wg_denoms[0]; + } else if (gqa_ratio > 1) { // When using gqa, we want one actual workgroup per batch, so cancel out wg_denoms workgroups_x *= pipeline->wg_denoms[0]; } ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, - {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, mask_opt_buf, sparse_buf}, + {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, mask_opt_buf, sparse_buf, rel_table_buf, rel_pos_buf}, pc, { workgroups_x, workgroups_y, workgroups_z }); } if (use_dequant_kv) { ctx->prealloc_x_need_sync = true; } - if (use_mask_opt || use_sparse) { + if (use_mask_opt) { + ctx->prealloc_mask_opt_need_sync = true; + } + if (use_sparse) { ctx->prealloc_y_need_sync = true; + for (uint32_t s = 0; s < VK_PREALLOC_RING; ++s) { + ctx->prealloc_y_slot_need_sync[s] = true; + } } } @@ -9750,7 +13344,8 @@ static vk_conv_shapes ggml_vk_conv3d_select_shape(ggml_backend_vk_context * ctx, return CONV_SHAPE_256x128; } -static vk_pipeline ggml_vk_rms_norm_pipeline(const std::array & pipelines, int64_t ncols) { +template +static vk_pipeline ggml_vk_rms_norm_pipeline(const std::array & pipelines, int64_t ncols) { if (pipelines[0] && ncols <= 128) { return pipelines[0]; } @@ -9807,6 +13402,22 @@ static vk_pipeline ggml_vk_float_pipeline(const vk_pipeline (&pipelines)[3], con return pipelines[ggml_vk_float_type_idx(dst->type)]; } +static int ggml_vk_rms_norm_fast_v4_idx(const std::array & pipelines, int64_t ncols) { + if (ncols == 128 && pipelines[3]) { + return 3; // BLOCK_SIZE = 32 (1 subgroup, 1 vec4/lane, 0 barriers) + } + if ((ncols == 512 || ncols == 2048) && pipelines[0]) { + return 0; // BLOCK_SIZE = 128 (1 or 4 vec4s/lane, 4 subgroups) + } + if ((ncols == 1024 || ncols == 4096) && pipelines[1]) { + return 1; // BLOCK_SIZE = 256 + } + if (ncols == 8192 && pipelines[2]) { + return 2; // BLOCK_SIZE = 512 + } + return -1; +} + static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * dst, ggml_op op) { switch (op) { case GGML_OP_GET_ROWS: @@ -9856,6 +13467,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const if ((ctx->num_additional_fused_ops > 0 || ctx->do_add_rms_partials) && (s0 == 2 || s1 == 2 || d == 2)) { return nullptr; } + if (ctx->s10_add_rms_dst != nullptr) { + return ctx->device->pipeline_multi_add_rms_mul[ctx->s10_add_rms_num_adds - 1][ctx->s10_add_rms_tree_mode][ctx->s10_add_rms_weight != nullptr ? 1 : 0]; + } if (ctx->num_additional_fused_ops > 0) { if (ctx->do_add_rms_partials) { return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops]; @@ -9948,6 +13562,16 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const } return nullptr; case GGML_OP_SCALE: + if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { + static const bool disable_s10_fuse = getenv("GGML_VK_DISABLE_S10_FUSE") != nullptr && atoi(getenv("GGML_VK_DISABLE_S10_FUSE")) != 0; + if (!disable_s10_fuse && ctx->device->pipeline_scale_zero_f32 != nullptr) { + const float sc = ggml_get_op_params_f32(dst, 0); + const float bi = ggml_get_op_params_f32(dst, 1); + if (sc == 0.0f && !std::signbit(sc) && bi == 0.0f && !std::signbit(bi)) { + return ctx->device->pipeline_scale_zero_f32; + } + } + } return ggml_vk_float_pipeline(ctx->device->pipeline_scale, src0, dst); case GGML_OP_SQR: return ggml_vk_float_pipeline(ctx->device->pipeline_sqr, src0, dst); @@ -10030,6 +13654,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const if (ctx->do_add_rms_partials) { return ctx->fused_rms_norm_mode == RMS_NORM_MUL ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32; } + if (ctx->fused_rms_norm_mode == RMS_NORM_SCALE) { + return ggml_vk_rms_norm_pipeline(ctx->device->pipeline_rms_norm_scale_f32, src0->ne[0]); + } return ggml_vk_rms_norm_pipeline(ctx->device->pipeline_rms_norm[0][ctx->fused_rms_norm_mode == RMS_NORM_MUL], src0->ne[0]); } if (src0->type == GGML_TYPE_BF16 && dst->type == GGML_TYPE_BF16 && !ctx->do_add_rms_partials) { @@ -10242,6 +13869,22 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const return ctx->device->pipeline_gated_linear_attn_f32; } return nullptr; + case GGML_OP_INKLING_FUSED: + { + int32_t m = ggml_get_op_params_i32(dst, 0); + if (m == 1) { + const uint32_t n_seq_t = (uint32_t)ggml_get_op_params_i32(dst, 2); + const uint32_t n_sq = (uint32_t)ggml_get_op_params_i32(dst, 3); + const ggml_tensor * c0 = dst->src[0]; + const bool has_n_exp = c0 && (c0->ne[2] > 1 || c0->ne[1] != (int64_t)(n_seq_t * n_sq)); + if (dst->src[6] != nullptr || has_n_exp) { + m = 14; + } + } else if (m == 3 && dst->src[ggml_get_op_params_i32(dst, 1) + 1] != nullptr) { + m = 13; + } + return (m >= 0 && m < 16) ? ctx->device->pipeline_inkling_fused[m] : nullptr; + } case GGML_OP_LIGHTNING_INDEXER: // only the k type selects a pipeline, the other types are fixed by ggml_lightning_indexer() if (ggml_vk_lightning_indexer_k_type_supported(src1->type)) { @@ -10261,6 +13904,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const case 128: si = 3; break; default: return nullptr; } + if (!rep && ctx->gen_gdn_state_out != nullptr) { + return ctx->device->pipeline_gated_delta_net_sout[si][kda]; + } return ctx->device->pipeline_gated_delta_net[si][kda][rep]; } return nullptr; @@ -10278,6 +13924,23 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const return nullptr; case GGML_OP_SSM_CONV: if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { + const bool apply_silu = (dst->op == GGML_OP_UNARY); + if (ctx->s10_ssm_conv_mode == 1 || ctx->s10_ssm_conv_mode == 3) { + if (dst->ne[1] > 8 && !ggml_vk_exact_s8_enabled()) { + return apply_silu ? ctx->device->pipeline_ssm_conv_concat_cpy_mt_silu_f32 + : ctx->device->pipeline_ssm_conv_concat_cpy_mt_f32; + } + return apply_silu ? ctx->device->pipeline_ssm_conv_concat_cpy_silu_f32 + : ctx->device->pipeline_ssm_conv_concat_cpy_f32; + } + if (ctx->s10_ssm_conv_mode == 2) { + return apply_silu ? ctx->device->pipeline_ssm_conv_silu_sout_f32 + : ctx->device->pipeline_ssm_conv_sout_f32; + } + if (dst->ne[1] == 1 && ctx->num_additional_fused_ops <= 1) { + return (ctx->num_additional_fused_ops == 1) ? ctx->device->pipeline_ssm_conv_silu_1t_f32 + : ctx->device->pipeline_ssm_conv_1t_f32; + } switch (ctx->num_additional_fused_ops) { case 0: return ctx->device->pipeline_ssm_conv_f32; case 1: return ctx->device->pipeline_ssm_conv_silu_f32; @@ -10546,8 +14209,8 @@ static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, co break; case GGML_OP_RMS_NORM: if (ctx->do_add_rms_partials) { - // Run one element per thread, 128 threads per workgroup - elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 }; + // Run one element per thread, 128 threads per workgroup (gen: one row of workgroups per row) + elements = { (uint32_t)CEIL_DIV(ne00, 128), (uint32_t)ne01, 1 }; } else { elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 }; elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]); @@ -10949,15 +14612,16 @@ void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_t } void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) { + static constexpr uint32_t MULTI_ADD_BINDINGS = 12; const ggml_tensor *first_node = cgraph->nodes[node_idx]; const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // Make a list of all the tensors used by the op. // Last element of the list is the dest tensor. - const ggml_tensor *tensors[MAX_PARAMETER_COUNT]; + const ggml_tensor *tensors[MULTI_ADD_BINDINGS]; uint32_t num_srcs = ctx->num_additional_fused_ops + 2; uint32_t num_tensors = num_srcs + 1; - GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT); + GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MULTI_ADD_BINDINGS); tensors[0] = first_node->src[0]; tensors[1] = first_node->src[1]; @@ -10995,10 +14659,10 @@ void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_c ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); - ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT]; - vk_buffer buf[MAX_PARAMETER_COUNT]; - size_t offset[MAX_PARAMETER_COUNT]; - bool uma[MAX_PARAMETER_COUNT]; + ggml_backend_vk_buffer_context * buf_ctx[MULTI_ADD_BINDINGS]; + vk_buffer buf[MULTI_ADD_BINDINGS]; + size_t offset[MULTI_ADD_BINDINGS]; + bool uma[MULTI_ADD_BINDINGS]; for (uint32_t i = 0; i < num_tensors; ++i) { buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context; @@ -11017,7 +14681,7 @@ void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_c GGML_ASSERT(buf[i] != nullptr); } // If any remaining descriptors are unused, just point them at src[0] - for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) { + for (uint32_t i = num_tensors; i < MULTI_ADD_BINDINGS; ++i) { buf[i] = buf[0]; offset[i] = 0; } @@ -11037,7 +14701,7 @@ void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_c elements = { ne, 1, 1 }; } - static_assert(MAX_PARAMETER_COUNT == 12); + static_assert(MULTI_ADD_BINDINGS <= MAX_PARAMETER_COUNT); ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { ggml_vk_subbuffer(ctx, buf[0], offset[0]), @@ -11055,6 +14719,74 @@ void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_c }, pc, elements); } +static void ggml_vk_multi_add_rms_mul(ggml_backend_vk_context * ctx, vk_context & subctx, ggml_cgraph * cgraph, int node_idx) { + GGML_UNUSED(cgraph); + GGML_UNUSED(node_idx); + const ggml_tensor * dst = ctx->s10_add_rms_dst; + const uint32_t num_srcs = ctx->s10_add_rms_num_adds + 1; + GGML_ASSERT(dst != nullptr && num_srcs >= 2 && num_srcs <= 10); + + vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, ctx->s10_add_rms_srcs[0], ctx->s10_add_rms_srcs[1], nullptr, dst, GGML_OP_ADD); + if (pipeline == nullptr) { + std::cerr << "ggml_vulkan: Error: Missing multi_add_rms_mul" << std::endl; + GGML_ABORT("fatal error"); + } + + const uint32_t ne0 = (uint32_t)dst->ne[0]; + const uint32_t nrows = (uint32_t)ggml_nrows(dst); + static const bool disable_f16_dual = getenv("GGML_VK_DISABLE_F16_DUAL") != nullptr; + const bool want_f16_dual = !disable_f16_dual && + ctx->s10_add_rms_tree_mode == 2u && + nrows >= 32u && + !gen_batch_invariant_for_n(nrows) && + ggml_is_contiguous(dst) && + get_misalign_bytes(ctx, dst) == 0; + const size_t req_y_bytes = sizeof(ggml_fp16_t) * (size_t)ROUNDUP_POW2(nrows, 128u) * ne0; + const size_t wr_y_bytes = sizeof(ggml_fp16_t) * (size_t)nrows * ne0; + if (want_f16_dual) { + ggml_vk_reserve_prealloc_y(ctx, subctx, req_y_bytes); + } + + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + + vk_op_multi_add_rms_push_constants pc {}; + pc.ne0 = ne0; + pc.nrows = nrows; + pc.eps = ctx->s10_add_rms_eps; + pc.write_add_dst = ctx->s10_add_rms_write_add | (want_f16_dual ? 2u : 0u); + for (uint32_t s = 0; s < num_srcs; ++s) { + pc.nb1[s] = (uint32_t)(ctx->s10_add_rms_srcs[s]->nb[1] / sizeof(float)); + } + + vk_subbuffer sbuf[14]; + for (uint32_t s = 0; s < num_srcs; ++s) { + sbuf[s] = ggml_vk_tensor_subbuffer(ctx, ctx->s10_add_rms_srcs[s]); + } + for (uint32_t s = num_srcs; s < 10; ++s) { + sbuf[s] = sbuf[0]; + } + sbuf[10] = (ctx->s10_add_rms_write_add && ctx->s10_add_rms_add_dst) + ? ggml_vk_tensor_subbuffer(ctx, ctx->s10_add_rms_add_dst) + : sbuf[0]; + sbuf[11] = ctx->s10_add_rms_weight + ? ggml_vk_tensor_subbuffer(ctx, ctx->s10_add_rms_weight) + : sbuf[0]; + sbuf[12] = ggml_vk_tensor_subbuffer(ctx, dst); + sbuf[13] = want_f16_dual + ? ggml_vk_produce_prealloc_y_f16(ctx, subctx, dst, wr_y_bytes, true) + : sbuf[12]; + + const uint32_t wg_x = std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[0]); + const uint32_t wg_y = CEIL_DIV(nrows, wg_x); + const std::array elements = { wg_x, wg_y, 1 }; + + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { + sbuf[0], sbuf[1], sbuf[2], sbuf[3], sbuf[4], sbuf[5], sbuf[6], + sbuf[7], sbuf[8], sbuf[9], sbuf[10], sbuf[11], sbuf[12], sbuf[13], + }, pc, elements); +} + void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { const uint32_t src0_type_size = ggml_type_size(src0->type); const uint32_t src1_type_size = ggml_type_size(src1->type); @@ -11162,6 +14894,40 @@ void ggml_vk_unary_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const }, pipeline); } +static void ggml_vk_cont_unary_mul(ggml_backend_vk_context * ctx, vk_context & subctx, const struct ggml_cgraph * cgraph, int node_idx) { + const ggml_tensor * cont = cgraph->nodes[node_idx]; + const ggml_tensor * unary = cgraph->nodes[node_idx + ctx->num_additional_fused_ops - 1]; + ggml_tensor * mul = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; + + const ggml_tensor * src0 = cont->src[0]; + const ggml_tensor * src1 = (mul->src[0] == unary) ? mul->src[1] : mul->src[0]; + + const bool f16 = src0->type == GGML_TYPE_F16; + const int oi = ggml_vk_unary_mul_op_index(ggml_get_unary_op(unary)); + if (oi < 0) { + GGML_ABORT("fatal error"); + } + vk_pipeline pipeline = ctx->device->pipeline_unary_mul[oi][f16][1][0]; + + const uint32_t ts = ggml_type_size(src0->type); + const uint32_t d0 = (uint32_t) src0->ne[0]; + const uint32_t d1 = (uint32_t) src0->ne[1]; + const uint32_t d2 = (uint32_t) src0->ne[2]; + const uint32_t d3 = (uint32_t) src0->ne[3]; + const uint32_t s1 = d0; + const uint32_t s2 = d0 * d1; + const uint32_t s3 = d0 * d1 * d2; + + ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, mul, GGML_OP_UNARY, { + (uint32_t) ggml_nelements(mul), + d0, d1, d2, d3, (uint32_t) (src0->nb[0] / ts), (uint32_t) (src0->nb[1] / ts), (uint32_t) (src0->nb[2] / ts), (uint32_t) (src0->nb[3] / ts), + d0, d1, d2, d3, 1u, s1, s2, s3, + d0, d1, d2, d3, 1u, s1, s2, s3, + 0, + 0.0f, 0.0f, 0, + }, pipeline); +} + void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { const uint32_t src0_type_size = ggml_type_size(src0->type); const uint32_t src1_type_size = ggml_type_size(src1->type); @@ -11457,6 +15223,9 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, const uint32_t rq3 = (uint32_t)(src_v->ne[3] / src_q->ne[3]); const float scale = 1.0f / sqrtf((float)S_v); + const uint32_t sout_nb2 = (ctx->gen_gdn_state_out != nullptr && K > 1) + ? (uint32_t)(ctx->gen_gdn_state_out->nb[2] / sizeof(float)) : 0u; + const uint32_t pc_K = K | (ctx->gen_gdn_zero_state ? 0x80000000u : 0u); const vk_op_gated_delta_net_push_constants pc = { H, n_tokens, n_seqs, s_off, sq1, sq2, sq3, @@ -11465,7 +15234,7 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, sb1, sb2, sb3, neq1, rq3, scale, - K, + pc_K, src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 1) : 0u, src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0u, src_pk ? (uint32_t)(src_pk->nb[1] / sizeof(float)) : 0u, @@ -11477,8 +15246,19 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, src_pgb ? (uint32_t)(src_pgb->nb[1] / sizeof(float)) : 0u, src_pgb ? (uint32_t)(src_pgb->nb[2] / sizeof(float)) : 0u, src_pgb ? (uint32_t)(src_pgb->nb[3] / sizeof(float)) : 0u, + sout_nb2 }; + if (!use_cm && !replay && ctx->gen_gdn_state_out != nullptr) { + // gen: the final state / rollback snapshots are written straight into the CPY destination + vk_subbuffer state_out_buf = ggml_vk_strided_subbuffer(ctx, ctx->gen_gdn_state_out); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, + src_buf[6], src_buf[7], src_buf[8], src_buf[9], state_out_buf}, + pc, { H, n_seqs, S_v }); + return; + } + const std::array groups = use_cm ? std::array{ S_v / cm_V, n_seqs, H } : std::array{ H, n_seqs, S_v }; if (use_v128 && replay) { @@ -11563,36 +15343,73 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te } void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { - ggml_tensor * conv = cgraph->nodes[node_idx]; - const ggml_tensor * src0 = conv->src[0]; + const int mode = ctx->s10_ssm_conv_mode; + const bool is_sliding = (mode == 1 || mode == 3); + const ggml_tensor * conv = (mode != 0) ? ctx->s10_ssm_conv_node : cgraph->nodes[node_idx]; + const ggml_tensor * src0 = (mode == 3) ? ctx->s10_ssm_old_st : ((mode == 1) ? cgraph->nodes[node_idx]->src[0] : conv->src[0]); const ggml_tensor * src1 = conv->src[1]; - // Pick the destination tensor (last node in the fused chain) and the optional bias. - // Fusion modes: 0 = ssm_conv, 1 = ssm_conv+silu, 2 = ssm_conv+add(bias)+silu. - ggml_tensor * dst = conv; + ggml_tensor * dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; const ggml_tensor * bias = nullptr; - if (ctx->num_additional_fused_ops == 1) { - dst = cgraph->nodes[node_idx + 1]; // silu - } else if (ctx->num_additional_fused_ops == 2) { - ggml_tensor * add = cgraph->nodes[node_idx + 1]; - bias = (add->src[0] == conv) ? add->src[1] : add->src[0]; - dst = cgraph->nodes[node_idx + 2]; // silu + if (mode == 0) { + if (ctx->num_additional_fused_ops == 1) { + dst = cgraph->nodes[node_idx + 1]; // silu + } else if (ctx->num_additional_fused_ops == 2) { + ggml_tensor * add = cgraph->nodes[node_idx + 1]; + bias = (add->src[0] == conv) ? add->src[1] : add->src[0]; + dst = cgraph->nodes[node_idx + 2]; // silu + } } - // The shader always declares 4 bindings; bind src0 as a dummy when bias isn't fused. - const ggml_tensor * src2 = bias ? bias : src0; + const ggml_tensor * src2 = is_sliding ? ctx->s10_ssm_qkv : (bias ? bias : src0); + const ggml_tensor * state_out = (mode != 0) ? ctx->s10_ssm_state_out : dst; + + vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, GGML_OP_SSM_CONV); + if (pipeline == nullptr) { + std::cerr << "ggml_vulkan: Error: Missing ssm_conv pipeline" << std::endl; + GGML_ABORT("fatal error"); + } + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); - ggml_vk_op_f32(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SSM_CONV, { + const uint32_t nc = (uint32_t)src1->ne[0]; + const uint32_t ncs = (uint32_t)conv->src[0]->ne[0]; + const uint32_t nr = (uint32_t)conv->src[0]->ne[1]; + const uint32_t n_t = (uint32_t)dst->ne[1]; + const uint32_t n_s = (uint32_t)dst->ne[2]; + + const uint32_t st_nb1 = (mode == 3) ? (uint32_t)state_out->nb[2] : ((mode != 0) ? (uint32_t)((nc - 1) * sizeof(float)) : 0u); + const uint32_t st_nb2 = (mode == 3) ? (uint32_t)state_out->nb[3] : ((mode != 0) ? (uint32_t)((nc - 1) * nr * sizeof(float)) : 0u); + const uint32_t qkv_nb0 = is_sliding ? (uint32_t)ctx->s10_ssm_qkv->nb[0] : 0u; + const uint32_t qkv_nb1 = is_sliding ? (uint32_t)ctx->s10_ssm_qkv->nb[1] : 0u; + const uint32_t qkv_nb2 = is_sliding ? (uint32_t)ctx->s10_ssm_qkv->nb[2] : 0u; + const uint32_t st_k = ((mode == 3) ? ctx->s10_ssm_st_k : 0u) | ((is_sliding && ctx->s10_ssm_zero_state) ? 0x80000000u : 0u); + const uint32_t st_slot_nb = (mode == 3) ? ctx->s10_ssm_st_slot_nb : 0u; + + vk_op_ssm_conv_push_constants pc = { (uint32_t)src0->nb[1], (uint32_t)src0->nb[2], (uint32_t)src1->nb[1], (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2], - (uint32_t)src1->ne[0], - (uint32_t)src0->ne[0], - (uint32_t)src0->ne[1], - (uint32_t)dst->ne[1], - (uint32_t)dst->ne[2], - }); + nc, ncs, nr, n_t, n_s, + st_nb1, st_nb2, + qkv_nb0, qkv_nb1, qkv_nb2, + st_k, st_slot_nb, + }; + + const std::array elements = { + nr, + (is_sliding && (n_t <= 8 || ggml_vk_exact_s8_enabled())) ? 1u : n_t, + n_s, + }; + + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { + ggml_vk_strided_subbuffer(ctx, src0), + ggml_vk_tensor_subbuffer(ctx, src1), + ggml_vk_strided_subbuffer(ctx, src2), + ggml_vk_tensor_subbuffer(ctx, dst), + ggml_vk_strided_subbuffer(ctx, state_out), + }, pc, elements); } static void ggml_vk_op_f32_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_push_constants&& pc) { @@ -11947,6 +15764,13 @@ uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_ten return num_bytes; } +// gen (GGML_VK_BATCH_INVARIANT=1): the partials of a multi-row ADD+RMS_NORM, one row's partials after another; the +// per-row values are exactly those of the same row evaluated alone +static uint32_t gen_rms_partials_size_rows(ggml_backend_vk_context * ctx, const ggml_tensor *node) { + const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node) * (uint32_t) ggml_nrows(node); + return ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment); +} + static vk_op_rope_push_constants ggml_vk_make_rope_constants(const ggml_tensor *dst, const ggml_tensor *src0, const bool has_ff, bool backprop, const uint32_t set_rows_stride) { const int n_dims = ((const int32_t *) dst->op_params)[1]; const int mode = ((const int32_t *) dst->op_params)[2]; @@ -11996,7 +15820,8 @@ static vk_op_rope_push_constants ggml_vk_make_rope_constants(const ggml_tensor * static void ggml_vk_rms_norm_finish(ggml_backend_vk_context * ctx, const ggml_tensor * src0) { if (ctx->do_add_rms_partials_offset_calculation) { - ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0); + ctx->prealloc_size_add_rms_partials_offset += gen_batch_invariant() ? gen_rms_partials_size_rows(ctx, src0) : ggml_vk_rms_partials_size(ctx, src0); + ctx->gen_n1_partials_offset += ggml_vk_rms_partials_size(ctx, src0); ctx->do_add_rms_partials = false; ctx->do_add_rms_partials_offset_calculation = false; } @@ -12010,11 +15835,54 @@ void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const s GGML_ASSERT(ctx->num_additional_fused_ops == 2); ggml_tensor * set_rows = cgraph->nodes[node_idx + 2]; const ggml_tensor * indices = set_rows->src[1]; + const uint32_t i_misalign = (uint32_t)(get_misalign_bytes(ctx, indices) / sizeof(int64_t)); vk_op_binary_push_constants pc = ggml_vk_rms_norm_push_constants(src0, src0, set_rows, op_params[0], 0); init_pushconst_tensor_offsets(ctx, pc, src0, src0, nullptr, nullptr, set_rows); - vk_pipeline pipeline = set_rows->type == GGML_TYPE_F16 ? - ctx->device->pipeline_rms_norm_set_rows_f32_f16 : ctx->device->pipeline_rms_norm_set_rows_f32_f32; + if (set_rows->type == GGML_TYPE_Q8_0) { + vk_pipeline pipeline = ctx->device->pipeline_rms_norm_set_rows_f32_q8_0_32; + GGML_ASSERT(pipeline != nullptr); + const uint32_t d_blk_off = (uint32_t)(get_misalign_bytes(ctx, set_rows) / ggml_type_size(GGML_TYPE_Q8_0)); + GGML_ASSERT(d_blk_off <= 0x7FFFu); + const bool v4_ok = src0->ne[0] == 128 && + ((pc.misalign_offsets >> 16) % 4 == 0) && + (src0->ne[1] == 1 || pc.nb01 % 4 == 0) && + (src0->ne[2] == 1 || pc.nb02 % 4 == 0); + pc.param3 = (int)((i_misalign << 16) | (v4_ok ? 0x8000u : 0u) | d_blk_off); + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { + ggml_vk_tensor_subbuffer(ctx, src0, true), + ggml_vk_tensor_subbuffer(ctx, src0, true), + ggml_vk_tensor_subbuffer(ctx, set_rows, true), + ggml_vk_tensor_subbuffer(ctx, indices), + }, pc, { + (uint32_t)src0->ne[1], + std::min((uint32_t)src0->ne[2], ctx->device->properties.limits.maxComputeWorkGroupCount[1]), + std::min((uint32_t)src0->ne[3], ctx->device->properties.limits.maxComputeWorkGroupCount[2]), + }); + ggml_vk_rms_norm_finish(ctx, src0); + return; + } + + static const bool force_128 = getenv("GGML_VK_S17_RMS_SET_ROWS_128") != nullptr; + vk_pipeline pipe_32 = set_rows->type == GGML_TYPE_F16 + ? ctx->device->pipeline_rms_norm_set_rows_f32_f16_32 + : ctx->device->pipeline_rms_norm_set_rows_f32_f32_32; + const bool v4_32_ok = !force_128 && pipe_32 != nullptr && + src0->ne[0] == 128 && + ((pc.misalign_offsets >> 16) % 4 == 0) && + ((pc.misalign_offsets & 0xFF) % 4 == 0) && + (src0->ne[1] == 1 || pc.nb01 % 4 == 0) && + (src0->ne[2] == 1 || pc.nb02 % 4 == 0) && + (pc.nb21 % 4 == 0); + pc.param3 = (int)((i_misalign << 16) | (v4_32_ok ? 2u : 0u)); + + vk_pipeline pipeline = v4_32_ok + ? pipe_32 + : (set_rows->type == GGML_TYPE_F16 + ? ctx->device->pipeline_rms_norm_set_rows_f32_f16 + : ctx->device->pipeline_rms_norm_set_rows_f32_f32); ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { @@ -12031,6 +15899,96 @@ void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const s return; } + if (ctx->fused_rms_norm_mode == RMS_NORM_MUL_SILU_GATE) { + // gen: nodes RMS_NORM, MUL(w), [RESHAPE/VIEW(z)], UNARY silu(z), MUL -> one dispatch + GGML_ASSERT(ctx->num_additional_fused_ops == 3 || ctx->num_additional_fused_ops == 4); + ggml_tensor * mul = cgraph->nodes[node_idx + 1]; + ggml_tensor * silu = cgraph->nodes[node_idx + ctx->num_additional_fused_ops - 1]; + ggml_tensor * dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; + const ggml_tensor * weight = mul->src[0] == rms ? mul->src[1] : mul->src[0]; + const ggml_tensor * z = silu->src[0]; + vk_op_binary_push_constants pc = ggml_vk_rms_norm_push_constants(src0, weight, dst, op_params[0], 0); + init_pushconst_tensor_offsets(ctx, pc, src0, weight, nullptr, nullptr, dst); + init_pushconst_fastdiv(pc); + + static const bool disable_fast_rms = getenv("GGML_VK_DISABLE_FAST_RMS") != nullptr; + static const bool disable_f16_dual = getenv("GGML_VK_DISABLE_F16_DUAL") != nullptr; + static const bool keep_silu_f32 = getenv("GGML_VK_KEEP_SILU_F32") != nullptr; + const int fast_idx = (!disable_fast_rms && ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled()) + ? ggml_vk_rms_norm_fast_v4_idx(ctx->device->pipeline_rms_norm_mul_silu_f32, src0->ne[0]) + : -1; + const bool v4_ok = fast_idx >= 0 && + ((pc.misalign_offsets >> 16) % 4 == 0) && + (((pc.misalign_offsets >> 8) & 0xFF) % 4 == 0) && + ((pc.misalign_offsets & 0xFF) == 0) && + (src0->ne[1] == 1 || pc.nb01 % 4 == 0) && + (src0->ne[2] == 1 || pc.nb02 % 4 == 0) && + (src0->ne[3] == 1 || pc.nb03 % 4 == 0) && + (weight->ne[0] % 4 == 0) && + (weight->ne[1] == 1 || pc.nb11 % 4 == 0) && + (weight->ne[2] == 1 || pc.nb12 % 4 == 0) && + (weight->ne[3] == 1 || pc.nb13 % 4 == 0) && + get_misalign_bytes(ctx, dst) == 0 && + get_misalign_bytes(ctx, z) == 0; + const uint64_t tok_dim = dst->ne[2] > 1 ? (uint64_t)(dst->ne[2] * dst->ne[3]) : (uint64_t)dst->ne[1]; + const uint64_t feat_dim = ggml_nelements(dst) / std::max(1, tok_dim); + const bool want_f16_dual = v4_ok && !disable_f16_dual && + tok_dim >= 128 && !gen_batch_invariant_for_n(tok_dim) && + ggml_is_contiguous(dst); + const size_t req_y_bytes = sizeof(ggml_fp16_t) * (size_t)ROUNDUP_POW2(tok_dim, 128ULL) * feat_dim; + const size_t wr_y_bytes = sizeof(ggml_fp16_t) * (size_t)ggml_nelements(dst); + if (want_f16_dual) { + ggml_vk_reserve_prealloc_y(ctx, subctx, req_y_bytes); + } + uint32_t rms_flags = 0u; + if (v4_ok) { + rms_flags |= 2u; + if (want_f16_dual) { + rms_flags |= 4u; + if (ctx->gen_rms_silu_sole_mm_next && !keep_silu_f32) { + rms_flags |= 8u; + } + } + } + pc.param3 = (int)rms_flags; + vk_pipeline pipeline = v4_ok + ? ctx->device->pipeline_rms_norm_mul_silu_f32[fast_idx] + : ggml_vk_rms_norm_pipeline(ctx->device->pipeline_rms_norm_mul_silu_f32, src0->ne[0]); + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); + if (pipeline->parameter_count == 5) { + vk_subbuffer f16_buf = want_f16_dual + ? ggml_vk_produce_prealloc_y_f16(ctx, subctx, dst, wr_y_bytes, false) + : dst_buf; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { + ggml_vk_tensor_subbuffer(ctx, src0, true), + ggml_vk_tensor_subbuffer(ctx, weight, true), + dst_buf, + ggml_vk_tensor_subbuffer(ctx, z), + f16_buf, + }, pc, { + (uint32_t)src0->ne[1], + std::min((uint32_t)src0->ne[2], ctx->device->properties.limits.maxComputeWorkGroupCount[1]), + std::min((uint32_t)src0->ne[3], ctx->device->properties.limits.maxComputeWorkGroupCount[2]), + }); + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { + ggml_vk_tensor_subbuffer(ctx, src0, true), + ggml_vk_tensor_subbuffer(ctx, weight, true), + dst_buf, + ggml_vk_tensor_subbuffer(ctx, z), + }, pc, { + (uint32_t)src0->ne[1], + std::min((uint32_t)src0->ne[2], ctx->device->properties.limits.maxComputeWorkGroupCount[1]), + std::min((uint32_t)src0->ne[3], ctx->device->properties.limits.maxComputeWorkGroupCount[2]), + }); + } + ggml_vk_rms_norm_finish(ctx, src0); + return; + } + if (ctx->fused_rms_norm_mode == RMS_NORM_MUL_ADD || ctx->fused_rms_norm_mode == RMS_NORM_MUL_ADD_MUL) { ggml_tensor * mul = cgraph->nodes[node_idx + 1]; ggml_tensor * add = cgraph->nodes[node_idx + 2]; @@ -12066,7 +16024,7 @@ void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const s ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset), ggml_vk_tensor_subbuffer(ctx, residual), ggml_vk_tensor_subbuffer(ctx, post_scale), - }, pc, { (uint32_t)CEIL_DIV(src0->ne[0], 128), 1, 1 }); + }, pc, { (uint32_t)CEIL_DIV(src0->ne[0], 128), (uint32_t)src0->ne[1], 1 }); } else { ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { @@ -12085,6 +16043,53 @@ void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const s return; } + if (ctx->fused_rms_norm_mode == RMS_NORM_SCALE) { + ggml_tensor * dst0 = const_cast(ctx->gen_rms_scale_dst); + ggml_tensor * dst1 = const_cast(ctx->gen_rms_scale_dst2); + vk_op_binary_push_constants pc = ggml_vk_rms_norm_push_constants(src0, src0, dst0, op_params[0], 0); + init_pushconst_tensor_offsets(ctx, pc, src0, src0, nullptr, nullptr, dst0); + init_pushconst_fastdiv(pc); + pc.param2 = ggml_get_op_params_f32(dst0, 0); + uint32_t p3_bits = dst1 ? (1u | (((uint32_t)(get_misalign_bytes(ctx, dst1) / sizeof(float))) << 8)) : 0u; + static const bool disable_fast_rms = getenv("GGML_VK_DISABLE_FAST_RMS") != nullptr; + const int fast_idx = (!disable_fast_rms && ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled()) + ? ggml_vk_rms_norm_fast_v4_idx(ctx->device->pipeline_rms_norm_scale_f32, src0->ne[0]) + : -1; + const bool v4_ok = fast_idx >= 0 && + ((pc.misalign_offsets >> 16) % 4 == 0) && + ((pc.misalign_offsets & 0xFF) % 4 == 0) && + ((dst1 != nullptr || src0->ne[1] > 1) ? (pc.nb01 % 4 == 0) : true) && + (src0->ne[2] == 1 || pc.nb02 % 4 == 0) && + (src0->ne[3] == 1 || pc.nb03 % 4 == 0) && + (!dst1 || (get_misalign_bytes(ctx, dst1) % 16 == 0)); + if (v4_ok) { + p3_bits |= 2u; + } + pc.param3 = (int)p3_bits; + vk_pipeline pipeline = v4_ok + ? ctx->device->pipeline_rms_norm_scale_f32[fast_idx] + : ggml_vk_rms_norm_pipeline(ctx->device->pipeline_rms_norm_scale_f32, src0->ne[0]); + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + vk_subbuffer s0_buf = ggml_vk_strided_subbuffer(ctx, src0, true); + if (dst1 != nullptr && ctx->gen_rms_scale_rsrc2 != nullptr) { + vk_subbuffer s1_buf = ggml_vk_strided_subbuffer(ctx, ctx->gen_rms_scale_rsrc2, true); + const size_t end1 = s1_buf.offset + s1_buf.size; + if (end1 > s0_buf.offset + s0_buf.size) { + s0_buf.size = end1 - s0_buf.offset; + } + } + vk_subbuffer d0_buf = ggml_vk_tensor_subbuffer(ctx, dst0, true); + vk_subbuffer d1_buf = dst1 ? ggml_vk_tensor_subbuffer(ctx, dst1, true) : d0_buf; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { s0_buf, s0_buf, d0_buf, d1_buf }, pc, { + (uint32_t)(dst1 ? 2 * src0->ne[1] : src0->ne[1]), + std::min((uint32_t)src0->ne[2], ctx->device->properties.limits.maxComputeWorkGroupCount[1]), + std::min((uint32_t)src0->ne[3], ctx->device->properties.limits.maxComputeWorkGroupCount[2]), + }); + ggml_vk_rms_norm_finish(ctx, src0); + return; + } + ggml_tensor * dst; const ggml_tensor * src1; @@ -12182,7 +16187,73 @@ void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const s ggml_vk_subbuffer(ctx, buf[6], offset[6]), }, pc, elements); } else { - GGML_ASSERT(ctx->fused_rms_norm_mode == RMS_NORM_MUL || ctx->fused_rms_norm_mode == RMS_NORM_COUNT); + GGML_ASSERT(ctx->fused_rms_norm_mode == RMS_NORM_MUL || ctx->fused_rms_norm_mode == RMS_NORM_SCALE || ctx->fused_rms_norm_mode == RMS_NORM_COUNT); + static const bool disable_fast_rms = getenv("GGML_VK_DISABLE_FAST_RMS") != nullptr; + static const bool disable_f16_dual = getenv("GGML_VK_DISABLE_F16_DUAL") != nullptr; + const auto & pipe_arr = ctx->device->pipeline_rms_norm[0][ctx->fused_rms_norm_mode == RMS_NORM_MUL]; + const int fast_idx = (!ctx->do_add_rms_partials && !disable_fast_rms && + ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled() && + src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) + ? ggml_vk_rms_norm_fast_v4_idx(pipe_arr, src0->ne[0]) + : -1; + if (fast_idx >= 0) { + vk_op_binary_push_constants pc = bin; + init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, dst); + init_pushconst_fastdiv(pc); + const bool v4_ok = + ((pc.misalign_offsets >> 16) % 4 == 0) && + (((pc.misalign_offsets >> 8) & 0xFF) % 4 == 0) && + ((pc.misalign_offsets & 0xFF) % 4 == 0) && + (src0->ne[1] == 1 || pc.nb01 % 4 == 0) && + (src0->ne[2] == 1 || pc.nb02 % 4 == 0) && + (src0->ne[3] == 1 || pc.nb03 % 4 == 0) && + (src1->ne[0] % 4 == 0) && + (src1->ne[1] == 1 || pc.nb11 % 4 == 0) && + (src1->ne[2] == 1 || pc.nb12 % 4 == 0) && + (src1->ne[3] == 1 || pc.nb13 % 4 == 0); + if (v4_ok) { + const int next_i = node_idx + ctx->num_additional_fused_ops + 1; + const bool has_mm_consumer = cgraph != nullptr && next_i < cgraph->n_nodes && + (cgraph->nodes[next_i]->op == GGML_OP_MUL_MAT || + cgraph->nodes[next_i]->op == GGML_OP_MUL_MAT_ID || + cgraph->nodes[next_i]->op == GGML_OP_RESHAPE || + cgraph->nodes[next_i]->op == GGML_OP_VIEW); + const uint32_t nrows = (uint32_t)src0->ne[1]; + const bool want_f16_dual = !disable_f16_dual && + ctx->fused_rms_norm_mode == RMS_NORM_MUL && + has_mm_consumer && + src0->ne[2] == 1 && src0->ne[3] == 1 && + nrows >= 32u && + !gen_batch_invariant_for_n(nrows) && + ggml_is_contiguous(dst) && + get_misalign_bytes(ctx, dst) == 0; + const size_t req_y_bytes = sizeof(ggml_fp16_t) * (size_t)ROUNDUP_POW2(nrows, 128u) * (size_t)src0->ne[0]; + const size_t wr_y_bytes = sizeof(ggml_fp16_t) * (size_t)nrows * (size_t)src0->ne[0]; + if (want_f16_dual) { + ggml_vk_reserve_prealloc_y(ctx, subctx, req_y_bytes); + } + pc.param3 = (int)(2u | (want_f16_dual ? 4u : 0u)); + vk_pipeline pipeline = pipe_arr[fast_idx]; + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); + vk_subbuffer f16_buf = want_f16_dual + ? ggml_vk_produce_prealloc_y_f16(ctx, subctx, dst, wr_y_bytes, false) + : dst_buf; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { + ggml_vk_tensor_subbuffer(ctx, src0, true), + ggml_vk_tensor_subbuffer(ctx, src1, true), + dst_buf, + f16_buf, + }, pc, { + (uint32_t)src0->ne[1], + std::min((uint32_t)src0->ne[2], ctx->device->properties.limits.maxComputeWorkGroupCount[1]), + std::min((uint32_t)src0->ne[3], ctx->device->properties.limits.maxComputeWorkGroupCount[2]), + }); + ggml_vk_rms_norm_finish(ctx, src0); + return; + } + } ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin)); } @@ -12327,8 +16398,8 @@ void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const g vk_subbuffer buf_y = { ctx->prealloc_y, 0, tmp_size }; // the partial results overwrite a matmul input converted into prealloc_y - ctx->prealloc_y_last_pipeline_used = nullptr; - ctx->prealloc_y_last_tensor_used = nullptr; + ggml_vk_invalidate_prealloc_y_ring(ctx); + ctx->prealloc_y_slot_need_sync[0] = true; std::array elements = { num_wgs, nrows_x, 1 }; @@ -12348,6 +16419,9 @@ void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const g ctx->prealloc_x_need_sync = true; ctx->prealloc_y_need_sync = true; + for (uint32_t s = 0; s < VK_PREALLOC_RING; ++s) { + ctx->prealloc_y_slot_need_sync[s] = true; + } } } @@ -12358,13 +16432,14 @@ void ggml_vk_soft_max_back(ggml_backend_vk_context * ctx, vk_context& subctx, co void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) { topk_moe_mode mode = ctx->fused_topk_moe_mode; - const bool has_bias = mode == TOPK_MOE_SIGMOID_NORM_BIAS || mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS; + const bool is_sig_bias = mode == TOPK_MOE_SIGMOID_NORM_BIAS || mode == TOPK_MOE_SIGMOID_NORM_BIAS_EPS; + const bool has_bias = is_sig_bias || mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS; ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0]; - ggml_tensor * bias = mode == TOPK_MOE_SIGMOID_NORM_BIAS ? cgraph->nodes[node_idx + 2]->src[1] : + ggml_tensor * bias = is_sig_bias ? cgraph->nodes[node_idx + 2]->src[1] : mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS ? cgraph->nodes[node_idx + 3]->src[1] : logits; ggml_tensor * weights = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; - ggml_tensor * ids = mode == TOPK_MOE_SIGMOID_NORM_BIAS ? cgraph->nodes[node_idx + 4] : + ggml_tensor * ids = is_sig_bias ? cgraph->nodes[node_idx + 4] : mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS ? cgraph->nodes[node_idx + 5] : mode == TOPK_MOE_LATE_SOFTMAX ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3]; @@ -12380,7 +16455,49 @@ void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cg GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts); - vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX); + static const bool disable_topk_count = getenv("GGML_VK_DISABLE_TOPK_COUNT") != nullptr; + const uint32_t topk_idx = (uint32_t)ceilf(log2f(float(logits->ne[0]))); + const bool topk_use_push = logits->ne[0] != (1 << topk_idx); + const uint32_t topk_wg16 = (n_rows > 8) ? 1u : 0u; + bool emit_expert_counts = false; + const ggml_tensor * emit_sel_ids = ids; + if (!disable_topk_count && + n_rows > (int)ctx->device->mmv_id_max_tokens && n_rows <= 16 && + n_experts > 0 && n_experts <= 256 && topk_idx <= 8 && + n_expert_used > 0 && n_expert_used <= 32 && + ggml_vk_is_apple_agx_coopmat(ctx->device) && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(n_rows) && + !getenv("GGML_VK_DISABLE_MMA_ID") && + !getenv("GGML_VK_MMA_ID_RT") && + !getenv("GGML_VK_MMA_ID_PGLU_RT") && + !getenv("GGML_VK_MMA_ID_FEP_RT") && + CEIL_DIV((uint64_t)n_expert_used * (uint64_t)n_rows, (uint64_t)n_experts) <= 4u && + get_misalign_bytes(ctx, ids) == 0 && + ctx->device->pipeline_topk_moe_count[topk_idx][topk_use_push][topk_wg16] != nullptr) { + const int search_end = std::min(cgraph->n_nodes, node_idx + ctx->num_additional_fused_ops + 32); + for (int k = node_idx + ctx->num_additional_fused_ops + 1; k < search_end; ++k) { + const ggml_tensor * cn = cgraph->nodes[k]; + if (cn->op == GGML_OP_MUL_MAT_ID && + cn->src[0]->ne[2] == n_experts && + (ids->op == GGML_OP_ARGSORT || (ids->view_src && ids->view_src->op == GGML_OP_ARGSORT))) { + const ggml_tensor * cand = cn->src[2]; + const bool matches_ids = (cand == ids) || + (cand->op == GGML_OP_VIEW && cand->view_src == ids && cand->view_offs == 0 && + cand->ne[0] == n_expert_used && cand->ne[1] == n_rows && + cand->nb[0] == ids->nb[0] && cand->nb[1] == ids->nb[1]); + if (matches_ids) { + emit_sel_ids = cand; + emit_expert_counts = true; + break; + } + } + } + } + + vk_pipeline pipeline = emit_expert_counts + ? ctx->device->pipeline_topk_moe_count[topk_idx][topk_use_push][topk_wg16] + : ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX); ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); @@ -12407,6 +16524,12 @@ void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cg pc.clamp_min = ggml_get_op_params_f32(clamp, 0); pc.clamp_max = ggml_get_op_params_f32(clamp, 1); } + if (mode == TOPK_MOE_SIGMOID_NORM_BIAS_EPS) { + ggml_tensor * sc = cgraph->nodes[node_idx + 8]; + GGML_ASSERT(sc->op == GGML_OP_SCALE); + pc.clamp_min = ggml_get_op_params_f32(sc, 1); + pc.clamp_max = -1.0f; // signals wt_sum += clamp_min in topk_moe.comp + } if (mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS) { ggml_tensor * clamp = cgraph->nodes[node_idx + 9]; GGML_ASSERT(clamp->op == GGML_OP_CLAMP); @@ -12419,7 +16542,7 @@ void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cg #define GATING_FUNC_SOFTMAX_WEIGHT 2 #define GATING_FUNC_SQRT_SOFTPLUS 3 - pc.gating_func = mode == TOPK_MOE_SIGMOID_NORM_BIAS ? GATING_FUNC_SIGMOID : + pc.gating_func = is_sig_bias ? GATING_FUNC_SIGMOID : mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS ? GATING_FUNC_SQRT_SOFTPLUS : mode == TOPK_MOE_LATE_SOFTMAX ? GATING_FUNC_SOFTMAX_WEIGHT : GATING_FUNC_SOFTMAX; @@ -12436,6 +16559,36 @@ void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cg GGML_ASSERT(n_expert_used <= n_experts); + if (emit_expert_counts) { + const uint32_t bn = 8u; + const uint64_t max_tiles = ggml_vk_mul_mat_id_max_tiles((uint64_t)n_experts, (uint64_t)n_expert_used * (uint64_t)n_rows, bn); + const uint64_t row_ids_offset = 1u + 2u * max_tiles; + const size_t expert_data_size = sizeof(uint32_t) * (size_t)(row_ids_offset + max_tiles * bn); + if (ctx->prealloc_size_split_k < expert_data_size) { + ctx->prealloc_size_split_k = expert_data_size; + ggml_vk_preallocate_buffers(ctx, subctx); + } + const uint32_t sk_ring_slot = ggml_vk_acquire_prealloc_split_k_slot(ctx, subctx, expert_data_size); + vk_subbuffer expert_count_buf = { ctx->prealloc_split_k, sk_ring_slot * ctx->prealloc_split_k_ring_stride, expert_data_size }; + struct { + vk_op_topk_moe_push_constants base; + uint32_t count_bn; + uint32_t row_ids_offset; + } pc_ext = { pc, bn, (uint32_t)row_ids_offset }; + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + { logits_buf, bias_buf, weights_buf, ids_buf, expert_count_buf }, pc_ext, { 1, 1, 1 }); + ctx->last_expert_ids_tensor = emit_sel_ids; + ctx->last_expert_bn = bn; + ctx->last_expert_row_ids_offset = (uint32_t)row_ids_offset; + ctx->last_expert_n_as = (uint32_t)n_experts; + ctx->last_expert_slot = sk_ring_slot; + ctx->last_expert_count_buf = expert_count_buf; + ctx->last_expert_count_valid = true; + ctx->prealloc_split_k_need_sync = true; + ctx->prealloc_split_k_slot_need_sync[sk_ring_slot] = true; + return; + } + const uint32_t rows_per_block = 4; std::array elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 }; @@ -12793,6 +16946,10 @@ void ggml_vk_cumsum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggm ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, {src_buf, dst_buf, temp_buf}, pc, elements); ctx->prealloc_split_k_need_sync = true; + for (uint32_t s = 0; s < VK_PREALLOC_RING; ++s) { + ctx->prealloc_split_k_slot_need_sync[s] = true; + } + ctx->last_expert_count_valid = false; } static std::array ggml_vk_nrows_elements(uint32_t nr) { @@ -12893,8 +17050,36 @@ void ggml_vk_cross_entropy_loss_back(ggml_backend_vk_context * ctx, vk_context& ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { grad_buf, logits_buf, labels_buf, dst_buf }, pc, ggml_vk_nrows_elements(nrows)); } +static void ggml_vk_argmax_ex(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, + float softcap_s0, float softcap_s1, const ggml_tensor * src1 = nullptr) { + vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, nullptr, nullptr, dst, GGML_OP_ARGMAX); + GGML_ASSERT(pipeline != nullptr); + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + const vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, true); + const vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); + const vk_subbuffer src1_buf = src1 ? ggml_vk_tensor_subbuffer(ctx, src1, true) : src0_buf; + const uint32_t a_misalign = (uint32_t)(get_misalign_bytes(ctx, src0) / sizeof(float)); + const uint32_t d_misalign = (uint32_t)(get_misalign_bytes(ctx, dst) / sizeof(int32_t)); + const uint32_t b_misalign = src1 ? (uint32_t)(get_misalign_bytes(ctx, src1) / sizeof(float)) : 0u; + GGML_ASSERT(d_misalign < 1024u && b_misalign < 1024u); + const uint32_t packed4 = 0x40000000u | (d_misalign & 0x3FFu) | ((b_misalign & 0x3FFu) << 10u) | ((src1 ? 1u : 0u) << 20u); + float param4_f = 0.0f; + memcpy(¶m4_f, &packed4, sizeof(float)); + const vk_op_push_constants pc = { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], softcap_s0, softcap_s1, (float)a_misalign, param4_f }; + const uint32_t nr = (uint32_t)ggml_nrows(src0); + std::array elements; + if (nr > 262144u) { + elements = { 512u, 512u, CEIL_DIV(nr, 262144u) }; + } else if (nr > 512u) { + elements = { 512u, CEIL_DIV(nr, 512u), 1u }; + } else { + elements = { nr, 1u, 1u }; + } + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf, src1_buf }, pc, elements); +} + void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { - ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGMAX, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], 0.0f, 0.0f, 0.0f, 0.0f }); + ggml_vk_argmax_ex(ctx, subctx, src0, dst, 0.0f, 0.0f); } void ggml_vk_count_equal(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { @@ -13383,9 +17568,24 @@ void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subct #endif if (subctx) { + if (ctx->recording_replay) { + ctx->replay_abort = true; + ctx->recording_replay = false; + ctx->active_replay_cmd_pool = nullptr; + subctx->p = &ctx->compute_cmd_pool; + } // Submit and wait for any pending work before reallocating the buffers + ggml_vk_ensure_fence_free(ctx); ggml_vk_ctx_end(subctx); - ggml_vk_submit(subctx, {}); + const bool need_tsem = ctx->device->async_use_transfer_queue && + ctx->transfer_semaphore_last_submitted < ctx->transfer_semaphore.value; + if (!need_tsem && subctx->out_memcpys.empty() && !subctx->seqs.empty()) { + ctx->last_submit_us = ggml_time_us(); + ggml_vk_submit(subctx, ctx->fence); + ctx->fence_submitted = true; + } else { + ggml_vk_submit(subctx, {}); + } ctx->submit_pending = true; ggml_vk_synchronize(ctx); GGML_ASSERT(ctx->compute_ctx.expired()); @@ -13401,24 +17601,47 @@ void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subct } ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x); } - if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) { - VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")"); + const size_t y_stride = ctx->prealloc_size_y > 0 ? ROUNDUP_POW2(ctx->prealloc_size_y, 4096ULL) : 0; + const uint32_t y_ring = (y_stride > 0 && y_stride * VK_PREALLOC_RING <= ctx->device->properties.limits.maxStorageBufferRange && + y_stride * VK_PREALLOC_RING <= 512ULL * 1024 * 1024) ? VK_PREALLOC_RING : 1u; + const size_t y_total = y_ring > 1 ? y_stride * y_ring : ctx->prealloc_size_y; + if (ctx->prealloc_y == nullptr || (y_total > 0 && ctx->prealloc_y->size < y_total)) { + VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << y_total << ")"); // Resize buffer if (ctx->prealloc_y != nullptr) { ggml_vk_destroy_buffer(ctx->prealloc_y); } - ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y); - ctx->prealloc_y_last_pipeline_used = nullptr; - ctx->prealloc_y_last_tensor_used = nullptr; - ctx->prealloc_y_last_k_padded = false; - } - if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) { - VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")"); + ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, y_total); + ctx->prealloc_y_ring_stride = y_stride; + ctx->prealloc_y_ring_count = y_ring; + ctx->prealloc_y_ring_idx = 0; + ggml_vk_invalidate_prealloc_y_ring(ctx); + } else if (y_total > 0) { + if (ctx->prealloc_y_ring_stride != y_stride || ctx->prealloc_y_ring_count != y_ring) { + ctx->prealloc_y_ring_idx = 0; + ggml_vk_invalidate_prealloc_y_ring(ctx); + } + ctx->prealloc_y_ring_stride = y_stride; + ctx->prealloc_y_ring_count = y_ring; + } + const size_t sk_stride = ctx->prealloc_size_split_k > 0 ? ROUNDUP_POW2(ctx->prealloc_size_split_k, 4096ULL) : 0; + const uint32_t sk_ring = (sk_stride > 0 && sk_stride * VK_PREALLOC_RING <= ctx->device->properties.limits.maxStorageBufferRange && + sk_stride * VK_PREALLOC_RING <= 128ULL * 1024 * 1024) ? VK_PREALLOC_RING : 1u; + const size_t sk_total = sk_ring > 1 ? sk_stride * sk_ring : ctx->prealloc_size_split_k; + if (ctx->prealloc_split_k == nullptr || (sk_total > 0 && ctx->prealloc_split_k->size < sk_total)) { + VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << sk_total << ")"); // Resize buffer if (ctx->prealloc_split_k != nullptr) { ggml_vk_destroy_buffer(ctx->prealloc_split_k); } - ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k); + ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, sk_total); + ctx->prealloc_split_k_ring_stride = sk_stride; + ctx->prealloc_split_k_ring_count = sk_ring; + ctx->prealloc_split_k_ring_idx = 0; + ctx->last_expert_count_valid = false; + } else if (sk_total > 0) { + ctx->prealloc_split_k_ring_stride = sk_stride; + ctx->prealloc_split_k_ring_count = sk_ring; } if (ctx->prealloc_add_rms_partials == nullptr || (ctx->prealloc_size_add_rms_partials > 0 && ctx->prealloc_add_rms_partials->size < ctx->prealloc_size_add_rms_partials)) { VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")"); @@ -13428,6 +17651,15 @@ void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subct } ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials); } + if (ctx->prealloc_size_mask_opt > 0 && (ctx->prealloc_mask_opt == nullptr || ctx->prealloc_mask_opt->size < ctx->prealloc_size_mask_opt)) { + VK_LOG_MEMORY("ggml_vk_preallocate_buffers(mask_opt_size: " << ctx->prealloc_size_mask_opt << ")"); + if (ctx->prealloc_mask_opt != nullptr) { + ggml_vk_destroy_buffer(ctx->prealloc_mask_opt); + } + ctx->prealloc_mask_opt = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_mask_opt); + ctx->last_mask_opt_valid = false; + ctx->prealloc_mask_opt_need_sync = false; + } } bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool last_node, bool almost_ready, bool submit){ @@ -13447,18 +17679,27 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in ggml_tensor * src2 = node->src[2]; ggml_tensor * src3 = node->src[3]; - if (node->op == GGML_OP_ADD) { + if (node->op == GGML_OP_ADD && ctx->s10_add_rms_dst == nullptr) { int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops; if (next_node_idx < cgraph->n_nodes && cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM && cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] && cgraph->nodes[next_node_idx]->type == GGML_TYPE_F32 && node->type == GGML_TYPE_F32 && - ggml_nrows(cgraph->nodes[next_node_idx]) == 1 && + (ggml_nrows(cgraph->nodes[next_node_idx]) == 1 || + (gen_batch_invariant() && ggml_nrows(cgraph->nodes[next_node_idx]) <= 64 && + ggml_is_contiguous(cgraph->nodes[node_idx]) && ggml_is_contiguous(cgraph->nodes[next_node_idx]) && + cgraph->nodes[node_idx]->ne[0] % ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0] == 0)) && ctx->device->add_rms_fusion && !ctx->device->disable_fusion) { uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]); ctx->do_add_rms_partials_offset_calculation = true; - if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) { + // gen: in batch-invariant mode the same ADD+RMS pairs fuse as for one row (budget counted per row, as at + // n=1), the real buffer holds every row's partials + const bool fits = gen_batch_invariant() ? + ctx->gen_n1_partials_offset + size <= 1024 && + ctx->prealloc_size_add_rms_partials_offset + gen_rms_partials_size_rows(ctx, cgraph->nodes[node_idx]) <= ctx->prealloc_size_add_rms_partials : + ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials; + if (fits) { ctx->do_add_rms_partials = true; ggml_vk_count_fusion(ctx->device, "ADD_RMS_NORM_PARTIALS"); } @@ -13485,7 +17726,7 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in return false; } auto n_base = vk_tensor_offset(node) + node->view_offs; - auto n_size = ggml_nbytes(node); + auto n_size = std::max(ggml_nbytes(node), ggml_vk_tensor_byte_span(node)); ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context; vk_buffer a_buf = a_buf_ctx->dev_buffer; for (auto &other : unsynced_nodes) { @@ -13493,7 +17734,7 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in vk_buffer o_buf = o_buf_ctx->dev_buffer; if (a_buf == o_buf) { auto o_base = vk_tensor_offset(other) + other->view_offs; - auto o_size = ggml_nbytes(other); + auto o_size = std::max(ggml_nbytes(other), ggml_vk_tensor_byte_span(other)); if ((o_base <= n_base && n_base < o_base + o_size) || (n_base <= o_base && o_base < n_base + n_size)) { @@ -13504,6 +17745,24 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in return false; }; + auto is_intra_elided = [&](const ggml_tensor * t, int32_t limit_i) -> bool { + const ggml_tensor * base = t; + while (base && base->view_src != nullptr) { + base = base->view_src; + } + if (!base || base->op == GGML_OP_NONE) { + return false; + } + for (int32_t m = 0; m < limit_i; ++m) { + if ((ctx->fused_ops_write_mask & (1 << m)) == 0 && + cgraph->nodes[node_idx + m] == base && + base->view_src == nullptr) { + return true; + } + } + return false; + }; + // For all fused ops, check if the destination node or any of the source // nodes require synchronization. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) { @@ -13516,10 +17775,39 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in } } for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) { - if (!cur_node->src[j]) { + if (!cur_node->src[j] || is_intra_elided(cur_node->src[j], i) || + ((ctx->s10_ssm_conv_mode == 3 || (ctx->s10_ssm_zero_state && ctx->s10_ssm_conv_mode == 1)) && i == 0 && j == 0) || + (ctx->gen_gdn_zero_state && cur_node->op == GGML_OP_GATED_DELTA_NET && i == 0 && j == 5)) { continue; } - if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) { + if (cur_node->op == GGML_OP_INKLING_FUSED && ggml_get_op_params_i32(cur_node, 0) == 1 && + (j == 4 || (j == 1 && cur_node->src[6] != nullptr))) { + if (overlaps_unsynced(cur_node->src[4], ctx->unsynced_nodes_read)) { + need_sync = true; + break; + } + bool non_conv_w = false; + for (const ggml_tensor * wt : ctx->unsynced_nodes_written) { + if (wt != cur_node->src[4] && overlaps_unsynced(cur_node->src[4], { wt })) { + non_conv_w = true; + break; + } + } + if (non_conv_w) { + need_sync = true; + break; + } + continue; + } + if (cur_node->op == GGML_OP_INKLING_FUSED && ggml_get_op_params_i32(cur_node, 0) == 10 && j == 7) { + if (overlaps_unsynced(cur_node->src[7], ctx->unsynced_nodes_read) || + overlaps_unsynced(cur_node->src[7], ctx->unsynced_nodes_written)) { + need_sync = true; + break; + } + continue; + } + if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) { need_sync = true; break; } @@ -13546,9 +17834,31 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list. if (ctx->fused_ops_write_mask & (1 << i)) { ctx->unsynced_nodes_written.push_back(cur_node); + for (uint32_t s = 0; s < ctx->prealloc_y_ring_count; ++s) { + const ggml_tensor * cy = ctx->prealloc_y_last_tensor_ring[s]; + if (cy && cy->buffer == cur_node->buffer && ggml_vk_tensors_overlap(cur_node, cy, false)) { + ctx->prealloc_y_last_tensor_ring[s] = nullptr; + ctx->prealloc_y_last_pipeline_ring[s] = nullptr; + } + } + if (ctx->last_expert_count_valid && ctx->last_expert_ids_tensor && + ctx->last_expert_ids_tensor->buffer == cur_node->buffer && + ggml_vk_tensors_overlap(cur_node, ctx->last_expert_ids_tensor, false)) { + ctx->last_expert_count_valid = false; + } + if (ctx->last_mask_opt_valid && ctx->last_mask_opt_tensor && + ctx->last_mask_opt_tensor->buffer == cur_node->buffer && + ggml_vk_tensors_overlap(cur_node, ctx->last_mask_opt_tensor, false)) { + ctx->last_mask_opt_valid = false; + } } for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) { - if (!cur_node->src[j]) { + if (!cur_node->src[j] || is_intra_elided(cur_node->src[j], i) || + ((ctx->s10_ssm_conv_mode == 3 || (ctx->s10_ssm_zero_state && ctx->s10_ssm_conv_mode == 1)) && i == 0 && j == 0) || + (ctx->gen_gdn_zero_state && cur_node->op == GGML_OP_GATED_DELTA_NET && i == 0 && j == 5) || + (cur_node->op == GGML_OP_INKLING_FUSED && ggml_get_op_params_i32(cur_node, 0) == 1 && + (j == 4 || (j == 1 && cur_node->src[6] != nullptr))) || + (cur_node->op == GGML_OP_INKLING_FUSED && ggml_get_op_params_i32(cur_node, 0) == 10 && j == 7)) { continue; } ctx->unsynced_nodes_read.push_back(cur_node->src[j]); @@ -13600,7 +17910,15 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in break; case GGML_OP_ADD: - if (ctx->num_additional_fused_ops) { + if (ctx->fused_add_softcap_argmax) { + ggml_tensor * sc0 = cgraph->nodes[node_idx + 1]; + ggml_tensor * sc1 = cgraph->nodes[node_idx + 3]; + ggml_tensor * argmax = cgraph->nodes[node_idx + 4]; + ggml_vk_argmax_ex(ctx, compute_ctx, src0, argmax, + ggml_get_op_params_f32(sc0, 0), ggml_get_op_params_f32(sc1, 0), src1); + } else if (ctx->s10_add_rms_dst != nullptr) { + ggml_vk_multi_add_rms_mul(ctx, compute_ctx, cgraph, node_idx); + } else if (ctx->num_additional_fused_ops) { ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx); } else { ggml_vk_add(ctx, compute_ctx, src0, src1, node); @@ -13630,7 +17948,11 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in break; case GGML_OP_CONCAT: - ggml_vk_concat(ctx, compute_ctx, src0, src1, node); + if (ctx->s10_ssm_conv_mode == 1) { + ggml_vk_ssm_conv(ctx, compute_ctx, cgraph, node_idx); + } else { + ggml_vk_concat(ctx, compute_ctx, src0, src1, node); + } break; case GGML_OP_UPSCALE: @@ -13653,6 +17975,11 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in if (ctx->fused_hc_post_gate) { ggml_tensor * hc_post = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; ggml_vk_dsv4_hc_post(ctx, compute_ctx, hc_post->src[0], hc_post->src[1], hc_post->src[2], hc_post->src[3], hc_post, node); + } else if (ctx->fused_softcap_argmax) { + ggml_tensor * sc1 = cgraph->nodes[node_idx + 2]; + ggml_tensor * argmax = cgraph->nodes[node_idx + 3]; + ggml_vk_argmax_ex(ctx, compute_ctx, src0, argmax, + ggml_get_op_params_f32(node, 0), ggml_get_op_params_f32(sc1, 0)); } else { ggml_vk_scale(ctx, compute_ctx, src0, node); } @@ -13702,10 +18029,21 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in ggml_vk_roll(ctx, compute_ctx, src0, node); break; - case GGML_OP_CPY: case GGML_OP_CONT: - case GGML_OP_DUP: + if (ctx->num_additional_fused_ops >= 2 && + cgraph->nodes[node_idx + ctx->num_additional_fused_ops]->op == GGML_OP_MUL) { + ggml_vk_cont_unary_mul(ctx, compute_ctx, cgraph, node_idx); + break; + } ggml_vk_cpy(ctx, compute_ctx, src0, node); + break; + case GGML_OP_CPY: + case GGML_OP_DUP: + if (node->op == GGML_OP_CPY && ctx->s10_ssm_conv_mode == 2) { + ggml_vk_ssm_conv(ctx, compute_ctx, cgraph, node_idx); + } else { + ggml_vk_cpy(ctx, compute_ctx, src0, node); + } break; case GGML_OP_SET_ROWS: @@ -13785,6 +18123,7 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in case GGML_GLU_OP_GEGLU_ERF: case GGML_GLU_OP_GEGLU_QUICK: case GGML_GLU_OP_SWIGLU_CLAMP: + case GGML_GLU_OP_SITU: ggml_vk_glu(ctx, compute_ctx, src0, src1, node); break; default: @@ -13834,6 +18173,10 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in case GGML_OP_CUMSUM: ggml_vk_cumsum(ctx, compute_ctx, src0, node); + break; + case GGML_OP_INKLING_FUSED: + ggml_vk_inkling_fused(ctx, compute_ctx, node, cgraph, node_idx); + break; case GGML_OP_DSV4_HC_COMB: ggml_vk_dsv4_hc_comb(ctx, compute_ctx, src0, src1, src2, node); @@ -13994,7 +18337,7 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in last_node = true; #endif - if (submit || last_node) { + if ((submit || last_node) && !ctx->recording_replay) { ggml_vk_ctx_end(compute_ctx); // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward @@ -14035,11 +18378,19 @@ void ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph memset(mset.dst, mset.val, mset.n); } + ggml_vk_ensure_fence_free(ctx); + const bool is_exit = (tensor_idx == subctx->exit_tensor_idx); + const bool need_transfer_sem = ctx->device->async_use_transfer_queue && + ctx->transfer_semaphore_last_submitted < ctx->transfer_semaphore.value; if (ctx->device->serialize_submissions) { ggml_vk_submit(subctx, ctx->fence); } else if (almost_ready && !ctx->almost_ready_fence_pending) { ggml_vk_submit(subctx, ctx->almost_ready_fence); ctx->almost_ready_fence_pending = true; + } else if (is_exit && !need_transfer_sem && subctx->out_memcpys.empty()) { + ctx->last_submit_us = ggml_time_us(); + ggml_vk_submit(subctx, ctx->fence); + ctx->fence_submitted = true; } else { ggml_vk_submit(subctx, {}); } @@ -14062,15 +18413,40 @@ void ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph } } +static void ggml_vk_destroy_replay_entry(vk_device & device, vk_graph_replay_entry & e) { + for (auto & pool : e.descriptor_pools) { + device->device.destroyDescriptorPool(pool); + } + e.descriptor_pools.clear(); + e.descriptor_sets.clear(); + e.descriptor_set_bindings.clear(); + if (e.cmd_pool.pool) { + e.cmd_pool.destroy(device->device); + } + e.cmd_bufs.clear(); + e.memsets.clear(); + e.sig_words.clear(); + e.ready = false; +} + void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) { VK_LOG_DEBUG("ggml_vk_graph_cleanup()"); - ctx->prealloc_y_last_pipeline_used = {}; - ctx->prealloc_y_last_tensor_used = nullptr; - ctx->prealloc_y_last_k_padded = false; + ggml_vk_invalidate_prealloc_y_ring(ctx); + ctx->prealloc_y_ring_idx = 0; + ctx->prealloc_split_k_ring_idx = 0; + ctx->last_expert_count_valid = false; + ctx->last_expert_ids_tensor = nullptr; + ctx->last_mask_opt_valid = false; + ctx->last_mask_opt_tensor = nullptr; ctx->unsynced_nodes_written.clear(); ctx->unsynced_nodes_read.clear(); ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false; + ctx->prealloc_mask_opt_need_sync = false; + for (uint32_t s = 0; s < VK_PREALLOC_RING; ++s) { + ctx->prealloc_y_slot_need_sync[s] = false; + ctx->prealloc_split_k_slot_need_sync[s] = false; + } ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool); if (ctx->device->async_use_transfer_queue) { @@ -14107,6 +18483,10 @@ void ggml_vk_cleanup(ggml_backend_vk_context * ctx) { ctx->compute_ctx.reset(); // wait for any pending command buffers to finish ggml_vk_synchronize(ctx); + if (ctx->alive_token) { + *ctx->alive_token = false; + ctx->alive_token.reset(); + } ggml_vk_graph_cleanup(ctx); @@ -14114,6 +18494,7 @@ void ggml_vk_cleanup(ggml_backend_vk_context * ctx) { ggml_vk_destroy_buffer(ctx->prealloc_y); ggml_vk_destroy_buffer(ctx->prealloc_split_k); ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials); + ggml_vk_destroy_buffer(ctx->prealloc_mask_opt); ggml_vk_destroy_buffer(ctx->sync_staging); ctx->prealloc_y_last_pipeline_used = nullptr; @@ -14123,6 +18504,7 @@ void ggml_vk_cleanup(ggml_backend_vk_context * ctx) { ctx->prealloc_size_x = 0; ctx->prealloc_size_y = 0; ctx->prealloc_size_split_k = 0; + ctx->prealloc_size_mask_opt = 0; for (auto& event : ctx->gc.events) { ctx->device->device.destroyEvent(event); @@ -14137,6 +18519,11 @@ void ggml_vk_cleanup(ggml_backend_vk_context * ctx) { ctx->device->device.destroyFence(ctx->fence); ctx->device->device.destroyFence(ctx->almost_ready_fence); + for (auto & re : ctx->replay_cache) { + ggml_vk_destroy_replay_entry(ctx->device, re); + } + ctx->replay_cache.clear(); + for (auto& pool : ctx->descriptor_pools) { ctx->device->device.destroyDescriptorPool(pool); } @@ -14173,7 +18560,8 @@ void ggml_vk_get_device_description(int device, char * description, size_t descr } bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) { - return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name; + return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name || + buffer->buft->iface.get_name == ggml_backend_vk_repack_buffer_type_name; } void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) { @@ -14269,7 +18657,7 @@ bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_ return true; } - if (ggml_backend_buffer_is_vk(src->buffer)) { + if (ggml_backend_buffer_is_vk(src->buffer) && !ggml_vk_tensor_is_repack(src)) { ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context; ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; @@ -14317,7 +18705,8 @@ void ggml_backend_vk_buffer_get_tensor_n(ggml_backend_buffer_t buffer, const ggm bool ggml_backend_vk_buffer_cpy_tensor_n(ggml_backend_buffer_t buffer, const ggml_tensor * const * srcs, ggml_tensor * const * dsts, size_t n_tensors) { VK_LOG_DEBUG("ggml_backend_vk_buffer_cpy_tensor_n(" << buffer << ", " << n_tensors << ")"); for (size_t i = 0; i < n_tensors; i++) { - if (!ggml_backend_buffer_is_vk(srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer)) { + ggml_backend_buffer_t sbuf = srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer; + if (!ggml_backend_buffer_is_vk(sbuf) || ggml_vk_tensor_is_repack(srcs[i])) { return false; } } @@ -14379,6 +18768,470 @@ size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buf UNUSED(buft); } +static inline uint16_t ggml_vk_load_u16(const uint8_t * p) { + uint16_t v; + memcpy(&v, p, sizeof(v)); + return v; +} + +static inline void ggml_vk_store_u16(uint8_t * p, uint16_t v) { + memcpy(p, &v, sizeof(v)); +} + +static inline uint32_t ggml_vk_load_u32(const uint8_t * p) { + uint32_t v; + memcpy(&v, p, sizeof(v)); + return v; +} + +static inline void ggml_vk_store_u32(uint8_t * p, uint32_t v) { + memcpy(p, &v, sizeof(v)); +} + +static void ggml_vk_repack_row_range(ggml_type type, const uint8_t * src_raw, uint8_t * dst_packed, + size_t n_sb, size_t r0, size_t r1) { + const size_t sb_bytes = ggml_vk_repack_sb_bytes(type); + const size_t raw_blk_bytes = ggml_type_size(type); + const size_t row_raw_bytes = n_sb * raw_blk_bytes; + const size_t row_pack_bytes = n_sb * sb_bytes; + + for (size_t r = r0; r < r1; ++r) { + const uint8_t * row_src = src_raw + r * row_raw_bytes; + uint8_t * row_dst = dst_packed + r * row_pack_bytes; + for (size_t sb = 0; sb < n_sb; ++sb) { + const uint8_t * blk = row_src + sb * raw_blk_bytes; + uint32_t * sb_u32 = (uint32_t *)(row_dst + sb * sb_bytes); + if (type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K) { + sb_u32[0] = ggml_vk_load_u32(blk + 0); + sb_u32[1] = ggml_vk_load_u32(blk + 4); + sb_u32[2] = ggml_vk_load_u32(blk + 8); + sb_u32[3] = ggml_vk_load_u32(blk + 12); + const uint8_t * qs_b = blk + (type == GGML_TYPE_Q4_K ? 16 : 48); + for (uint32_t itid8 = 0; itid8 < 8u; ++itid8) { + uint32_t * qs_out = sb_u32 + 4u + itid8 * 4u; + qs_out[0] = ggml_vk_load_u32(qs_b + (itid8 + 0u) * 4u); + qs_out[1] = ggml_vk_load_u32(qs_b + (itid8 + 8u) * 4u); + qs_out[2] = ggml_vk_load_u32(qs_b + (itid8 + 16u) * 4u); + qs_out[3] = ggml_vk_load_u32(qs_b + (itid8 + 24u) * 4u); + } + if (type == GGML_TYPE_Q5_K) { + const uint8_t * qh_b = blk + 16; + for (uint32_t itid8 = 0; itid8 < 8u; ++itid8) { + sb_u32[36u + itid8] = ggml_vk_load_u32(qh_b + itid8 * 4u); + } + } + } else { + // GGML_TYPE_Q6_K: ql[128], qh[64], scales[16] (int8), d (fp16) + const uint8_t * ql_b = blk + 0; + const uint8_t * qh_b = blk + 128; + const uint8_t * sc_b = blk + 192; + sb_u32[0] = ggml_vk_load_u32(sc_b + 0); + sb_u32[1] = ggml_vk_load_u32(sc_b + 4); + sb_u32[2] = ggml_vk_load_u32(sc_b + 8); + sb_u32[3] = ggml_vk_load_u32(sc_b + 12); + sb_u32[4] = (uint32_t)ggml_vk_load_u16(blk + 208); + sb_u32[5] = 0u; + sb_u32[6] = 0u; + sb_u32[7] = 0u; + for (uint32_t itid8 = 0; itid8 < 8u; ++itid8) { + uint32_t * ql_out = sb_u32 + 8u + itid8 * 4u; + ql_out[0] = ggml_vk_load_u32(ql_b + (itid8 + 0u) * 4u); + ql_out[1] = ggml_vk_load_u32(ql_b + (itid8 + 8u) * 4u); + ql_out[2] = ggml_vk_load_u32(ql_b + (itid8 + 16u) * 4u); + ql_out[3] = ggml_vk_load_u32(ql_b + (itid8 + 24u) * 4u); + uint32_t * qh_out = sb_u32 + 40u + itid8 * 2u; + qh_out[0] = ggml_vk_load_u32(qh_b + (itid8 + 0u) * 4u); + qh_out[1] = ggml_vk_load_u32(qh_b + (itid8 + 8u) * 4u); + } + } + } + } +} + +static void ggml_vk_unpack_row_range(ggml_type type, const uint8_t * src_packed, uint8_t * dst_raw, + size_t n_sb, size_t r0, size_t r1) { + const size_t sb_bytes = ggml_vk_repack_sb_bytes(type); + const size_t raw_blk_bytes = ggml_type_size(type); + const size_t row_raw_bytes = n_sb * raw_blk_bytes; + const size_t row_pack_bytes = n_sb * sb_bytes; + + for (size_t r = r0; r < r1; ++r) { + const uint8_t * row_src = src_packed + r * row_pack_bytes; + uint8_t * row_dst = dst_raw + r * row_raw_bytes; + for (size_t sb = 0; sb < n_sb; ++sb) { + const uint32_t * sb_u32 = (const uint32_t *)(row_src + sb * sb_bytes); + uint8_t * blk = row_dst + sb * raw_blk_bytes; + if (type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K) { + ggml_vk_store_u32(blk + 0, sb_u32[0]); + ggml_vk_store_u32(blk + 4, sb_u32[1]); + ggml_vk_store_u32(blk + 8, sb_u32[2]); + ggml_vk_store_u32(blk + 12, sb_u32[3]); + uint8_t * qs_b = blk + (type == GGML_TYPE_Q4_K ? 16 : 48); + for (uint32_t itid8 = 0; itid8 < 8u; ++itid8) { + const uint32_t * qs_in = sb_u32 + 4u + itid8 * 4u; + ggml_vk_store_u32(qs_b + (itid8 + 0u) * 4u, qs_in[0]); + ggml_vk_store_u32(qs_b + (itid8 + 8u) * 4u, qs_in[1]); + ggml_vk_store_u32(qs_b + (itid8 + 16u) * 4u, qs_in[2]); + ggml_vk_store_u32(qs_b + (itid8 + 24u) * 4u, qs_in[3]); + } + if (type == GGML_TYPE_Q5_K) { + uint8_t * qh_b = blk + 16; + for (uint32_t itid8 = 0; itid8 < 8u; ++itid8) { + ggml_vk_store_u32(qh_b + itid8 * 4u, sb_u32[36u + itid8]); + } + } + } else { + uint8_t * ql_b = blk + 0; + uint8_t * qh_b = blk + 128; + uint8_t * sc_b = blk + 192; + ggml_vk_store_u32(sc_b + 0, sb_u32[0]); + ggml_vk_store_u32(sc_b + 4, sb_u32[1]); + ggml_vk_store_u32(sc_b + 8, sb_u32[2]); + ggml_vk_store_u32(sc_b + 12, sb_u32[3]); + ggml_vk_store_u16(blk + 208, (uint16_t)(sb_u32[4] & 0xFFFFu)); + for (uint32_t itid8 = 0; itid8 < 8u; ++itid8) { + const uint32_t * ql_in = sb_u32 + 8u + itid8 * 4u; + ggml_vk_store_u32(ql_b + (itid8 + 0u) * 4u, ql_in[0]); + ggml_vk_store_u32(ql_b + (itid8 + 8u) * 4u, ql_in[1]); + ggml_vk_store_u32(ql_b + (itid8 + 16u) * 4u, ql_in[2]); + ggml_vk_store_u32(ql_b + (itid8 + 24u) * 4u, ql_in[3]); + const uint32_t * qh_in = sb_u32 + 40u + itid8 * 2u; + ggml_vk_store_u32(qh_b + (itid8 + 0u) * 4u, qh_in[0]); + ggml_vk_store_u32(qh_b + (itid8 + 8u) * 4u, qh_in[1]); + } + } + } + } +} + +struct vk_repack_thread_pool { + std::mutex mtx; + std::mutex run_mtx; + std::condition_variable cv_work; + std::condition_variable cv_done; + std::vector workers; + const std::function * cur_fn = nullptr; + uint32_t cur_n_threads = 0; + uint32_t pending = 0; + uint64_t epoch = 0; + bool stop = false; + + vk_repack_thread_pool() { + const uint32_t hw = std::max(1u, std::thread::hardware_concurrency()); + workers.reserve(hw > 1u ? hw - 1u : 0u); + for (uint32_t w = 0; w + 1u < hw; ++w) { + const uint32_t tid = w; + workers.emplace_back([this, tid]() { + uint64_t my_epoch = 0; + while (true) { + std::unique_lock lk(mtx); + cv_work.wait(lk, [this, &my_epoch]() { return stop || epoch != my_epoch; }); + if (stop) { + return; + } + my_epoch = epoch; + const std::function * fn = cur_fn; + const uint32_t nt = cur_n_threads; + lk.unlock(); + if (tid + 1u < nt) { + (*fn)(tid, nt); + } + lk.lock(); + if (--pending == 0) { + cv_done.notify_one(); + } + } + }); + } + } + + ~vk_repack_thread_pool() { + { + std::lock_guard lk(mtx); + stop = true; + } + cv_work.notify_all(); + for (auto & th : workers) { + if (th.joinable()) { + th.join(); + } + } + } + + void run(uint32_t n_threads, const std::function & fn) { + std::lock_guard rlk(run_mtx); + const uint32_t max_threads = (uint32_t)workers.size() + 1u; + const uint32_t nt = std::min(n_threads, max_threads); + if (nt <= 1u || workers.empty()) { + fn(0u, 1u); + return; + } + { + std::lock_guard lk(mtx); + cur_fn = &fn; + cur_n_threads = nt; + pending = (uint32_t)workers.size(); + ++epoch; + } + cv_work.notify_all(); + fn(nt - 1u, nt); + std::unique_lock lk(mtx); + cv_done.wait(lk, [this]() { return pending == 0; }); + } +}; + +static vk_repack_thread_pool & ggml_vk_get_repack_pool() { + static vk_repack_thread_pool pool; + return pool; +} + +static void ggml_vk_repack_run_rows(bool pack, ggml_type type, const uint8_t * src, uint8_t * dst, + size_t n_sb, size_t r0, size_t r1, size_t work_bytes) { + const size_t n_rows = r1 - r0; + if (n_rows == 0) { + return; + } + const uint32_t hw = std::max(1u, std::thread::hardware_concurrency()); + const uint32_t n_threads = (n_rows >= 64u && work_bytes >= 262144u) ? std::min((uint32_t)n_rows, hw) : 1u; + if (n_threads <= 1u) { + if (pack) { + ggml_vk_repack_row_range(type, src, dst, n_sb, r0, r1); + } else { + ggml_vk_unpack_row_range(type, src, dst, n_sb, r0, r1); + } + return; + } + ggml_vk_get_repack_pool().run(n_threads, [&](uint32_t tid, uint32_t nt) { + const size_t a = r0 + (n_rows * tid) / nt; + const size_t b = r0 + (n_rows * (tid + 1u)) / nt; + if (pack) { + ggml_vk_repack_row_range(type, src, dst, n_sb, a, b); + } else { + ggml_vk_unpack_row_range(type, src, dst, n_sb, a, b); + } + }); +} + +static inline size_t ggml_vk_nvfp4_planar_byte_idx(size_t raw_pos, size_t s_blks) { + const size_t ib = raw_pos / 36u; + const size_t rem = raw_pos - ib * 36u; + const size_t e = ib / s_blks; + const size_t b = ib - e * s_blks; + return e * (s_blks * 36u) + ((rem < 4u) ? (s_blks * 32u + b * 4u + rem) : (b * 32u + (rem - 4u))); +} + +static void ggml_vk_nvfp4_repack_range(bool pack, const uint8_t * raw_or_packed, uint8_t * dst_or_raw, + size_t s_blks, size_t offset, size_t size) { + if (size == 0) { + return; + } + const size_t end_pos = offset + size; + size_t cur = offset; + while (cur < end_pos && (cur % 36u) != 0u) { + const size_t p_idx = ggml_vk_nvfp4_planar_byte_idx(cur, s_blks); + if (pack) { + dst_or_raw[p_idx] = raw_or_packed[cur - offset]; + } else { + dst_or_raw[cur - offset] = raw_or_packed[p_idx]; + } + ++cur; + } + const size_t blk0 = cur / 36u; + const size_t blk1 = end_pos / 36u; + if (blk1 > blk0) { + const size_t n_blks = blk1 - blk0; + const uint32_t hw = std::max(1u, std::thread::hardware_concurrency()); + const uint32_t n_threads = (n_blks >= 4096u) ? std::min((uint32_t)(n_blks / 1024u), hw) : 1u; + auto body = [&](size_t b_start, size_t b_end) { + size_t e = b_start / s_blks; + size_t b = b_start - e * s_blks; + for (size_t ib = b_start; ib < b_end; ++ib) { + const size_t raw_off = ib * 36u - offset; + const size_t slice_off = e * (s_blks * 36u); + if (pack) { + const uint8_t * s = raw_or_packed + raw_off; + memcpy(dst_or_raw + slice_off + s_blks * 32u + b * 4u, s, 4u); + memcpy(dst_or_raw + slice_off + b * 32u, s + 4u, 32u); + } else { + uint8_t * d = dst_or_raw + raw_off; + memcpy(d, raw_or_packed + slice_off + s_blks * 32u + b * 4u, 4u); + memcpy(d + 4u, raw_or_packed + slice_off + b * 32u, 32u); + } + if (++b == s_blks) { + b = 0u; + ++e; + } + } + }; + if (n_threads <= 1u) { + body(blk0, blk1); + } else { + ggml_vk_get_repack_pool().run(n_threads, [&](uint32_t tid, uint32_t nt) { + const size_t a = blk0 + (n_blks * tid) / nt; + const size_t b = blk0 + (n_blks * (tid + 1u)) / nt; + body(a, b); + }); + } + cur = blk1 * 36u; + } + while (cur < end_pos) { + const size_t p_idx = ggml_vk_nvfp4_planar_byte_idx(cur, s_blks); + if (pack) { + dst_or_raw[p_idx] = raw_or_packed[cur - offset]; + } else { + dst_or_raw[cur - offset] = raw_or_packed[p_idx]; + } + ++cur; + } +} + +static void ggml_backend_vk_repack_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { + if (size == 0) { + return; + } + ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context; + vk_buffer buf = buf_ctx->dev_buffer; + const size_t raw_bytes = ggml_nbytes(tensor); + const size_t pack_bytes = ggml_vk_repack_alloc_bytes(tensor); + const size_t dev_offs = vk_tensor_offset(tensor) + tensor->view_offs; + if (tensor->type == GGML_TYPE_NVFP4) { + GGML_ASSERT(pack_bytes == raw_bytes && pack_bytes > 0); + const size_t s_blks = ((size_t)tensor->ne[0] / 64u) * (size_t)tensor->ne[1]; + if (buf->ptr != nullptr) { + ggml_vk_nvfp4_repack_range(false, (const uint8_t *)buf->ptr + dev_offs, (uint8_t *)data, s_blks, offset, size); + } else { + std::vector packed_tmp(pack_bytes); + ggml_vk_buffer_read(buf, dev_offs, packed_tmp.data(), pack_bytes); + ggml_vk_nvfp4_repack_range(false, packed_tmp.data(), (uint8_t *)data, s_blks, offset, size); + } + return; + } + GGML_ASSERT(pack_bytes > 0 && tensor->ne[0] % 256 == 0); + const size_t n_sb = (size_t)tensor->ne[0] / 256u; + const size_t n_rows = (size_t)tensor->ne[1] * (size_t)tensor->ne[2] * (size_t)tensor->ne[3]; + const size_t row_raw_bytes = n_sb * ggml_type_size(tensor->type); + + std::vector packed_tmp; + const uint8_t * packed_ptr = nullptr; + if (buf->ptr != nullptr) { + packed_ptr = (const uint8_t *)buf->ptr + dev_offs; + } else { + packed_tmp.resize(pack_bytes); + ggml_vk_buffer_read(buf, dev_offs, packed_tmp.data(), pack_bytes); + packed_ptr = packed_tmp.data(); + } + + if (offset == 0 && size == raw_bytes) { + ggml_vk_repack_run_rows(false, tensor->type, packed_ptr, (uint8_t *)data, n_sb, 0, n_rows, pack_bytes); + } else { + const size_t r0 = offset / row_raw_bytes; + const size_t r1 = std::min(n_rows, (offset + size + row_raw_bytes - 1u) / row_raw_bytes); + std::vector raw_sub((r1 - r0) * row_raw_bytes); + ggml_vk_repack_run_rows(false, tensor->type, + packed_ptr + r0 * n_sb * ggml_vk_repack_sb_bytes(tensor->type), + raw_sub.data(), n_sb, 0, r1 - r0, raw_sub.size()); + memcpy(data, raw_sub.data() + (offset - r0 * row_raw_bytes), size); + } +} + +static void ggml_backend_vk_repack_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { + if (size == 0) { + return; + } + ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context; + vk_buffer buf = buf_ctx->dev_buffer; + const size_t raw_bytes = ggml_nbytes(tensor); + const size_t pack_bytes = ggml_vk_repack_alloc_bytes(tensor); + const size_t dev_offs = vk_tensor_offset(tensor) + tensor->view_offs; + if (tensor->type == GGML_TYPE_NVFP4) { + GGML_ASSERT(pack_bytes == raw_bytes && pack_bytes > 0); + const size_t s_blks = ((size_t)tensor->ne[0] / 64u) * (size_t)tensor->ne[1]; + if (buf->ptr != nullptr) { + ggml_vk_nvfp4_repack_range(true, (const uint8_t *)data, (uint8_t *)buf->ptr + dev_offs, s_blks, offset, size); + } else { + std::vector packed(pack_bytes); + if (offset != 0 || size != raw_bytes) { + ggml_vk_buffer_read(buf, dev_offs, packed.data(), pack_bytes); + } + ggml_vk_nvfp4_repack_range(true, (const uint8_t *)data, packed.data(), s_blks, offset, size); + ggml_vk_buffer_write(buf, dev_offs, packed.data(), pack_bytes); + } + return; + } + GGML_ASSERT(pack_bytes > 0 && tensor->ne[0] % 256 == 0); + const size_t n_sb = (size_t)tensor->ne[0] / 256u; + const size_t n_rows = (size_t)tensor->ne[1] * (size_t)tensor->ne[2] * (size_t)tensor->ne[3]; + + const uint8_t * full_src = (const uint8_t *)data; + std::vector full_tmp; + if (offset != 0 || size != raw_bytes) { + full_tmp.resize(raw_bytes); + ggml_backend_vk_repack_buffer_get_tensor(buffer, tensor, full_tmp.data(), 0, raw_bytes); + memcpy(full_tmp.data() + offset, data, size); + full_src = full_tmp.data(); + } + + if (buf->ptr != nullptr) { + uint8_t * dst_ptr = (uint8_t *)buf->ptr + dev_offs; + ggml_vk_repack_run_rows(true, tensor->type, full_src, dst_ptr, n_sb, 0, n_rows, pack_bytes); + } else { + std::vector packed(pack_bytes); + ggml_vk_repack_run_rows(true, tensor->type, full_src, packed.data(), n_sb, 0, n_rows, pack_bytes); + ggml_vk_buffer_write(buf, dev_offs, packed.data(), pack_bytes); + } +} + +static bool ggml_backend_vk_repack_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) { + UNUSED(buffer); + UNUSED(src); + UNUSED(dst); + return false; +} + +static const ggml_backend_buffer_i ggml_backend_vk_repack_buffer_interface = { + /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer, + /* .get_base = */ ggml_backend_vk_buffer_get_base, + /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor, + /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor, + /* .set_tensor = */ ggml_backend_vk_repack_buffer_set_tensor, + /* .get_tensor = */ ggml_backend_vk_repack_buffer_get_tensor, + /* .set_tensor_2d = */ nullptr, + /* .get_tensor_2d = */ nullptr, + /* .cpy_tensor = */ ggml_backend_vk_repack_buffer_cpy_tensor, + /* .clear = */ ggml_backend_vk_buffer_clear, + /* .reset = */ nullptr, + /* .set_tensor_n = */ nullptr, + /* .get_tensor_n = */ nullptr, + /* .cpy_tensor_n = */ nullptr, +}; + +static ggml_backend_buffer_t ggml_backend_vk_repack_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) { + VK_LOG_MEMORY("ggml_backend_vk_repack_buffer_type_alloc_buffer(" << size << ")"); + ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context; + + vk_buffer dev_buffer = nullptr; + try { + dev_buffer = ggml_vk_create_buffer_device(ctx->device, size); + } catch (const vk::SystemError& e) { + return nullptr; + } + + ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name); + + return ggml_backend_buffer_init(buft, ggml_backend_vk_repack_buffer_interface, bufctx, size); +} + +static size_t ggml_backend_vk_repack_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) { + ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context; + return std::max(128u, ctx->device->properties.limits.minStorageBufferOffsetAlignment); +} + +static size_t ggml_backend_vk_repack_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) { + UNUSED(buft); + const size_t sz = ggml_vk_repack_alloc_bytes(tensor); + return sz > 0 ? sz : ggml_nbytes(tensor); +} + ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) { ggml_vk_instance_init(); @@ -14487,7 +19340,27 @@ static void ggml_backend_vk_set_tensor_2d_async(ggml_backend_t backend, ggml_ten return; } + if (!ctx->uma_out_memcpys.empty()) { + ggml_vk_synchronize(ctx); + } + ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context; + vk_buffer buf = buf_ctx->dev_buffer; + auto dst_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset; + + // Series 9: On UMA when the backend is idle (between graph evaluations), write directly into + // coherent unified memory on the CPU instead of allocating sync_staging + submitting a GPU copyBuffer + fence wait. + const bool transfer_idle = !ctx->device->async_use_transfer_queue || + ctx->transfer_semaphore_last_submitted == ctx->transfer_semaphore.value; + const bool backend_idle = ctx->compute_ctx.expired() && ctx->transfer_ctx.expired() && + !ctx->submit_pending && !ctx->fence_submitted && !ctx->almost_ready_fence_pending && transfer_idle; + const bool dst_host_coherent = + (buf->memory_property_flags & (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent)) == + (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); + if (ctx->device->uma && backend_idle && dst_host_coherent && buf->ptr != nullptr) { + ggml_vk_buffer_write_2d(buf, dst_offset, data, stride_data, stride_tensor, size, n_copies); + return; + } vk_context cpy_ctx; @@ -14497,10 +19370,6 @@ static void ggml_backend_vk_set_tensor_2d_async(ggml_backend_t backend, ggml_ten cpy_ctx = ggml_vk_get_compute_ctx(ctx); } - vk_buffer buf = buf_ctx->dev_buffer; - - auto dst_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset; - bool ret = ggml_vk_buffer_write_2d_async(cpy_ctx, buf, dst_offset, data, stride_data, stride_tensor, size, n_copies); if (!ret) { @@ -14537,6 +19406,12 @@ static void ggml_backend_vk_set_tensor_2d_async(ggml_backend_t backend, ggml_ten static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")"); + if (ggml_vk_tensor_is_repack(tensor)) { + ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; + ggml_vk_synchronize(ctx); + tensor->buffer->iface.set_tensor(tensor->buffer, tensor, data, offset, size); + return; + } ggml_backend_vk_set_tensor_2d_async(backend, tensor, data, offset, size, 1, size, size); } @@ -14551,12 +19426,27 @@ static void ggml_backend_vk_get_tensor_2d_async(ggml_backend_t backend, const gg } ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context; - - vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); - vk_buffer buf = buf_ctx->dev_buffer; - auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset; + + // Series 9: On cached coherent UMA (Apple Silicon), defer the host memcpy until after ctx->fence + // signals in ggml_vk_synchronize instead of recording/submitting an extra GPU copyBuffer + fence round-trip. + const auto cached_coherent = vk::MemoryPropertyFlagBits::eHostVisible | + vk::MemoryPropertyFlagBits::eHostCoherent | + vk::MemoryPropertyFlagBits::eHostCached; + if (ctx->device->uma && buf->ptr != nullptr && (buf->memory_property_flags & cached_coherent) == cached_coherent) { + const uint8_t * base_src = (const uint8_t *) buf->ptr + src_offset; + if (size == stride_tensor && size == stride_data) { + deferred_memcpy(data, base_src, size * n_copies, &ctx->uma_out_memcpys); + } else { + for (size_t i = 0; i < n_copies; ++i) { + deferred_memcpy((uint8_t *) data + i * stride_data, base_src + i * stride_tensor, size, &ctx->uma_out_memcpys); + } + } + return; + } + + vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); bool ret = ggml_vk_buffer_read_2d_async(compute_ctx, buf, src_offset, data, stride_tensor, stride_data, size, n_copies); if (!ret) { @@ -14591,8 +19481,36 @@ static void ggml_backend_vk_get_tensor_2d_async(ggml_backend_t backend, const gg } } +const void * ggml_backend_vk_get_cached_uma_ptr(ggml_backend_t backend, const ggml_tensor * tensor) { + if (!backend || !tensor || !ggml_backend_is_vk(backend) || ggml_vk_tensor_is_repack(tensor)) { + return nullptr; + } + ggml_backend_vk_context * ctx = (ggml_backend_vk_context *) backend->context; + if (!ctx || !ctx->device || !ctx->device->uma) { + return nullptr; + } + ggml_backend_buffer_t b = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; + if (!b || !ggml_backend_buffer_is_vk(b)) { + return nullptr; + } + vk_buffer buf = ((ggml_backend_vk_buffer_context *) b->context)->dev_buffer; + const auto cached_coherent = vk::MemoryPropertyFlagBits::eHostVisible | + vk::MemoryPropertyFlagBits::eHostCoherent | + vk::MemoryPropertyFlagBits::eHostCached; + if (!buf || buf->ptr == nullptr || (buf->memory_property_flags & cached_coherent) != cached_coherent) { + return nullptr; + } + return (const uint8_t *) buf->ptr + vk_tensor_offset(tensor) + tensor->view_offs; +} + static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")"); + if (ggml_vk_tensor_is_repack(tensor)) { + ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; + ggml_vk_synchronize(ctx); + tensor->buffer->iface.get_tensor(tensor->buffer, tensor, data, offset, size); + return; + } ggml_backend_vk_get_tensor_2d_async(backend, tensor, data, offset, size, 1, size, size); } @@ -14605,6 +19523,10 @@ static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend_src, ggml_ba return true; } + if (!ctx->uma_out_memcpys.empty()) { + ggml_vk_synchronize(ctx); + } + if (dst->buffer->buft != ggml_backend_vk_get_default_buffer_type(backend_dst)) { return false; } @@ -14612,18 +19534,51 @@ static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend_src, ggml_ba ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; vk_buffer dst_buf = dst_buf_ctx->dev_buffer; - if (ggml_backend_buffer_is_vk(src->buffer)) { + auto is_vk_ctx_completely_idle = [](const ggml_backend_vk_context * c) -> bool { + if (!c) { + return false; + } + const bool t_idle = !c->device->async_use_transfer_queue || + c->transfer_semaphore_last_submitted == c->transfer_semaphore.value; + return c->compute_ctx.expired() && c->transfer_ctx.expired() && + !c->submit_pending && !c->fence_submitted && !c->almost_ready_fence_pending && + c->uma_out_memcpys.empty() && t_idle; + }; + + if (ggml_backend_buffer_is_vk(src->buffer) && !ggml_vk_tensor_is_repack(src) && !ggml_vk_tensor_is_repack(dst)) { ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context; + vk_buffer src_buf = src_buf_ctx->dev_buffer; // Async copy only works within the same device - if (src_buf_ctx->dev_buffer->device != dst_buf->device) { + if (src_buf->device != dst_buf->device) { return false; } + // Series 20 (Blocker 5 + X-4): On idle UMA contexts (e.g. DSpark ctx_tgt -> ctx_dft t_layer_inp), + // copy cached-coherent UMA directly on CPU so ctx_dft->compute_ctx stays expired for graph replay. + const auto cached_coherent = vk::MemoryPropertyFlagBits::eHostVisible | + vk::MemoryPropertyFlagBits::eHostCoherent | + vk::MemoryPropertyFlagBits::eHostCached; + const auto host_coherent = vk::MemoryPropertyFlagBits::eHostVisible | + vk::MemoryPropertyFlagBits::eHostCoherent; + const bool both_ctx_idle = is_vk_ctx_completely_idle(ctx) && + (backend_src == backend_dst || + (ggml_backend_is_vk(backend_src) && + is_vk_ctx_completely_idle((const ggml_backend_vk_context *) backend_src->context))); + if (ctx->device->uma && both_ctx_idle && ggml_nbytes(src) <= 4 * 1024 * 1024 && + src_buf->ptr != nullptr && dst_buf->ptr != nullptr && + (src_buf->memory_property_flags & cached_coherent) == cached_coherent && + (dst_buf->memory_property_flags & host_coherent) == host_coherent) { + const uint8_t * sp = (const uint8_t *) src_buf->ptr + vk_tensor_offset(src) + src->view_offs; + uint8_t * dp = (uint8_t *) dst_buf->ptr + vk_tensor_offset(dst) + dst->view_offs; + memcpy(dp, sp, ggml_nbytes(src)); + return true; + } + vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); ggml_vk_buffer_copy_async(compute_ctx, dst_buf, vk_tensor_offset(dst) + dst->view_offs, - src_buf_ctx->dev_buffer, vk_tensor_offset(src) + src->view_offs, + src_buf, vk_tensor_offset(src) + src->view_offs, ggml_nbytes(src)); return true; } @@ -14636,13 +19591,10 @@ static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend_src, ggml_ba return false; } - // If the backend is idle, use a CPU copy to avoid GPU synchronization overhead. - static constexpr size_t max_cpu_copy_size = 128 * 1024; + // If the backend is idle, use a CPU copy to avoid GPU synchronization overhead (16 MiB on UMA for 128K rel_pos). + const size_t max_cpu_copy_size = ctx->device->uma ? (16 * 1024 * 1024) : (128 * 1024); const bool src_backend_synchronous = backend_src->iface.synchronize == nullptr; - const bool transfer_idle = !ctx->device->async_use_transfer_queue || - ctx->transfer_semaphore_last_submitted == ctx->transfer_semaphore.value; - const bool backend_idle = ctx->compute_ctx.expired() && ctx->transfer_ctx.expired() && - !ctx->submit_pending && !ctx->almost_ready_fence_pending && transfer_idle; + const bool backend_idle = is_vk_ctx_completely_idle(ctx); const bool dst_host_coherent = (dst_buf->memory_property_flags & (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent)) == (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); @@ -14679,6 +19631,9 @@ void ggml_vk_synchronize(ggml_backend_vk_context * ctx) { vk_context compute_ctx; vk_command_buffer* cmd_buf = nullptr; if (do_transfer) { + if (ctx->fence_submitted) { + ggml_vk_wait_for_fence(ctx); + } compute_ctx = ctx->compute_ctx.lock(); if (compute_ctx->s) { cmd_buf = compute_ctx->s->buffer; @@ -14689,11 +19644,23 @@ void ggml_vk_synchronize(ggml_backend_vk_context * ctx) { for (auto& cpy : compute_ctx->in_memcpys) { memcpy(cpy.dst, cpy.src, cpy.n); } + for (auto& mset : compute_ctx->memsets) { + memset(mset.dst, mset.val, mset.n); + } + const bool need_transfer_sem_submit = ctx->device->async_use_transfer_queue && + ctx->transfer_semaphore_last_submitted < ctx->transfer_semaphore.value; if (ctx->device->serialize_submissions) { ggml_vk_submit(compute_ctx, ctx->fence); VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "synchronize waitForFences", ctx->device); ctx->device->device.resetFences({ ctx->fence }); + ctx->fence_submitted = false; + ctx->fence_epoch++; + } else if (!need_transfer_sem_submit && !compute_ctx->seqs.empty()) { + // Series 9: Signal ctx->fence directly on compute_ctx submit instead of issuing a second empty vkQueueSubmit + ctx->last_submit_us = ggml_time_us(); + ggml_vk_submit(compute_ctx, ctx->fence); + ctx->fence_submitted = true; } else { ggml_vk_submit(compute_ctx, {}); } @@ -14704,6 +19671,9 @@ void ggml_vk_synchronize(ggml_backend_vk_context * ctx) { if (ctx->device->serialize_submissions) { ctx->submit_pending = false; } else if (ctx->device->async_use_transfer_queue && ctx->transfer_semaphore_last_submitted < ctx->transfer_semaphore.value) { + if (ctx->fence_submitted) { + ggml_vk_wait_for_fence(ctx); + } vk::TimelineSemaphoreSubmitInfo tl_info{ 1, &ctx->transfer_semaphore.value, 0, nullptr, @@ -14715,10 +19685,14 @@ void ggml_vk_synchronize(ggml_backend_vk_context * ctx) { 0, nullptr, }; si.setPNext(&tl_info); + ctx->last_submit_us = ggml_time_us(); ctx->device->compute_queue->handle->submit({ si }, ctx->fence); + ctx->fence_submitted = true; ctx->transfer_semaphore_last_submitted = ctx->transfer_semaphore.value; - } else { + } else if (!ctx->fence_submitted) { + ctx->last_submit_us = ggml_time_us(); ctx->device->compute_queue->handle->submit({}, ctx->fence); + ctx->fence_submitted = true; } if (!ctx->device->serialize_submissions) { ggml_vk_wait_for_fence(ctx); @@ -14734,16 +19708,33 @@ void ggml_vk_synchronize(ggml_backend_vk_context * ctx) { for (auto& cpy : compute_ctx->out_memcpys) { memcpy(cpy.dst, cpy.src, cpy.n); } + compute_ctx->in_memcpys.clear(); + compute_ctx->out_memcpys.clear(); + compute_ctx->memsets.clear(); ctx->compute_ctx.reset(); } + + if (!ctx->uma_out_memcpys.empty()) { + for (auto & cpy : ctx->uma_out_memcpys) { + memcpy(cpy.dst, cpy.src, cpy.n); + } + ctx->uma_out_memcpys.clear(); + } } static void ggml_backend_vk_synchronize(ggml_backend_t backend) { VK_LOG_DEBUG("ggml_backend_vk_synchronize()"); ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; + static const bool gen_stats = getenv("GGML_VK_GRAPH_STATS") != nullptr && atoi(getenv("GGML_VK_GRAPH_STATS")) != 0; + const int64_t gen_t_start = gen_stats ? ggml_time_us() : 0; + ggml_vk_synchronize(ctx); + if (gen_stats) { + fprintf(stderr, "ggml_vk_sync_stats: wait_us=%lld\n", (long long) (ggml_time_us() - gen_t_start)); + } + ggml_vk_graph_cleanup(ctx); } @@ -14801,9 +19792,124 @@ static bool ggml_vk_can_fuse_hc_post_gate(const struct ggml_cgraph * cgraph, int ggml_are_same_shape(scale_in->src[0], scale_out); } -bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list ops) { - if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_MUL) { - return ggml_vk_can_fuse_unary_mul_pair(cgraph, node_idx); +static bool gen_uses_dmmv_noswap(const ggml_backend_vk_context * ctx, const ggml_tensor * mm); + +static bool gen_cm1_fused_type_supported(ggml_type t) { + switch (t) { + case GGML_TYPE_F32: + case GGML_TYPE_F16: + case GGML_TYPE_Q1_0: + case GGML_TYPE_Q2_0: + case GGML_TYPE_Q4_0: + case GGML_TYPE_Q4_1: + case GGML_TYPE_Q5_0: + case GGML_TYPE_Q5_1: + case GGML_TYPE_Q8_0: + case GGML_TYPE_Q2_K: + case GGML_TYPE_Q3_K: + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + case GGML_TYPE_Q6_K: + case GGML_TYPE_TQ1_0: + case GGML_TYPE_TQ2_0: + case GGML_TYPE_IQ4_XS: + case GGML_TYPE_IQ4_NL: + case GGML_TYPE_NVFP4: + return true; + default: + return false; + } +} + +static bool gen_uses_cm1_fused_mm(const ggml_backend_vk_context * ctx, const ggml_tensor * mm) { + if (!mm || mm->op != GGML_OP_MUL_MAT || mm->type != GGML_TYPE_F32) { + return false; + } + if (!ctx->device->coopmat_support || ctx->device->coopmat2 || !ctx->device->coopmat_acc_f32_support || + ggml_vk_exact_s8_enabled() || gen_batch_invariant_for_n(mm->ne[1])) { + return false; + } + const ggml_tensor * src0 = mm->src[0]; + const ggml_tensor * src1 = mm->src[1]; + if (!src0 || !src1 || ggml_vk_tensor_is_repack(src0) || !gen_cm1_fused_type_supported(src0->type) || + (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16)) { + return false; + } + if (!ggml_vk_dim01_contiguous(src0) || + (src0->type == GGML_TYPE_F32 && !ggml_vk_dim01_contiguous(src1))) { + return false; + } + if ((mm->ne[2] == 1 && mm->ne[3] == 1 && ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) || + ggml_vk_can_use_fwht(ctx, src1, const_cast(mm)) || + ggml_vk_get_mul_mat_mat_f16acc(ctx, src0->type, src1->type, ggml_prec_get_acc(mm))) { + return false; + } + const ggml_type b_type = ggml_vk_dim01_contiguous(src1) ? src1->type : GGML_TYPE_F16; + return ggml_vk_get_mul_mat_mat_pipeline_map(const_cast(ctx), src0->type, b_type, ggml_prec_get_acc(mm), false) != nullptr; +} + +static bool gen_uses_cm1_fused_mmid(const ggml_backend_vk_context * ctx, const ggml_tensor * mmid, bool is_pair_glu = false) { + if (!mmid || mmid->op != GGML_OP_MUL_MAT_ID || mmid->type != GGML_TYPE_F32) { + return false; + } + if (!ctx->device->coopmat_support || ctx->device->coopmat2 || !ctx->device->coopmat_acc_f32_support || + ggml_vk_exact_s8_enabled() || gen_batch_invariant_for_n(mmid->src[2] ? mmid->src[2]->ne[1] : 0)) { + return false; + } + const ggml_tensor * src0 = mmid->src[0]; + const ggml_tensor * src1 = mmid->src[1]; + const ggml_tensor * ids = mmid->src[2]; + if (!src0 || !src1 || !ids || ids->type != GGML_TYPE_I32 || + !gen_cm1_fused_type_supported(src0->type) || + (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16)) { + return false; + } + if (ggml_vk_tensor_is_repack(src0)) { + const int ri = ggml_vk_repack_type_idx(src0->type); + static const int env_mma_id_max_n = getenv("GGML_VK_MMA_ID_MAX_N") ? atoi(getenv("GGML_VK_MMA_ID_MAX_N")) : 2048; + static const int env_mma_id_pglu_max_n = getenv("GGML_VK_MMA_ID_PGLU_MAX_N") ? atoi(getenv("GGML_VK_MMA_ID_PGLU_MAX_N")) : -1; + const int eff_mma_id_max_n = is_pair_glu + ? (env_mma_id_pglu_max_n >= 0 ? env_mma_id_pglu_max_n : env_mma_id_max_n) + : env_mma_id_max_n; + return ri >= 0 && + ggml_vk_is_apple_agx_coopmat(ctx->device) && + !getenv("GGML_VK_DISABLE_MMA_ID") && + src1->type == GGML_TYPE_F32 && + ggml_is_contiguous(src0) && + (src1->ne[1] == 1 || src1->ne[1] >= ids->ne[0]) && + ids->ne[1] <= eff_mma_id_max_n && + (src1->ne[0] % 64 == 0) && + get_misalign_bytes(ctx, src1) % 4 == 0 && + ctx->device->pipeline_mul_mv_mma_id_repack[ri][0][0][0] != nullptr; + } + if (src0->type == GGML_TYPE_NVFP4) { + static const int env_mma_id_max_n = getenv("GGML_VK_MMA_ID_MAX_N") ? atoi(getenv("GGML_VK_MMA_ID_MAX_N")) : 2048; + static const int env_mma_id_fep_max_n = getenv("GGML_VK_MMA_ID_FASTEP_MAX_N") ? atoi(getenv("GGML_VK_MMA_ID_FASTEP_MAX_N")) : -1; + const int eff_max_n = env_mma_id_fep_max_n >= 0 ? env_mma_id_fep_max_n : env_mma_id_max_n; + return ggml_vk_is_apple_agx_coopmat(ctx->device) && + !getenv("GGML_VK_DISABLE_MMA_ID") && + !ggml_vk_exact_s8_enabled() && + !gen_batch_invariant_for_n(ids->ne[1]) && + src1->type == GGML_TYPE_F32 && + ggml_is_contiguous(src0) && + (src1->ne[1] == 1 || src1->ne[1] >= ids->ne[0]) && + ids->ne[1] <= eff_max_n && + (src1->ne[0] % 64 == 0) && + get_misalign_bytes(ctx, src1) % 4 == 0 && + ctx->device->pipeline_mul_mv_mma_id[GGML_TYPE_NVFP4][0][0][0] != nullptr; + } + if (!ggml_vk_dim01_contiguous(src0) || + (src0->type == GGML_TYPE_F32 && !ggml_vk_dim01_contiguous(src1)) || + ggml_vk_get_mul_mat_mat_f16acc(ctx, src0->type, src1->type, ggml_prec_get_acc(mmid))) { + return false; + } + const ggml_type b_type = ggml_vk_dim01_contiguous(src1) ? src1->type : GGML_TYPE_F16; + return ggml_vk_get_mul_mat_mat_pipeline_map(const_cast(ctx), src0->type, b_type, ggml_prec_get_acc(mmid), true) != nullptr; +} + +bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list ops) { + if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_MUL) { + return ggml_vk_can_fuse_unary_mul_pair(cgraph, node_idx); } if (!ggml_can_fuse(cgraph, node_idx, ops)) { @@ -14884,11 +19990,19 @@ bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgr } } - auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) { + auto const &mm_add_ok = [&](const ggml_tensor *root_mm, const ggml_tensor *mul, const ggml_tensor *add) { const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0]; - // mat-vec only - if (ggml_nrows(mul) != 1) { + // mat-vec, or multi-column mat-vec / cm1 matmul when not in exact-s8 / batch-invariant<=8 mode + const bool ok_rows = + ggml_nrows(mul) == 1 || + (gen_batch_invariant_for_n(mul->ne[1]) + ? (mul->ne[2] == 1 && mul->ne[3] == 1 && mul->ne[1] <= 8 && + mul->src[1] && mul->src[1]->ne[2] * mul->src[1]->ne[3] == 1) + : (!ggml_vk_exact_s8_enabled() && + ((gen_uses_dmmv_noswap(ctx, root_mm) && ggml_is_contiguous(root_mm)) || + gen_uses_cm1_fused_mm(ctx, root_mm)))); + if (!ok_rows) { return false; } // shaders assume the types match @@ -14897,11 +20011,13 @@ bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgr } // shaders reuse the D shape for bias if (!ggml_are_same_shape(mul, bias) || - !ggml_are_same_stride(mul, bias)) { + !ggml_are_same_stride(mul, bias) || + !ggml_are_same_shape(mul, add) || + !ggml_are_same_stride(mul, add)) { return false; } - // unaligned bias isn't handled - if (get_misalign_bytes(ctx, bias) != 0) { + // unaligned bias/dst isn't handled + if (get_misalign_bytes(ctx, bias) != 0 || get_misalign_bytes(ctx, add) != 0) { return false; } return true; @@ -14912,14 +20028,14 @@ bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgr const ggml_tensor *mul = cgraph->nodes[node_idx]; const ggml_tensor *add = cgraph->nodes[node_idx + 1]; - if (!mm_add_ok(mul, add)) { + if (!mm_add_ok(mul, mul, add)) { return false; } if (ops.size() == 3) { if (ops.begin()[2] != GGML_OP_ADD) { return false; } - if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) { + if (!mm_add_ok(mul, add, cgraph->nodes[node_idx + 2])) { return false; } } @@ -14931,8 +20047,9 @@ bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgr if (mmid != mul->src[0]) { return false; } - // mat-vec only - if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) { + // mat-vec or cm1 fused matmul_id + if (!ggml_vk_use_mul_mat_vec_id(ctx, cgraph, node_idx) && + !gen_uses_cm1_fused_mmid(ctx, cgraph->nodes[node_idx])) { return false; } // shaders assume the types match @@ -14943,14 +20060,14 @@ bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgr if (!ggml_is_contiguous(scale)) { return false; } - // unaligned bias isn't handled - if (get_misalign_bytes(ctx, scale) != 0) { + // unaligned bias/dst isn't handled + if (get_misalign_bytes(ctx, scale) != 0 || get_misalign_bytes(ctx, mul) != 0) { return false; } - // shader only indexes by expert index + // shader indexes by expert slot, or (slot, token) via SCALE0_TOK / SCALE1_TOK if (scale->ne[0] != 1 || scale->ne[1] != mul->ne[1] || - scale->ne[2] != 1 || + (scale->ne[2] != 1 && scale->ne[2] != mul->ne[2]) || scale->ne[3] != 1) { return false; } @@ -14966,8 +20083,9 @@ bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgr if (mul != add->src[0]) { return false; } - // mat-vec only - if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) { + // mat-vec or cm1 fused matmul_id + if (!ggml_vk_use_mul_mat_vec_id(ctx, cgraph, node_idx) && + !gen_uses_cm1_fused_mmid(ctx, mul)) { return false; } // shaders assume the types match @@ -14982,8 +20100,8 @@ bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgr if (mul->src[2] != add->src[2]) { return false; } - // unaligned bias isn't handled - if (get_misalign_bytes(ctx, bias) != 0) { + // unaligned bias/dst isn't handled + if (get_misalign_bytes(ctx, bias) != 0 || get_misalign_bytes(ctx, add) != 0) { return false; } @@ -15080,6 +20198,7 @@ bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_ argsort = cgraph->nodes[node_idx + 2]; break; case TOPK_MOE_SIGMOID_NORM_BIAS: + case TOPK_MOE_SIGMOID_NORM_BIAS_EPS: softmax = cgraph->nodes[node_idx + 0]; // really sigmoid weights = cgraph->nodes[node_idx + 10]; get_rows = cgraph->nodes[node_idx + 5]; @@ -15087,6 +20206,12 @@ bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_ if (ggml_get_unary_op(softmax) != GGML_UNARY_OP_SIGMOID) { return false; } + if (mode == TOPK_MOE_SIGMOID_NORM_BIAS_EPS) { + const ggml_tensor * sc = cgraph->nodes[node_idx + 8]; + if (sc->op != GGML_OP_SCALE || ggml_get_op_params_f32(sc, 0) != 1.0f || ggml_get_op_params_f32(sc, 1) < 0.0f) { + return false; + } + } // bias is expected to be 1D if (ggml_nrows(cgraph->nodes[node_idx + 2]->src[1]) != 1 || !ggml_is_contiguous(cgraph->nodes[node_idx + 2]->src[1])) { @@ -15136,6 +20261,7 @@ bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_ if (probs != selection_probs && mode != TOPK_MOE_SIGMOID_NORM_BIAS && + mode != TOPK_MOE_SIGMOID_NORM_BIAS_EPS && mode != TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS) { return false; } @@ -15276,7 +20402,7 @@ bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct // The shader reads each aligned I64 index as a uvec2 and uses its low 32 bits. if (set_rows->src[1]->type != GGML_TYPE_I64 || !ggml_is_contiguous(set_rows->src[1]) || - set_rows->nb[0] != ggml_type_size(set_rows->type) || get_misalign_bytes(ctx, set_rows->src[1]) != 0) { + set_rows->nb[0] != ggml_type_size(set_rows->type) || (get_misalign_bytes(ctx, set_rows->src[1]) % sizeof(int64_t)) != 0) { return false; } @@ -15298,17 +20424,136 @@ bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct return true; } +static const std::initializer_list softcap_argmax_pattern = { + GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_ARGMAX +}; +static const std::initializer_list add_softcap_argmax_pattern = { + GGML_OP_ADD, GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_ARGMAX +}; + +static bool ggml_vk_can_fuse_add_softcap_argmax(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) { + static const bool no_add_sc_am = getenv("S19_NO_ADD_SOFTCAP_ARGMAX") != nullptr; + if (no_add_sc_am || !ggml_can_fuse(cgraph, node_idx, add_softcap_argmax_pattern)) { + return false; + } + const ggml_tensor * add = cgraph->nodes[node_idx + 0]; + const ggml_tensor * sc0 = cgraph->nodes[node_idx + 1]; + const ggml_tensor * un = cgraph->nodes[node_idx + 2]; + const ggml_tensor * sc1 = cgraph->nodes[node_idx + 3]; + const ggml_tensor * am = cgraph->nodes[node_idx + 4]; + const ggml_tensor * a = add->src[0]; + const ggml_tensor * b = add->src[1]; + if (!a || !b || a->type != GGML_TYPE_F32 || b->type != GGML_TYPE_F32 || + add->type != GGML_TYPE_F32 || sc0->type != GGML_TYPE_F32 || + un->type != GGML_TYPE_F32 || sc1->type != GGML_TYPE_F32 || am->type != GGML_TYPE_I32) { + return false; + } + if (ggml_get_unary_op(un) != GGML_UNARY_OP_TANH) { + return false; + } + if (!ggml_are_same_shape(a, b) || + !ggml_is_contiguous(a) || !ggml_is_contiguous(b) || + a->ne[2] != 1 || a->ne[3] != 1 || !ggml_is_contiguous(am)) { + return false; + } + const float s0 = ggml_get_op_params_f32(sc0, 0); + const float b0 = ggml_get_op_params_f32(sc0, 1); + const float b1 = ggml_get_op_params_f32(sc1, 1); + if (s0 == 0.0f || b0 != 0.0f || b1 != 0.0f) { + return false; + } + if ((get_misalign_bytes(ctx, a) % sizeof(float)) != 0 || + (get_misalign_bytes(ctx, b) % sizeof(float)) != 0 || + (get_misalign_bytes(ctx, am) % sizeof(int32_t)) != 0) { + return false; + } + return true; +} +static const std::initializer_list inkling_clip_view_set_rows_pattern = { + GGML_OP_INKLING_FUSED, GGML_OP_VIEW, GGML_OP_SET_ROWS +}; + +static bool ggml_vk_can_fuse_softcap_argmax(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) { + if (!ggml_can_fuse(cgraph, node_idx, softcap_argmax_pattern)) { + return false; + } + const ggml_tensor * sc0 = cgraph->nodes[node_idx + 0]; + const ggml_tensor * un = cgraph->nodes[node_idx + 1]; + const ggml_tensor * sc1 = cgraph->nodes[node_idx + 2]; + const ggml_tensor * am = cgraph->nodes[node_idx + 3]; + if (sc0->src[0]->type != GGML_TYPE_F32 || sc0->type != GGML_TYPE_F32 || + un->type != GGML_TYPE_F32 || sc1->type != GGML_TYPE_F32 || am->type != GGML_TYPE_I32) { + return false; + } + if (ggml_get_unary_op(un) != GGML_UNARY_OP_TANH) { + return false; + } + if (!ggml_is_contiguous_rows(sc0->src[0]) || sc0->src[0]->ne[2] != 1 || sc0->src[0]->ne[3] != 1 || + !ggml_is_contiguous(am)) { + return false; + } + const float s0 = ggml_get_op_params_f32(sc0, 0); + const float b0 = ggml_get_op_params_f32(sc0, 1); + const float b1 = ggml_get_op_params_f32(sc1, 1); + if (s0 == 0.0f || b0 != 0.0f || b1 != 0.0f) { + return false; + } + if ((get_misalign_bytes(ctx, sc0->src[0]) % sizeof(float)) != 0 || + (get_misalign_bytes(ctx, am) % sizeof(int32_t)) != 0) { + return false; + } + return true; +} + +static bool ggml_vk_can_fuse_inkling_clip_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) { + static const bool dis_q8_sr = getenv("GGML_VK_DISABLE_S23_Q8_KV_SR") != nullptr; + const ggml_tensor * clip = cgraph->nodes[node_idx + 0]; + const ggml_tensor * view = cgraph->nodes[node_idx + 1]; + const ggml_tensor * set_rows = cgraph->nodes[node_idx + 2]; + if (clip->op != GGML_OP_INKLING_FUSED || ggml_get_op_params_i32(clip, 0) != 0) { + return false; + } + const ggml_tensor * cur = clip->src[0]; + const bool q8_ok = !dis_q8_sr && set_rows->type == GGML_TYPE_Q8_0 && + ctx->device->subgroup_shuffle && ctx->device->subgroup_size == 32 && ctx->device->fp16 && + cur && (cur->ne[0] % 32 == 0); + if (!cur || cur->type != GGML_TYPE_F32 || clip->type != GGML_TYPE_F32 || + (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16 && !q8_ok) || + set_rows->src[1]->type != GGML_TYPE_I64 || !ggml_is_contiguous(set_rows->src[1]) || + set_rows->nb[0] != ggml_type_size(set_rows->type) || + (get_misalign_bytes(ctx, set_rows->src[1]) % sizeof(int64_t)) != 0 || + (get_misalign_bytes(ctx, set_rows) % ggml_type_size(set_rows->type)) != 0) { + return false; + } + if (cur->ne[3] != 1 || !ggml_is_contiguous(cur) || !ggml_is_contiguous(view)) { + return false; + } + if (view->ne[0] != cur->ne[0] * cur->ne[1] || view->ne[1] != cur->ne[2] || + view->ne[2] != 1 || view->ne[3] != 1 || + ggml_nelements(set_rows->src[1]) != cur->ne[2]) { + return false; + } + return true; +} + bool ggml_vk_can_fuse_rms_norm_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) { + static const bool dis_q8_sr = getenv("GGML_VK_DISABLE_S23_Q8_KV_SR") != nullptr; const ggml_tensor * rms = cgraph->nodes[node_idx]; const ggml_tensor * view = cgraph->nodes[node_idx + 1]; const ggml_tensor * set_rows = cgraph->nodes[node_idx + 2]; - // The RMS kernel reads F32 and writes directly to the F32 or F16 SET_ROWS destination. + const bool q8_ok = !dis_q8_sr && set_rows->type == GGML_TYPE_Q8_0 && + ctx->device->pipeline_rms_norm_set_rows_f32_q8_0_32 != nullptr && + (rms->src[0]->ne[0] % 32 == 0) && + (get_misalign_bytes(ctx, set_rows) % ggml_type_size(GGML_TYPE_Q8_0) == 0) && + (get_misalign_bytes(ctx, set_rows) / ggml_type_size(GGML_TYPE_Q8_0) <= 0x7FFFu); + + // The RMS kernel reads F32 and writes directly to the F32, F16, or Q8_0 SET_ROWS destination. if (rms->src[0]->type != GGML_TYPE_F32 || rms->type != GGML_TYPE_F32 || - (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) || + (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16 && !q8_ok) || set_rows->src[1]->type != GGML_TYPE_I64 || !ggml_is_contiguous(set_rows->src[1]) || - set_rows->nb[0] != ggml_type_size(set_rows->type) || get_misalign_bytes(ctx, set_rows->src[1]) != 0) { + set_rows->nb[0] != ggml_type_size(set_rows->type) || (get_misalign_bytes(ctx, set_rows->src[1]) % sizeof(int64_t)) != 0) { return false; } // As with the ROPE epilogue, each ne2 slice supplies one flattened row and ne3 is not encoded. @@ -15403,6 +20648,25 @@ bool ggml_vk_tensors_overlap(const ggml_tensor * a, const ggml_tensor * b, bool return false; } +static bool ggml_vk_tensors_overlap_strided(const ggml_tensor * a, const ggml_tensor * b) { + if (!a || !b || !a->buffer || !b->buffer) { + return false; + } + ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context; + ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context; + if (a_buf_ctx->dev_buffer != b_buf_ctx->dev_buffer) { + return false; + } + const size_t a_base = vk_tensor_offset(a) + a->view_offs; + const size_t a_size = std::max(ggml_nbytes(a), ggml_vk_tensor_byte_span(a)); + const size_t b_base = vk_tensor_offset(b) + b->view_offs; + const size_t b_size = std::max(ggml_nbytes(b), ggml_vk_tensor_byte_span(b)); + return (b_base <= a_base && a_base < b_base + b_size) || + (a_base <= b_base && b_base < a_base + a_size); +} + +static bool gen_fuse_enabled(const char * what); + bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) { const ggml_tensor *rms = cgraph->nodes[node_idx + 0]; @@ -15422,8 +20686,9 @@ bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const str return false; } - // only norm/neox are handled in the shader - if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) { + // norm/neox always; mrope/imrope when GGML_GEN_FUSE=mrope + if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL && + !(gen_fuse_enabled("mrope") && (mode == GGML_ROPE_TYPE_MROPE || mode == GGML_ROPE_TYPE_IMROPE))) { return false; } @@ -15504,65 +20769,2062 @@ static int32_t find_first_set(uint32_t x) { return ret; } -static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) { - VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)"); - ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; - - ctx->device->diag_cgraph = nullptr; - ctx->device->diag_prev_start = -1; - ctx->device->diag_prev_end = -1; +// gen: GGML_GEN_FUSE=glu,l2 (or all; default all unless none/0) enables the extra fusions +static bool gen_fuse_enabled(const char * what) { + static const std::string v = getenv("GGML_GEN_FUSE") ? getenv("GGML_GEN_FUSE") : "all"; + if (v.empty() || v == "none" || v == "0") { + return false; + } + if (v == "all") { + return true; + } + return ("," + v + ",").find("," + std::string(what) + ",") != std::string::npos; +} - if (vk_instance.debug_utils_support) { - ctx->device->debug_cmdbuf_idx = 0; +static bool gen_uses_dmmv_noswap(const ggml_backend_vk_context * ctx, const ggml_tensor * mm) { + if (mm->op != GGML_OP_MUL_MAT || mm->type != GGML_TYPE_F32 || mm->ne[2] != 1 || mm->ne[3] != 1) { + return false; + } + const ggml_tensor * src0 = mm->src[0]; + const ggml_tensor * src1 = mm->src[1]; + if (!(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) { + return false; + } + if (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) { + return false; + } + if ((ggml_vk_tensor_is_repack(src0) ? ggml_vk_repack_alloc_bytes(src0) : ggml_nbytes(src0)) > ctx->device->properties.limits.maxStorageBufferRange) { + return false; + } + if (ggml_vk_can_use_fwht(ctx, src1, const_cast(mm))) { + return false; + } + if (!ggml_is_contiguous(src0) || ggml_is_permuted(src0) || ggml_is_permuted(src1) || ggml_is_transposed(src1)) { + return false; + } + static const int env_mma_q8_min_n_fn = getenv("GGML_VK_MMA_Q8_MIN_N") ? atoi(getenv("GGML_VK_MMA_Q8_MIN_N")) : 8; + static const int env_mma_q8_min_m_fn = getenv("GGML_VK_MMA_Q8_MIN_M") ? atoi(getenv("GGML_VK_MMA_Q8_MIN_M")) : 0; + static const int env_mma_q8_max_m_s_fn = getenv("GGML_VK_MMA_Q8_MAX_M") ? atoi(getenv("GGML_VK_MMA_Q8_MAX_M")) : 65536; + static const int env_mma_q8_max_m_l_fn = getenv("GGML_VK_MMA_Q8_MAX_M") ? atoi(getenv("GGML_VK_MMA_Q8_MAX_M")) : 65536; + static const int env_mma_f32_max_m_fn = getenv("GGML_VK_MMA_F32_MAX_M") ? atoi(getenv("GGML_VK_MMA_F32_MAX_M")) : 256; + return src1->ne[2] * src1->ne[3] == 1 && + (mm->ne[1] <= (int64_t) ggml_vk_mul_mat_vec_max_cols(ctx->device) || + (ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled() && !gen_batch_invariant_for_n(mm->ne[1]) && + mm->ne[1] <= 4096 && + ((src0->type == GGML_TYPE_F32 && mm->ne[0] <= (mm->ne[1] <= 32 ? 256 : env_mma_f32_max_m_fn)) || + (src0->type == GGML_TYPE_Q8_0 && (mm->ne[1] <= 32 + ? (mm->ne[0] <= env_mma_q8_max_m_s_fn) + : (mm->ne[1] >= env_mma_q8_min_n_fn && mm->ne[0] >= env_mma_q8_min_m_fn && mm->ne[0] <= env_mma_q8_max_m_l_fn))) || + (ggml_vk_tensor_is_repack(src0) && mm->ne[1] >= 8 && mm->ne[0] >= 4)))); +} + +static bool gen_supports_pair_type(ggml_type t) { + switch (t) { + case GGML_TYPE_F32: + case GGML_TYPE_F16: + case GGML_TYPE_BF16: + case GGML_TYPE_Q8_0: + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + case GGML_TYPE_Q6_K: + case GGML_TYPE_NVFP4: + return true; + default: + return false; } +} - // queue scope, so it encloses every submit this evaluation makes. - // closed when the function returns - ggml_vk_debug_label queue_dbg(ctx->device->compute_queue->handle.get(), "ggml_backend_vk_graph_compute"); +static bool gen_can_fuse_gate_up_glu(const ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int i) { + if (!gen_fuse_enabled("gateup") || i + 2 >= cgraph->n_nodes) { + return false; + } + const ggml_tensor * n0 = cgraph->nodes[i]; + const ggml_tensor * n1 = cgraph->nodes[i + 1]; + const ggml_tensor * glu = cgraph->nodes[i + 2]; + if ((n0->op != GGML_OP_MUL_MAT && n0->op != GGML_OP_MUL_MAT_ID) || n1->op != n0->op || glu->op != GGML_OP_GLU || n0 == n1) { + return false; + } + if (!ggml_can_fuse_subgraph(cgraph, i, { n0->op, n1->op, GGML_OP_GLU }, { i + 2 })) { + return false; + } + if (ggml_get_glu_op(glu) != GGML_GLU_OP_SWIGLU || glu->src[1] == nullptr || ggml_get_op_params_i32(glu, 1) != 0) { + return false; + } + if (!((glu->src[0] == n0 && glu->src[1] == n1) || (glu->src[0] == n1 && glu->src[1] == n0))) { + return false; + } + if (n0->src[1] != n1->src[1] || (n0->op == GGML_OP_MUL_MAT_ID && n0->src[2] != n1->src[2])) { + return false; + } + const ggml_tensor * w0 = n0->src[0]; + const ggml_tensor * w1 = n1->src[0]; + if (w0->type != w1->type || ggml_vk_tensor_is_repack(w0) != ggml_vk_tensor_is_repack(w1) || (w0->ne[0] & 3) != 0) { + return false; + } + if (!ggml_are_same_shape(w0, w1) || !ggml_are_same_stride(w0, w1) || + !ggml_is_contiguous(w0) || !ggml_is_contiguous(w1) || + !w0->buffer || !w1->buffer || get_misalign_bytes(ctx, w0) != 0 || get_misalign_bytes(ctx, w1) != 0) { + return false; + } + if (!n0->src[1]->buffer || get_misalign_bytes(ctx, n0->src[1]) != 0) { + return false; + } + if (n0->type != GGML_TYPE_F32 || n1->type != GGML_TYPE_F32 || glu->type != GGML_TYPE_F32 || + !ggml_are_same_shape(n0, n1) || !ggml_are_same_shape(n0, glu) || + !ggml_are_same_stride(n0, n1) || !ggml_are_same_stride(n0, glu) || + !ggml_is_contiguous(n0) || !ggml_is_contiguous(glu) || !glu->buffer || get_misalign_bytes(ctx, glu) != 0) { + return false; + } + if (n0->op == GGML_OP_MUL_MAT) { + if (gen_uses_dmmv_noswap(ctx, n0) && gen_uses_dmmv_noswap(ctx, n1)) { + if (gen_supports_pair_type(w0->type)) { + return true; + } + return ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled() && !gen_batch_invariant_for_n(n0->ne[1]) && + n0->ne[1] >= 2 && (w0->type == GGML_TYPE_IQ4_XS || w0->type == GGML_TYPE_IQ4_NL) && (w0->ne[0] % 64 == 0); + } + return gen_uses_cm1_fused_mm(ctx, n0) && gen_uses_cm1_fused_mm(ctx, n1); + } + if (ggml_vk_use_mul_mat_vec_id(ctx, cgraph, i) && ggml_vk_use_mul_mat_vec_id(ctx, cgraph, i + 1)) { + return gen_supports_pair_type(w0->type); + } + return gen_uses_cm1_fused_mmid(ctx, n0, true) && gen_uses_cm1_fused_mmid(ctx, n1, true); +} - ctx->prealloc_size_add_rms_partials_offset = 0; - ctx->do_add_rms_partials = false; - ctx->do_add_rms_partials_offset_calculation = false; +static bool gen_can_fuse_mm_glu(const ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int i) { + if (!gen_fuse_enabled("glu") || i + 1 >= cgraph->n_nodes) { + return false; + } + const ggml_tensor * mm = cgraph->nodes[i]; + const ggml_tensor * glu = cgraph->nodes[i + 1]; + if ((mm->op != GGML_OP_MUL_MAT && mm->op != GGML_OP_MUL_MAT_ID) || glu->op != GGML_OP_GLU) { + return false; + } + if (!ggml_can_fuse(cgraph, i, { mm->op, GGML_OP_GLU })) { + return false; + } + if (ggml_get_glu_op(glu) != GGML_GLU_OP_SWIGLU || glu->src[1] == nullptr || ggml_get_op_params_i32(glu, 1) != 0) { + return false; + } + if (glu->src[0] != mm && glu->src[1] != mm) { + return false; + } + const ggml_tensor * other = glu->src[0] == mm ? glu->src[1] : glu->src[0]; + if (other == mm || mm->type != GGML_TYPE_F32 || other->type != GGML_TYPE_F32 || glu->type != GGML_TYPE_F32) { + return false; + } + if (!ggml_are_same_shape(mm, other) || !ggml_are_same_stride(mm, other) || + !ggml_are_same_shape(mm, glu) || !ggml_are_same_stride(mm, glu) || !ggml_is_contiguous(mm)) { + return false; + } + if (get_misalign_bytes(ctx, other) != 0 || get_misalign_bytes(ctx, glu) != 0) { + return false; + } + if (mm->op == GGML_OP_MUL_MAT) { + return gen_uses_dmmv_noswap(ctx, mm) || gen_uses_cm1_fused_mm(ctx, mm); + } + return ggml_vk_use_mul_mat_vec_id(ctx, cgraph, i) || gen_uses_cm1_fused_mmid(ctx, mm); +} - int last_node = cgraph->n_nodes - 1; +struct gen_mm_epilogue { + const ggml_tensor * dst {}; + const ggml_tensor * f0 {}; + const ggml_tensor * f1 {}; + uint32_t flags {}; + int skip[3] { -1, -1, -1 }; + const char * name {}; +}; - // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly - while (last_node > 0 && (ggml_vk_is_empty(cgraph->nodes[last_node]) || ((cgraph->nodes[last_node]->flags & GGML_TENSOR_FLAG_COMPUTE) == 0))) { - last_node -= 1; +struct vk_cgraph_use_index { + struct slot_t { + const ggml_tensor * t; + uint32_t epoch; + int32_t first_node; + uint32_t head_edge; + }; + std::vector slots; + std::vector edge_node; + std::vector edge_next; + uint32_t epoch = 1; + size_t mask = 0; + + uint32_t find_or_insert(const ggml_tensor * t) { + uintptr_t p = (uintptr_t) t; + size_t s = ((p >> 5) * 11400714819323198485ULL) & mask; + while (slots[s].epoch == epoch) { + if (slots[s].t == t) { + return (uint32_t) s; + } + s = (s + 1) & mask; + } + slots[s].t = t; + slots[s].epoch = epoch; + slots[s].first_node = -1; + slots[s].head_edge = UINT32_MAX; + return (uint32_t) s; } - // Reserve tensor context space for all nodes - ctx->tensor_ctxs.resize(cgraph->n_nodes); + int32_t find_slot(const ggml_tensor * t) const { + if (!t || slots.empty()) { + return -1; + } + uintptr_t p = (uintptr_t) t; + size_t s = ((p >> 5) * 11400714819323198485ULL) & mask; + while (slots[s].epoch == epoch) { + if (slots[s].t == t) { + return (int32_t) s; + } + s = (s + 1) & mask; + } + return -1; + } - bool first_node_in_batch = true; // true if next node will be first node in a batch - int submit_node_idx = 0; // index to first node in a batch + void add_reader(const ggml_tensor * t, int32_t k) { + uint32_t s = find_or_insert(t); + uint32_t head = slots[s].head_edge; + if (head != UINT32_MAX && edge_node[head] == k) { + return; + } + uint32_t eid = (uint32_t) edge_node.size(); + edge_node.push_back(k); + edge_next.push_back(head); + slots[s].head_edge = eid; + } + + void build(const ggml_cgraph * g) { + const int n_nodes = g->n_nodes; + size_t cap = 4096; + const size_t min_cap = (size_t) (n_nodes + 64) * 8; + while (cap < min_cap) { + cap <<= 1; + } + if (slots.size() < cap) { + slots.assign(cap, slot_t{ nullptr, 0, -1, UINT32_MAX }); + epoch = 1; + } else if (++epoch == 0) { + for (auto & sl : slots) { + sl.epoch = 0; + } + epoch = 1; + } + mask = slots.size() - 1; + edge_node.clear(); + edge_next.clear(); + edge_node.reserve((size_t) n_nodes * 4); + edge_next.reserve((size_t) n_nodes * 4); + + for (int32_t k = 0; k < n_nodes; ++k) { + const ggml_tensor * n = g->nodes[k]; + uint32_t ns = find_or_insert(n); + if (slots[ns].first_node < 0) { + slots[ns].first_node = k; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + const ggml_tensor * src = n->src[s]; + if (!src) { + continue; + } + add_reader(src, k); + if (src->view_src && src->view_src != src) { + add_reader(src->view_src, k); + } + } + } + } - ggml_vk_submit_transfer_ctx(ctx); + int32_t first_node_idx(const ggml_tensor * t) const { + int32_t s = find_slot(t); + return s >= 0 ? slots[s].first_node : -1; + } - vk_context compute_ctx; - if (vk_perf_logger_enabled) { - // allocate/resize the query pool - if (ctx->num_queries < cgraph->n_nodes + 1) { - if (ctx->query_pool) { - ctx->device->device.destroyQueryPool(ctx->query_pool); + template + bool any_reader(const ggml_tensor * t, Pred && pred) const { + int32_t s = find_slot(t); + if (s < 0) { + return false; + } + for (uint32_t e = slots[s].head_edge; e != UINT32_MAX; e = edge_next[e]) { + if (pred(edge_node[e])) { + return true; } - vk::QueryPoolCreateInfo query_create_info; - query_create_info.queryType = vk::QueryType::eTimestamp; - query_create_info.queryCount = cgraph->n_nodes + 100; - ctx->query_pool = ctx->device->device.createQueryPool(query_create_info); - ctx->num_queries = query_create_info.queryCount; - ctx->query_fusion_names.resize(ctx->num_queries); - ctx->query_fusion_node_count.resize(ctx->num_queries); - ctx->query_nodes.resize(ctx->num_queries); - ctx->query_node_idx.resize(ctx->num_queries); } + return false; + } +}; - ctx->device->device.resetQueryPool(ctx->query_pool, 0, cgraph->n_nodes+1); - std::fill(ctx->query_fusion_names.begin(), ctx->query_fusion_names.end(), nullptr); - std::fill(ctx->query_fusion_node_count.begin(), ctx->query_fusion_node_count.end(), 0); +static bool gen_find_mm_epilogue(const ggml_backend_vk_context * ctx, const ggml_cgraph * g, int i, int last_node, + const std::vector & gen_skip, const vk_cgraph_use_index & use_idx, gen_mm_epilogue & out) { + const bool do_mmgate = gen_fuse_enabled("mmgate"); + const bool do_shexp = gen_fuse_enabled("shexp"); + if (!do_mmgate && !do_shexp) { + return false; + } + const ggml_tensor * mm = g->nodes[i]; + if ((!gen_uses_dmmv_noswap(ctx, mm) && !gen_uses_cm1_fused_mm(ctx, mm)) || !ggml_is_contiguous(mm) || !mm->buffer || + get_misalign_bytes(ctx, mm) != 0 || (mm->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + auto same_bytes_of_mm = [&](const ggml_tensor * t) { + return t == mm || ((t->op == GGML_OP_RESHAPE || t->op == GGML_OP_VIEW) && + t->view_src == mm && t->view_offs == 0 && t->type == GGML_TYPE_F32 && + ggml_is_contiguous(t) && ggml_nbytes(t) == ggml_nbytes(mm)); + }; + auto check_valid = [&](const ggml_tensor * dst_out, const ggml_tensor * f0, const ggml_tensor * f1, + int final_idx, const int (&skips)[3], const ggml_tensor * const (&elided)[4]) { + if (!dst_out || dst_out->type != GGML_TYPE_F32 || !ggml_is_contiguous(dst_out) || + ggml_nbytes(dst_out) != ggml_nbytes(mm) || !dst_out->buffer || get_misalign_bytes(ctx, dst_out) != 0) { + return false; + } + for (const ggml_tensor * e : elided) { + if (e && (e->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + } + auto is_skipped = [&](int idx) { + return idx == skips[0] || idx == skips[1] || idx == skips[2] || (!gen_skip.empty() && gen_skip[idx]); + }; + for (const ggml_tensor * e : elided) { + if (e && use_idx.any_reader(e, [&](int k) { + return k != i && !is_skipped(k) && !ggml_op_is_empty(g->nodes[k]->op); + })) { + return false; + } + } + if (ggml_vk_tensors_overlap(mm->src[0], dst_out, false) || + ggml_vk_tensors_overlap(mm->src[1], dst_out, false) || + (f0 && ggml_vk_tensors_overlap(f0, dst_out, false)) || + (f1 && ggml_vk_tensors_overlap(f1, dst_out, false))) { + return false; + } + for (int k = i + 1; k < final_idx; k++) { + const ggml_tensor * n = g->nodes[k]; + if (is_skipped(k) || ggml_op_is_empty(n->op)) { + continue; + } + if (n->buffer && ggml_vk_tensors_overlap(n, dst_out, false)) { + return false; + } + if ((f0 && n->buffer && ggml_vk_tensors_overlap(n, f0, false)) || + (f1 && n->buffer && ggml_vk_tensors_overlap(n, f1, false))) { + return false; + } + for (int s = 0; s < GGML_MAX_SRC; s++) { + const ggml_tensor * src = n->src[s]; + if (src && src->buffer && ggml_vk_tensors_overlap(src, dst_out, false)) { + return false; + } + } + } + return true; + }; + + const int hi = std::min(last_node, i + 32); + if (do_mmgate) { + for (int j = i + 1; j < hi; j++) { + if (!gen_skip.empty() && gen_skip[j]) { + continue; + } + const ggml_tensor * n = g->nodes[j]; + if (n->op == GGML_OP_UNARY && ggml_get_unary_op(n) == GGML_UNARY_OP_SIGMOID && same_bytes_of_mm(n->src[0])) { + // Do not steal UNARY(SIGMOID) from a 12-op TOPK_MOE_SIGMOID_NORM_BIAS(_EPS) router subgraph! + if (ggml_can_fuse_subgraph(g, j, topk_moe_sigmoid_norm_bias, { j + 4, j + 10 }) || + ggml_can_fuse_subgraph(g, j, topk_moe_sigmoid_norm_bias_eps, { j + 4, j + 10 })) { + break; + } + const int skips[3] = { j, -1, -1 }; + const ggml_tensor * elided[4] = { mm, n->src[0], nullptr, nullptr }; + if (check_valid(n, nullptr, nullptr, j, skips, elided)) { + out = { n, nullptr, nullptr, MAT_VEC_FUSION_FLAGS_SIGMOID, { j, -1, -1 }, "GEN_MUL_MAT_SIGMOID" }; + return true; + } + break; + } + if (n->op == GGML_OP_ADD && j + 2 < last_node && (same_bytes_of_mm(n->src[0]) || same_bytes_of_mm(n->src[1]))) { + const ggml_tensor * view_t = same_bytes_of_mm(n->src[0]) ? n->src[0] : n->src[1]; + const ggml_tensor * dt = same_bytes_of_mm(n->src[0]) ? n->src[1] : n->src[0]; + const ggml_tensor * sp = g->nodes[j + 1]; + const ggml_tensor * mul = g->nodes[j + 2]; + const ggml_tensor * a_w = (mul->op == GGML_OP_MUL) ? (mul->src[0] == sp ? mul->src[1] : (mul->src[1] == sp ? mul->src[0] : nullptr)) : nullptr; + if (dt && a_w && dt->op == GGML_OP_NONE && a_w->op == GGML_OP_NONE && + dt->type == GGML_TYPE_F32 && a_w->type == GGML_TYPE_F32 && + ggml_is_contiguous(dt) && ggml_is_contiguous(a_w) && + dt->ne[0] == mm->ne[0] && ggml_nrows(dt) == 1 && + a_w->ne[0] == mm->ne[0] && ggml_nrows(a_w) == 1 && + dt->buffer && a_w->buffer && + get_misalign_bytes(ctx, dt) == 0 && get_misalign_bytes(ctx, a_w) == 0 && + n->type == GGML_TYPE_F32 && ggml_is_contiguous(n) && + sp->op == GGML_OP_UNARY && ggml_get_unary_op(sp) == GGML_UNARY_OP_SOFTPLUS && sp->src[0] == n && + sp->type == GGML_TYPE_F32 && ggml_is_contiguous(sp)) { + const int skips[3] = { j, j + 1, j + 2 }; + const ggml_tensor * elided[4] = { mm, view_t, n, sp }; + if (check_valid(mul, dt, a_w, j + 2, skips, elided)) { + out = { mul, dt, a_w, MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE, { j, j + 1, j + 2 }, "GEN_MUL_MAT_SOFTPLUS_GATE" }; + return true; + } + } + break; + } + } + } + if (do_shexp) { + for (int j = i + 1; j < hi; j++) { + if (!gen_skip.empty() && gen_skip[j]) { + continue; + } + const ggml_tensor * mul = g->nodes[j]; + if (mul->op == GGML_OP_MUL && (mul->src[0] == mm || mul->src[1] == mm)) { + const ggml_tensor * gate = (mul->src[0] == mm) ? mul->src[1] : mul->src[0]; + bool gate_ready = gate && gate->op == GGML_OP_NONE; + if (gate && !gate_ready) { + const int32_t gfirst = use_idx.first_node_idx(gate); + if (gfirst >= 0 && gfirst < i) { + gate_ready = true; + } + if (!gate_ready && !gen_skip.empty()) { + for (int k = i + 1; k < j; k++) { + if (g->nodes[k] == gate && gen_skip[k]) { + gate_ready = true; + break; + } + } + } + } + if (gate_ready && gate != mm && gate->type == GGML_TYPE_F32 && ggml_is_contiguous(gate) && + gate->ne[0] == 1 && gate->ne[1] == mm->ne[1] && gate->ne[2] == 1 && gate->ne[3] == 1 && + gate->buffer && get_misalign_bytes(ctx, gate) == 0 && + ggml_are_same_shape(mul, mm) && ggml_are_same_stride(mul, mm)) { + const int skips[3] = { j, -1, -1 }; + const ggml_tensor * elided[4] = { mm, nullptr, nullptr, nullptr }; + if (check_valid(mul, gate, nullptr, j, skips, elided)) { + out = { mul, gate, nullptr, MAT_VEC_FUSION_FLAGS_ROW_SCALE0, { j, -1, -1 }, "GEN_MUL_MAT_ROW_SCALE0" }; + return true; + } + } + break; + } + } + } + return false; +} + +static int gen_find_mm_deferred_scale0(const ggml_backend_vk_context * ctx, const ggml_cgraph * g, int i, int last_node, + const vk_cgraph_use_index & use_idx) { + if (!gen_fuse_enabled("shexp")) { + return -1; + } + const ggml_tensor * mm = g->nodes[i]; + if ((!gen_uses_dmmv_noswap(ctx, mm) && !gen_uses_cm1_fused_mm(ctx, mm)) || !ggml_is_contiguous(mm) || !mm->buffer || + get_misalign_bytes(ctx, mm) != 0 || (mm->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return -1; + } + int mul_idx = -1; + for (int j = i + 1; j < std::min(last_node, i + 8); j++) { + const ggml_tensor * n = g->nodes[j]; + if (n->op == GGML_OP_MUL && (n->src[0] == mm || n->src[1] == mm)) { + mul_idx = j; + break; + } + } + if (mul_idx < 0) { + return -1; + } + const ggml_tensor * mul = g->nodes[mul_idx]; + const ggml_tensor * gate = (mul->src[0] == mm) ? mul->src[1] : mul->src[0]; + if (!gate || gate == mm || gate->type != GGML_TYPE_F32 || !ggml_is_contiguous(gate) || + gate->ne[0] != 1 || gate->ne[1] != mm->ne[1] || gate->ne[2] != 1 || gate->ne[3] != 1 || + !gate->buffer || get_misalign_bytes(ctx, gate) != 0 || + mul->type != GGML_TYPE_F32 || !ggml_is_contiguous(mul) || !mul->buffer || get_misalign_bytes(ctx, mul) != 0 || + !ggml_are_same_shape(mul, mm) || !ggml_are_same_stride(mul, mm)) { + return -1; + } + if (use_idx.any_reader(mm, [&](int k) { return k != mul_idx; })) { + return -1; + } + if (ggml_vk_tensors_overlap(mm->src[0], mul, false) || + ggml_vk_tensors_overlap(mm->src[1], mul, false) || + ggml_vk_tensors_overlap(gate, mul, false)) { + return -1; + } + for (int k = i + 1; k < mul_idx; k++) { + const ggml_tensor * n = g->nodes[k]; + if (!ggml_op_is_empty(n->op) && n->buffer) { + if ((mm->src[0]->buffer && ggml_vk_tensors_overlap(n, mm->src[0], false)) || + (mm->src[1]->buffer && ggml_vk_tensors_overlap(n, mm->src[1], false))) { + return -1; + } + } + } + return mul_idx; +} + +static bool s10_fuse_disabled() { + static const bool v = getenv("GGML_VK_DISABLE_S10_FUSE") != nullptr && atoi(getenv("GGML_VK_DISABLE_S10_FUSE")) != 0; + return v; +} + +static bool s10_pair_gdn_disabled() { + static const bool v = getenv("GGML_VK_DISABLE_S10_PAIR_GDN") != nullptr && atoi(getenv("GGML_VK_DISABLE_S10_PAIR_GDN")) != 0; + return s10_fuse_disabled() || v; +} + +static bool s10_ssm_conv_disabled() { + static const bool v = getenv("GGML_VK_DISABLE_S10_SSM_CONV") != nullptr && atoi(getenv("GGML_VK_DISABLE_S10_SSM_CONV")) != 0; + return s10_fuse_disabled() || v; +} + +static bool s10_add_rms_disabled() { + static const bool v = getenv("GGML_VK_DISABLE_S10_ADD_RMS") != nullptr && atoi(getenv("GGML_VK_DISABLE_S10_ADD_RMS")) != 0; + return s10_fuse_disabled() || v; +} + +static int gen_can_fuse_pair_mm(ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int i, int last_node, + const std::vector & gen_skip, const vk_cgraph_use_index & use_idx) { + ctx->gen_pair_mul0_rel = 0; + if (!gen_fuse_enabled("pairmm") || i + 1 >= cgraph->n_nodes) { + return 0; + } + if (!gen_skip.empty() && gen_skip[i]) { + return 0; + } + ggml_tensor * mm0 = cgraph->nodes[i]; + if (mm0->op != GGML_OP_MUL_MAT || (mm0->ne[0] & 7) != 0) { + return 0; + } + const bool mm0_dmmv = gen_uses_dmmv_noswap(ctx, mm0); + const bool mm0_cm1 = !mm0_dmmv && mm0->ne[1] > 1 && mm0->ne[2] == 1 && mm0->ne[3] == 1 && + mm0->src[1] && mm0->src[1]->ne[2] * mm0->src[1]->ne[3] == 1 && + (mm0->ne[0] % 128 == 0) && gen_uses_cm1_fused_mm(ctx, mm0); + if (!mm0_dmmv && !mm0_cm1) { + return 0; + } + const ggml_tensor * w0 = mm0->src[0]; + if (!gen_supports_pair_type(w0->type) || (w0->ne[0] & 3) != 0 || w0->ne[2] != 1 || w0->ne[3] != 1 || + !ggml_is_contiguous(w0) || !w0->buffer || get_misalign_bytes(ctx, w0) != 0 || + !mm0->src[1]->buffer || get_misalign_bytes(ctx, mm0->src[1]) != 0 || + !mm0->buffer || !ggml_is_contiguous(mm0) || get_misalign_bytes(ctx, mm0) != 0) { + return 0; + } + + auto is_zero_offs_contig_view = [](const ggml_tensor * v, const ggml_tensor * base) -> bool { + return v && (v->op == GGML_OP_RESHAPE || v->op == GGML_OP_VIEW) && + v->view_src == base && v->view_offs == 0 && v->type == GGML_TYPE_F32 && + ggml_is_contiguous(v) && ggml_nbytes(v) == ggml_nbytes(base); + }; + + // S10.3: 6/7/8-node GDN [mm0, [reshape0], add(dt), softplus, mul(a_w), mm1, [reshape1], sigmoid] + if (mm0_dmmv && !s10_pair_gdn_disabled() && gen_fuse_enabled("mmgate") && i + 5 < cgraph->n_nodes && !(mm0->flags & GGML_TENSOR_FLAG_OUTPUT)) { + int pos = i + 1; + const ggml_tensor * view0 = mm0; + if (pos < cgraph->n_nodes && is_zero_offs_contig_view(cgraph->nodes[pos], mm0)) { + view0 = cgraph->nodes[pos]; + pos++; + } + if (pos + 4 < cgraph->n_nodes) { + ggml_tensor * add0 = cgraph->nodes[pos]; + ggml_tensor * sp0 = cgraph->nodes[pos + 1]; + ggml_tensor * mul0 = cgraph->nodes[pos + 2]; + ggml_tensor * mm1 = cgraph->nodes[pos + 3]; + const int mul0_idx = pos + 2; + const int mm1_idx = pos + 3; + int pos1 = mm1_idx + 1; + const ggml_tensor * view1 = mm1; + if (pos1 < cgraph->n_nodes && is_zero_offs_contig_view(cgraph->nodes[pos1], mm1)) { + view1 = cgraph->nodes[pos1]; + pos1++; + } + if (pos1 < cgraph->n_nodes && + add0->op == GGML_OP_ADD && (add0->src[0] == view0 || add0->src[1] == view0) && + sp0->op == GGML_OP_UNARY && ggml_get_unary_op(sp0) == GGML_UNARY_OP_SOFTPLUS && sp0->src[0] == add0 && + mul0->op == GGML_OP_MUL && (mul0->src[0] == sp0 || mul0->src[1] == sp0) && + mm1->op == GGML_OP_MUL_MAT && mm1 != mm0 && mm1->src[1] == mm0->src[1] && + mm0->ne[1] == mm1->ne[1] && gen_uses_dmmv_noswap(ctx, mm1)) { + ggml_tensor * sig1 = cgraph->nodes[pos1]; + const int sig1_idx = pos1; + const ggml_tensor * w1 = mm1->src[0]; + const ggml_tensor * dt = (add0->src[0] == view0) ? add0->src[1] : add0->src[0]; + const ggml_tensor * a_w = (mul0->src[0] == sp0) ? mul0->src[1] : mul0->src[0]; + bool any_skip = false; + if (!gen_skip.empty()) { + for (int k = i; k <= sig1_idx; ++k) { + any_skip = any_skip || (gen_skip[k] != 0); + } + } + if (!any_skip && + w1->type == w0->type && ggml_vk_tensor_is_repack(w1) == ggml_vk_tensor_is_repack(w0) && + w1->ne[0] == w0->ne[0] && w1->ne[2] == 1 && w1->ne[3] == 1 && + ggml_is_contiguous(w1) && w1->buffer && get_misalign_bytes(ctx, w1) == 0 && + dt && a_w && dt->op == GGML_OP_NONE && a_w->op == GGML_OP_NONE && + dt->type == GGML_TYPE_F32 && a_w->type == GGML_TYPE_F32 && + ggml_is_contiguous(dt) && ggml_is_contiguous(a_w) && + dt->ne[0] == mm0->ne[0] && ggml_nrows(dt) == 1 && + a_w->ne[0] == mm0->ne[0] && ggml_nrows(a_w) == 1 && + dt->buffer && a_w->buffer && get_misalign_bytes(ctx, dt) == 0 && get_misalign_bytes(ctx, a_w) == 0 && + add0->type == GGML_TYPE_F32 && ggml_is_contiguous(add0) && + sp0->type == GGML_TYPE_F32 && ggml_is_contiguous(sp0) && + mul0->type == GGML_TYPE_F32 && ggml_is_contiguous(mul0) && ggml_nbytes(mul0) == ggml_nbytes(mm0) && + mul0->buffer && get_misalign_bytes(ctx, mul0) == 0 && + mm1->type == GGML_TYPE_F32 && ggml_is_contiguous(mm1) && !(mm1->flags & GGML_TENSOR_FLAG_OUTPUT) && + sig1->op == GGML_OP_UNARY && ggml_get_unary_op(sig1) == GGML_UNARY_OP_SIGMOID && + sig1->src[0] == view1 && sig1->type == GGML_TYPE_F32 && + ggml_is_contiguous(sig1) && ggml_nbytes(sig1) == ggml_nbytes(mm1) && + sig1->buffer && get_misalign_bytes(ctx, sig1) == 0) { + const ggml_tensor * elided[6] = { + mm0, (view0 != mm0 ? view0 : nullptr), add0, sp0, mm1, (view1 != mm1 ? view1 : nullptr) + }; + bool elided_ok = true; + for (const ggml_tensor * e : elided) { + if (!e) { + continue; + } + if ((e->flags & GGML_TENSOR_FLAG_OUTPUT) || + use_idx.any_reader(e, [&](int k) { + return (k < i || k > sig1_idx) && !ggml_op_is_empty(cgraph->nodes[k]->op); + })) { + elided_ok = false; + break; + } + } + const ggml_tensor * inputs[5] = { w0, mm0->src[1], w1, dt, a_w }; + for (const ggml_tensor * inp : inputs) { + if (ggml_vk_tensors_overlap(inp, mul0, false) || ggml_vk_tensors_overlap(inp, sig1, false)) { + elided_ok = false; + } + } + if (ggml_vk_tensors_overlap(mul0, sig1, false)) { + elided_ok = false; + } + if (elided_ok) { + ctx->gen_pair_mm1 = mm1; + ctx->gen_pair_dst1 = sig1; + ctx->gen_mm_dst = mul0; + ctx->gen_mm_f0 = dt; + ctx->gen_mm_f1 = a_w; + ctx->gen_mm_flags = MAT_VEC_FUSION_FLAGS_PAIR_MM | MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE | MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1; + ctx->gen_pair_mul0_rel = mul0_idx - i; + return sig1_idx - i; + } + } + } + } + } + + if (!gen_skip.empty() && gen_skip[i + 1]) { + return 0; + } + ggml_tensor * mm1 = cgraph->nodes[i + 1]; + if (mm1->op != GGML_OP_MUL_MAT || mm0 == mm1 || mm0->src[1] != mm1->src[1] || + mm0->ne[1] != mm1->ne[1]) { + return 0; + } + static const bool unfuse_pair_mm1 = getenv("GGML_VK_UNFUSE_PAIR_MM1") != nullptr; + static const bool disable_unfuse_dmmv_mm1 = getenv("GGML_VK_DISABLE_UNFUSE_DMMV_MM1") != nullptr; + if (!mm0_dmmv && unfuse_pair_mm1 && mm1->ne[0] == 1 && mm0->ne[0] >= 64 && (mm0->ne[0] % 64 == 0) && mm0->ne[1] > 32) { + return 0; + } + if (mm0_dmmv && !disable_unfuse_dmmv_mm1 && ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled() && + mm1->ne[0] == 1 && mm0->ne[0] >= 64 && (mm0->ne[0] % 64 == 0) && mm0->ne[1] >= 64) { + return 0; + } + const bool pair_path_ok = mm0_dmmv + ? gen_uses_dmmv_noswap(ctx, mm1) + : (mm1->ne[2] == 1 && mm1->ne[3] == 1 && + mm1->src[0] && ggml_nbytes(mm1->src[0]) <= ctx->device->properties.limits.maxStorageBufferRange && + gen_uses_cm1_fused_mm(ctx, mm1)); + if (!pair_path_ok) { + return 0; + } + const ggml_tensor * w1 = mm1->src[0]; + if (w0->type != w1->type || ggml_vk_tensor_is_repack(w0) != ggml_vk_tensor_is_repack(w1) || + w0->ne[0] != w1->ne[0] || w1->ne[2] != 1 || w1->ne[3] != 1 || + !ggml_is_contiguous(w1) || !w1->buffer || get_misalign_bytes(ctx, w1) != 0) { + return 0; + } + // Check 3/4-node [mm0, mm1, [reshape1], sigmoid(mm1)] first (e.g. [ffn_gate_inp, ffn_gate_inp_shexp, sigmoid]) + gen_mm_epilogue tmp_ep {}; + if (gen_find_mm_epilogue(ctx, cgraph, i, last_node, gen_skip, use_idx, tmp_ep) || + gen_find_mm_deferred_scale0(ctx, cgraph, i, last_node, use_idx) >= 0) { + return 0; + } + if (i + 2 < cgraph->n_nodes && !getenv("GGML_VK_DISABLE_PAIR_MM_SIGMOID") && !(mm1->flags & GGML_TENSOR_FLAG_OUTPUT)) { + int s_pos = i + 2; + const ggml_tensor * view1 = mm1; + if (s_pos + 1 < cgraph->n_nodes && is_zero_offs_contig_view(cgraph->nodes[s_pos], mm1)) { + view1 = cgraph->nodes[s_pos]; + s_pos++; + } + if (s_pos < cgraph->n_nodes && + (gen_skip.empty() || (!gen_skip[i + 2] && !gen_skip[s_pos]))) { + ggml_tensor * sig1 = cgraph->nodes[s_pos]; + if (sig1->op == GGML_OP_UNARY && ggml_get_unary_op(sig1) == GGML_UNARY_OP_SIGMOID && + sig1->src[0] == view1 && sig1->type == GGML_TYPE_F32 && + ggml_nbytes(sig1) == ggml_nbytes(mm1) && ggml_is_contiguous(sig1) && + sig1->buffer && get_misalign_bytes(ctx, sig1) == 0 && + !(view1 != mm1 && (view1->flags & GGML_TENSOR_FLAG_OUTPUT)) && + !ggml_vk_tensors_overlap(mm0, sig1, false) && + !ggml_vk_tensors_overlap(w0, sig1, false) && + !ggml_vk_tensors_overlap(w1, sig1, false) && + !ggml_vk_tensors_overlap(mm0->src[1], sig1, false)) { + auto out_of_span = [&](int k) { return (k < i || k > s_pos) && !ggml_op_is_empty(cgraph->nodes[k]->op); }; + const bool mm1_only_here = !use_idx.any_reader(mm1, out_of_span) && + !(view1 != mm1 && use_idx.any_reader(view1, out_of_span)); + if (mm1_only_here && + !ggml_vk_tensors_overlap(w0, mm0, false) && + !ggml_vk_tensors_overlap(w1, mm0, false) && + !ggml_vk_tensors_overlap(mm0->src[1], mm0, false)) { + ctx->gen_pair_mm1 = mm1; + ctx->gen_pair_dst1 = sig1; + ctx->gen_mm_flags = MAT_VEC_FUSION_FLAGS_PAIR_MM | MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1; + return s_pos - i; + } + } + } + } + // Protect downstream fusions on mm1 (glu, bias add, mmgate, shexp) + if (gen_can_fuse_mm_glu(ctx, cgraph, i + 1) || + ggml_vk_can_fuse(ctx, cgraph, i + 1, { GGML_OP_MUL_MAT, GGML_OP_ADD }) || + gen_find_mm_epilogue(ctx, cgraph, i + 1, last_node, gen_skip, use_idx, tmp_ep) || + gen_find_mm_deferred_scale0(ctx, cgraph, i + 1, last_node, use_idx) >= 0) { + return 0; + } + // In [Q, K, V] with matching types, leave Q standalone and let i + 1 pair [K, V] + if (i + 2 < cgraph->n_nodes) { + const ggml_tensor * mm2 = cgraph->nodes[i + 2]; + if (mm2->op == GGML_OP_MUL_MAT && mm2->src[1] == mm0->src[1] && + mm2->src[0]->type == w1->type && mm0->ne[0] > mm1->ne[0] && mm1->ne[0] == mm2->ne[0]) { + return 0; + } + } + if (!mm1->buffer || !ggml_is_contiguous(mm1) || get_misalign_bytes(ctx, mm1) != 0 || + !ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT }, { i, i + 1 }) || + ggml_vk_tensors_overlap(mm0, mm1, false)) { + return 0; + } + ctx->gen_pair_mm1 = mm1; + ctx->gen_pair_dst1 = mm1; + ctx->gen_mm_flags = MAT_VEC_FUSION_FLAGS_PAIR_MM; + return 1; +} + +static bool gen_lora_fuse_disabled() { + static const bool v = getenv("GGML_VK_DISABLE_LORA_FUSE") != nullptr && atoi(getenv("GGML_VK_DISABLE_LORA_FUSE")) != 0; + return v; +} + +struct vk_lora_tail_match { + ggml_tensor * mm {}; + const ggml_tensor * b {}; + const ggml_tensor * h {}; + ggml_tensor * lb {}; + ggml_tensor * ls {}; + ggml_tensor * add {}; + uint32_t r {}; + float scale {}; +}; + +static bool gen_match_lora_tail4(const ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int s, + const std::vector & gen_skip, vk_lora_tail_match & out) { + if (s < 0 || s + 3 >= cgraph->n_nodes) { + return false; + } + for (int t = 0; t < 4; ++t) { + if (!gen_skip.empty() && gen_skip[s + t]) { + return false; + } + } + ggml_tensor * mm = cgraph->nodes[s + 0]; + ggml_tensor * lb = cgraph->nodes[s + 1]; + ggml_tensor * ls = cgraph->nodes[s + 2]; + ggml_tensor * add = cgraph->nodes[s + 3]; + if (mm->op != GGML_OP_MUL_MAT || lb->op != GGML_OP_MUL_MAT || + ls->op != GGML_OP_SCALE || add->op != GGML_OP_ADD) { + return false; + } + if (!gen_uses_dmmv_noswap(ctx, mm)) { + return false; + } + const ggml_tensor * w = mm->src[0]; + const ggml_tensor * x = mm->src[1]; + const ggml_tensor * b = lb->src[0]; + const ggml_tensor * h = lb->src[1]; + if (!w || !x || !b || !h || b->op != GGML_OP_NONE || w->op != GGML_OP_NONE) { + return false; + } + if (!gen_supports_pair_type(w->type) || (w->ne[0] & 3) != 0 || w->ne[2] != 1 || w->ne[3] != 1 || + !ggml_is_contiguous(w) || !w->buffer || get_misalign_bytes(ctx, w) != 0 || + !x->buffer || get_misalign_bytes(ctx, x) != 0) { + return false; + } + const int64_t r = b->ne[0]; + if (r <= 0 || r > 64 || b->type != GGML_TYPE_F32 || h->type != GGML_TYPE_F32 || + b->ne[1] != mm->ne[0] || b->ne[2] != 1 || b->ne[3] != 1 || + h->ne[0] != r || h->ne[1] != mm->ne[1] || h->ne[2] != 1 || h->ne[3] != 1 || + !ggml_is_contiguous(b) || !ggml_is_contiguous(h) || + !b->buffer || !h->buffer || get_misalign_bytes(ctx, b) != 0 || get_misalign_bytes(ctx, h) != 0) { + return false; + } + if (ls->src[0] != lb || ggml_get_op_params_f32(ls, 1) != 0.0f) { + return false; + } + if (!((add->src[0] == mm && add->src[1] == ls) || (add->src[0] == ls && add->src[1] == mm))) { + return false; + } + if (mm->type != GGML_TYPE_F32 || lb->type != GGML_TYPE_F32 || ls->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32 || + !ggml_are_same_shape(mm, lb) || !ggml_are_same_shape(mm, ls) || !ggml_are_same_shape(mm, add) || + !ggml_are_same_stride(mm, add) || !ggml_is_contiguous(mm) || !ggml_is_contiguous(add) || + !add->buffer || get_misalign_bytes(ctx, add) != 0) { + return false; + } + out = { mm, b, h, lb, ls, add, (uint32_t)r, ggml_get_op_params_f32(ls, 0) }; + return true; +} + +static int gen_can_fuse_lora(ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int i, + const std::vector & gen_skip, const vk_cgraph_use_index & use_idx, + const char *& out_fusion_name, bool * op_srcs_fused_elementwise) { + if (gen_lora_fuse_disabled() || !ggml_vk_is_apple_agx_coopmat(ctx->device) || ggml_vk_exact_s8_enabled()) { + return 0; + } + vk_lora_tail_match t0 {}; + if (!gen_match_lora_tail4(ctx, cgraph, i, gen_skip, t0)) { + return 0; + } + + auto elided_ok_in = [&](const ggml_tensor * const * elided, int n_elided, int end_idx) -> bool { + for (int idx = 0; idx < n_elided; ++idx) { + const ggml_tensor * e = elided[idx]; + if (!e) { continue; } + if ((e->flags & GGML_TENSOR_FLAG_OUTPUT) || + use_idx.any_reader(e, [&](int k) { + return (k < i || k > end_idx) && !ggml_op_is_empty(cgraph->nodes[k]->op); + })) { + return false; + } + } + return true; + }; + + auto h_outside_span = [&](const ggml_tensor * h, int end_idx) -> bool { + for (int k = i; k <= end_idx; ++k) { + if (cgraph->nodes[k] == h) { + return false; + } + } + return true; + }; + + // Check paired [tail0, tail1, [GLU]] + vk_lora_tail_match t1 {}; + if (gen_match_lora_tail4(ctx, cgraph, i + 4, gen_skip, t1) && + t0.mm != t1.mm && t0.mm->src[1] == t1.mm->src[1] && + t0.mm->ne[1] == t1.mm->ne[1] && t0.r == t1.r && + t0.mm->src[0]->type == t1.mm->src[0]->type && + ggml_vk_tensor_is_repack(t0.mm->src[0]) == ggml_vk_tensor_is_repack(t1.mm->src[0]) && + t0.mm->src[0]->ne[0] == t1.mm->src[0]->ne[0]) { + + // 1. 9-node [tail0, tail1, SWIGLU] -> GEN_MUL_MAT_GATE_UP_GLU + LORA0|LORA1 + if (gen_fuse_enabled("gateup") && i + 8 < cgraph->n_nodes && (gen_skip.empty() || !gen_skip[i + 8])) { + ggml_tensor * glu = cgraph->nodes[i + 8]; + if (glu->op == GGML_OP_GLU && ggml_get_glu_op(glu) == GGML_GLU_OP_SWIGLU && + glu->src[1] != nullptr && ggml_get_op_params_i32(glu, 1) == 0 && + ((glu->src[0] == t0.add && glu->src[1] == t1.add) || (glu->src[0] == t1.add && glu->src[1] == t0.add)) && + ggml_are_same_shape(t0.mm->src[0], t1.mm->src[0]) && + ggml_are_same_stride(t0.mm->src[0], t1.mm->src[0]) && + glu->type == GGML_TYPE_F32 && ggml_are_same_shape(t0.mm, glu) && + ggml_are_same_stride(t0.mm, glu) && ggml_is_contiguous(glu) && + glu->buffer && get_misalign_bytes(ctx, glu) == 0 && + h_outside_span(t0.h, i + 8) && h_outside_span(t1.h, i + 8)) { + const ggml_tensor * elided[8] = { t0.mm, t0.lb, t0.ls, t0.add, t1.mm, t1.lb, t1.ls, t1.add }; + const ggml_tensor * inps[7] = { t0.mm->src[0], t1.mm->src[0], t0.mm->src[1], t0.b, t0.h, t1.b, t1.h }; + bool ov_ok = elided_ok_in(elided, 8, i + 8); + for (const ggml_tensor * inp : inps) { + if (ggml_vk_tensors_overlap(inp, glu, false)) { ov_ok = false; } + } + if (ov_ok) { + const bool t0_is_gate = (glu->src[0] == t0.add); + const vk_lora_tail_match & tg = t0_is_gate ? t0 : t1; + const vk_lora_tail_match & tu = t0_is_gate ? t1 : t0; + ctx->gen_lora_gate_src0 = tg.mm->src[0]; + ctx->gen_lora_up_src0 = tu.mm->src[0]; + ctx->gen_lora_b0 = tg.b; + ctx->gen_lora_h0 = tg.h; + ctx->gen_lora_scale0 = tg.scale; + ctx->gen_lora_b1 = tu.b; + ctx->gen_lora_h1 = tu.h; + ctx->gen_lora_scale1 = tu.scale; + ctx->gen_lora_r = tg.r; + std::fill_n(op_srcs_fused_elementwise, 9, false); + op_srcs_fused_elementwise[8] = true; + out_fusion_name = "GEN_LORA_GATE_UP_GLU"; + return 8; + } + } + } + + // 2. 8-node [tail0, tail1] -> GEN_PAIR_MM + LORA0|LORA1 (provided tail1 doesn't feed an immediate ADD/GLU) + const bool t1_has_res_add = (i + 8 < cgraph->n_nodes) && + cgraph->nodes[i + 8]->op == GGML_OP_ADD && + (cgraph->nodes[i + 8]->src[0] == t1.add || cgraph->nodes[i + 8]->src[1] == t1.add); + const bool t0_has_res_add = cgraph->nodes[i + 4]->op == GGML_OP_ADD && + (cgraph->nodes[i + 4]->src[0] == t0.add || cgraph->nodes[i + 4]->src[1] == t0.add); + if (gen_fuse_enabled("pairmm") && !t0_has_res_add && !t1_has_res_add && + (t0.mm->ne[0] & 7) == 0 && + h_outside_span(t0.h, i + 7) && h_outside_span(t1.h, i + 7)) { + const ggml_tensor * elided[6] = { t0.mm, t0.lb, t0.ls, t1.mm, t1.lb, t1.ls }; + const ggml_tensor * inps[7] = { t0.mm->src[0], t1.mm->src[0], t0.mm->src[1], t0.b, t0.h, t1.b, t1.h }; + bool ov_ok = elided_ok_in(elided, 6, i + 7) && !ggml_vk_tensors_overlap(t0.add, t1.add, false); + for (const ggml_tensor * inp : inps) { + if (ggml_vk_tensors_overlap(inp, t0.add, false) || ggml_vk_tensors_overlap(inp, t1.add, false)) { + ov_ok = false; + } + } + if (ov_ok) { + ctx->gen_mm_dst = t0.add; + ctx->gen_pair_mm1 = t1.mm; + ctx->gen_pair_dst1 = t1.add; + ctx->gen_mm_flags = MAT_VEC_FUSION_FLAGS_PAIR_MM; + ctx->gen_pair_mul0_rel = 3; + ctx->fused_ops_write_mask |= (1u << 3); + ctx->gen_lora_b0 = t0.b; + ctx->gen_lora_h0 = t0.h; + ctx->gen_lora_scale0 = t0.scale; + ctx->gen_lora_b1 = t1.b; + ctx->gen_lora_h1 = t1.h; + ctx->gen_lora_scale1 = t1.scale; + ctx->gen_lora_r = t0.r; + std::fill_n(op_srcs_fused_elementwise, 8, false); + out_fusion_name = "GEN_LORA_PAIR_MM"; + return 7; + } + } + } + + // 3. 5-node [tail0, ADD(t0.add, residual)] -> MUL_MAT_ADD + LORA0 + if (i + 4 < cgraph->n_nodes && (gen_skip.empty() || !gen_skip[i + 4])) { + ggml_tensor * radd = cgraph->nodes[i + 4]; + if (radd->op == GGML_OP_ADD && (radd->src[0] == t0.add || radd->src[1] == t0.add)) { + const ggml_tensor * bias = (radd->src[0] == t0.add) ? radd->src[1] : radd->src[0]; + if (bias && bias != t0.add && bias->type == GGML_TYPE_F32 && radd->type == GGML_TYPE_F32 && + ggml_are_same_shape(t0.add, bias) && ggml_are_same_stride(t0.add, bias) && + ggml_are_same_shape(t0.add, radd) && ggml_are_same_stride(t0.add, radd) && + ggml_is_contiguous(bias) && ggml_is_contiguous(radd) && + bias->buffer && radd->buffer && + get_misalign_bytes(ctx, bias) == 0 && get_misalign_bytes(ctx, radd) == 0 && + h_outside_span(t0.h, i + 4) && h_outside_span(bias, i + 4)) { + const ggml_tensor * elided[4] = { t0.mm, t0.lb, t0.ls, t0.add }; + const ggml_tensor * inps[4] = { t0.mm->src[0], t0.mm->src[1], t0.b, t0.h }; + bool ov_ok = elided_ok_in(elided, 4, i + 4) && !ggml_vk_tensors_overlap(bias, radd, true); + for (const ggml_tensor * inp : inps) { + if (ggml_vk_tensors_overlap(inp, radd, false)) { ov_ok = false; } + } + if (ov_ok) { + ctx->gen_mm_dst = radd; + ctx->gen_mm_f0 = bias; + ctx->gen_mm_flags = MAT_VEC_FUSION_FLAGS_BIAS0; + ctx->gen_lora_b0 = t0.b; + ctx->gen_lora_h0 = t0.h; + ctx->gen_lora_scale0 = t0.scale; + ctx->gen_lora_r = t0.r; + std::fill_n(op_srcs_fused_elementwise, 4, false); + op_srcs_fused_elementwise[4] = true; + out_fusion_name = "GEN_LORA_MUL_MAT_ADD"; + return 4; + } + } + } + } + + // 4. 4-node [tail0] -> MUL_MAT + LORA0 + if (h_outside_span(t0.h, i + 3)) { + const ggml_tensor * elided[3] = { t0.mm, t0.lb, t0.ls }; + const ggml_tensor * inps[4] = { t0.mm->src[0], t0.mm->src[1], t0.b, t0.h }; + bool ov_ok = elided_ok_in(elided, 3, i + 3); + for (const ggml_tensor * inp : inps) { + if (ggml_vk_tensors_overlap(inp, t0.add, false)) { ov_ok = false; } + } + if (ov_ok) { + ctx->gen_mm_dst = t0.add; + ctx->gen_mm_flags = 0; + ctx->gen_lora_b0 = t0.b; + ctx->gen_lora_h0 = t0.h; + ctx->gen_lora_scale0 = t0.scale; + ctx->gen_lora_r = t0.r; + std::fill_n(op_srcs_fused_elementwise, 4, false); + out_fusion_name = "GEN_LORA_MUL_MAT"; + return 3; + } + } + + return 0; +} + +// gen (GGML_GEN_FUSE=gate): RMS_NORM, MUL(weight), [RESHAPE/VIEW(z)], UNARY silu(z), MUL(that, silu) in 4 or 5 consecutive nodes, +// z contiguous with dst's shape, all f32; the rms rows contiguous (as RMS_NORM_MUL requires) +static int gen_can_fuse_rms_mul_silu(const ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int i) { + if (!gen_fuse_enabled("gate") || i + 3 >= cgraph->n_nodes || ctx->do_add_rms_partials) { + return 0; + } + const ggml_tensor * rms = cgraph->nodes[i], * mul = cgraph->nodes[i + 1]; + if (rms->op != GGML_OP_RMS_NORM || mul->op != GGML_OP_MUL) { + return 0; + } + int silu_off = 2; + const ggml_tensor * maybe_view = cgraph->nodes[i + 2]; + if ((maybe_view->op == GGML_OP_RESHAPE || maybe_view->op == GGML_OP_VIEW) && i + 4 < cgraph->n_nodes) { + silu_off = 3; + } + const ggml_tensor * silu = cgraph->nodes[i + silu_off]; + const ggml_tensor * out = cgraph->nodes[i + silu_off + 1]; + if (silu->op != GGML_OP_UNARY || out->op != GGML_OP_MUL || ggml_get_unary_op(silu) != GGML_UNARY_OP_SILU) { + return 0; + } + if (silu_off == 3 && silu->src[0] != maybe_view) { + return 0; + } + if (!((out->src[0] == mul && out->src[1] == silu) || (out->src[0] == silu && out->src[1] == mul))) { + return 0; + } + if (mul->src[0] != rms && mul->src[1] != rms) { + return 0; + } + const ggml_tensor * w = mul->src[0] == rms ? mul->src[1] : mul->src[0]; + const ggml_tensor * z = silu->src[0]; + const ggml_tensor * gen_ts[6] = { rms->src[0], w, z, mul, silu, out }; + for (const ggml_tensor * t : gen_ts) { + if (t->type != GGML_TYPE_F32) { + return 0; + } + } + if (!ggml_are_same_shape(mul, rms) || !ggml_are_same_shape(out, mul) || !ggml_are_same_shape(z, out) || + !ggml_is_contiguous(z) || !ggml_is_contiguous(out) || !ggml_is_contiguous_rows(rms->src[0]) || + !ggml_is_contiguous_rows(w) || w->ne[0] != rms->ne[0] || get_misalign_bytes(ctx, z) != 0) { + return 0; + } + if (mul->src[1] == rms && !ggml_are_same_shape(mul->src[0], rms)) { + return 0; + } + if (silu_off == 3) { + const int outs[1] = { i + 4 }; + const int idxs[5] = { i, i + 1, i + 2, i + 3, i + 4 }; + const ggml_op ops[5] = { GGML_OP_RMS_NORM, GGML_OP_MUL, maybe_view->op, GGML_OP_UNARY, GGML_OP_MUL }; + return ggml_can_fuse_subgraph_ext(cgraph, idxs, 5, ops, outs, 1) ? 4 : 0; + } + const int outs[1] = { i + 3 }; + const int idxs[4] = { i, i + 1, i + 2, i + 3 }; + const ggml_op ops[4] = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_UNARY, GGML_OP_MUL }; + return ggml_can_fuse_subgraph_ext(cgraph, idxs, 4, ops, outs, 1) ? 3 : 0; +} + +// gen (GGML_GEN_FUSE=s8): CONT(gate_view), [empty view(s)], UNARY, MUL(other, unary) -> single strided unary_mul dispatch +static int gen_can_fuse_cont_unary_mul(const ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int i) { + GGML_UNUSED(ctx); + if (!gen_fuse_enabled("s8") || i + 2 >= cgraph->n_nodes) { + return 0; + } + const ggml_tensor * cont = cgraph->nodes[i]; + if (cont->op != GGML_OP_CONT) { + return 0; + } + const ggml_tensor * gate_view = cont->src[0]; + if (!gate_view || (gate_view->type != GGML_TYPE_F32 && gate_view->type != GGML_TYPE_F16) || + cont->type != gate_view->type || !ggml_is_contiguous_1(gate_view) || !gate_view->buffer) { + return 0; + } + const size_t ts = ggml_type_size(gate_view->type); + for (int d = 0; d < GGML_MAX_DIMS; ++d) { + if (gate_view->nb[d] % ts != 0) { + return 0; + } + } + int u_off = 1; + while (u_off <= 2 && i + u_off + 1 < cgraph->n_nodes && ggml_op_is_empty(cgraph->nodes[i + u_off]->op) && + cgraph->nodes[i + u_off]->op != GGML_OP_NONE) { + u_off++; + } + if (i + u_off + 1 >= cgraph->n_nodes) { + return 0; + } + const ggml_tensor * unary = cgraph->nodes[i + u_off]; + const ggml_tensor * mul = cgraph->nodes[i + u_off + 1]; + if (unary->op != GGML_OP_UNARY || mul->op != GGML_OP_MUL) { + return 0; + } + if (ggml_vk_unary_mul_op_index(ggml_get_unary_op(unary)) < 0) { + return 0; + } + const bool unary_reads_cont = unary->src[0] == cont || + ((unary->src[0]->op == GGML_OP_RESHAPE || unary->src[0]->op == GGML_OP_VIEW) && + unary->src[0]->view_src == cont && unary->src[0]->view_offs == 0 && + ggml_is_contiguous(unary->src[0]) && ggml_nelements(unary->src[0]) == ggml_nelements(cont)); + if (!unary_reads_cont || (mul->src[0] != unary && mul->src[1] != unary)) { + return 0; + } + const ggml_tensor * other = (mul->src[0] == unary) ? mul->src[1] : mul->src[0]; + if (!other || !other->buffer || !mul->buffer || + unary->type != gate_view->type || other->type != gate_view->type || mul->type != gate_view->type || + !ggml_is_contiguous(cont) || !ggml_is_contiguous(other) || !ggml_is_contiguous(mul) || + ggml_nelements(cont) != ggml_nelements(gate_view) || + ggml_nelements(other) != ggml_nelements(gate_view) || + ggml_nelements(mul) != ggml_nelements(gate_view)) { + return 0; + } + int idxs[5]; + ggml_op ops[5]; + const int n_nodes = u_off + 2; + for (int k = 0; k < n_nodes; ++k) { + idxs[k] = i + k; + ops[k] = cgraph->nodes[i + k]->op; + } + const int outs[1] = { i + n_nodes - 1 }; + return ggml_can_fuse_subgraph_ext(cgraph, idxs, n_nodes, ops, outs, 1) ? (n_nodes - 1) : 0; +} + +// gen (GGML_GEN_FUSE=l2): the SCALE (bias 0) that is the only consumer of RMS_NORM node i, a few nodes later. +// The RMS_NORM is deferred and runs fused at the SCALE's position (its own output is never written). +static int gen_find_rms_norm_scale(const ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int i, int last_node, + const vk_cgraph_use_index & use_idx) { + if (!gen_fuse_enabled("l2") || ctx->do_add_rms_partials) { + return -1; + } + const ggml_tensor * rms = cgraph->nodes[i]; + if (rms->op != GGML_OP_RMS_NORM || rms->type != GGML_TYPE_F32 || rms->src[0]->type != GGML_TYPE_F32 || + (rms->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return -1; + } + int sc_idx = -1; + for (int j = i + 1; j < std::min(last_node, i + 24); j++) { + const ggml_tensor * n = cgraph->nodes[j]; + if (n->op == GGML_OP_SCALE && n->src[0] == rms) { + sc_idx = j; + break; + } + } + if (sc_idx < 0) { + return -1; + } + const ggml_tensor * sc = cgraph->nodes[sc_idx]; + if (sc->type != GGML_TYPE_F32 || ggml_get_op_params_f32(sc, 1) != 0.0f || !ggml_is_contiguous(sc) || + !ggml_are_same_shape(rms, sc) || !sc->buffer) { + return -1; + } + // rms_norm's output is elided: the scale must be its only reader + if (use_idx.any_reader(rms, [&](int k) { return k != sc_idx; })) { + return -1; + } + if (rms->src[0]->buffer && ggml_vk_tensors_overlap(rms->src[0], sc, true)) { + return -1; + } + // the fused kernel runs at the SCALE's position: nothing in between may write the RMS_NORM input + for (int k = i + 1; k < sc_idx; k++) { + const ggml_tensor * n = cgraph->nodes[k]; + if (!ggml_op_is_empty(n->op) && n->buffer && rms->src[0]->buffer && ggml_vk_tensors_overlap(n, rms->src[0], false)) { + return -1; + } + } + return sc_idx; +} + +// Series 10 (S10.3): +// Mode 1: CONCAT(old_state, qkv) -> VIEW -> CPY(state_out) -> SSM_CONV -> [UNARY(SILU)] (5 -> 1 dispatch) +// Mode 2: CPY(state_out) -> SSM_CONV -> [UNARY(SILU)] (3 -> 1 dispatch, when n_t > max_sliding_nt) +static int s10_can_fuse_ssm_conv(ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int i, + const std::vector & gen_skip, const vk_cgraph_use_index & use_idx) { + static const int max_sliding_nt = getenv("GGML_VK_SSM_SLIDING_MAX_NT") ? atoi(getenv("GGML_VK_SSM_SLIDING_MAX_NT")) : (ggml_vk_exact_s8_enabled() ? 32 : 65536); + if (s10_ssm_conv_disabled()) { + return 0; + } + const ggml_tensor * n0 = cgraph->nodes[i]; + + // Mode 1: CONCAT -> VIEW -> CPY -> SSM_CONV -> [SILU] + if (n0->op == GGML_OP_CONCAT && i + 3 < cgraph->n_nodes) { + const ggml_tensor * concat = n0; + const ggml_tensor * view = cgraph->nodes[i + 1]; + const ggml_tensor * cpy = cgraph->nodes[i + 2]; + const ggml_tensor * conv = cgraph->nodes[i + 3]; + if (view->op != GGML_OP_VIEW || cpy->op != GGML_OP_CPY || conv->op != GGML_OP_SSM_CONV) { + return 0; + } + if (!gen_skip.empty() && (gen_skip[i] || gen_skip[i + 1] || gen_skip[i + 2] || gen_skip[i + 3])) { + return 0; + } + if (ggml_get_op_params_i32(concat, 0) != 0 || conv->src[0] != concat || + concat->type != GGML_TYPE_F32 || conv->type != GGML_TYPE_F32 || + !ggml_is_contiguous(concat) || !ggml_is_contiguous(conv) || + !conv->buffer || get_misalign_bytes(ctx, conv) != 0) { + return 0; + } + const ggml_tensor * c_w = conv->src[1]; + if (!c_w || c_w->type != GGML_TYPE_F32 || !ggml_is_contiguous_rows(c_w) || + !c_w->buffer || get_misalign_bytes(ctx, c_w) != 0) { + return 0; + } + const int64_t nc = c_w->ne[0]; + const int64_t nr = c_w->ne[1]; + const int64_t n_t = conv->ne[1]; + const int64_t n_s = conv->ne[2]; + if (nc != 4 || conv->ne[0] != nr || conv->ne[3] != 1 || n_t < 1 || n_t > max_sliding_nt || n_s < 1 || + concat->ne[0] != (nc - 1) + n_t || concat->ne[1] != nr || concat->ne[2] != n_s || concat->ne[3] != 1) { + return 0; + } + const ggml_tensor * old_st = concat->src[0]; + const ggml_tensor * qkv = concat->src[1]; + if (!old_st || !qkv || old_st->type != GGML_TYPE_F32 || qkv->type != GGML_TYPE_F32 || + !old_st->buffer || !qkv->buffer || + get_misalign_bytes(ctx, old_st) != 0 || get_misalign_bytes(ctx, qkv) != 0 || + old_st->ne[0] != nc - 1 || old_st->ne[1] != nr || old_st->ne[2] != n_s || old_st->ne[3] != 1 || + old_st->nb[0] != sizeof(float) || (old_st->nb[1] % sizeof(float)) != 0 || (old_st->nb[2] % sizeof(float)) != 0 || + qkv->ne[0] != n_t || qkv->ne[1] != nr || qkv->ne[2] != n_s || qkv->ne[3] != 1 || + (qkv->nb[0] % sizeof(float)) != 0 || (qkv->nb[1] % sizeof(float)) != 0 || (qkv->nb[2] % sizeof(float)) != 0) { + return 0; + } + if (view->view_src != concat || view->type != GGML_TYPE_F32 || + view->ne[0] != nc - 1 || view->ne[1] != nr || view->ne[2] != n_s || view->ne[3] != 1 || + view->nb[0] != sizeof(float) || view->nb[1] != concat->nb[1] || view->nb[2] != concat->nb[2] || + view->view_offs != (size_t)n_t * sizeof(float) || + cpy->src[0] != view || cpy->type != GGML_TYPE_F32 || !ggml_is_contiguous(cpy) || + !cpy->buffer || get_misalign_bytes(ctx, cpy) != 0 || + ggml_nbytes(cpy) != (size_t)(nc - 1) * (size_t)nr * (size_t)n_s * sizeof(float)) { + return 0; + } + int end_idx = i + 3; + const ggml_tensor * final_dst = conv; + if (i + 4 < cgraph->n_nodes && (gen_skip.empty() || !gen_skip[i + 4]) && !(conv->flags & GGML_TENSOR_FLAG_OUTPUT)) { + const ggml_tensor * u = cgraph->nodes[i + 4]; + if (u->op == GGML_OP_UNARY && ggml_get_unary_op(u) == GGML_UNARY_OP_SILU && + u->src[0] == conv && u->type == GGML_TYPE_F32 && + ggml_are_same_shape(u, conv) && ggml_are_same_stride(u, conv) && + u->buffer && get_misalign_bytes(ctx, u) == 0) { + const bool conv_only_here = !use_idx.any_reader(conv, [&](int k) { + return k != i + 4 && !ggml_op_is_empty(cgraph->nodes[k]->op); + }); + if (conv_only_here) { + end_idx = i + 4; + final_dst = u; + } + } + } + if ((concat->flags & GGML_TENSOR_FLAG_OUTPUT) || (view->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return 0; + } + auto out_of_ssm_span = [&](int k) { return (k < i || k > end_idx) && !ggml_op_is_empty(cgraph->nodes[k]->op); }; + if (use_idx.any_reader(concat, out_of_ssm_span) || use_idx.any_reader(view, out_of_ssm_span)) { + return 0; + } + // old_st may alias cpy iff exact same contiguous [nc-1, nr, n_s] slice (per-channel register shift) + if (ggml_vk_tensors_overlap(old_st, cpy, false)) { + const bool exact_same = + old_st->buffer == cpy->buffer && + vk_tensor_offset(old_st) + old_st->view_offs == vk_tensor_offset(cpy) + cpy->view_offs && + ggml_nbytes(old_st) == ggml_nbytes(cpy) && + ggml_is_contiguous(old_st); + if (!exact_same) { + return 0; + } + } + if (ggml_vk_tensors_overlap(qkv, cpy, false) || + ggml_vk_tensors_overlap(c_w, cpy, false) || + ggml_vk_tensors_overlap(cpy, final_dst, false) || + ggml_vk_tensors_overlap(old_st, final_dst, false) || + ggml_vk_tensors_overlap(qkv, final_dst, false) || + ggml_vk_tensors_overlap(c_w, final_dst, false)) { + return 0; + } + ctx->s10_ssm_conv_mode = 1; + ctx->s10_ssm_conv_node = conv; + ctx->s10_ssm_state_out = cpy; + ctx->s10_ssm_qkv = qkv; + ctx->fused_ops_write_mask |= (1u << 2); + return end_idx - i; + } + + // Mode 2: CPY -> SSM_CONV -> [SILU] + if (n0->op == GGML_OP_CPY && i + 1 < cgraph->n_nodes) { + const ggml_tensor * cpy = n0; + const ggml_tensor * conv = cgraph->nodes[i + 1]; + if (conv->op != GGML_OP_SSM_CONV) { + return 0; + } + if (!gen_skip.empty() && (gen_skip[i] || gen_skip[i + 1])) { + return 0; + } + const ggml_tensor * view = cpy->src[0]; + const ggml_tensor * src0 = conv->src[0]; + const ggml_tensor * c_w = conv->src[1]; + if (!view || !src0 || !c_w || view->op != GGML_OP_VIEW || view->view_src != src0 || + src0->type != GGML_TYPE_F32 || c_w->type != GGML_TYPE_F32 || conv->type != GGML_TYPE_F32 || + !ggml_is_contiguous_rows(src0) || !ggml_is_contiguous_rows(c_w) || !ggml_is_contiguous(conv) || + !src0->buffer || !c_w->buffer || !conv->buffer || + get_misalign_bytes(ctx, src0) != 0 || get_misalign_bytes(ctx, c_w) != 0 || get_misalign_bytes(ctx, conv) != 0) { + return 0; + } + const int64_t nc = c_w->ne[0]; + const int64_t nr = c_w->ne[1]; + const int64_t n_t = conv->ne[1]; + const int64_t n_s = conv->ne[2]; + if (nc < 2 || conv->ne[0] != nr || conv->ne[3] != 1 || n_t < 1 || n_s < 1 || + src0->ne[0] != (nc - 1) + n_t || src0->ne[1] != nr || src0->ne[2] != n_s || src0->ne[3] != 1 || + view->type != GGML_TYPE_F32 || view->ne[0] != nc - 1 || view->ne[1] != nr || view->ne[2] != n_s || view->ne[3] != 1 || + view->nb[0] != sizeof(float) || view->nb[1] != src0->nb[1] || view->nb[2] != src0->nb[2] || + view->view_offs != (size_t)n_t * sizeof(float) || + cpy->type != GGML_TYPE_F32 || !ggml_is_contiguous(cpy) || !cpy->buffer || get_misalign_bytes(ctx, cpy) != 0 || + ggml_nbytes(cpy) != (size_t)(nc - 1) * (size_t)nr * (size_t)n_s * sizeof(float)) { + return 0; + } + int end_idx = i + 1; + const ggml_tensor * final_dst = conv; + if (i + 2 < cgraph->n_nodes && (gen_skip.empty() || !gen_skip[i + 2]) && !(conv->flags & GGML_TENSOR_FLAG_OUTPUT)) { + const ggml_tensor * u = cgraph->nodes[i + 2]; + if (u->op == GGML_OP_UNARY && ggml_get_unary_op(u) == GGML_UNARY_OP_SILU && + u->src[0] == conv && u->type == GGML_TYPE_F32 && + ggml_are_same_shape(u, conv) && ggml_are_same_stride(u, conv) && + u->buffer && get_misalign_bytes(ctx, u) == 0) { + const bool conv_only_here = !use_idx.any_reader(conv, [&](int k) { + return k != i + 2 && !ggml_op_is_empty(cgraph->nodes[k]->op); + }); + if (conv_only_here) { + end_idx = i + 2; + final_dst = u; + } + } + } + if (ggml_vk_tensors_overlap(src0, cpy, false) || + ggml_vk_tensors_overlap(c_w, cpy, false) || + ggml_vk_tensors_overlap(cpy, final_dst, false) || + ggml_vk_tensors_overlap(src0, final_dst, false) || + ggml_vk_tensors_overlap(c_w, final_dst, false)) { + return 0; + } + ctx->s10_ssm_conv_mode = 2; + ctx->s10_ssm_conv_node = conv; + ctx->s10_ssm_state_out = cpy; + ctx->s10_ssm_qkv = nullptr; + ctx->fused_ops_write_mask |= 1u; + return end_idx - i; + } + return 0; +} + +// Series 10 (S10.3): 1..9 ADD -> ... -> RMS_NORM -> [MUL(weight)] in a single row-per-WG dispatch +static uint32_t s10_can_fuse_multi_add_rms_mul(ggml_backend_vk_context * ctx, const ggml_cgraph * cgraph, int i, + int last_node, std::vector & gen_skip, + const vk_cgraph_use_index & use_idx, int & out_final_idx) { + out_final_idx = -1; + if (s10_add_rms_disabled() || !ctx->device->multi_add || ctx->device->pipeline_multi_add_rms_mul[0][0][0] == nullptr) { + return 0; + } + const ggml_tensor * first_add = cgraph->nodes[i]; + if (first_add->op != GGML_OP_ADD || first_add->type != GGML_TYPE_F32 || + !first_add->buffer || get_misalign_bytes(ctx, first_add) != 0) { + return 0; + } + const int64_t ne0 = first_add->ne[0]; + const int64_t nrows = ggml_nrows(first_add); + if (ne0 <= 0 || ne0 > 4096 || nrows <= 0) { + return 0; + } + + auto valid_add_src = [&](const ggml_tensor * t) -> bool { + if (!t || t->type != GGML_TYPE_F32 || !t->buffer || get_misalign_bytes(ctx, t) != 0 || + !ggml_are_same_shape(first_add, t) || t->nb[0] != sizeof(float)) { + return false; + } + if (nrows == 1) { + return true; + } + return (t->ne[2] == 1 && t->ne[3] == 1 && (t->nb[1] % sizeof(float)) == 0) || ggml_is_contiguous(t); + }; + + if (!valid_add_src(first_add->src[0]) || !valid_add_src(first_add->src[1])) { + return 0; + } + + int32_t num_adds = 1; + while (i + num_adds < cgraph->n_nodes && num_adds < MAX_FUSED_ADDS && + (gen_skip.empty() || !gen_skip[i + num_adds])) { + const ggml_tensor * prev = cgraph->nodes[i + num_adds - 1]; + const ggml_tensor * na = cgraph->nodes[i + num_adds]; + if (na->op != GGML_OP_ADD || na->type != GGML_TYPE_F32 || !na->buffer || get_misalign_bytes(ctx, na) != 0 || + (na->src[0] != prev && na->src[1] != prev) || + !valid_add_src(na->src[0]) || !valid_add_src(na->src[1])) { + break; + } + num_adds++; + } + ggml_op adds[MAX_FUSED_ADDS]; + for (int32_t k = 0; k < num_adds; ++k) { + adds[k] = GGML_OP_ADD; + } + while (num_adds > 1 && !ggml_can_fuse(cgraph, i, adds, num_adds)) { + num_adds--; + } + + const int add_end_idx = i + num_adds - 1; + if (num_adds == 1 && i > 0) { + const ggml_tensor * prev_node = cgraph->nodes[i - 1]; + if ((prev_node->op == GGML_OP_MUL_MAT || prev_node->op == GGML_OP_MUL_MAT_ID) && + (first_add->src[0] == prev_node || first_add->src[1] == prev_node)) { + return 0; + } + } + const ggml_tensor * last_add = cgraph->nodes[add_end_idx]; + + int rms_idx = -1; + const int search_hi = std::min(last_node + 1, add_end_idx + 17); + for (int j = add_end_idx + 1; j < search_hi; ++j) { + if (!gen_skip.empty() && gen_skip[j]) { + continue; + } + const ggml_tensor * n = cgraph->nodes[j]; + if (n->op == GGML_OP_RMS_NORM && n->src[0] == last_add) { + rms_idx = j; + break; + } + } + if (rms_idx < 0) { + return 0; + } + const ggml_tensor * rms = cgraph->nodes[rms_idx]; + if (rms->type != GGML_TYPE_F32 || !ggml_are_same_shape(rms, last_add) || + !ggml_is_contiguous(rms) || !rms->buffer || get_misalign_bytes(ctx, rms) != 0) { + return 0; + } + + const bool was_adjacent_cand = + (rms_idx == add_end_idx + 1) && + (nrows == 1 || + (gen_batch_invariant() && nrows <= 64 && + ggml_is_contiguous(first_add) && ggml_is_contiguous(rms) && + (ne0 % ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0]) == 0)) && + ctx->device->add_rms_fusion && !ctx->device->disable_fusion; + + bool fits = false; + if (was_adjacent_cand) { + const uint32_t psize = ggml_vk_rms_partials_size(ctx, first_add); + fits = gen_batch_invariant() + ? (ctx->gen_n1_partials_offset + psize <= 1024 && + ctx->prealloc_size_add_rms_partials_offset + gen_rms_partials_size_rows(ctx, first_add) <= ctx->prealloc_size_add_rms_partials) + : (ctx->prealloc_size_add_rms_partials_offset + psize <= ctx->prealloc_size_add_rms_partials); + } + const uint32_t tree_mode = (was_adjacent_cand && fits) ? 1u : 0u; + if (tree_mode == 1u) { + if (ne0 < 512 || ne0 > 4096 || (ne0 % 512) != 0) { + return 0; + } + } else { + const bool rms_subgroups = (ctx->device->vendor_id == VK_VENDOR_ID_INTEL || ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA || ctx->device->vendor_id == VK_VENDOR_ID_AMD) && ctx->device->subgroup_arithmetic && ctx->device->subgroup_require_full_support; + if (rms_subgroups || ne0 <= 256 || ne0 > 4096) { + return 0; + } + } + + // Preserve specialized downstream RMS_NORM fusions (rope, set_rows, add, silu_gate, scale) + if (!fits) { + if (gen_can_fuse_rms_mul_silu(ctx, cgraph, rms_idx) > 0 || + gen_find_rms_norm_scale(ctx, cgraph, rms_idx, last_node, use_idx) >= 0) { + return 0; + } + } + if ((rms_idx + 2 < cgraph->n_nodes && + cgraph->nodes[rms_idx + 1]->op == GGML_OP_MUL && + cgraph->nodes[rms_idx + 2]->op == GGML_OP_ROPE) || + (rms_idx + 2 < cgraph->n_nodes && + cgraph->nodes[rms_idx + 1]->op == GGML_OP_VIEW && + cgraph->nodes[rms_idx + 2]->op == GGML_OP_SET_ROWS) || + ggml_vk_can_fuse(ctx, cgraph, rms_idx, rms_norm_mul_add_pattern)) { + return 0; + } + + int mul_idx = -1; + const ggml_tensor * weight = nullptr; + const ggml_tensor * final_dst = rms; + int final_idx = rms_idx; + + if (rms_idx + 1 <= last_node && (gen_skip.empty() || !gen_skip[rms_idx + 1]) && + !(rms->flags & GGML_TENSOR_FLAG_OUTPUT)) { + const ggml_tensor * m = cgraph->nodes[rms_idx + 1]; + if (m->op == GGML_OP_MUL && (m->src[0] == rms || m->src[1] == rms)) { + const ggml_tensor * w = (m->src[0] == rms) ? m->src[1] : m->src[0]; + if (m->type == GGML_TYPE_F32 && ggml_are_same_shape(m, rms) && ggml_is_contiguous(m) && + m->buffer && get_misalign_bytes(ctx, m) == 0 && + w && w != rms && w->type == GGML_TYPE_F32 && ggml_is_contiguous(w) && + w->ne[0] == ne0 && ggml_nrows(w) == 1 && w->buffer && get_misalign_bytes(ctx, w) == 0) { + bool weight_ready = (w->op == GGML_OP_NONE); + if (!weight_ready) { + const int32_t wfirst = use_idx.first_node_idx(w); + weight_ready = (wfirst >= 0 && wfirst < i); + } + const bool rms_only_here = weight_ready && !use_idx.any_reader(rms, [&](int k) { + return k != rms_idx + 1 && !ggml_op_is_empty(cgraph->nodes[k]->op); + }); + if (rms_only_here) { + mul_idx = rms_idx + 1; + weight = w; + final_dst = m; + final_idx = mul_idx; + } + } + } + } + + const bool write_add = ((last_add->flags & GGML_TENSOR_FLAG_OUTPUT) != 0) || + use_idx.any_reader(last_add, [&](int k) { + return (k < i || k > add_end_idx) && k != rms_idx && !ggml_op_is_empty(cgraph->nodes[k]->op); + }); + if (write_add && (!ggml_is_contiguous(last_add) || !last_add->buffer || get_misalign_bytes(ctx, last_add) != 0)) { + return 0; + } + + const ggml_tensor * srcs[10] {}; + srcs[0] = first_add->src[0]; + srcs[1] = first_add->src[1]; + for (int32_t k = 0; k < num_adds - 1; ++k) { + const ggml_tensor * prev = cgraph->nodes[i + k]; + const ggml_tensor * next = cgraph->nodes[i + k + 1]; + srcs[k + 2] = (next->src[0] == prev) ? next->src[1] : next->src[0]; + } + + if (write_add && ggml_vk_tensors_overlap(last_add, final_dst, false)) { + return 0; + } + if (weight && (ggml_vk_tensors_overlap(weight, final_dst, false) || + (write_add && ggml_vk_tensors_overlap(weight, last_add, false)))) { + return 0; + } + for (int32_t s = 0; s <= num_adds; ++s) { + if (ggml_vk_tensors_overlap(srcs[s], final_dst, true) || + (write_add && ggml_vk_tensors_overlap(srcs[s], last_add, true))) { + return 0; + } + } + + // Intervening ops in (add_end_idx .. final_idx) run AFTER our fused dispatch at i + for (int k = add_end_idx + 1; k < final_idx; ++k) { + if (k == rms_idx || k == mul_idx || (!gen_skip.empty() && gen_skip[k])) { + continue; + } + const ggml_tensor * mid = cgraph->nodes[k]; + if (ggml_op_is_empty(mid->op)) { + continue; + } + if (mid->buffer) { + if (ggml_vk_tensors_overlap(mid, final_dst, false) || + (write_add && ggml_vk_tensors_overlap(mid, last_add, false)) || + (weight && ggml_vk_tensors_overlap(mid, weight, false))) { + return 0; + } + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + const ggml_tensor * msrc = mid->src[s]; + if (msrc && msrc->buffer && ggml_vk_tensors_overlap(msrc, final_dst, false)) { + return 0; + } + } + } + + if (was_adjacent_cand) { + ctx->prealloc_size_add_rms_partials_offset += gen_batch_invariant() + ? gen_rms_partials_size_rows(ctx, first_add) + : ggml_vk_rms_partials_size(ctx, first_add); + ctx->gen_n1_partials_offset += ggml_vk_rms_partials_size(ctx, first_add); + } + + uint32_t eff_tree_mode = tree_mode; + if (eff_tree_mode == 0u && ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled() && + !getenv("GGML_VK_DISABLE_S14_ADD_RMS") && (ne0 % 16 == 0) && + ctx->device->pipeline_multi_add_rms_mul[num_adds - 1][2][weight != nullptr ? 1 : 0] != nullptr) { + bool v4_ok = (get_misalign_bytes(ctx, final_dst) == 0) && + (!write_add || get_misalign_bytes(ctx, last_add) == 0) && + (!weight || get_misalign_bytes(ctx, weight) == 0); + for (int32_t s = 0; s <= num_adds && v4_ok; ++s) { + if ((srcs[s]->nb[1] % 16 != 0) || (get_misalign_bytes(ctx, srcs[s]) != 0)) { + v4_ok = false; + } + } + if (v4_ok) { + eff_tree_mode = 2u; + } + } + + for (int32_t s = 0; s <= num_adds; ++s) { + ctx->s10_add_rms_srcs[s] = srcs[s]; + } + ctx->s10_add_rms_add_dst = last_add; + ctx->s10_add_rms_weight = weight; + ctx->s10_add_rms_dst = final_dst; + ctx->s10_add_rms_num_adds = (uint32_t)num_adds; + ctx->s10_add_rms_tree_mode = eff_tree_mode; + ctx->s10_add_rms_write_add = write_add ? 1u : 0u; + memcpy(&ctx->s10_add_rms_eps, rms->op_params, sizeof(float)); + + gen_skip[rms_idx] = 1; + if (mul_idx >= 0) { + gen_skip[mul_idx] = 1; + } + out_final_idx = final_idx; + return (uint32_t)num_adds; +} + +// gen (GGML_GEN_GDN_INPLACE): find the CPY that stores GATED_DELTA_NET node i's final/rollback state (K >= 1) and +// nothing else reads, so the GDN dispatch can write the state straight to the CPY destination. +static int gen_find_gdn_state_cpy(const ggml_backend_vk_context * ctx, const ggml_cgraph * g, int i, int last_node, const vk_cgraph_use_index & use_idx) { + const ggml_tensor * gdn = g->nodes[i]; + const int32_t K = ggml_get_op_params_i32(gdn, 0); + if (K < 1 || gdn->type != GGML_TYPE_F32 || !gdn->buffer || (gdn->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return -1; + } + const ggml_tensor * v = gdn->src[2]; + const size_t S_v = v->ne[0], H = v->ne[1], n_tokens = v->ne[2], n_seqs = v->ne[3]; + const size_t D = S_v * S_v * H; + const size_t n_written = std::min(n_tokens, (size_t) K); + if (n_written == 0) { + return -1; + } + const size_t s_off_bytes = S_v * H * n_tokens * n_seqs * sizeof(float); + const size_t snap_bytes = D * n_seqs * sizeof(float); + const size_t state_bytes = n_written * snap_bytes; + int cpy = -1; + for (int j = i + 1; j < std::min(last_node, i + 32); j++) { + const ggml_tensor * n = g->nodes[j]; + if (n->op != GGML_OP_CPY || !n->src[0] || n->src[0]->view_src != gdn || n->src[0]->view_offs != s_off_bytes || + n->src[0]->type != GGML_TYPE_F32 || n->type != GGML_TYPE_F32 || + ggml_nbytes(n->src[0]) != state_bytes || !ggml_is_contiguous(n->src[0]) || + !n->buffer || get_misalign_bytes(ctx, n) != 0) { + continue; + } + const bool dst_layout_ok = (K == 1) + ? (ggml_nbytes(n) == state_bytes && ggml_is_contiguous(n)) + : (n->ne[0] == (int64_t) D && n->ne[1] == (int64_t) n_seqs && + n->ne[2] == (int64_t) n_written && n->ne[3] == 1 && + n->nb[0] == sizeof(float) && + (n_seqs == 1 || n->nb[1] == D * sizeof(float)) && + (n_written == 1 || (n->nb[2] % sizeof(float)) == 0)); + if (dst_layout_ok) { + cpy = j; + break; + } + } + if (cpy < 0) { + return -1; + } + // nothing else may read the state part of the GDN result + if (use_idx.any_reader(gdn, [&](int k) { + const ggml_tensor * n = g->nodes[k]; + if (k == cpy || ggml_op_is_empty(n->op)) { + return false; + } + for (int s = 0; s < GGML_MAX_SRC; s++) { + const ggml_tensor * src = n->src[s]; + if (src == nullptr) { + continue; + } + if (src == gdn && k != i) { + return true; + } + if (src->view_src == gdn && src->view_offs + ggml_nbytes(src) > s_off_bytes) { + return true; + } + } + return false; + })) { + return -1; + } + // the destination must not overlap q, k, v, g, beta or intervening ops; it may be the K==1 state input in place or disjoint + const ggml_tensor * dst = g->nodes[cpy]; + for (int m_idx = i + 1; m_idx < cpy; ++m_idx) { + const ggml_tensor * mid = g->nodes[m_idx]; + if (ggml_op_is_empty(mid->op)) { + continue; + } + if (mid->buffer && ggml_vk_tensors_overlap_strided(mid, dst)) { + return -1; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + if (mid->src[s] && mid->src[s]->buffer && ggml_vk_tensors_overlap_strided(mid->src[s], dst)) { + return -1; + } + } + } + for (int s = 0; s < 5; s++) { + if (gdn->src[s] && gdn->src[s]->buffer && ggml_vk_tensors_overlap_strided(gdn->src[s], dst)) { + return -1; + } + } + const ggml_tensor * st = gdn->src[5]; + if (st->buffer && ggml_vk_tensors_overlap_strided(st, dst)) { + const bool same = K == 1 && st->buffer == dst->buffer && + vk_tensor_offset(st) + st->view_offs == vk_tensor_offset(dst) + dst->view_offs && + ggml_nbytes(st) == snap_bytes && ggml_is_contiguous(st) && ggml_is_contiguous(dst); + if (!same) { + return -1; + } + } + return cpy; +} + +static uint32_t ggml_vk_node_max_dispatches( + const ggml_backend_vk_context * ctx, + const ggml_cgraph * cgraph, + int node_idx) { + const ggml_tensor * n = cgraph->nodes[node_idx]; + if (!n || ggml_vk_is_empty(const_cast(n))) { + return 0u; + } + if (n->op == GGML_OP_ARGSORT && ctx->fused_topk_moe_mode == TOPK_MOE_COUNT) { + const uint32_t ncols = (uint32_t) std::max(1, n->src[0] ? n->src[0]->ne[0] : n->ne[0]); + const uint32_t lg = ncols > 1u ? (uint32_t) ceilf(log2f((float) ncols)) : 1u; + return (lg * (lg + 1u)) / 2u + 8u; + } + if (n->op == GGML_OP_MUL_MAT && n->src[0] != nullptr) { + const size_t max_range = ctx->device->properties.limits.maxStorageBufferRange; + const size_t row_nb = n->src[0]->nb[1]; + if (row_nb > 0 && (size_t) ggml_nbytes(n->src[0]) > max_range) { + const uint64_t m_split = std::max(1ULL, (uint64_t) max_range / (2ULL * (uint64_t) row_nb)); + const uint64_t n_splits = ((uint64_t) n->ne[0] + m_split - 1ULL) / m_split; + return (uint32_t) std::min(4096ULL, n_splits * 4ULL + 8ULL); + } + return ctx->gen_pair_mm1 != nullptr ? 6u : 4u; + } + if (n->op == GGML_OP_MUL_MAT_ID) { + if (ggml_vk_use_mul_mat_vec_id(ctx, cgraph, node_idx)) { + const int64_t nei1 = n->src[2] ? n->src[2]->ne[1] : 1; + return (uint32_t) std::min(128, std::max(1, nei1) + 2); + } + return 6u; + } + switch (n->op) { + case GGML_OP_INKLING_FUSED: + case GGML_OP_SET_ROWS: + case GGML_OP_GET_ROWS: + case GGML_OP_ADD: + case GGML_OP_SUB: + case GGML_OP_MUL: + case GGML_OP_DIV: + case GGML_OP_SCALE: + case GGML_OP_CLAMP: + case GGML_OP_UNARY: + case GGML_OP_GLU: + case GGML_OP_CONCAT: + case GGML_OP_REPEAT: + case GGML_OP_FILL: + case GGML_OP_PAD: + case GGML_OP_CPY: + case GGML_OP_CONT: + case GGML_OP_ARGMAX: + case GGML_OP_SUM_ROWS: + case GGML_OP_ROPE: + case GGML_OP_RMS_NORM: + case GGML_OP_NORM: + case GGML_OP_L2_NORM: + return 2u; + case GGML_OP_SOFT_MAX: + case GGML_OP_FLASH_ATTN_EXT: + return 4u; + default: + return 8u; + } +} + +static bool ggml_vk_build_replay_sig( + ggml_backend_vk_context * ctx, + const ggml_cgraph * cgraph, + std::vector & out_dyn_words, + uint64_t & out_h1, + uint64_t & out_h2, + uint64_t & out_h3, + uint64_t & out_h4) { + if (cgraph->n_nodes <= 0) { + return false; + } + struct seen_table_t { + std::vector ptrs; + std::vector epochs; + std::vector ids; + uint32_t epoch = 1; + }; + static thread_local seen_table_t tbl; + size_t cap = 4096; + const size_t min_cap = (size_t) (cgraph->n_nodes + 256) * 4; + while (cap < min_cap) { + cap <<= 1; + } + if (tbl.ptrs.size() < cap) { + tbl.ptrs.assign(cap, nullptr); + tbl.epochs.assign(cap, 0); + tbl.ids.assign(cap, 0); + tbl.epoch = 1; + } else if (++tbl.epoch == 0) { + std::fill(tbl.epochs.begin(), tbl.epochs.end(), 0); + tbl.epoch = 1; + } + const size_t mask = tbl.ptrs.size() - 1; + const uint32_t ep = tbl.epoch; + + out_dyn_words.clear(); + uint64_t h1 = 0x9e3779b97f4a7c15ULL ^ (uint64_t) cgraph->n_nodes; + uint64_t h2 = 0xbf58476d1ce4e5b9ULL ^ ((uint64_t) cgraph->n_nodes * 31ULL); + uint64_t h3 = 0x94d049bb133111ebULL ^ ((uint64_t) cgraph->n_nodes << 17); + uint64_t h4 = 0x2545f4914f6cdd1dULL ^ ~((uint64_t) cgraph->n_nodes); + + auto mix_w = [&](uint64_t w) { + h1 ^= w + 0x9e3779b97f4a7c15ULL + (h1 << 6) + (h1 >> 2); + h2 = (h2 ^ w) * 0xbf58476d1ce4e5b9ULL; + h2 ^= (h2 >> 31); + h3 = (h3 + w + 0x94d049bb133111ebULL) ^ (h3 << 13) ^ (h3 >> 7); + h4 = (h4 ^ (w * 0x9e3779b97f4a7c15ULL)) * 0x2545f4914f6cdd1dULL; + h4 ^= (h4 >> 29); + }; + + uint32_t next_id = 0; + auto intern_tensor = [&](auto & self, const ggml_tensor * t, uint32_t & out_id) -> bool { + if (t == nullptr) { + out_id = 0; + return true; + } + uintptr_t p = (uintptr_t) t; + size_t slot = ((p >> 5) * 11400714819323198485ULL) & mask; + while (tbl.epochs[slot] == ep) { + if (tbl.ptrs[slot] == t) { + out_id = tbl.ids[slot]; + return true; + } + slot = (slot + 1) & mask; + } + uint32_t vs_id = 0; + if (t->view_src != nullptr) { + if (!self(self, t->view_src, vs_id)) { + return false; + } + } + ggml_backend_buffer_t b = t->buffer ? t->buffer : (t->view_src ? t->view_src->buffer : nullptr); + uint64_t buf_handle = 0; + uint64_t byte_off = (uint64_t) t->view_offs; + if (b != nullptr) { + if (ggml_backend_buffer_is_vk(b)) { + vk_buffer db = ((ggml_backend_vk_buffer_context *) b->context)->dev_buffer; + if (!db) { + return false; + } + buf_handle = (uint64_t) (VkBuffer) db->buffer; + byte_off = vk_tensor_offset(t) + t->view_offs; + } else if (ctx && ctx->device->uma && ggml_backend_buffer_is_host(b) && t->data != nullptr) { + vk_buffer hb = nullptr; + size_t ho = 0; + ggml_vk_host_get(ctx->device, t->data, hb, ho); + if (!hb) { + return false; + } + buf_handle = (uint64_t) (VkBuffer) hb->buffer; + byte_off = (uint64_t) ho; + } else { + return false; + } + } else if (t->data != nullptr && !ggml_op_is_empty(t->op)) { + return false; + } + + const uint32_t id = ++next_id; + if (t->view_src != nullptr) { + slot = ((p >> 5) * 11400714819323198485ULL) & mask; + while (tbl.epochs[slot] == ep) { + slot = (slot + 1) & mask; + } + } + tbl.ptrs[slot] = t; + tbl.epochs[slot] = ep; + tbl.ids[slot] = id; + out_id = id; + + mix_w(((uint64_t) id << 32) | 0x54454e53ULL); + mix_w((uint64_t) t->op | ((uint64_t) t->type << 16) | ((uint64_t) (uint32_t) t->flags << 32)); + mix_w((uint64_t) t->ne[0]); + mix_w((uint64_t) t->ne[1]); + mix_w((uint64_t) t->ne[2]); + mix_w((uint64_t) t->ne[3]); + mix_w((uint64_t) t->nb[0]); + mix_w((uint64_t) t->nb[1]); + mix_w((uint64_t) t->nb[2]); + mix_w((uint64_t) t->nb[3]); + mix_w(buf_handle); + mix_w(byte_off); + mix_w((uint64_t) vs_id); + if (t->op != GGML_OP_NONE) { + uint64_t opw[8]; + static_assert(sizeof(t->op_params) == sizeof(opw), "op_params size"); + memcpy(opw, t->op_params, sizeof(opw)); + for (int k = 0; k < 8; ++k) { + mix_w(opw[k]); + } + } + return true; + }; + + for (int i = 0; i < cgraph->n_nodes; ++i) { + const ggml_tensor * n = cgraph->nodes[i]; + uint32_t nid = 0; + if (!intern_tensor(intern_tensor, n, nid)) { + return false; + } + uint32_t sids[GGML_MAX_SRC]; + for (int s = 0; s < GGML_MAX_SRC; ++s) { + if (!intern_tensor(intern_tensor, n->src[s], sids[s])) { + return false; + } + } + mix_w(nid); + for (int s = 0; s < GGML_MAX_SRC; s += 2) { + const uint64_t lo = sids[s]; + const uint64_t hi = (s + 1 < GGML_MAX_SRC) ? sids[s + 1] : 0u; + mix_w(lo | (hi << 32)); + } + if (n->op == GGML_OP_FLASH_ATTN_EXT || + (n->op == GGML_OP_INKLING_FUSED && ggml_get_op_params_i32(n, 0) == 2)) { + uint32_t blk_min = 0u, blk_max = UINT32_MAX, const_end = 0u; + const uint64_t dyn_w = ggml_vk_get_node_active_kv_span(ctx, n, &blk_min, &blk_max, &const_end) + ? (((uint64_t)blk_min & 0x1FFFFFu) | + (((uint64_t)blk_max & 0x1FFFFFu) << 21) | + (((uint64_t)const_end & 0x1FFFFFu) << 42)) + : UINT64_MAX; + mix_w(dyn_w); + out_dyn_words.push_back(dyn_w); + } + } + + out_h1 = h1; + out_h2 = h2; + out_h3 = h3; + out_h4 = h4; + return true; +} + +static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) { + VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)"); + ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; + + if (!ctx->uma_out_memcpys.empty()) { + ggml_vk_synchronize(ctx); + } + + ctx->device->diag_cgraph = nullptr; + ctx->device->diag_prev_start = -1; + ctx->device->diag_prev_end = -1; + + if (vk_instance.debug_utils_support) { + ctx->device->debug_cmdbuf_idx = 0; + } + + // queue scope, so it encloses every submit this evaluation makes. + // closed when the function returns + ggml_vk_debug_label queue_dbg(ctx->device->compute_queue->handle.get(), "ggml_backend_vk_graph_compute"); + + for (int i = 0; i < 4; ++i) { + ctx->mask_span_cache[i].valid = false; + } + ctx->prealloc_size_add_rms_partials_offset = 0; + ctx->gen_n1_partials_offset = 0; + ctx->do_add_rms_partials = false; + ctx->do_add_rms_partials_offset_calculation = false; + + // gen instrumentation (env-gated, off by default): + // GGML_VK_GRAPH_STATS=1 one line per graph: nodes, dispatches, syncs, submits, CPU recording time + // GGML_VK_FLOPS_PER_SUBMIT=N override the flops-based submit threshold (0 disables it) + // GGML_VK_DUP_OPS=A,B|ALL record matching non-in-place nodes twice (timing ablation; results unchanged) + struct gen_env_t { + bool stats = false; + int64_t flops_per_submit = -1; + bool dup_all = false; + std::vector dup; + gen_env_t() { + const char * s = getenv("GGML_VK_GRAPH_STATS"); + stats = s != nullptr && atoi(s) != 0; + const char * f = getenv("GGML_VK_FLOPS_PER_SUBMIT"); + flops_per_submit = f != nullptr ? std::stoll(f) : -1; + const char * d = getenv("GGML_VK_DUP_OPS"); + if (d != nullptr) { + std::string list(d); + size_t pos = 0; + while (pos <= list.size()) { + size_t comma = list.find(',', pos); + if (comma == std::string::npos) { + comma = list.size(); + } + std::string item = list.substr(pos, comma - pos); + if (item == "ALL") { + dup_all = true; + } else if (!item.empty()) { + dup.push_back(item); + } + pos = comma + 1; + } + } + } + }; + static const gen_env_t gen_env; + const int64_t gen_t_start = gen_env.stats ? ggml_time_us() : 0; + ctx->stat_dispatches = 0; + ctx->stat_syncs = 0; + uint32_t gen_dups = 0; + auto const gen_dup_match = [&](const ggml_tensor * n) -> bool { + if (n->op == GGML_OP_ADD || n->op == GGML_OP_NONE || ggml_vk_is_empty(const_cast(n))) { + return false; // ADD may carry rms partials state; views record nothing + } + for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) { + if (n->src[s] && n->src[s]->buffer && n->buffer && ggml_vk_tensors_overlap(n->src[s], n, false)) { + return false; // in-place: a second run would not be idempotent + } + } + if (gen_env.dup_all) { + return true; + } + const char * name = ggml_op_desc(n); + for (const std::string & d : gen_env.dup) { + if (d == name) { + return true; + } + } + return false; + }; + + int last_node = cgraph->n_nodes - 1; + + // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly + while (last_node > 0 && (ggml_vk_is_empty(cgraph->nodes[last_node]) || ((cgraph->nodes[last_node]->flags & GGML_TENSOR_FLAG_COMPUTE) == 0))) { + last_node -= 1; + } + + // Reserve tensor context space for all nodes + ctx->tensor_ctxs.resize(cgraph->n_nodes); + + bool first_node_in_batch = true; // true if next node will be first node in a batch + int submit_node_idx = 0; // index to first node in a batch + + ggml_vk_submit_transfer_ctx(ctx); + + vk_context compute_ctx; + if (vk_perf_logger_enabled) { + // allocate/resize the query pool + if (ctx->num_queries < cgraph->n_nodes + 1) { + if (ctx->query_pool) { + ctx->device->device.destroyQueryPool(ctx->query_pool); + } + vk::QueryPoolCreateInfo query_create_info; + query_create_info.queryType = vk::QueryType::eTimestamp; + query_create_info.queryCount = cgraph->n_nodes + 100; + ctx->query_pool = ctx->device->device.createQueryPool(query_create_info); + ctx->num_queries = query_create_info.queryCount; + ctx->query_fusion_names.resize(ctx->num_queries); + ctx->query_fusion_node_count.resize(ctx->num_queries); + ctx->query_nodes.resize(ctx->num_queries); + ctx->query_node_idx.resize(ctx->num_queries); + } + + ctx->device->device.resetQueryPool(ctx->query_pool, 0, cgraph->n_nodes+1); + std::fill(ctx->query_fusion_names.begin(), ctx->query_fusion_names.end(), nullptr); + std::fill(ctx->query_fusion_node_count.begin(), ctx->query_fusion_node_count.end(), 0); std::fill(ctx->query_nodes.begin(), ctx->query_nodes.end(), nullptr); std::fill(ctx->query_node_idx.begin(), ctx->query_node_idx.end(), 0); + if (!ctx->compute_ctx.expired()) { + ggml_vk_synchronize(ctx); + } GGML_ASSERT(ctx->compute_ctx.expired()); compute_ctx = ggml_vk_get_compute_ctx(ctx); ctx->query_idx = 0; @@ -15570,9 +22832,207 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg ggml_vk_sync_buffers(ctx, compute_ctx); } - ctx->prealloc_y_last_pipeline_used = nullptr; - ctx->prealloc_y_last_tensor_used = nullptr; - ctx->prealloc_y_last_k_padded = false; + ggml_vk_invalidate_prealloc_y_ring(ctx); + ctx->prealloc_y_ring_idx = 0; + ctx->prealloc_split_k_ring_idx = 0; + ctx->last_expert_count_valid = false; + ctx->last_expert_ids_tensor = nullptr; + ctx->last_mask_opt_valid = false; + ctx->last_mask_opt_tensor = nullptr; + + // Series 20 (Pillar S20.1): Multi-chunk Ioto-safe reusable command buffer LRU cache (enabled by default on Apple AGX coopmat). + static const int s9_single_front_env = getenv("GGML_VK_SINGLE_FRONT") ? atoi(getenv("GGML_VK_SINGLE_FRONT")) : -1; + const bool single_front_enabled = s9_single_front_env >= 0 ? (s9_single_front_env > 0) : ggml_vk_is_apple_agx_coopmat(ctx->device); + vk_graph_replay_entry * rec_entry = nullptr; + auto pre_buf_h = [](const vk_buffer & b) -> uint64_t { return b ? (uint64_t) (VkBuffer) b->buffer : 0ULL; }; + auto pre_buf_sz = [](const vk_buffer & b) -> size_t { return b ? b->size : 0; }; + + if (single_front_enabled && !vk_perf_logger_enabled && !gen_env.dup_all && gen_env.dup.empty() && + !ctx->device->serialize_submissions && !vk_instance.debug_utils_support && + ctx->compute_ctx.expired()) { + const bool throttle_sig = (ctx->replay_consec_misses >= 32 && + (ctx->replay_consec_misses & 31u) != 0); + if (throttle_sig) { + ++ctx->replay_consec_misses; + } else { + static thread_local std::vector cur_sig; + uint64_t h1 = 0, h2 = 0, h3 = 0, h4 = 0; + if (ggml_vk_build_replay_sig(ctx, cgraph, cur_sig, h1, h2, h3, h4)) { + const uint64_t cur_destroy = ctx->device->buffer_destroy_count.load(std::memory_order_acquire); + if ((ctx->prealloc_size_add_rms_partials && + (ctx->prealloc_add_rms_partials == nullptr || ctx->prealloc_add_rms_partials->size < ctx->prealloc_size_add_rms_partials)) || + (ctx->prealloc_size_mask_opt && + (ctx->prealloc_mask_opt == nullptr || ctx->prealloc_mask_opt->size < ctx->prealloc_size_mask_opt))) { + ggml_vk_preallocate_buffers(ctx, nullptr); + } + const uint64_t cur_xh = pre_buf_h(ctx->prealloc_x); + const uint64_t cur_yh = pre_buf_h(ctx->prealloc_y); + const uint64_t cur_skh = pre_buf_h(ctx->prealloc_split_k); + const uint64_t cur_ah = pre_buf_h(ctx->prealloc_add_rms_partials); + const uint64_t cur_moh = pre_buf_h(ctx->prealloc_mask_opt); + const size_t cur_xsz = pre_buf_sz(ctx->prealloc_x); + const size_t cur_ysz = pre_buf_sz(ctx->prealloc_y); + const size_t cur_sks = pre_buf_sz(ctx->prealloc_split_k); + const size_t cur_asz = pre_buf_sz(ctx->prealloc_add_rms_partials); + const size_t cur_mos = pre_buf_sz(ctx->prealloc_mask_opt); + + vk_graph_replay_entry * hit = nullptr; + for (auto & e : ctx->replay_cache) { + if (e.n_nodes == cgraph->n_nodes && e.hash1 == h1 && e.hash2 == h2 && + e.hash3 == h3 && e.hash4 == h4 && e.sig_words == cur_sig) { + hit = &e; + break; + } + } + if (hit != nullptr && hit->ready && !hit->cmd_bufs.empty() && + hit->destroy_count == cur_destroy && + hit->pre_x_handle == cur_xh && hit->pre_x_size == cur_xsz && + hit->pre_y_handle == cur_yh && hit->pre_y_size == cur_ysz && + hit->pre_sk_handle == cur_skh && hit->pre_sk_size == cur_sks && + hit->pre_arp_handle == cur_ah && hit->pre_arp_size == cur_asz && + hit->pre_mo_handle == cur_moh && hit->pre_mo_size == cur_mos) { + ctx->replay_consec_misses = 0; + hit->lru_tick = ++ctx->replay_lru_clock; + ggml_vk_ensure_fence_free(ctx); + for (const auto & m : hit->memsets) { + memset(m.dst, m.val, m.n); + } + const uint32_t n_cbs = (uint32_t) hit->cmd_bufs.size(); + const int64_t sub_ts = ggml_time_us(); + ctx->replay_submit_us = sub_ts; + ctx->last_submit_us = sub_ts; + if (ctx->device->async_use_transfer_queue && ctx->transfer_semaphore_last_submitted < ctx->transfer_semaphore.value) { + vk::TimelineSemaphoreSubmitInfo tl_info{ 1, &ctx->transfer_semaphore.value, 0, nullptr }; + vk::PipelineStageFlags stage = ctx->device->transfer_queue->stage_flags; + vk::SubmitInfo si{ 1, &ctx->transfer_semaphore.s, &stage, n_cbs, hit->cmd_bufs.data(), 0, nullptr }; + si.setPNext(&tl_info); + ctx->device->compute_queue->handle->submit({ si }, ctx->fence); + ctx->transfer_semaphore_last_submitted = ctx->transfer_semaphore.value; + } else { + vk::SubmitInfo si{ 0, nullptr, nullptr, n_cbs, hit->cmd_bufs.data(), 0, nullptr }; + ctx->device->compute_queue->handle->submit({ si }, ctx->fence); + } + ctx->fence_submitted = true; + ctx->submit_pending = true; + ctx->active_replay_entry = hit; + ctx->last_total_flops = hit->total_flops; + ctx->last_cgraph_ptr = cgraph; + if (gen_env.stats) { + fprintf(stderr, "ggml_vk_graph_stats: nodes=%d dispatches=%llu syncs=%llu submits=1 cbs=%u dups=0 replay=1 cpu_record_us=%lld\n", + cgraph->n_nodes, (unsigned long long) hit->stat_dispatches, (unsigned long long) hit->stat_syncs, + n_cbs, (long long) (ggml_time_us() - gen_t_start)); + } + if (!ctx->device->support_async) { + ggml_vk_synchronize(ctx); + } + return GGML_STATUS_SUCCESS; + } + + const uint64_t max_replay_disp = AGX_REPLAY_MAX_CHUNKS * 1360u; + bool start_record = false; + if (hit != nullptr) { + ctx->replay_consec_misses = 0; + if (!hit->ready && hit->stable_runs >= 1 && hit->destroy_count == cur_destroy && + (!ggml_vk_is_apple_agx_coopmat(ctx->device) || hit->stat_dispatches <= max_replay_disp)) { + start_record = true; + } else if (ggml_vk_is_apple_agx_coopmat(ctx->device) && hit->stat_dispatches > max_replay_disp && + hit->destroy_count == cur_destroy) { + hit->lru_tick = ++ctx->replay_lru_clock; + } else { + ggml_vk_synchronize(ctx); + if (hit->cmd_pool.pool) { + ggml_vk_command_pool_cleanup(ctx->device, hit->cmd_pool); + } + hit->cmd_bufs.clear(); + hit->ready = false; + hit->destroy_count = cur_destroy; + hit->stable_runs = 1; + hit->lru_tick = ++ctx->replay_lru_clock; + } + } else { + bool in_probation = false; + for (uint32_t p = 0; p < VK_REPLAY_PROB_SLOTS; ++p) { + if (ctx->replay_probation_h1[p] == h1 && + ctx->replay_probation_h2[p] == h2) { + in_probation = true; + break; + } + } + const bool prealloc_steady = + (ctx->prealloc_size_x == 0 || (ctx->prealloc_x != nullptr && ctx->prealloc_x->size >= ctx->prealloc_size_x)) && + (ctx->prealloc_size_y == 0 || (ctx->prealloc_y != nullptr && ctx->prealloc_y->size >= ctx->prealloc_size_y)) && + (ctx->prealloc_size_split_k == 0 || (ctx->prealloc_split_k != nullptr && ctx->prealloc_split_k->size >= ctx->prealloc_size_split_k)) && + (ctx->prealloc_size_add_rms_partials == 0 || (ctx->prealloc_add_rms_partials != nullptr && ctx->prealloc_add_rms_partials->size >= ctx->prealloc_size_add_rms_partials)) && + (ctx->prealloc_size_mask_opt == 0 || (ctx->prealloc_mask_opt != nullptr && ctx->prealloc_mask_opt->size >= ctx->prealloc_size_mask_opt)); + const bool skip_probation = (cgraph == ctx->last_cgraph_ptr) && prealloc_steady && !ctx->replay_cache.empty(); + if (!in_probation && !skip_probation) { + const uint32_t slot = ctx->replay_probation_clock++ & (VK_REPLAY_PROB_SLOTS - 1u); + ctx->replay_probation_h1[slot] = h1; + ctx->replay_probation_h2[slot] = h2; + ctx->replay_probation_destroy[slot] = cur_destroy; + ctx->replay_miss_n_nodes = cgraph->n_nodes; + ++ctx->replay_consec_misses; + } else { + ctx->replay_consec_misses = 0; + if (ctx->replay_cache.size() >= VK_REPLAY_CACHE_MAX) { + ggml_vk_synchronize(ctx); + size_t victim = 0; + for (size_t k = 1; k < ctx->replay_cache.size(); ++k) { + if (ctx->replay_cache[k].lru_tick < ctx->replay_cache[victim].lru_tick) { + victim = k; + } + } + ggml_vk_destroy_replay_entry(ctx->device, ctx->replay_cache[victim]); + hit = &ctx->replay_cache[victim]; + } else { + ctx->replay_cache.emplace_back(); + hit = &ctx->replay_cache.back(); + } + hit->hash1 = h1; + hit->hash2 = h2; + hit->hash3 = h3; + hit->hash4 = h4; + hit->n_nodes = cgraph->n_nodes; + hit->sig_words = cur_sig; + hit->destroy_count = cur_destroy; + hit->stable_runs = 1; + hit->ready = false; + start_record = true; + } + } + + if (start_record && hit != nullptr) { + ggml_vk_synchronize(ctx); + if (!hit->cmd_pool.pool) { + hit->cmd_pool.cmd_buffers.clear(); + hit->cmd_pool.q = ctx->device->compute_queue.get(); + hit->cmd_pool.pool = ctx->device->device.createCommandPool({ + vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT), + ctx->device->compute_queue->queue_family_index + }); + } else { + ggml_vk_command_pool_cleanup(ctx->device, hit->cmd_pool); + } + hit->lru_tick = ++ctx->replay_lru_clock; + hit->pre_x_handle = cur_xh; hit->pre_x_size = cur_xsz; + hit->pre_y_handle = cur_yh; hit->pre_y_size = cur_ysz; + hit->pre_sk_handle = cur_skh; hit->pre_sk_size = cur_sks; + hit->pre_arp_handle = cur_ah; hit->pre_arp_size = cur_asz; + hit->pre_mo_handle = cur_moh; hit->pre_mo_size = cur_mos; + rec_entry = hit; + ctx->recording_replay = true; + ctx->replay_abort = false; + ctx->active_replay_cmd_pool = &hit->cmd_pool; + std::swap(ctx->descriptor_pools, hit->descriptor_pools); + std::swap(ctx->descriptor_sets, hit->descriptor_sets); + std::swap(ctx->descriptor_set_bindings, hit->descriptor_set_bindings); + std::swap(ctx->descriptor_set_bindings_destroy_count, hit->descriptor_destroy_count); + ctx->descriptor_set_idx = 0; + ctx->pipeline_descriptor_set_requirements = 0; + } + } + } + } if (ctx->prealloc_size_add_rms_partials) { ggml_vk_preallocate_buffers(ctx, nullptr); @@ -15582,59 +23042,885 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg ggml_vk_sync_buffers(ctx, compute_ctx); } - // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution. - // Estimate the amount of compute work using flops, and submit every 200 GFLOP - // (and scaled down based on total graph flops, so smaller models submit earlier). - // Also submit at least every 100 nodes, in case there are workloads without heavy compute. - uint32_t submitted_nodes = 0; - uint32_t submit_count = 0; - uint64_t batch_flops = 0; - uint64_t total_flops = 0; - uint64_t flops_cap = 200'000'000'000ULL; - - // On weaker AMD GPUs larger submissions can hit a driver timeout, submit more often to avoid this - if (ctx->device->vendor_id == VK_VENDOR_ID_AMD && ctx->device->shader_core_count > 0) { - if (ctx->device->architecture == AMD_GCN && ctx->device->shader_core_count < 32) { - flops_cap = 500'000'000ULL * ctx->device->shader_core_count; - } else if (ctx->device->architecture != AMD_GCN && ctx->device->shader_core_count < 24) { - flops_cap = 2'000'000'000ULL * ctx->device->shader_core_count; + // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution. + // Estimate the amount of compute work using flops, and submit every 200 GFLOP + // (and scaled down based on total graph flops, so smaller models submit earlier). + // Also submit at least every 100 nodes, in case there are workloads without heavy compute. + uint32_t submitted_nodes = 0; + uint32_t submit_count = 0; + uint64_t batch_flops = 0; + uint64_t total_flops = 0; + uint64_t flops_cap = 200'000'000'000ULL; + + // On weaker AMD GPUs larger submissions can hit a driver timeout, submit more often to avoid this + if (ctx->device->vendor_id == VK_VENDOR_ID_AMD && ctx->device->shader_core_count > 0) { + if (ctx->device->architecture == AMD_GCN && ctx->device->shader_core_count < 32) { + flops_cap = 500'000'000ULL * ctx->device->shader_core_count; + } else if (ctx->device->architecture != AMD_GCN && ctx->device->shader_core_count < 24) { + flops_cap = 2'000'000'000ULL * ctx->device->shader_core_count; + } + } + // small graphs gain nothing from splitting, each submit costs CPU time + uint64_t flops_per_submit = ctx->last_total_flops < 1'000'000'000ULL ? 0 : + std::clamp(ctx->last_total_flops / 40u, std::min(100'000'000ULL, flops_cap), flops_cap); + if (gen_env.flops_per_submit >= 0) { + flops_per_submit = (uint64_t) gen_env.flops_per_submit; + } + + // gen: submit policy (GGML_VK_SUBMIT_MODE): + // default upstream: every max_nodes_per_submit nodes and on the flops threshold + // one a single submit per graph (no flops/node/almost-ready submits) + // geo first submit after GGML_VK_SUBMIT_FIRST nodes (default 32), each later batch + // GGML_VK_SUBMIT_GROWTH times larger (default 4); no flops-based submits + static const int gen_submit_mode = [] { + const char * m = getenv("GGML_VK_SUBMIT_MODE"); + if (m == nullptr) return -1; + if (strcmp(m, "default") == 0) return 0; + if (strcmp(m, "one") == 0) return 1; + if (strcmp(m, "geo") == 0) return 2; + GGML_ABORT("GGML_VK_SUBMIT_MODE must be default, one or geo"); + }(); + const int eff_submit_mode = gen_submit_mode >= 0 + ? gen_submit_mode + : (ggml_vk_is_apple_agx_coopmat(ctx->device) ? 2 : 0); + static const uint32_t gen_submit_first = getenv("GGML_VK_SUBMIT_FIRST") ? (uint32_t) std::max(1, atoi(getenv("GGML_VK_SUBMIT_FIRST"))) : 96u; + static const uint32_t gen_submit_growth = getenv("GGML_VK_SUBMIT_GROWTH") ? (uint32_t) std::max(1, atoi(getenv("GGML_VK_SUBMIT_GROWTH"))) : 4096u; + uint32_t gen_max_nodes = ctx->device->max_nodes_per_submit; + if (eff_submit_mode == 1 || ctx->recording_replay) { + flops_per_submit = 0; + gen_max_nodes = UINT32_MAX; + } else if (eff_submit_mode == 2) { + bool has_mm_id = false; + for (int ni = 0; ni < cgraph->n_nodes; ++ni) { + if (cgraph->nodes[ni] && cgraph->nodes[ni]->op == GGML_OP_MUL_MAT_ID) { + has_mm_id = true; + break; + } + } + static const uint64_t env_submit_flops = getenv("GGML_VK_SUBMIT_FLOPS") ? strtoull(getenv("GGML_VK_SUBMIT_FLOPS"), nullptr, 10) : 25000000000000ULL; + flops_per_submit = (has_mm_id && !getenv("GGML_VK_SUBMIT_FLOPS")) ? 0 : env_submit_flops; + gen_max_nodes = gen_submit_first; + } + + uint64_t batch_disp_start = 0; + auto const submit_after = [&](int start, int end) { + if (ctx->device->serialize_submissions) { + try { + auto res = ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX); + if (res != vk::Result::eSuccess) { + GGML_LOG_ERROR("ggml_vulkan: waitForFences error during serialized submission\n"); + throw vk::SystemError(vk::make_error_code(res), "ggml_vulkan: waitForFences during serialized submission"); + } + } catch (vk::DeviceLostError &) { + ggml_vk_print_device_fault_info(ctx->device); + GGML_LOG_ERROR("ggml_vulkan: device lost on %s waiting for submission (nodes %d to %d):\n", + ctx->device->name.c_str(), start, end); + ggml_vk_print_node_list(cgraph, start, end); + throw; + } + ctx->device->device.resetFences({ ctx->fence }); + ctx->submit_pending = false; + ctx->device->diag_cgraph = cgraph; + ctx->device->diag_prev_start = start; + ctx->device->diag_prev_end = end; + } + first_node_in_batch = true; + submitted_nodes = 0; + batch_flops = 0; + batch_disp_start = ctx->stat_dispatches; + if (eff_submit_mode != 2 && submit_count < 3) { + flops_per_submit *= 2; + } + if (eff_submit_mode == 2) { + gen_max_nodes = gen_max_nodes > UINT32_MAX / gen_submit_growth ? UINT32_MAX : gen_max_nodes * gen_submit_growth; + } + submit_count++; + }; + + static const bool gen_gdn_inplace = getenv("GGML_GEN_GDN_INPLACE") ? (atoi(getenv("GGML_GEN_GDN_INPLACE")) != 0) : true; + static const int s10_max_sliding_nt = getenv("GGML_VK_SSM_SLIDING_MAX_NT") ? atoi(getenv("GGML_VK_SSM_SLIDING_MAX_NT")) : (ggml_vk_exact_s8_enabled() ? 32 : 65536); + struct s10_rb_info { + bool active = false; + int num_extra = 0; + int sr_idx = -1; + const ggml_tensor * conv = nullptr; + const ggml_tensor * state_out = nullptr; + const ggml_tensor * old_st = nullptr; + const ggml_tensor * qkv = nullptr; + uint32_t st_k = 0; + uint32_t st_slot_nb = 0; + }; + struct s10_pair_rms_info { + int rms0_idx = -1; + int sc0_idx = -1; + int rms1_idx = -1; + }; + std::vector s10_rb; + std::vector s10_pair_rms; + std::vector s12_zero_sc; + std::vector gen_deferred_rms; + std::vector gen_deferred_mm; + std::vector gen_skip; + static thread_local vk_cgraph_use_index use_idx; + if (!ctx->device->disable_fusion || gen_gdn_inplace || gen_fuse_enabled("mmgate") || gen_fuse_enabled("shexp")) { + gen_skip.assign(cgraph->n_nodes, 0); + use_idx.build(cgraph); + + if (!ctx->device->disable_fusion && !s10_ssm_conv_disabled()) { + for (int conv_idx = 1; conv_idx < cgraph->n_nodes; ++conv_idx) { + const ggml_tensor * conv = cgraph->nodes[conv_idx]; + if (conv->op != GGML_OP_SSM_CONV || !conv->src[0] || conv->src[0]->op != GGML_OP_CONCAT || gen_skip[conv_idx]) { + continue; + } + const ggml_tensor * concat = conv->src[0]; + int concat_idx = -1; + for (int k = conv_idx - 1; k >= std::max(0, conv_idx - 24); --k) { + if (cgraph->nodes[k] == concat) { + concat_idx = k; + break; + } + } + if (concat_idx < 0 || concat_idx >= last_node || gen_skip[concat_idx]) { + continue; + } + int sr_idx = -1; + for (int k = concat_idx + 1; k < conv_idx; ++k) { + const ggml_tensor * n = cgraph->nodes[k]; + if (n->op == GGML_OP_SET_ROWS && n->src[0] && n->src[0]->op == GGML_OP_VIEW && n->src[0]->view_src == concat) { + sr_idx = k; + break; + } + } + if (sr_idx < 0 || sr_idx >= last_node || gen_skip[sr_idx]) { + continue; + } + if (ggml_get_op_params_i32(concat, 0) != 0 || + concat->type != GGML_TYPE_F32 || conv->type != GGML_TYPE_F32 || + !ggml_is_contiguous(concat) || !ggml_is_contiguous(conv) || + !conv->buffer || get_misalign_bytes(ctx, conv) != 0) { + continue; + } + const ggml_tensor * c_w = conv->src[1]; + if (!c_w || c_w->type != GGML_TYPE_F32 || !ggml_is_contiguous_rows(c_w) || + !c_w->buffer || get_misalign_bytes(ctx, c_w) != 0) { + continue; + } + const int64_t nc = c_w->ne[0]; + const int64_t nr = c_w->ne[1]; + const int64_t n_t = conv->ne[1]; + const int64_t n_s = conv->ne[2]; + if (nc != 4 || conv->ne[0] != nr || conv->ne[3] != 1 || n_t < 1 || n_t > s10_max_sliding_nt || n_s < 1 || + concat->ne[0] != (nc - 1) + n_t || concat->ne[1] != nr || concat->ne[2] != n_s || concat->ne[3] != 1) { + continue; + } + const ggml_tensor * old_st = concat->src[0]; + const ggml_tensor * qkv = concat->src[1]; + if (!old_st || !qkv || old_st->type != GGML_TYPE_F32 || qkv->type != GGML_TYPE_F32 || + !old_st->buffer || !qkv->buffer || + get_misalign_bytes(ctx, old_st) != 0 || get_misalign_bytes(ctx, qkv) != 0 || + old_st->ne[0] != nc - 1 || old_st->ne[1] != nr || old_st->ne[2] != n_s || old_st->ne[3] != 1 || + old_st->nb[0] != sizeof(float) || (old_st->nb[1] % sizeof(float)) != 0 || (old_st->nb[2] % sizeof(float)) != 0 || + qkv->ne[0] != n_t || qkv->ne[1] != nr || qkv->ne[2] != n_s || qkv->ne[3] != 1 || + (qkv->nb[0] % sizeof(float)) != 0 || (qkv->nb[1] % sizeof(float)) != 0 || (qkv->nb[2] % sizeof(float)) != 0) { + continue; + } + const ggml_tensor * sr = cgraph->nodes[sr_idx]; + const int64_t K = sr->ne[1]; + const int64_t Kw = std::min(n_t, K); + if (K < 1 || sr->type != GGML_TYPE_F32 || !sr->buffer || get_misalign_bytes(ctx, sr) != 0 || + sr->ne[0] != nc - 1 || sr->ne[2] != nr || sr->ne[3] != n_s || + sr->nb[0] != sizeof(float) || (sr->nb[1] % sizeof(float)) != 0 || + (sr->nb[2] % sizeof(float)) != 0 || (sr->nb[3] % sizeof(float)) != 0) { + continue; + } + const ggml_tensor * windows = sr->src[0]; + const ggml_tensor * slot_order = sr->src[1]; + if (!windows || windows->op != GGML_OP_VIEW || windows->view_src != concat || windows->type != GGML_TYPE_F32 || + windows->ne[0] != nc - 1 || windows->ne[1] != Kw || windows->ne[2] != nr || windows->ne[3] != n_s || + windows->nb[0] != sizeof(float) || windows->nb[1] != sizeof(float) || + windows->nb[2] != concat->nb[1] || windows->nb[3] != concat->nb[2] || + windows->view_offs != (size_t)(n_t - (Kw - 1)) * sizeof(float) || + !slot_order || slot_order->op != GGML_OP_VIEW || slot_order->type != GGML_TYPE_I32 || + slot_order->ne[0] != Kw || ggml_nrows(slot_order) != 1 || slot_order->nb[0] != sizeof(int32_t) || + slot_order->view_offs != (size_t)(K - Kw) * sizeof(int32_t)) { + continue; + } + const ggml_tensor * cast_i32 = slot_order->view_src; + const ggml_tensor * sc = cast_i32 ? cast_i32->src[0] : nullptr; + const ggml_tensor * ar = sc ? sc->src[0] : nullptr; + if (!cast_i32 || cast_i32->op != GGML_OP_CPY || cast_i32->type != GGML_TYPE_I32 || cast_i32->src[1] != cast_i32 || + cast_i32->ne[0] != K || ggml_nrows(cast_i32) != 1 || !ggml_is_contiguous(cast_i32) || + !sc || sc->op != GGML_OP_SCALE || sc->type != GGML_TYPE_F32 || + sc->ne[0] != K || ggml_nrows(sc) != 1 || + ggml_get_op_params_f32(sc, 0) != -1.0f || ggml_get_op_params_f32(sc, 1) != (float)(K - 1) || + !ar || ar->op != GGML_OP_ARANGE || ar->type != GGML_TYPE_F32 || + ar->ne[0] != K || ggml_nrows(ar) != 1 || + ggml_get_op_params_f32(ar, 0) != 0.0f || ggml_get_op_params_f32(ar, 1) != (float)K || ggml_get_op_params_f32(ar, 2) != 1.0f) { + continue; + } + if ((concat->flags & GGML_TENSOR_FLAG_OUTPUT) || (windows->flags & GGML_TENSOR_FLAG_OUTPUT) || (sr->flags & GGML_TENSOR_FLAG_OUTPUT)) { + continue; + } + if (use_idx.any_reader(concat, [&](int k) { return k != sr_idx && k != conv_idx && !ggml_op_is_empty(cgraph->nodes[k]->op); }) || + use_idx.any_reader(windows, [&](int k) { return k != sr_idx && !ggml_op_is_empty(cgraph->nodes[k]->op); }) || + use_idx.any_reader(sr, [&](int k) { return !ggml_op_is_empty(cgraph->nodes[k]->op); })) { + continue; + } + int end_idx = conv_idx; + const ggml_tensor * final_dst = conv; + if (conv_idx + 1 <= last_node && !gen_skip[conv_idx + 1] && !(conv->flags & GGML_TENSOR_FLAG_OUTPUT)) { + const ggml_tensor * u = cgraph->nodes[conv_idx + 1]; + if (u->op == GGML_OP_UNARY && ggml_get_unary_op(u) == GGML_UNARY_OP_SILU && + u->src[0] == conv && u->type == GGML_TYPE_F32 && + ggml_are_same_shape(u, conv) && ggml_are_same_stride(u, conv) && + u->buffer && get_misalign_bytes(ctx, u) == 0 && + !use_idx.any_reader(conv, [&](int k) { return k != conv_idx + 1 && !ggml_op_is_empty(cgraph->nodes[k]->op); })) { + end_idx = conv_idx + 1; + final_dst = u; + } + } + if (ggml_vk_tensors_overlap_strided(old_st, sr) || + ggml_vk_tensors_overlap_strided(qkv, sr) || + ggml_vk_tensors_overlap_strided(c_w, sr) || + ggml_vk_tensors_overlap_strided(sr, final_dst) || + ggml_vk_tensors_overlap_strided(old_st, final_dst) || + ggml_vk_tensors_overlap_strided(qkv, final_dst) || + ggml_vk_tensors_overlap_strided(c_w, final_dst)) { + continue; + } + int cast_idx = -1, sc_idx = -1, ar_idx = -1; + for (int k = std::max(0, concat_idx - 8); k < sr_idx; ++k) { + if (cgraph->nodes[k] == cast_i32) cast_idx = k; + else if (cgraph->nodes[k] == sc) sc_idx = k; + else if (cgraph->nodes[k] == ar) ar_idx = k; + } + bool mid_hazard = false; + for (int m_idx = concat_idx + 1; m_idx < conv_idx; ++m_idx) { + if (m_idx == sr_idx || m_idx == cast_idx || m_idx == sc_idx || m_idx == ar_idx || gen_skip[m_idx]) { + continue; + } + const ggml_tensor * mid = cgraph->nodes[m_idx]; + if (ggml_op_is_empty(mid->op)) { + continue; + } + if (mid->buffer && (ggml_vk_tensors_overlap_strided(mid, old_st) || + ggml_vk_tensors_overlap_strided(mid, qkv) || + ggml_vk_tensors_overlap_strided(mid, sr))) { + mid_hazard = true; + break; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + if (mid->src[s] && mid->src[s]->buffer && ggml_vk_tensors_overlap_strided(mid->src[s], sr)) { + mid_hazard = true; + break; + } + } + if (mid_hazard) { + break; + } + } + if (mid_hazard) { + continue; + } + if (s10_rb.empty()) { + s10_rb.resize(cgraph->n_nodes); + } + s10_rb[conv_idx] = { + true, + end_idx - conv_idx, + sr_idx, + conv, + sr, + old_st, + qkv, + (uint32_t) K, + (uint32_t) sr->nb[1], + }; + gen_skip[concat_idx] = 1; + gen_skip[sr_idx] = 1; + if (cast_idx >= 0 && cast_idx < last_node && !(cast_i32->flags & GGML_TENSOR_FLAG_OUTPUT) && + !use_idx.any_reader(slot_order, [&](int k) { return k != sr_idx && !ggml_op_is_empty(cgraph->nodes[k]->op); }) && + !use_idx.any_reader(cast_i32, [&](int k) { return k != sr_idx && !ggml_op_is_empty(cgraph->nodes[k]->op); })) { + gen_skip[cast_idx] = 1; + if (sc_idx >= 0 && sc_idx < last_node && !(sc->flags & GGML_TENSOR_FLAG_OUTPUT) && + !use_idx.any_reader(sc, [&](int k) { return k != cast_idx && !ggml_op_is_empty(cgraph->nodes[k]->op); })) { + gen_skip[sc_idx] = 1; + if (ar_idx >= 0 && ar_idx < last_node && !(ar->flags & GGML_TENSOR_FLAG_OUTPUT) && + !use_idx.any_reader(ar, [&](int k) { return k != sc_idx && !ggml_op_is_empty(cgraph->nodes[k]->op); })) { + gen_skip[ar_idx] = 1; + } + } + } + } + } + + if (!ctx->device->disable_fusion && gen_fuse_enabled("l2") && !ctx->do_add_rms_partials) { + for (int rms0_idx = 0; rms0_idx < cgraph->n_nodes; ++rms0_idx) { + if (gen_skip[rms0_idx] || cgraph->nodes[rms0_idx]->op != GGML_OP_RMS_NORM) { + continue; + } + const int sc0_idx = gen_find_rms_norm_scale(ctx, cgraph, rms0_idx, last_node, use_idx); + if (sc0_idx < 0 || sc0_idx >= last_node || gen_skip[sc0_idx]) { + continue; + } + int rms1_idx = -1, sc1_idx = -1; + for (int j = rms0_idx + 1; j <= std::min(cgraph->n_nodes - 1, sc0_idx + 6); ++j) { + if (j == sc0_idx || gen_skip[j] || cgraph->nodes[j]->op != GGML_OP_RMS_NORM) { + continue; + } + const int cand_sc1 = gen_find_rms_norm_scale(ctx, cgraph, j, last_node, use_idx); + if (cand_sc1 > sc0_idx && cand_sc1 <= sc0_idx + 8 && !gen_skip[cand_sc1]) { + rms1_idx = j; + sc1_idx = cand_sc1; + break; + } + } + if (rms1_idx < 0 || sc1_idx < 0) { + continue; + } + const ggml_tensor * rms0 = cgraph->nodes[rms0_idx]; + const ggml_tensor * sc0 = cgraph->nodes[sc0_idx]; + const ggml_tensor * rms1 = cgraph->nodes[rms1_idx]; + const ggml_tensor * sc1 = cgraph->nodes[sc1_idx]; + const ggml_tensor * r0 = rms0->src[0]; + const ggml_tensor * r1 = rms1->src[0]; + if (!r0 || !r1 || !r0->buffer || r0->buffer != r1->buffer || + !ggml_are_same_shape(r0, r1) || !ggml_are_same_stride(r0, r1) || + r0->nb[0] != sizeof(float) || (r0->nb[1] % sizeof(float)) != 0 || + (r0->nb[2] % sizeof(float)) != 0 || (r0->nb[3] % sizeof(float)) != 0 || + (get_misalign_bytes(ctx, r0) % sizeof(float)) != 0 || + (vk_tensor_offset(r1) + r1->view_offs) != (vk_tensor_offset(r0) + r0->view_offs) + (size_t)r0->ne[1] * r0->nb[1] || + 2 * (uint64_t)r0->ne[1] > ctx->device->properties.limits.maxComputeWorkGroupCount[0] || + ggml_get_op_params_f32(rms0, 0) != ggml_get_op_params_f32(rms1, 0) || + ggml_get_op_params_f32(sc0, 0) != ggml_get_op_params_f32(sc1, 0) || + (get_misalign_bytes(ctx, sc0) % sizeof(float)) != 0 || + (get_misalign_bytes(ctx, sc1) % sizeof(float)) != 0 || + (get_misalign_bytes(ctx, sc1) / sizeof(float)) > 0xFFFFFFu || + ggml_vk_tensors_overlap_strided(sc0, sc1) || + ggml_vk_tensors_overlap_strided(r0, sc0) || + ggml_vk_tensors_overlap_strided(r0, sc1) || + ggml_vk_tensors_overlap_strided(r1, sc0) || + ggml_vk_tensors_overlap_strided(r1, sc1)) { + continue; + } + if ((sc0->flags & GGML_TENSOR_FLAG_OUTPUT) || + use_idx.any_reader(sc0, [&](int k) { return k > sc0_idx && k < sc1_idx && k != rms1_idx && !ggml_op_is_empty(cgraph->nodes[k]->op); })) { + continue; + } + bool mid_hazard = false; + for (int m_idx = rms0_idx + 1; m_idx < sc1_idx; ++m_idx) { + if (m_idx == sc0_idx || m_idx == rms1_idx || gen_skip[m_idx]) { + continue; + } + const ggml_tensor * mid = cgraph->nodes[m_idx]; + if (ggml_op_is_empty(mid->op)) { + continue; + } + if (mid->buffer && (ggml_vk_tensors_overlap_strided(mid, r0) || + ggml_vk_tensors_overlap_strided(mid, r1) || + (m_idx > sc0_idx && ggml_vk_tensors_overlap_strided(mid, sc0)))) { + mid_hazard = true; + break; + } + if (m_idx > sc0_idx) { + for (int s = 0; s < GGML_MAX_SRC; ++s) { + if (mid->src[s] && mid->src[s]->buffer && ggml_vk_tensors_overlap_strided(mid->src[s], sc0)) { + mid_hazard = true; + break; + } + } + } + if (mid_hazard) { + break; + } + } + if (mid_hazard) { + continue; + } + if (s10_pair_rms.empty()) { + s10_pair_rms.resize(cgraph->n_nodes); + } + s10_pair_rms[sc1_idx] = { rms0_idx, sc0_idx, rms1_idx }; + gen_skip[rms0_idx] = 1; + gen_skip[sc0_idx] = 1; + gen_skip[rms1_idx] = 1; + rms0_idx = sc1_idx; + } + } + + static const bool s12_zero_state_disabled = + getenv("GGML_VK_DISABLE_ZERO_STATE") != nullptr && atoi(getenv("GGML_VK_DISABLE_ZERO_STATE")) != 0; + if (!ctx->device->disable_fusion && !ggml_vk_exact_s8_enabled() && !s12_zero_state_disabled) { + auto same_vk_slice = [&](const ggml_tensor * a, const ggml_tensor * b) -> bool { + if (!a || !b || a->type != GGML_TYPE_F32 || b->type != GGML_TYPE_F32 || + !ggml_is_contiguous(a) || !ggml_is_contiguous(b) || + !a->buffer || !b->buffer || + !ggml_backend_buffer_is_vk(a->buffer) || !ggml_backend_buffer_is_vk(b->buffer)) { + return false; + } + const auto * ab = (const ggml_backend_vk_buffer_context *) a->buffer->context; + const auto * bb = (const ggml_backend_vk_buffer_context *) b->buffer->context; + if (!ab || !bb || ab->dev_buffer != bb->dev_buffer) { + return false; + } + const size_t nb = ggml_nbytes(a); + return nb > 0 && nb == ggml_nbytes(b) && + vk_tensor_offset(a) + a->view_offs == vk_tensor_offset(b) + b->view_offs; + }; + auto find_prior_zero_scale = [&](int consumer_idx, const ggml_tensor * st_in, const ggml_tensor * st_out) -> int { + if (!same_vk_slice(st_in, st_out)) { + return -1; + } + for (int k = consumer_idx - 1; k >= 0; --k) { + if (gen_skip[k]) { + continue; + } + const ggml_tensor * m = cgraph->nodes[k]; + if (ggml_op_is_empty(m->op)) { + continue; + } + if (m->op == GGML_OP_SCALE && k < last_node && + !(m->flags & GGML_TENSOR_FLAG_OUTPUT) && + ggml_get_op_params_f32(m, 0) == 0.0f && + ggml_get_op_params_f32(m, 1) == 0.0f && + same_vk_slice(m, st_in) && + !use_idx.any_reader(m, [&](int r) { + return r != consumer_idx && !gen_skip[r] && !ggml_op_is_empty(cgraph->nodes[r]->op); + })) { + return k; + } + if (m->buffer && ggml_vk_tensors_overlap_strided(m, st_in)) { + return -1; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + if (m->src[s] && m->src[s]->buffer && ggml_vk_tensors_overlap_strided(m->src[s], st_in)) { + return -1; + } + } + } + return -1; + }; + for (int idx = 0; idx < cgraph->n_nodes; ++idx) { + if (gen_skip[idx]) { + continue; + } + int sc_idx = -1; + if (!s10_rb.empty() && s10_rb[idx].active && s10_rb[idx].conv->ne[1] >= (int64_t) s10_rb[idx].st_k) { + sc_idx = find_prior_zero_scale(idx, s10_rb[idx].old_st, s10_rb[idx].state_out); + } else if (cgraph->nodes[idx]->op == GGML_OP_CONCAT && idx + 3 < cgraph->n_nodes) { + const uint32_t saved_wmask = ctx->fused_ops_write_mask; + const int n_ssm = s10_can_fuse_ssm_conv(ctx, cgraph, idx, gen_skip, use_idx); + const bool is_mode1 = n_ssm > 0 && ctx->s10_ssm_conv_mode == 1; + ctx->s10_ssm_conv_mode = 0; + ctx->s10_ssm_conv_node = nullptr; + ctx->s10_ssm_state_out = nullptr; + ctx->s10_ssm_old_st = nullptr; + ctx->s10_ssm_qkv = nullptr; + ctx->s10_ssm_st_k = 0; + ctx->s10_ssm_st_slot_nb = 0; + ctx->fused_ops_write_mask = saved_wmask; + if (is_mode1) { + sc_idx = find_prior_zero_scale(idx, cgraph->nodes[idx]->src[0], cgraph->nodes[idx + 2]); + } + } else if (gen_gdn_inplace && cgraph->nodes[idx]->op == GGML_OP_GATED_DELTA_NET) { + const ggml_tensor * gdn = cgraph->nodes[idx]; + const int32_t gdn_k = ggml_get_op_params_i32(gdn, 0); + if (gdn_k >= 1 && gdn->src[2] && gdn->src[2]->ne[2] >= gdn_k) { + const int cpy_idx = gen_find_gdn_state_cpy(ctx, cgraph, idx, last_node, use_idx); + if (cpy_idx >= 0) { + sc_idx = find_prior_zero_scale(idx, gdn->src[5], cgraph->nodes[cpy_idx]); + } + } + } + if (sc_idx >= 0) { + if (s12_zero_sc.empty()) { + s12_zero_sc.assign(cgraph->n_nodes, -1); + } + s12_zero_sc[idx] = sc_idx; + gen_skip[sc_idx] = 1; + } + } + } + } + + // Series 17 (A5): Pre-scan MUL_MAT_ID + per-expert .scale [REPEAT?, GET_ROWS(w_s, ids), MUL(mmid, gr), MUL?(weights)] + // so REPEAT and GET_ROWS are skipped even when scheduled BEFORE MUL_MAT_ID! + struct s17_mmid_exp_info { + const ggml_tensor * dst {}; + const ggml_tensor * f0 {}; + const ggml_tensor * f1 {}; + uint32_t flags {}; + float glu_alpha {}; + float glu_limit {}; + int skip[5] { -1, -1, -1, -1, -1 }; + int sole_down_idx { -1 }; + }; + std::vector s17_mmid_exp; + if (!ctx->device->disable_fusion && !getenv("GGML_VK_DISABLE_S17_EXP_SCALE")) { + for (int idx = 0; idx < last_node; ++idx) { + if (!gen_skip.empty() && gen_skip[idx]) { + continue; + } + const ggml_tensor * mmid = cgraph->nodes[idx]; + if (!mmid || mmid->op != GGML_OP_MUL_MAT_ID || mmid->type != GGML_TYPE_F32 || + (mmid->flags & GGML_TENSOR_FLAG_OUTPUT) || !mmid->buffer || get_misalign_bytes(ctx, mmid) != 0) { + continue; + } + if (!ggml_vk_use_mul_mat_vec_id(ctx, cgraph, idx) && !gen_uses_cm1_fused_mmid(ctx, mmid)) { + continue; + } + const ggml_tensor * ids = mmid->src[2]; + const int64_t n_expert = mmid->src[0]->ne[2]; + int mul0_idx = -1; + for (int j = idx + 1; j < std::min(last_node, idx + 16); ++j) { + const ggml_tensor * nj = cgraph->nodes[j]; + if (nj->op == GGML_OP_MUL && nj->src[0] == mmid) { + mul0_idx = j; + break; + } + } + if (mul0_idx < 0 || use_idx.any_reader(mmid, [&](int k) { return k != mul0_idx; })) { + continue; + } + const ggml_tensor * mul0 = cgraph->nodes[mul0_idx]; + const ggml_tensor * gr = mul0->src[1]; + if (!gr || gr->op != GGML_OP_GET_ROWS || gr->src[1] != ids || (gr->flags & GGML_TENSOR_FLAG_OUTPUT)) { + continue; + } + const int gr_idx = use_idx.first_node_idx(gr); + if (gr_idx < 0 || use_idx.any_reader(gr, [&](int k) { return k != mul0_idx; })) { + continue; + } + const ggml_tensor * s_cur = gr->src[0]; + int rep_idx = -1; + if (s_cur && s_cur->op == GGML_OP_REPEAT) { + if ((s_cur->flags & GGML_TENSOR_FLAG_OUTPUT) || use_idx.any_reader(s_cur, [&](int k) { return k != gr_idx; })) { + continue; + } + rep_idx = use_idx.first_node_idx(s_cur); + s_cur = s_cur->src[0]; + } + while (s_cur && (s_cur->op == GGML_OP_RESHAPE || s_cur->op == GGML_OP_VIEW) && s_cur->view_offs == 0) { + s_cur = s_cur->view_src; + } + if (!s_cur || s_cur->op != GGML_OP_NONE || s_cur->type != GGML_TYPE_F32 || + s_cur->ne[0] != n_expert || ggml_nrows(s_cur) != 1 || + !ggml_is_contiguous(s_cur) || !s_cur->buffer || get_misalign_bytes(ctx, s_cur) != 0) { + continue; + } + // Optional trailing MUL(mul0, router_weights): + int mul1_idx = -1; + const ggml_tensor * f1_t = nullptr; + uint32_t flags = MAT_VEC_FUSION_FLAGS_EXP_SCALE0; + if (!(mul0->flags & GGML_TENSOR_FLAG_OUTPUT)) { + for (int j = mul0_idx + 1; j < std::min(last_node, mul0_idx + 8); ++j) { + const ggml_tensor * nj = cgraph->nodes[j]; + if (nj->op == GGML_OP_MUL && nj->src[0] == mul0) { + const ggml_tensor * ts = nj->src[1]; + const int ts_idx = ts ? use_idx.first_node_idx(ts) : -1; + const bool ts_ready = ts && (ts->op == GGML_OP_NONE || (ts_idx >= 0 && ts_idx < idx)); + if (ts_ready && ts->type == GGML_TYPE_F32 && ggml_is_contiguous(ts) && + ts->buffer && get_misalign_bytes(ctx, ts) == 0 && + ts->ne[0] == 1 && ts->ne[1] == nj->ne[1] && + (ts->ne[2] == 1 || ts->ne[2] == nj->ne[2]) && ts->ne[3] == 1 && + !use_idx.any_reader(mul0, [&](int k) { return k != j; })) { + mul1_idx = j; + f1_t = ts; + flags |= MAT_VEC_FUSION_FLAGS_SCALE1; + if (ts->ne[2] == ids->ne[1] && ids->ne[1] > 1) { + flags |= MAT_VEC_FUSION_FLAGS_SCALE1_TOK; + } + } + break; + } + } + } + const int final_idx = mul1_idx >= 0 ? mul1_idx : mul0_idx; + const ggml_tensor * dst_out = cgraph->nodes[final_idx]; + if (!dst_out || dst_out->type != GGML_TYPE_F32 || !ggml_is_contiguous(dst_out) || + !ggml_are_same_shape(dst_out, mmid) || !ggml_are_same_stride(dst_out, mmid) || + !dst_out->buffer || get_misalign_bytes(ctx, dst_out) != 0) { + continue; + } + if (ggml_vk_tensors_overlap(mmid->src[0], dst_out, false) || + ggml_vk_tensors_overlap(mmid->src[1], dst_out, false) || + ggml_vk_tensors_overlap(ids, dst_out, false) || + ggml_vk_tensors_overlap(s_cur, dst_out, false) || + (f1_t && ggml_vk_tensors_overlap(f1_t, dst_out, false))) { + continue; + } + auto is_sk = [&](int k) { + return k == rep_idx || k == gr_idx || k == mul0_idx || k == mul1_idx; + }; + bool hazard = false; + for (int k = idx + 1; k < final_idx; ++k) { + const ggml_tensor * nk = cgraph->nodes[k]; + if (is_sk(k) || ggml_op_is_empty(nk->op)) { + continue; + } + if (nk->buffer && (ggml_vk_tensors_overlap(nk, dst_out, false) || ggml_vk_tensors_overlap(nk, mmid, false))) { + hazard = true; break; + } + if (f1_t && nk->buffer && ggml_vk_tensors_overlap(nk, f1_t, false)) { + hazard = true; break; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + if (nk->src[s] && nk->src[s]->buffer && + (ggml_vk_tensors_overlap(nk->src[s], dst_out, false) || ggml_vk_tensors_overlap(nk->src[s], mmid, false))) { + hazard = true; break; + } + } + if (hazard) break; + } + if (hazard) { + continue; + } + if (s17_mmid_exp.empty()) { + s17_mmid_exp.resize(cgraph->n_nodes); + } + if (gen_skip.empty()) { + gen_skip.assign(cgraph->n_nodes, 0); + } + s17_mmid_exp[idx] = { dst_out, s_cur, f1_t, flags, 0.0f, 0.0f, { rep_idx, gr_idx, mul0_idx, mul1_idx, -1 }, -1 }; + if (rep_idx >= 0) gen_skip[rep_idx] = 1; + if (gr_idx >= 0) gen_skip[gr_idx] = 1; + if (mul0_idx >= 0) gen_skip[mul0_idx] = 1; + if (mul1_idx >= 0) gen_skip[mul1_idx] = 1; + } + } + + // Series 19 (W4.5): Fuse unsplit GGML_GLU_OP_SITU (+ optional EXP_SCALE0) into mul_mv_mma_id FUSE_MODE=3 for 2 <= N <= 2048 + static const int env_s19_situ_max_n = getenv("GGML_VK_S19_SITU_MAX_N") ? atoi(getenv("GGML_VK_S19_SITU_MAX_N")) : 2048; + if (!ctx->device->disable_fusion && gen_fuse_enabled("glu") && !getenv("GGML_VK_DISABLE_S19_MMID_SITU") && + ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled() && !getenv("GGML_VK_DISABLE_MMA_ID")) { + for (int idx = 0; idx < last_node; ++idx) { + if (!gen_skip.empty() && gen_skip[idx]) { + continue; + } + const ggml_tensor * mmid = cgraph->nodes[idx]; + if (!mmid || mmid->op != GGML_OP_MUL_MAT_ID || mmid->type != GGML_TYPE_F32 || + (mmid->flags & GGML_TENSOR_FLAG_OUTPUT) || !mmid->buffer || get_misalign_bytes(ctx, mmid) != 0) { + continue; + } + const ggml_tensor * w0 = mmid->src[0]; + const ggml_tensor * b1 = mmid->src[1]; + const ggml_tensor * ids = mmid->src[2]; + const bool uses_mmv_id = ggml_vk_use_mul_mat_vec_id(ctx, cgraph, idx) || ids->ne[1] <= (int64_t)ctx->device->mmv_id_max_tokens; + if (!w0 || !b1 || !ids || (w0->type != GGML_TYPE_NVFP4 && w0->type != GGML_TYPE_Q8_0) || + (w0->type == GGML_TYPE_Q8_0 && uses_mmv_id && ggml_vk_tensor_is_repack(w0)) || + (uses_mmv_id && getenv("GGML_VK_ENABLE_S19_MMVID_SITU") == nullptr) || + !ggml_vk_dim01_contiguous(w0) || b1->type != GGML_TYPE_F32 || (get_misalign_bytes(ctx, b1) % 4 != 0) || + (b1->ne[0] % 64 != 0) || (w0->ne[1] % 16 != 0) || (w0->ne[1] / 2) < 64 || + !(b1->ne[1] == 1 || b1->ne[1] >= ids->ne[0]) || + ids->ne[1] > env_s19_situ_max_n || gen_batch_invariant_for_n(ids->ne[1])) { + continue; + } + const bool has_exp = !s17_mmid_exp.empty() && s17_mmid_exp[idx].dst != nullptr && + s17_mmid_exp[idx].flags == MAT_VEC_FUSION_FLAGS_EXP_SCALE0; + if (!has_exp && !s17_mmid_exp.empty() && s17_mmid_exp[idx].dst != nullptr) { + continue; + } + const ggml_tensor * prev_dst = has_exp ? s17_mmid_exp[idx].dst : mmid; + const int prev_idx = has_exp ? s17_mmid_exp[idx].skip[2] : idx; + if (!prev_dst || prev_idx < idx || (prev_dst->flags & GGML_TENSOR_FLAG_OUTPUT)) { + continue; + } + int glu_idx = -1; + for (int j = prev_idx + 1; j < std::min(last_node, prev_idx + 24); ++j) { + if (!gen_skip.empty() && gen_skip[j]) { + continue; + } + const ggml_tensor * nj = cgraph->nodes[j]; + if (nj && nj->op == GGML_OP_GLU && nj->src[0] == prev_dst) { + glu_idx = j; + break; + } + } + if (glu_idx < 0) { + continue; + } + const ggml_tensor * glu = cgraph->nodes[glu_idx]; + if (ggml_get_glu_op(glu) != GGML_GLU_OP_SITU || glu->src[1] != nullptr || ggml_get_op_params_i32(glu, 1) != 0 || + glu->type != GGML_TYPE_F32 || !ggml_is_contiguous(glu) || !glu->buffer || get_misalign_bytes(ctx, glu) != 0 || + glu->ne[0] * 2 != mmid->ne[0] || glu->ne[1] != mmid->ne[1] || glu->ne[2] != mmid->ne[2] || glu->ne[3] != 1 || + use_idx.any_reader(prev_dst, [&](int k) { return k != glu_idx; })) { + continue; + } + const ggml_tensor * f0_t = has_exp ? s17_mmid_exp[idx].f0 : nullptr; + auto is_sk = [&](int k) { + if (k == glu_idx) return true; + if (has_exp) { + for (int sk : s17_mmid_exp[idx].skip) { if (sk == k) return true; } + } + return false; + }; + int sole_down_idx = -1; + if (!uses_mmv_id && !(glu->flags & GGML_TENSOR_FLAG_OUTPUT)) { + for (int j = glu_idx + 1; j < std::min(cgraph->n_nodes, glu_idx + 16); ++j) { + const ggml_tensor * nj = cgraph->nodes[j]; + if (is_sk(j) || (!gen_skip.empty() && gen_skip[j]) || ggml_op_is_empty(nj->op)) { + continue; + } + if (nj->op == GGML_OP_MUL_MAT_ID && nj->src[1] == glu && nj->src[2] == ids && + nj->src[0] && nj->src[0]->type != GGML_TYPE_F32 && nj->src[0]->ne[1] >= 32 && + (glu->ne[0] % ((nj->src[0]->type == GGML_TYPE_Q4_0) ? 32 : 64) == 0) && + !use_idx.any_reader(glu, [&](int r) { return r != j; })) { + bool mid_non_empty = false; + for (int k = idx + 1; k < j; ++k) { + if (!is_sk(k) && (gen_skip.empty() || !gen_skip[k]) && !ggml_op_is_empty(cgraph->nodes[k]->op)) { + mid_non_empty = true; + break; + } + } + if (!mid_non_empty) { + sole_down_idx = j; + } + } + break; + } + } + static const bool s19_dis_pglu_f16 = getenv("GGML_VK_DISABLE_PGLU_F16_OUT") != nullptr; + static const bool s19_keep_pglu_f32 = getenv("GGML_VK_KEEP_PGLU_F32") != nullptr; + static const int s19_env_id_f16_b = getenv("GGML_VK_MMA_ID_F16_B") ? atoi(getenv("GGML_VK_MMA_ID_F16_B")) : -1; + const bool ids_non_neg = (ids->op == GGML_OP_ARGSORT) || (ids->view_src && ids->view_src->op == GGML_OP_ARGSORT); + const bool will_skip_f32_d = sole_down_idx >= 0 && ids_non_neg && + !s19_dis_pglu_f16 && !s19_keep_pglu_f32 && + ctx->prealloc_y_ring_count >= 2 && + ((ggml_vk_is_apple_agx_coopmat(ctx->device) && s19_env_id_f16_b != 0) || s19_env_id_f16_b == 1) && + b1 && (b1->ne[0] % 64 == 0) && + (b1->type == GGML_TYPE_F32 || b1->type == GGML_TYPE_F16) && + ggml_vk_dim01_contiguous(w0); + if (has_exp && !will_skip_f32_d) { + continue; + } + if (!will_skip_f32_d && + (ggml_vk_tensors_overlap(w0, glu, false) || ggml_vk_tensors_overlap(b1, glu, false) || + ggml_vk_tensors_overlap(ids, glu, false) || (f0_t && ggml_vk_tensors_overlap(f0_t, glu, false)))) { + continue; + } + bool hazard = false; + for (int k = idx + 1; k < glu_idx; ++k) { + const ggml_tensor * nk = cgraph->nodes[k]; + if (is_sk(k) || ggml_op_is_empty(nk->op)) continue; + if (nk->buffer && ((!will_skip_f32_d && ggml_vk_tensors_overlap(nk, glu, false)) || ggml_vk_tensors_overlap(nk, prev_dst, false) || ggml_vk_tensors_overlap(nk, mmid, false))) { + hazard = true; break; + } + if (nk->buffer && (ggml_vk_tensors_overlap(nk, b1, false) || ggml_vk_tensors_overlap(nk, ids, false) || (f0_t && ggml_vk_tensors_overlap(nk, f0_t, false)))) { + hazard = true; break; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + if (nk->src[s] && nk->src[s]->buffer && + ((!will_skip_f32_d && ggml_vk_tensors_overlap(nk->src[s], glu, false)) || ggml_vk_tensors_overlap(nk->src[s], prev_dst, false))) { + hazard = true; break; + } + } + if (hazard) break; + } + if (hazard) continue; + if (s17_mmid_exp.empty()) s17_mmid_exp.resize(cgraph->n_nodes); + if (gen_skip.empty()) gen_skip.assign(cgraph->n_nodes, 0); + if (has_exp) { + s17_mmid_exp[idx].dst = glu; + s17_mmid_exp[idx].flags |= MAT_VEC_FUSION_FLAGS_SITU_MERGED; + s17_mmid_exp[idx].glu_alpha = ggml_get_op_params_f32(glu, 2); + s17_mmid_exp[idx].glu_limit = ggml_get_op_params_f32(glu, 3); + s17_mmid_exp[idx].skip[4] = glu_idx; + s17_mmid_exp[idx].sole_down_idx = sole_down_idx; + } else { + s17_mmid_exp[idx] = { glu, nullptr, nullptr, MAT_VEC_FUSION_FLAGS_SITU_MERGED, + ggml_get_op_params_f32(glu, 2), ggml_get_op_params_f32(glu, 3), + { -1, -1, -1, -1, glu_idx }, sole_down_idx }; + } + gen_skip[glu_idx] = 1; } } - // small graphs gain nothing from splitting, each submit costs CPU time - uint64_t flops_per_submit = ctx->last_total_flops < 1'000'000'000ULL ? 0 : - std::clamp(ctx->last_total_flops / 40u, std::min(100'000'000ULL, flops_cap), flops_cap); - auto const submit_after = [&](int start, int end) { - if (ctx->device->serialize_submissions) { - try { - auto res = ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX); - if (res != vk::Result::eSuccess) { - GGML_LOG_ERROR("ggml_vulkan: waitForFences error during serialized submission\n"); - throw vk::SystemError(vk::make_error_code(res), "ggml_vulkan: waitForFences during serialized submission"); + struct s19_mm_src1_info { + const ggml_tensor * src1 {}; + const ggml_tensor * f0 {}; + int mul_idx { -1 }; + }; + static const bool s19_enable_src1_scale = getenv("GGML_VK_ENABLE_S19_SRC1_SCALE") != nullptr; + std::vector s19_mm_src1; + if (s19_enable_src1_scale && !ctx->device->disable_fusion && !ctx->device->integer_dot_product && gen_fuse_enabled("mmgate")) { + for (int idx = 1; idx < cgraph->n_nodes; ++idx) { + if (!gen_skip.empty() && gen_skip[idx]) { + continue; + } + const ggml_tensor * mm = cgraph->nodes[idx]; + if (mm->op != GGML_OP_MUL_MAT || !gen_uses_dmmv_noswap(ctx, mm) || + mm->ne[1] > 7 || mm->ne[2] != 1 || mm->ne[3] != 1 || + !ggml_is_contiguous(mm) || !mm->buffer || get_misalign_bytes(ctx, mm) != 0) { + continue; + } + const ggml_tensor * w0 = mm->src[0]; + if (!w0 || w0->type != GGML_TYPE_Q8_0 || ggml_vk_tensor_is_repack(w0) || + w0->ne[2] != 1 || w0->ne[3] != 1 || (w0->ne[0] & 31) != 0 || + !ggml_is_contiguous(w0) || !w0->buffer || get_misalign_bytes(ctx, w0) != 0) { + continue; + } + gen_mm_epilogue probe_ep {}; + if (gen_find_mm_epilogue(ctx, cgraph, idx, last_node, gen_skip, use_idx, probe_ep) || + gen_can_fuse_mm_glu(ctx, cgraph, idx) || + ggml_vk_can_fuse(ctx, cgraph, idx, { GGML_OP_MUL_MAT, GGML_OP_ADD })) { + continue; + } + const ggml_tensor * mul = mm->src[1]; + if (!mul || mul->op != GGML_OP_MUL || (mul->flags & GGML_TENSOR_FLAG_OUTPUT) || + mul->type != GGML_TYPE_F32 || !ggml_is_contiguous(mul) || + mul->ne[2] != 1 || mul->ne[3] != 1 || (mul->ne[0] & 31) != 0) { + continue; + } + const int mul_idx = use_idx.first_node_idx(mul); + if (mul_idx < 0 || mul_idx >= idx || (!gen_skip.empty() && gen_skip[mul_idx])) { + continue; + } + if (use_idx.any_reader(mul, [&](int k) { return k != idx && !ggml_op_is_empty(cgraph->nodes[k]->op); })) { + continue; + } + const ggml_tensor * a = mul->src[0]; + const ggml_tensor * b = mul->src[1]; + if (!a || !b || a->type != GGML_TYPE_F32 || b->type != GGML_TYPE_F32 || + !ggml_is_contiguous(a) || !ggml_is_contiguous(b) || + !ggml_are_same_shape(a, mul) || !ggml_are_same_shape(b, mul) || + !a->buffer || !b->buffer || + get_misalign_bytes(ctx, a) != 0 || get_misalign_bytes(ctx, b) != 0) { + continue; + } + if (ggml_vk_tensors_overlap(w0, mm, false) || + ggml_vk_tensors_overlap(a, mm, false) || + ggml_vk_tensors_overlap(b, mm, false)) { + continue; + } + bool hazard = false; + for (int k = mul_idx + 1; k < idx; ++k) { + const ggml_tensor * nk = cgraph->nodes[k]; + if ((!gen_skip.empty() && gen_skip[k]) || ggml_op_is_empty(nk->op)) { + continue; + } + if (nk->buffer && (ggml_vk_tensors_overlap(nk, a, false) || ggml_vk_tensors_overlap(nk, b, false))) { + hazard = true; + break; } - } catch (vk::DeviceLostError &) { - ggml_vk_print_device_fault_info(ctx->device); - GGML_LOG_ERROR("ggml_vulkan: device lost on %s waiting for submission (nodes %d to %d):\n", - ctx->device->name.c_str(), start, end); - ggml_vk_print_node_list(cgraph, start, end); - throw; } - ctx->device->device.resetFences({ ctx->fence }); - ctx->submit_pending = false; - ctx->device->diag_cgraph = cgraph; - ctx->device->diag_prev_start = start; - ctx->device->diag_prev_end = end; - } - first_node_in_batch = true; - submitted_nodes = 0; - batch_flops = 0; - if (submit_count < 3) { - flops_per_submit *= 2; + if (hazard) { + continue; + } + if (s19_mm_src1.empty()) { + s19_mm_src1.resize(cgraph->n_nodes); + } + if (gen_skip.empty()) { + gen_skip.assign(cgraph->n_nodes, 0); + } + s19_mm_src1[idx] = { a, b, mul_idx }; + gen_skip[mul_idx] = 1; } - submit_count++; - }; + } for (int i = 0; i < cgraph->n_nodes; i++) { + if (!gen_skip.empty() && gen_skip[i]) { + continue; // gen: a state CPY or fused epilogue already done by an earlier dispatch + } if (first_node_in_batch) { submit_node_idx = i; } @@ -15661,27 +23947,98 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg // the fused result in an elementwise-way. This affects whether the memory for // the src is allowed to overlap the memory for the destination. // The array is sized to handle the largest fusion (asserted later). - bool op_srcs_fused_elementwise[13]; + bool op_srcs_fused_elementwise[16]; + int s10_add_rms_final_idx = -1; ctx->fused_topk_moe_mode = TOPK_MOE_COUNT; ctx->fused_topk_moe_scale = false; ctx->fused_topk_qsa = false; ctx->fused_hc_post_gate = false; + ctx->fused_softcap_argmax = false; + ctx->fused_add_softcap_argmax = false; + ctx->fused_inkling_clip_set_rows = false; ctx->fused_rms_norm_mode = RMS_NORM_COUNT; const char *fusion_string {}; - if (!ctx->device->disable_fusion) { - uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i); - if (num_adds) { + if (!ctx->device->disable_fusion && !ggml_op_is_empty(cgraph->nodes[i]->op) && + (s17_mmid_exp.empty() || s17_mmid_exp[i].dst == nullptr) && + (s19_mm_src1.empty() || s19_mm_src1[i].src1 == nullptr)) { + uint32_t s10_adds = s10_can_fuse_multi_add_rms_mul(ctx, cgraph, i, last_node, gen_skip, use_idx, s10_add_rms_final_idx); + uint32_t num_adds = s10_adds ? 0 : ggml_vk_fuse_multi_add(ctx, cgraph, i); + if (s10_adds) { + ctx->num_additional_fused_ops = s10_adds - 1; + fusion_string = ctx->s10_add_rms_weight != nullptr ? "S10_MULTI_ADD_RMS_MUL" : "S10_MULTI_ADD_RMS"; + std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, true); + } else if (num_adds) { ctx->num_additional_fused_ops = num_adds - 1; fusion_string = "MULTI_ADD"; std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, true); + } else if (int n_gate_ops = gen_can_fuse_rms_mul_silu(ctx, cgraph, i)) { + ctx->num_additional_fused_ops = n_gate_ops; + ctx->fused_rms_norm_mode = RMS_NORM_MUL_SILU_GATE; + fusion_string = "GEN_RMS_NORM_MUL_SILU"; + std::fill_n(op_srcs_fused_elementwise, n_gate_ops + 1, true); + const ggml_tensor * g_out = cgraph->nodes[i + n_gate_ops]; + const int r_idx = i + n_gate_ops + 1; + int mm_idx = -1; + if (r_idx < cgraph->n_nodes && !(g_out->flags & GGML_TENSOR_FLAG_OUTPUT)) { + if (cgraph->nodes[r_idx]->op == GGML_OP_MUL_MAT && cgraph->nodes[r_idx]->src[1] == g_out) { + mm_idx = r_idx; + } else if (cgraph->nodes[r_idx]->op == GGML_OP_RESHAPE && + !(cgraph->nodes[r_idx]->flags & GGML_TENSOR_FLAG_OUTPUT) && + cgraph->nodes[r_idx]->view_src == g_out && + cgraph->nodes[r_idx]->view_offs == 0 && + ggml_is_contiguous(cgraph->nodes[r_idx]) && + ggml_nelements(cgraph->nodes[r_idx]) == ggml_nelements(g_out) && + r_idx + 1 < cgraph->n_nodes && + cgraph->nodes[r_idx + 1]->op == GGML_OP_MUL_MAT && + cgraph->nodes[r_idx + 1]->src[1] == cgraph->nodes[r_idx]) { + mm_idx = r_idx + 1; + } + } + if (mm_idx >= 0) { + const ggml_tensor * mm_node = cgraph->nodes[mm_idx]; + const bool sole_ok = ggml_is_quantized(mm_node->src[0]->type) && + mm_node->src[1]->ne[1] >= 128 && + !use_idx.any_reader(g_out, [&](int k) { return k != r_idx && k != mm_idx; }) && + (r_idx == mm_idx || !use_idx.any_reader(cgraph->nodes[r_idx], [&](int k) { return k != mm_idx; })); + ctx->gen_rms_silu_sole_mm_next = sole_ok; + } + } else if (int n_lora_ops = gen_can_fuse_lora(ctx, cgraph, i, gen_skip, use_idx, fusion_string, op_srcs_fused_elementwise)) { + ctx->num_additional_fused_ops = n_lora_ops; + } else if (gen_can_fuse_gate_up_glu(ctx, cgraph, i)) { + ctx->num_additional_fused_ops = 2; + fusion_string = "GEN_MUL_MAT_GATE_UP_GLU"; + op_srcs_fused_elementwise[0] = false; + op_srcs_fused_elementwise[1] = false; + op_srcs_fused_elementwise[2] = true; + const ggml_tensor * glu_node = cgraph->nodes[i + 2]; + ctx->gen_pair_glu_sole_mmid_next = + cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID && + !(glu_node->flags & GGML_TENSOR_FLAG_OUTPUT) && + (i + 3 < cgraph->n_nodes) && + cgraph->nodes[i + 3]->op == GGML_OP_MUL_MAT_ID && + cgraph->nodes[i + 3]->src[1] == glu_node && + cgraph->nodes[i + 3]->src[2] == cgraph->nodes[i]->src[2] && + !use_idx.any_reader(glu_node, [&](int k) { return k != i + 3; }); + } else if (int n_pair_ops = gen_can_fuse_pair_mm(ctx, cgraph, i, last_node, gen_skip, use_idx)) { + ctx->num_additional_fused_ops = n_pair_ops; + ctx->fused_ops_write_mask |= (1u << ctx->gen_pair_mul0_rel); + fusion_string = ctx->gen_pair_mul0_rel > 0 ? "S10_PAIR_MM_GDN_GATES" + : (n_pair_ops >= 2 ? "GEN_PAIR_MM_SIGMOID" : "GEN_PAIR_MM"); + std::fill_n(op_srcs_fused_elementwise, n_pair_ops + 1, false); + } else if (gen_can_fuse_mm_glu(ctx, cgraph, i)) { + ctx->num_additional_fused_ops = 1; + fusion_string = "GEN_MUL_MAT_GLU"; + op_srcs_fused_elementwise[0] = false; + op_srcs_fused_elementwise[1] = true; } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) { ctx->num_additional_fused_ops = 2; fusion_string = "MUL_MAT_ADD_ADD"; op_srcs_fused_elementwise[0] = false; op_srcs_fused_elementwise[1] = true; op_srcs_fused_elementwise[2] = true; - } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) { + } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD }) && + !ggml_vk_can_fuse_add_softcap_argmax(ctx, cgraph, i + 1)) { ctx->num_additional_fused_ops = 1; fusion_string = "MUL_MAT_ADD"; op_srcs_fused_elementwise[0] = false; @@ -15740,6 +24097,23 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg ctx->fused_rms_norm_mode = RMS_NORM_MUL_ADD; fusion_string = "RMS_NORM_MUL_ADD"; std::fill_n(op_srcs_fused_elementwise, 3, true); + } else if (ggml_vk_can_fuse_add_softcap_argmax(ctx, cgraph, i)) { + ctx->num_additional_fused_ops = 4; + ctx->fused_add_softcap_argmax = true; + fusion_string = "ADD_SOFTCAP_ARGMAX"; + std::fill_n(op_srcs_fused_elementwise, 5, false); + } else if (ggml_vk_can_fuse_softcap_argmax(ctx, cgraph, i)) { + ctx->num_additional_fused_ops = 3; + ctx->fused_softcap_argmax = true; + fusion_string = "SOFTCAP_ARGMAX"; + std::fill_n(op_srcs_fused_elementwise, 4, false); + } else if (ggml_can_fuse_subgraph(cgraph, i, inkling_clip_view_set_rows_pattern, { i + 2 }) && + ggml_check_edges(cgraph, i, rms_norm_view_set_rows_edges) && + ggml_vk_can_fuse_inkling_clip_set_rows(ctx, cgraph, i)) { + ctx->num_additional_fused_ops = 2; + ctx->fused_inkling_clip_set_rows = true; + fusion_string = "INKLING_CLIP_VIEW_SET_ROWS"; + std::fill_n(op_srcs_fused_elementwise, 3, false); } else if (ggml_can_fuse_subgraph(cgraph, i, rms_norm_view_set_rows_pattern, { i + 2 }) && ggml_check_edges(cgraph, i, rms_norm_view_set_rows_edges) && ggml_vk_can_fuse_rms_norm_set_rows(ctx, cgraph, i)) { @@ -15755,7 +24129,9 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg // they are overwritten, and one workgroup per row. So close enough. op_srcs_fused_elementwise[0] = true; op_srcs_fused_elementwise[1] = true; - } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL })) { + } else if ((gen_deferred_mm.empty() || gen_deferred_mm[i + 1] < 0) && + (gen_skip.empty() || !gen_skip[i + 1]) && + ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL })) { ctx->num_additional_fused_ops = 1; switch (ggml_get_unary_op(cgraph->nodes[i])) { case GGML_UNARY_OP_GELU: fusion_string = "GELU_MUL"; break; @@ -15765,6 +24141,28 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg } op_srcs_fused_elementwise[0] = true; op_srcs_fused_elementwise[1] = true; + } else if (int n_cum_ops = gen_can_fuse_cont_unary_mul(ctx, cgraph, i)) { + ctx->num_additional_fused_ops = n_cum_ops; + fusion_string = "GEN_CONT_UNARY_MUL"; + op_srcs_fused_elementwise[0] = false; + for (int k = 1; k <= n_cum_ops; ++k) { + op_srcs_fused_elementwise[k] = true; + } + } else if (!s10_rb.empty() && s10_rb[i].active) { + ctx->num_additional_fused_ops = s10_rb[i].num_extra; + ctx->s10_ssm_conv_mode = 3; + ctx->s10_ssm_conv_node = s10_rb[i].conv; + ctx->s10_ssm_state_out = s10_rb[i].state_out; + ctx->s10_ssm_old_st = s10_rb[i].old_st; + ctx->s10_ssm_qkv = s10_rb[i].qkv; + ctx->s10_ssm_st_k = s10_rb[i].st_k; + ctx->s10_ssm_st_slot_nb = s10_rb[i].st_slot_nb; + fusion_string = "S10_SSM_CONV_SLIDING_RB"; + std::fill_n(op_srcs_fused_elementwise, s10_rb[i].num_extra + 1, false); + } else if (int n_ssm_ops = s10_can_fuse_ssm_conv(ctx, cgraph, i, gen_skip, use_idx)) { + ctx->num_additional_fused_ops = n_ssm_ops; + fusion_string = ctx->s10_ssm_conv_mode == 1 ? "S10_SSM_CONV_SLIDING" : "S10_SSM_CONV_SOUT"; + std::fill_n(op_srcs_fused_elementwise, n_ssm_ops + 1, false); } else if (ggml_vk_can_fuse_ssm_conv(ctx, cgraph, i, 2)) { ctx->num_additional_fused_ops = 2; fusion_string = "SSM_CONV_BIAS_SILU"; @@ -15817,6 +24215,14 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg ctx->fused_topk_moe_mode = TOPK_MOE_SIGMOID_NORM_BIAS; fusion_string = "TOPK_MOE_SIGMOID_NORM_BIAS"; std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, false); + } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_sigmoid_norm_bias_eps, { i + 4, i + 10 }) && + ggml_check_edges(cgraph, i, topk_moe_sigmoid_norm_bias_edges) && + ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_SIGMOID_NORM_BIAS_EPS)) { + ctx->num_additional_fused_ops = topk_moe_sigmoid_norm_bias_eps.size() - 1; + ctx->fused_ops_write_mask |= 1 << 4; + ctx->fused_topk_moe_mode = TOPK_MOE_SIGMOID_NORM_BIAS_EPS; + fusion_string = "TOPK_MOE_SIGMOID_NORM_BIAS_EPS"; + std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, false); } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_sqrt_softplus_norm_bias, { i + 5, i + 11 }) && ggml_check_edges(cgraph, i, topk_moe_sqrt_softplus_norm_bias_edges) && ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS)) { @@ -15857,10 +24263,13 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg } GGML_ASSERT(ctx->num_additional_fused_ops < (int)(sizeof(op_srcs_fused_elementwise) / sizeof(op_srcs_fused_elementwise[0]))); ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops; + if (ctx->s10_add_rms_dst != nullptr && !ctx->s10_add_rms_write_add) { + ctx->fused_ops_write_mask = 0; + } // Check whether fusion would overwrite src operands while they're still in use. // If so, disable fusion. - if (ctx->num_additional_fused_ops) { + if (ctx->num_additional_fused_ops && ctx->s10_ssm_conv_mode == 0 && ctx->s10_add_rms_dst == nullptr && ctx->gen_pair_mm1 == nullptr) { // There are up to two output nodes - topk_moe has two. uint32_t bits = ctx->fused_ops_write_mask & ~(1 << ctx->num_additional_fused_ops); ggml_tensor *output_nodes[2] {}; @@ -15882,6 +24291,12 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg // the destination and the src is not an intermediate node that's being // elided, then disable fusion. for (int k = 0; k <= ctx->num_additional_fused_ops; ++k) { + if ((ctx->fused_rms_norm_mode == RMS_NORM_MUL_SILU_GATE || + (cgraph->nodes[i]->op == GGML_OP_CONT && + cgraph->nodes[i + ctx->num_additional_fused_ops]->op == GGML_OP_MUL)) && + ggml_op_is_empty(cgraph->nodes[i + k]->op)) { + continue; + } for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) { ggml_tensor *src = cgraph->nodes[i + k]->src[s]; if (!src || src->op == GGML_OP_NONE) { @@ -15902,32 +24317,538 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg } } } - if (need_disable) { - ctx->num_additional_fused_ops = 0; - ctx->fused_ops_write_mask = 1; - ctx->fused_topk_moe_mode = TOPK_MOE_COUNT; - ctx->fused_topk_moe_scale = false; - ctx->fused_topk_qsa = false; - ctx->fused_hc_post_gate = false; - ctx->fused_rms_norm_mode = RMS_NORM_COUNT; - fusion_string = nullptr; + if (need_disable) { + ctx->num_additional_fused_ops = 0; + ctx->fused_ops_write_mask = 1; + ctx->fused_topk_moe_mode = TOPK_MOE_COUNT; + ctx->fused_topk_moe_scale = false; + ctx->fused_topk_qsa = false; + ctx->fused_hc_post_gate = false; + ctx->fused_softcap_argmax = false; + ctx->fused_add_softcap_argmax = false; + ctx->fused_inkling_clip_set_rows = false; + ctx->fused_rms_norm_mode = RMS_NORM_COUNT; + ctx->gen_pair_mm1 = nullptr; + ctx->gen_pair_dst1 = nullptr; + ctx->gen_mm_dst = nullptr; + ctx->gen_mm_f0 = nullptr; + ctx->gen_mm_f1 = nullptr; + ctx->gen_mm_flags = 0; + ctx->gen_lora_b0 = nullptr; + ctx->gen_lora_h0 = nullptr; + ctx->gen_lora_b1 = nullptr; + ctx->gen_lora_h1 = nullptr; + ctx->gen_lora_gate_src0 = nullptr; + ctx->gen_lora_up_src0 = nullptr; + ctx->gen_lora_r = 0; + ctx->gen_lora_scale0 = 0.0f; + ctx->gen_lora_scale1 = 0.0f; + ctx->gen_pair_glu_sole_mmid_next = false; + ctx->gen_rms_silu_sole_mm_next = false; + fusion_string = nullptr; + } + } + + // Series 20 (Pillar S20.1 + X-2): Pre-node Honeykrisp G17P Ioto <= 1,360 dispatch splitter + // on BOTH multi-chunk replay recording and non-replay paths (prevents post-node 1359+3=1362 overflow). + if (ggml_vk_is_apple_agx_coopmat(ctx->device)) { + const uint32_t node_max_disp = ggml_vk_node_max_dispatches(ctx, cgraph, i); + if (ctx->recording_replay && !ctx->replay_abort && node_max_disp > 1360u) { + ctx->replay_abort = true; + if (rec_entry != nullptr) { + rec_entry->stat_dispatches = ~0ull; + } + } + const uint64_t cur_chunk_disp = ctx->stat_dispatches - batch_disp_start; + if (cur_chunk_disp > 0 && cur_chunk_disp + node_max_disp > 1360u) { + if (ctx->recording_replay && !ctx->replay_abort && !ctx->compute_ctx.expired()) { + vk_context cctx = ctx->compute_ctx.lock(); + if (cctx->seqs.size() >= AGX_REPLAY_MAX_CHUNKS) { + ctx->replay_abort = true; + if (rec_entry != nullptr) { + rec_entry->stat_dispatches = ~0ull; + } + } else { + ggml_vk_ctx_end(cctx); + ggml_vk_ctx_begin_reusable(ctx->device, cctx); + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, cctx); + batch_disp_start = ctx->stat_dispatches; + } + } + if ((!ctx->recording_replay || ctx->replay_abort) && submitted_nodes > 0) { + vk_context flush_ctx = ggml_vk_get_compute_ctx(ctx); + ggml_vk_ctx_end(flush_ctx); + flush_ctx->exit_tensor_idx = -1; + ctx->compute_ctx.reset(); + ggml_vk_compute_forward(ctx, cgraph, cgraph->nodes[submit_node_idx], submit_node_idx, false); + submit_after(submit_node_idx, i - 1); + submit_node_idx = i; + } + } + } + + // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining), including AGX geo mode (eff_submit_mode == 2) + const bool is_last_in_graph = (i + ctx->num_additional_fused_ops >= last_node) || (s10_add_rms_final_idx >= last_node); + bool almost_ready = !ctx->recording_replay && eff_submit_mode != 1 && + !is_last_in_graph && !ctx->almost_ready_fence_pending && + cgraph->n_nodes >= 256 && + i >= (cgraph->n_nodes * 4) / 5 && + (ctx->stat_dispatches - batch_disp_start >= 64u); + const bool agx_ioto_cap = ggml_vk_is_apple_agx_coopmat(ctx->device) && + (!ctx->recording_replay || ctx->replay_abort) && + (ctx->stat_dispatches - batch_disp_start >= 1360u); + bool submit = (!ctx->recording_replay || ctx->replay_abort) && ( + (submitted_nodes >= gen_max_nodes) || + agx_ioto_cap || + (flops_per_submit != 0 && batch_flops >= flops_per_submit) || + is_last_in_graph || + (almost_ready && !ctx->almost_ready_fence_pending)); + + int gen_state_cpy = -1; + if (gen_gdn_inplace && cgraph->nodes[i]->op == GGML_OP_GATED_DELTA_NET && ctx->num_additional_fused_ops == 0) { + gen_state_cpy = gen_find_gdn_state_cpy(ctx, cgraph, i, last_node, use_idx); + } + if (gen_state_cpy < 0 && cgraph->nodes[i]->op == GGML_OP_RMS_NORM && ctx->num_additional_fused_ops == 0 && + ctx->fused_rms_norm_mode == RMS_NORM_COUNT) { + const int sc_idx = gen_find_rms_norm_scale(ctx, cgraph, i, last_node, use_idx); + if (sc_idx >= 0) { + // defer: this RMS_NORM runs fused when the loop reaches its SCALE + if (gen_deferred_rms.empty()) { + gen_deferred_rms.assign(cgraph->n_nodes, -1); + } + gen_deferred_rms[sc_idx] = i; + ctx->num_additional_fused_ops = 0; + ctx->fused_ops_write_mask = 0; + continue; + } + } + int gen_rms_idx = -1; + if (gen_state_cpy < 0 && !s10_pair_rms.empty() && s10_pair_rms[i].rms0_idx >= 0) { + const auto & pr = s10_pair_rms[i]; + gen_rms_idx = pr.rms0_idx; + const ggml_tensor * sc0 = cgraph->nodes[pr.sc0_idx]; + const ggml_tensor * sc1 = cgraph->nodes[i]; + const ggml_tensor * r0 = cgraph->nodes[pr.rms0_idx]->src[0]; + const ggml_tensor * r1 = cgraph->nodes[pr.rms1_idx]->src[0]; + bool need_sync = false; + for (const ggml_tensor * o : ctx->unsynced_nodes_read) { + need_sync = need_sync || ggml_vk_tensors_overlap_strided(o, sc0) || ggml_vk_tensors_overlap_strided(o, sc1); + } + for (const ggml_tensor * o : ctx->unsynced_nodes_written) { + need_sync = need_sync || + ggml_vk_tensors_overlap_strided(o, sc0) || + ggml_vk_tensors_overlap_strided(o, sc1) || + ggml_vk_tensors_overlap_strided(o, r0) || + ggml_vk_tensors_overlap_strided(o, r1); + } + vk_context gen_cctx = ggml_vk_get_compute_ctx(ctx); + if (need_sync) { + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, gen_cctx); + } + ctx->tensor_ctxs[pr.sc0_idx] = gen_cctx; + ctx->tensor_ctxs[i] = gen_cctx; + ctx->num_additional_fused_ops = 0; + ctx->fused_ops_write_mask = 0; + ctx->fused_rms_norm_mode = RMS_NORM_SCALE; + ctx->gen_rms_scale_dst = sc0; + ctx->gen_rms_scale_dst2 = sc1; + ctx->gen_rms_scale_rsrc2 = r1; + fusion_string = "S10_PAIR_RMS_NORM_SCALE"; + } else if (gen_state_cpy < 0 && !gen_deferred_rms.empty() && gen_deferred_rms[i] >= 0) { + gen_rms_idx = gen_deferred_rms[i]; + const ggml_tensor * sc = cgraph->nodes[i]; + const ggml_tensor * rsrc = cgraph->nodes[gen_rms_idx]->src[0]; + bool need_sync = false; + for (const ggml_tensor * o : ctx->unsynced_nodes_read) { + need_sync = need_sync || ggml_vk_tensors_overlap_strided(o, sc); + } + for (const ggml_tensor * o : ctx->unsynced_nodes_written) { + need_sync = need_sync || ggml_vk_tensors_overlap_strided(o, sc) || + ggml_vk_tensors_overlap_strided(o, rsrc); + } + vk_context gen_cctx = ggml_vk_get_compute_ctx(ctx); + if (need_sync) { + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, gen_cctx); + } + ctx->tensor_ctxs[i] = gen_cctx; + ctx->num_additional_fused_ops = 0; + ctx->fused_ops_write_mask = 0; + ctx->fused_rms_norm_mode = RMS_NORM_SCALE; + ctx->gen_rms_scale_dst = sc; + } + if (gen_state_cpy >= 0) { + const ggml_tensor * cpy = cgraph->nodes[gen_state_cpy]; + bool need_sync = false; + for (const ggml_tensor * o : ctx->unsynced_nodes_read) { + need_sync = need_sync || ggml_vk_tensors_overlap_strided(o, cpy); + } + for (const ggml_tensor * o : ctx->unsynced_nodes_written) { + need_sync = need_sync || ggml_vk_tensors_overlap_strided(o, cpy); + } + vk_context sync_ctx = ggml_vk_get_compute_ctx(ctx); + if (need_sync) { + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, sync_ctx); + } + ctx->tensor_ctxs[gen_state_cpy] = sync_ctx; + if (cgraph->nodes[i]->op == GGML_OP_GATED_DELTA_NET) { + ctx->gen_gdn_state_out = cpy; + } + gen_skip[gen_state_cpy] = 1; + } + + if (!s12_zero_sc.empty() && s12_zero_sc[i] >= 0) { + ctx->tensor_ctxs[s12_zero_sc[i]] = ggml_vk_get_compute_ctx(ctx); + if (gen_state_cpy >= 0 && cgraph->nodes[i]->op == GGML_OP_GATED_DELTA_NET) { + ctx->gen_gdn_zero_state = true; + } else if (ctx->s10_ssm_conv_mode == 1 || ctx->s10_ssm_conv_mode == 3) { + ctx->s10_ssm_zero_state = true; + } + GGML_ASSERT(ctx->gen_gdn_zero_state || ctx->s10_ssm_zero_state); + } + + if (ctx->s10_ssm_conv_mode == 3) { + const ggml_tensor * sout = ctx->s10_ssm_state_out; + const ggml_tensor * ost = ctx->s10_ssm_zero_state ? nullptr : ctx->s10_ssm_old_st; + const ggml_tensor * qkv = ctx->s10_ssm_qkv; + bool need_sync = false; + for (const ggml_tensor * o : ctx->unsynced_nodes_read) { + need_sync = need_sync || (sout && ggml_vk_tensors_overlap_strided(o, sout)); + } + for (const ggml_tensor * o : ctx->unsynced_nodes_written) { + need_sync = need_sync || + (sout && ggml_vk_tensors_overlap_strided(o, sout)) || + (ost && ggml_vk_tensors_overlap_strided(o, ost)) || + (qkv && ggml_vk_tensors_overlap_strided(o, qkv)); + } + vk_context sync_ctx = ggml_vk_get_compute_ctx(ctx); + if (need_sync) { + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, sync_ctx); + } + if (!s10_rb.empty() && s10_rb[i].sr_idx >= 0) { + ctx->tensor_ctxs[s10_rb[i].sr_idx] = sync_ctx; + } + } + + if (ctx->s10_add_rms_dst != nullptr) { + const ggml_tensor * fdst = ctx->s10_add_rms_dst; + const ggml_tensor * fw = ctx->s10_add_rms_weight; + bool need_sync = false; + for (const ggml_tensor * o : ctx->unsynced_nodes_read) { + need_sync = need_sync || (o->buffer == fdst->buffer && ggml_vk_tensors_overlap(o, fdst, false)); + } + for (const ggml_tensor * o : ctx->unsynced_nodes_written) { + need_sync = need_sync || + (o->buffer == fdst->buffer && ggml_vk_tensors_overlap(o, fdst, false)) || + (fw && o->buffer == fw->buffer && ggml_vk_tensors_overlap(o, fw, false)); + } + if (need_sync) { + vk_context sync_ctx = ggml_vk_get_compute_ctx(ctx); + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, sync_ctx); + } + } + + gen_mm_epilogue mm_ep {}; + int gen_mm_idx = -1; + if (!ctx->device->disable_fusion && gen_state_cpy < 0 && gen_rms_idx < 0 && + !gen_deferred_mm.empty() && gen_deferred_mm[i] >= 0) { + gen_mm_idx = gen_deferred_mm[i]; + const ggml_tensor * mul = cgraph->nodes[i]; + const ggml_tensor * mm = cgraph->nodes[gen_mm_idx]; + const ggml_tensor * gate = (mul->src[0] == mm) ? mul->src[1] : mul->src[0]; + bool need_sync = false; + for (const ggml_tensor * o : ctx->unsynced_nodes_read) { + need_sync = need_sync || (o->buffer == mul->buffer && ggml_vk_tensors_overlap(o, mul, false)); + } + for (const ggml_tensor * o : ctx->unsynced_nodes_written) { + need_sync = need_sync || (o->buffer == mul->buffer && ggml_vk_tensors_overlap(o, mul, false)) || + (o->buffer == gate->buffer && ggml_vk_tensors_overlap(o, gate, false)) || + (mm->src[0]->buffer && o->buffer == mm->src[0]->buffer && ggml_vk_tensors_overlap(o, mm->src[0], false)) || + (mm->src[1]->buffer && o->buffer == mm->src[1]->buffer && ggml_vk_tensors_overlap(o, mm->src[1], false)); + } + vk_context gen_cctx = ggml_vk_get_compute_ctx(ctx); + if (need_sync) { + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, gen_cctx); + } + ctx->tensor_ctxs[i] = gen_cctx; + ctx->num_additional_fused_ops = 0; + ctx->fused_ops_write_mask = 0; + mm_ep = { mul, gate, nullptr, MAT_VEC_FUSION_FLAGS_ROW_SCALE0, { -1, -1, -1 }, "GEN_MUL_MAT_ROW_SCALE0" }; + ctx->gen_mm_dst = mm_ep.dst; + ctx->gen_mm_f0 = mm_ep.f0; + ctx->gen_mm_flags = mm_ep.flags; + fusion_string = mm_ep.name; + } else if (!s17_mmid_exp.empty() && s17_mmid_exp[i].dst != nullptr && ctx->num_additional_fused_ops == 0) { + const auto & me = s17_mmid_exp[i]; + bool need_sync = false; + for (const ggml_tensor * o : ctx->unsynced_nodes_read) { + need_sync = need_sync || (o->buffer == me.dst->buffer && ggml_vk_tensors_overlap(o, me.dst, false)); + } + for (const ggml_tensor * o : ctx->unsynced_nodes_written) { + need_sync = need_sync || (o->buffer == me.dst->buffer && ggml_vk_tensors_overlap(o, me.dst, false)) || + (me.f0 && o->buffer == me.f0->buffer && ggml_vk_tensors_overlap(o, me.f0, false)) || + (me.f1 && o->buffer == me.f1->buffer && ggml_vk_tensors_overlap(o, me.f1, false)); + } + vk_context sync_ctx = ggml_vk_get_compute_ctx(ctx); + if (need_sync) { + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, sync_ctx); + } + for (int sk : me.skip) { + if (sk >= 0) { + ctx->tensor_ctxs[sk] = sync_ctx; + } + } + ctx->fused_ops_write_mask = 0; + const char * s17_name = (me.flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) + ? (me.f0 ? "S19_MMID_EXP_SITU" : "S19_MMID_SITU") + : (me.f1 ? "S17_MMID_EXP_TOK_SCALE" : "S17_MMID_EXP_SCALE"); + mm_ep = { me.dst, me.f0, me.f1, me.flags, { -1, -1, -1 }, s17_name }; + ctx->gen_mm_dst = mm_ep.dst; + ctx->gen_mm_f0 = mm_ep.f0; + ctx->gen_mm_f1 = mm_ep.f1; + ctx->gen_mm_flags = mm_ep.flags; + ctx->gen_glu_alpha = me.glu_alpha; + ctx->gen_glu_limit = me.glu_limit; + ctx->gen_pair_glu_sole_mmid_next = me.sole_down_idx >= 0; + fusion_string = mm_ep.name; + } else if (!s19_mm_src1.empty() && s19_mm_src1[i].src1 != nullptr && ctx->num_additional_fused_ops == 0) { + const auto & ms = s19_mm_src1[i]; + const ggml_tensor * mm = cgraph->nodes[i]; + bool need_sync = false; + for (const ggml_tensor * o : ctx->unsynced_nodes_read) { + need_sync = need_sync || (o->buffer == mm->buffer && ggml_vk_tensors_overlap(o, mm, false)); + } + for (const ggml_tensor * o : ctx->unsynced_nodes_written) { + need_sync = need_sync || + (o->buffer == mm->buffer && ggml_vk_tensors_overlap(o, mm, false)) || + (o->buffer == ms.src1->buffer && ggml_vk_tensors_overlap(o, ms.src1, false)) || + (o->buffer == ms.f0->buffer && ggml_vk_tensors_overlap(o, ms.f0, false)); + } + vk_context sync_ctx = ggml_vk_get_compute_ctx(ctx); + if (need_sync) { + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, sync_ctx); + } + if (ms.mul_idx >= 0) { + ctx->tensor_ctxs[ms.mul_idx] = sync_ctx; + } + ctx->fused_ops_write_mask = 0; + mm_ep = { mm, ms.f0, nullptr, MAT_VEC_FUSION_FLAGS_SRC1_SCALE, { -1, -1, -1 }, "S19_MM_SRC1_SCALE" }; + ctx->gen_mm_dst = mm_ep.dst; + ctx->gen_mm_f0 = mm_ep.f0; + ctx->gen_mm_f1 = nullptr; + ctx->gen_mm_src1_override = ms.src1; + ctx->gen_mm_flags = mm_ep.flags; + fusion_string = mm_ep.name; + } else if (!ctx->device->disable_fusion && gen_state_cpy < 0 && gen_rms_idx < 0 && + cgraph->nodes[i]->op == GGML_OP_MUL_MAT && ctx->num_additional_fused_ops == 0) { + if (gen_find_mm_epilogue(ctx, cgraph, i, last_node, gen_skip, use_idx, mm_ep)) { + bool need_sync = false; + for (const ggml_tensor * o : ctx->unsynced_nodes_read) { + need_sync = need_sync || (o->buffer == mm_ep.dst->buffer && ggml_vk_tensors_overlap(o, mm_ep.dst, false)); + } + for (const ggml_tensor * o : ctx->unsynced_nodes_written) { + need_sync = need_sync || (o->buffer == mm_ep.dst->buffer && ggml_vk_tensors_overlap(o, mm_ep.dst, false)) || + (mm_ep.f0 && o->buffer == mm_ep.f0->buffer && ggml_vk_tensors_overlap(o, mm_ep.f0, false)) || + (mm_ep.f1 && o->buffer == mm_ep.f1->buffer && ggml_vk_tensors_overlap(o, mm_ep.f1, false)); + } + if (need_sync) { + vk_context sync_ctx = ggml_vk_get_compute_ctx(ctx); + ctx->unsynced_nodes_written.clear(); + ctx->unsynced_nodes_read.clear(); + ggml_vk_sync_buffers(ctx, sync_ctx); + } + ctx->fused_ops_write_mask = 0; + ctx->gen_mm_dst = mm_ep.dst; + ctx->gen_mm_f0 = mm_ep.f0; + ctx->gen_mm_f1 = mm_ep.f1; + ctx->gen_mm_flags = mm_ep.flags; + fusion_string = mm_ep.name; + for (int sk : mm_ep.skip) { + if (sk >= 0) { + gen_skip[sk] = 1; + } + } + } else { + const int def_mul = gen_find_mm_deferred_scale0(ctx, cgraph, i, last_node, use_idx); + if (def_mul >= 0) { + if (gen_deferred_mm.empty()) { + gen_deferred_mm.assign(cgraph->n_nodes, -1); + } + gen_deferred_mm[def_mul] = i; + ctx->num_additional_fused_ops = 0; + ctx->fused_ops_write_mask = 0; + continue; + } + } + } + + if (gen_state_cpy < 0 && gen_rms_idx < 0 && gen_mm_idx < 0 && mm_ep.dst == nullptr && + ctx->gen_pair_mm1 == nullptr && ctx->s10_add_rms_dst == nullptr && ctx->s10_ssm_conv_mode == 0 && + (gen_env.dup_all || !gen_env.dup.empty()) && gen_dup_match(cgraph->nodes[i]) && + !(cgraph->nodes[i]->op == GGML_OP_RMS_NORM && ctx->do_add_rms_partials)) { + if (ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, false, false, false)) { + gen_dups++; + } + } + const int exec_idx = gen_rms_idx >= 0 ? gen_rms_idx : (gen_mm_idx >= 0 ? gen_mm_idx : i); + bool enqueued = ggml_vk_build_graph(ctx, cgraph, exec_idx, cgraph->nodes[submit_node_idx], submit_node_idx, is_last_in_graph, almost_ready, submit); + if (ctx->gen_pair_mm1 != nullptr) { + ctx->gen_pair_mm1 = nullptr; + ctx->gen_pair_dst1 = nullptr; + ctx->gen_pair_mul0_rel = 0; + ctx->gen_mm_dst = nullptr; + ctx->gen_mm_f0 = nullptr; + ctx->gen_mm_f1 = nullptr; + ctx->gen_mm_flags = 0; + ctx->gen_glu_alpha = 0.0f; + ctx->gen_glu_limit = 0.0f; + } + if (ctx->gen_lora_r != 0) { + ctx->gen_mm_dst = nullptr; + ctx->gen_mm_f0 = nullptr; + ctx->gen_mm_f1 = nullptr; + ctx->gen_mm_flags = 0; + ctx->gen_glu_alpha = 0.0f; + ctx->gen_glu_limit = 0.0f; + ctx->gen_lora_b0 = nullptr; + ctx->gen_lora_h0 = nullptr; + ctx->gen_lora_b1 = nullptr; + ctx->gen_lora_h1 = nullptr; + ctx->gen_lora_gate_src0 = nullptr; + ctx->gen_lora_up_src0 = nullptr; + ctx->gen_lora_r = 0; + ctx->gen_lora_scale0 = 0.0f; + ctx->gen_lora_scale1 = 0.0f; + } + if (ctx->s10_ssm_conv_mode != 0) { + if (ctx->s10_ssm_conv_mode == 3) { + if (ctx->s10_ssm_state_out != nullptr) { + ctx->unsynced_nodes_written.push_back(ctx->s10_ssm_state_out); + } + if (ctx->s10_ssm_old_st != nullptr && !ctx->s10_ssm_zero_state) { + ctx->unsynced_nodes_read.push_back(ctx->s10_ssm_old_st); + } + if (ctx->s10_ssm_qkv != nullptr) { + ctx->unsynced_nodes_read.push_back(ctx->s10_ssm_qkv); + } + } + ctx->s10_ssm_conv_mode = 0; + ctx->s10_ssm_conv_node = nullptr; + ctx->s10_ssm_state_out = nullptr; + ctx->s10_ssm_old_st = nullptr; + ctx->s10_ssm_qkv = nullptr; + ctx->s10_ssm_st_k = 0; + ctx->s10_ssm_st_slot_nb = 0; + } + ctx->s10_ssm_zero_state = false; + ctx->gen_gdn_zero_state = false; + ctx->gen_pair_glu_sole_mmid_next = false; + ctx->gen_rms_silu_sole_mm_next = false; + if (ctx->s10_add_rms_dst != nullptr) { + const ggml_tensor * fdst = ctx->s10_add_rms_dst; + ctx->unsynced_nodes_written.push_back(fdst); + for (uint32_t s = 0; s < ctx->prealloc_y_ring_count; ++s) { + if ((int)s == ctx->prealloc_y_keep_slot) { + continue; + } + const ggml_tensor * cy = ctx->prealloc_y_last_tensor_ring[s]; + if (cy && cy->buffer == fdst->buffer && ggml_vk_tensors_overlap(fdst, cy, false)) { + ctx->prealloc_y_last_tensor_ring[s] = nullptr; + ctx->prealloc_y_last_pipeline_ring[s] = nullptr; + } + } + ctx->prealloc_y_keep_slot = -1; + if (ctx->s10_add_rms_weight != nullptr) { + ctx->unsynced_nodes_read.push_back(ctx->s10_add_rms_weight); + } + ctx->s10_add_rms_dst = nullptr; + ctx->s10_add_rms_weight = nullptr; + ctx->s10_add_rms_add_dst = nullptr; + ctx->s10_add_rms_num_adds = 0; + ctx->s10_add_rms_tree_mode = 0; + ctx->s10_add_rms_write_add = 0; + } + auto invalidate_y_ring = [&](const ggml_tensor * wdst) { + if (!wdst || !wdst->buffer) { + return; + } + for (uint32_t s = 0; s < ctx->prealloc_y_ring_count; ++s) { + if ((int)s == ctx->prealloc_y_keep_slot) { + continue; + } + const ggml_tensor * cy = ctx->prealloc_y_last_tensor_ring[s]; + if (cy && cy->buffer == wdst->buffer && ggml_vk_tensors_overlap(wdst, cy, false)) { + ctx->prealloc_y_last_tensor_ring[s] = nullptr; + ctx->prealloc_y_last_pipeline_ring[s] = nullptr; + } + } + }; + if (gen_rms_idx >= 0) { + if (ctx->gen_rms_scale_dst != nullptr) { + ctx->unsynced_nodes_written.push_back(ctx->gen_rms_scale_dst); + invalidate_y_ring(ctx->gen_rms_scale_dst); + } + if (ctx->gen_rms_scale_dst2 != nullptr) { + ctx->unsynced_nodes_written.push_back(ctx->gen_rms_scale_dst2); + invalidate_y_ring(ctx->gen_rms_scale_dst2); + } + if (ctx->gen_rms_scale_rsrc2 != nullptr) { + ctx->unsynced_nodes_read.push_back(ctx->gen_rms_scale_rsrc2); + } + ctx->gen_rms_scale_dst = nullptr; + ctx->gen_rms_scale_dst2 = nullptr; + ctx->gen_rms_scale_rsrc2 = nullptr; + } + if (gen_state_cpy >= 0) { + ctx->gen_gdn_state_out = nullptr; + ctx->gen_rms_scale_dst = nullptr; + ctx->unsynced_nodes_written.push_back(cgraph->nodes[gen_state_cpy]); + invalidate_y_ring(cgraph->nodes[gen_state_cpy]); + } + if (mm_ep.dst != nullptr) { + if (ctx->gen_mm_src1_override != nullptr) { + ctx->unsynced_nodes_read.push_back(ctx->gen_mm_src1_override); + ctx->gen_mm_src1_override = nullptr; + } + ctx->gen_mm_dst = nullptr; + ctx->gen_mm_f0 = nullptr; + ctx->gen_mm_f1 = nullptr; + ctx->gen_mm_flags = 0; + ctx->gen_glu_alpha = 0.0f; + ctx->gen_glu_limit = 0.0f; + ctx->unsynced_nodes_written.push_back(mm_ep.dst); + invalidate_y_ring(mm_ep.dst); + if (mm_ep.f0 != nullptr) { + ctx->unsynced_nodes_read.push_back(mm_ep.f0); + } + if (mm_ep.f1 != nullptr) { + ctx->unsynced_nodes_read.push_back(mm_ep.f1); } } - - // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining) - bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5; - bool submit = (submitted_nodes >= ctx->device->max_nodes_per_submit) || - (flops_per_submit != 0 && batch_flops >= flops_per_submit) || - (i + ctx->num_additional_fused_ops >= last_node) || - (almost_ready && !ctx->almost_ready_fence_pending); - - bool enqueued = ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, i + ctx->num_additional_fused_ops >= last_node, almost_ready, submit); + ctx->prealloc_y_keep_slot = -1; if (vk_perf_logger_enabled && enqueued) { compute_ctx = ggml_vk_get_compute_ctx(ctx); if (!vk_perf_logger_concurrent) { // track a single node/fusion for the current query - ctx->query_nodes[ctx->query_idx] = cgraph->nodes[i]; + ctx->query_nodes[ctx->query_idx] = cgraph->nodes[exec_idx]; ctx->query_fusion_names[ctx->query_idx] = fusion_string; compute_ctx->s->buffer->buf.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++); ggml_vk_sync_buffers(ctx, compute_ctx); @@ -15959,14 +24880,122 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg } if (submit && enqueued) { - submit_after(submit_node_idx, i + (int)ctx->num_additional_fused_ops); + submit_after(submit_node_idx, std::max(i + (int)ctx->num_additional_fused_ops, s10_add_rms_final_idx)); } i += ctx->num_additional_fused_ops; ctx->num_additional_fused_ops = 0; ctx->fused_ops_write_mask = 0; } + if (rec_entry != nullptr) { + std::swap(ctx->descriptor_pools, rec_entry->descriptor_pools); + std::swap(ctx->descriptor_sets, rec_entry->descriptor_sets); + std::swap(ctx->descriptor_set_bindings, rec_entry->descriptor_set_bindings); + std::swap(ctx->descriptor_set_bindings_destroy_count, rec_entry->descriptor_destroy_count); + ctx->recording_replay = false; + ctx->active_replay_cmd_pool = nullptr; + + if (!ctx->replay_abort && !ctx->compute_ctx.expired()) { + compute_ctx = ctx->compute_ctx.lock(); + ggml_vk_ctx_end(compute_ctx); + + bool valid_seqs = !compute_ctx->seqs.empty() && compute_ctx->seqs.size() <= AGX_REPLAY_MAX_CHUNKS; + std::vector recorded_cbs; + if (valid_seqs) { + recorded_cbs.reserve(compute_ctx->seqs.size()); + for (size_t si = 0; si < compute_ctx->seqs.size(); ++si) { + const auto & seq = compute_ctx->seqs[si]; + const bool ok_wait = seq.size() == 1 && + (seq[0].wait_semaphores.empty() || + (si == 0 && ctx->device->async_use_transfer_queue && seq[0].wait_semaphores.size() == 1)); + if (!ok_wait || !seq[0].signal_semaphores.empty() || !seq[0].buffer) { + valid_seqs = false; + break; + } + recorded_cbs.push_back(seq[0].buffer->buf); + } + } + const bool no_staging = compute_ctx->in_memcpys.empty() && compute_ctx->out_memcpys.empty(); + const bool pre_unchanged = + rec_entry->pre_x_handle == pre_buf_h(ctx->prealloc_x) && rec_entry->pre_x_size == pre_buf_sz(ctx->prealloc_x) && + rec_entry->pre_y_handle == pre_buf_h(ctx->prealloc_y) && rec_entry->pre_y_size == pre_buf_sz(ctx->prealloc_y) && + rec_entry->pre_sk_handle == pre_buf_h(ctx->prealloc_split_k) && rec_entry->pre_sk_size == pre_buf_sz(ctx->prealloc_split_k) && + rec_entry->pre_arp_handle == pre_buf_h(ctx->prealloc_add_rms_partials) && rec_entry->pre_arp_size == pre_buf_sz(ctx->prealloc_add_rms_partials) && + rec_entry->pre_mo_handle == pre_buf_h(ctx->prealloc_mask_opt) && rec_entry->pre_mo_size == pre_buf_sz(ctx->prealloc_mask_opt) && + rec_entry->destroy_count == ctx->device->buffer_destroy_count.load(std::memory_order_acquire); + + for (auto & cpy : compute_ctx->in_memcpys) { + memcpy(cpy.dst, cpy.src, cpy.n); + } + for (auto & mset : compute_ctx->memsets) { + memset(mset.dst, mset.val, mset.n); + } + + ggml_vk_ensure_fence_free(ctx); + const bool need_transfer_sem = ctx->device->async_use_transfer_queue && + ctx->transfer_semaphore_last_submitted < ctx->transfer_semaphore.value; + const int64_t rec_sub_ts = ggml_time_us(); + if (!need_transfer_sem && no_staging && !compute_ctx->seqs.empty()) { + ctx->replay_submit_us = rec_sub_ts; + ctx->last_submit_us = rec_sub_ts; + ggml_vk_submit(compute_ctx, ctx->fence); + ctx->fence_submitted = true; + } else { + ggml_vk_submit(compute_ctx, {}); + } + ctx->submit_pending = true; + submit_count = 1; + + if (valid_seqs && no_staging && pre_unchanged) { + rec_entry->cmd_bufs = std::move(recorded_cbs); + rec_entry->memsets = compute_ctx->memsets; + rec_entry->total_flops = total_flops; + rec_entry->stat_dispatches = ctx->stat_dispatches; + rec_entry->stat_syncs = ctx->stat_syncs; + rec_entry->ready = true; + if (ctx->fence_submitted) { + ctx->active_replay_entry = rec_entry; + } + } + for (auto & cpy : compute_ctx->out_memcpys) { + memcpy(cpy.dst, cpy.src, cpy.n); + } + compute_ctx->in_memcpys.clear(); + compute_ctx->out_memcpys.clear(); + compute_ctx->memsets.clear(); + ctx->compute_ctx.reset(); + } else if (!ctx->compute_ctx.expired()) { + compute_ctx = ctx->compute_ctx.lock(); + ggml_vk_ctx_end(compute_ctx); + for (auto & cpy : compute_ctx->in_memcpys) { + memcpy(cpy.dst, cpy.src, cpy.n); + } + for (auto & mset : compute_ctx->memsets) { + memset(mset.dst, mset.val, mset.n); + } + ggml_vk_ensure_fence_free(ctx); + const bool need_transfer_sem = ctx->device->async_use_transfer_queue && + ctx->transfer_semaphore_last_submitted < ctx->transfer_semaphore.value; + if (!need_transfer_sem && compute_ctx->out_memcpys.empty() && !compute_ctx->seqs.empty()) { + ctx->last_submit_us = ggml_time_us(); + ggml_vk_submit(compute_ctx, ctx->fence); + ctx->fence_submitted = true; + } else { + ggml_vk_submit(compute_ctx, {}); + } + ctx->submit_pending = true; + ctx->compute_ctx.reset(); + } + } + ctx->last_total_flops = total_flops; + ctx->last_cgraph_ptr = cgraph; + + if (gen_env.stats) { + fprintf(stderr, "ggml_vk_graph_stats: nodes=%d dispatches=%llu syncs=%llu submits=%u dups=%u flops_per_submit=%llu cpu_record_us=%lld\n", + cgraph->n_nodes, (unsigned long long) ctx->stat_dispatches, (unsigned long long) ctx->stat_syncs, + submit_count, gen_dups, (unsigned long long) flops_per_submit, (long long) (ggml_time_us() - gen_t_start)); + } if (vk_perf_logger_enabled) { // End the command buffer and submit/wait @@ -16014,7 +25043,6 @@ static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cg if (!ctx->device->support_async) { ggml_vk_synchronize(ctx); } - return GGML_STATUS_SUCCESS; UNUSED(backend); @@ -16122,6 +25150,22 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, } }; + auto const &is_gate_up_glu = [&](int s) -> bool { + if (!gen_fuse_enabled("gateup") || s < 0 || s + 2 >= graph->n_nodes) { + return false; + } + if (used[s] || used[s + 1] || used[s + 2]) { + return false; + } + ggml_tensor * a = graph->nodes[s]; + ggml_tensor * b = graph->nodes[s + 1]; + ggml_tensor * g = graph->nodes[s + 2]; + return (a->op == GGML_OP_MUL_MAT || a->op == GGML_OP_MUL_MAT_ID) && + b->op == a->op && a->src[1] == b->src[1] && + g->op == GGML_OP_GLU && + ((g->src[0] == a && g->src[1] == b) || (g->src[0] == b && g->src[1] == a)); + }; + auto const &keep_topk_moe_pattern = [&](const std::initializer_list &pattern) -> bool { if (!match_pattern(pattern, first_unused)) { return false; @@ -16129,13 +25173,63 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, int last_node = first_unused + (int) pattern.size() - 1; // Some TOPK_MOE variants fuse a trailing scale. - if (last_node + 1 < graph->n_nodes && graph->nodes[last_node + 1]->op == GGML_OP_SCALE) { + const bool has_trailing_scale = last_node + 1 < graph->n_nodes && graph->nodes[last_node + 1]->op == GGML_OP_SCALE; + if (has_trailing_scale) { last_node++; } + ggml_tensor * topk_src0 = graph->nodes[first_unused]->src[0]; add_pattern_alloc_deps(pattern, last_node); - return keep_pattern(pattern); + keep_pattern(pattern); + if (has_trailing_scale && !used[last_node]) { + new_order.push_back(graph->nodes[last_node]); + used_node_set.insert(graph->nodes[last_node]); + used[last_node] = true; + while (first_unused < graph->n_nodes && used[first_unused]) { + first_unused++; + } + } + + // gen (s8): overlap 1-workgroup TOPK_MOE with ready shared-expert gate+up+glu + if (gen_fuse_enabled("s8") && !has_trailing_scale) { + for (int k = first_unused; k + 2 < std::min(first_unused + 32, graph->n_nodes); ++k) { + if (!is_gate_up_glu(k) || graph->nodes[k]->op != GGML_OP_MUL_MAT) { + continue; + } + ggml_tensor * g0 = graph->nodes[k]; + ggml_tensor * g1 = graph->nodes[k + 1]; + ggml_tensor * glu = graph->nodes[k + 2]; + if (g0->src[0]->op != GGML_OP_NONE || g1->src[0]->op != GGML_OP_NONE || + !(g0->src[1]->op == GGML_OP_NONE || used_node_set.find(g0->src[1]) != used_node_set.end())) { + continue; + } + bool dep_ok = true; + for (int c = first_unused; c < k; ++c) { + if (!used[c] && (is_src_of(g0, graph->nodes[c]) || is_src_of(g1, graph->nodes[c]) || is_src_of(glu, graph->nodes[c]))) { + dep_ok = false; + break; + } + } + if (dep_ok) { + if (params && params->add_alloc_dep && topk_src0) { + params->add_alloc_dep(params->user_data, topk_src0, g0); + params->add_alloc_dep(params->user_data, topk_src0, g1); + params->add_alloc_dep(params->user_data, topk_src0, glu); + } + for (int t = 0; t < 3; ++t) { + new_order.push_back(graph->nodes[k + t]); + used_node_set.insert(graph->nodes[k + t]); + used[k + t] = true; + } + while (first_unused < graph->n_nodes && used[first_unused]) { + first_unused++; + } + break; + } + } + } + return true; }; if (keep_topk_moe_pattern(topk_moe_early_softmax_norm)) { @@ -16144,6 +25238,9 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, if (keep_topk_moe_pattern(topk_moe_sigmoid_norm_bias)) { continue; } + if (keep_topk_moe_pattern(topk_moe_sigmoid_norm_bias_eps)) { + continue; + } if (keep_topk_moe_pattern(topk_moe_sqrt_softplus_norm_bias)) { continue; } @@ -16169,6 +25266,15 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, if (keep_pattern(rms_norm_mul_rope_view_set_rows_pattern)) { continue; } + if (keep_pattern(softcap_argmax_pattern)) { + continue; + } + if (match_pattern(inkling_clip_view_set_rows_pattern, first_unused) && + ggml_get_op_params_i32(graph->nodes[first_unused], 0) == 0 && + ggml_check_edges(graph, first_unused, rms_norm_view_set_rows_edges)) { + keep_pattern(inkling_clip_view_set_rows_pattern); + continue; + } if (keep_pattern(rms_norm_view_set_rows_pattern)) { continue; } @@ -16181,9 +25287,654 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, continue; } - // First, grab the next unused node. - current_set.push_back(first_unused); - + // Fused dynamic LoRA reordering: hoist [la_*] ahead of [mm_*, lb_*, ls_*, add_*] and extend alloc lifetimes + if (!gen_lora_fuse_disabled() && ggml_vk_is_apple_agx_coopmat(ctx->device) && !ggml_vk_exact_s8_enabled()) { + auto match_lora5 = [&](int s) -> bool { + if (s < 0 || s + 4 >= graph->n_nodes) { + return false; + } + for (int t = 0; t < 5; ++t) { + if (used[s + t]) { return false; } + } + ggml_tensor * mm = graph->nodes[s + 0]; + ggml_tensor * la = graph->nodes[s + 1]; + ggml_tensor * lb = graph->nodes[s + 2]; + ggml_tensor * ls = graph->nodes[s + 3]; + ggml_tensor * add = graph->nodes[s + 4]; + if (mm->op != GGML_OP_MUL_MAT || la->op != GGML_OP_MUL_MAT || lb->op != GGML_OP_MUL_MAT || + ls->op != GGML_OP_SCALE || add->op != GGML_OP_ADD) { + return false; + } + if (!mm->src[0] || !mm->src[1] || mm->src[0]->op != GGML_OP_NONE || + !gen_supports_pair_type(mm->src[0]->type) || (mm->src[0]->ne[0] & 3) != 0 || + mm->ne[2] != 1 || mm->ne[3] != 1 || mm->src[1]->ne[2] * mm->src[1]->ne[3] != 1 || + mm->type != GGML_TYPE_F32 || + !gen_uses_dmmv_noswap(ctx, mm)) { + return false; + } + if (!(mm->src[1]->op == GGML_OP_NONE || used_node_set.find(mm->src[1]) != used_node_set.end())) { + return false; + } + if (!la->src[0] || la->src[0]->op != GGML_OP_NONE || la->src[0]->type != GGML_TYPE_F32 || + la->src[1] != mm->src[1] || la->type != GGML_TYPE_F32 || + la->ne[0] <= 0 || la->ne[0] > 64) { + return false; + } + if (!lb->src[0] || lb->src[0]->op != GGML_OP_NONE || lb->src[0]->type != GGML_TYPE_F32 || + lb->src[1] != la || lb->src[0]->ne[0] != la->ne[0] || + lb->ne[0] != mm->ne[0] || lb->ne[1] != mm->ne[1] || lb->type != GGML_TYPE_F32) { + return false; + } + if (ls->src[0] != lb || ls->type != GGML_TYPE_F32 || ggml_get_op_params_f32(ls, 1) != 0.0f) { + return false; + } + return ((add->src[0] == mm && add->src[1] == ls) || (add->src[0] == ls && add->src[1] == mm)) && + add->type == GGML_TYPE_F32; + }; + auto emit_node = [&](int idx) { + new_order.push_back(graph->nodes[idx]); + used_node_set.insert(graph->nodes[idx]); + used[idx] = true; + }; + auto emit_tail4 = [&](int s) { + emit_node(s + 0); + emit_node(s + 2); + emit_node(s + 3); + emit_node(s + 4); + }; + auto dep = [&](ggml_tensor * src, ggml_tensor * dst_node) { + if (params && params->add_alloc_dep && src && dst_node) { + params->add_alloc_dep(params->user_data, src, dst_node); + } + }; + + if (match_lora5(first_unused)) { + const int s0 = first_unused; + ggml_tensor * cur = graph->nodes[s0]->src[1]; + const int64_t r0 = graph->nodes[s0 + 1]->ne[0]; + + // Case A: 3-way QKV [Q, K, V] (15 nodes) where Q > K == V + if (match_lora5(s0 + 5) && match_lora5(s0 + 10) && + graph->nodes[s0 + 5]->src[1] == cur && graph->nodes[s0 + 10]->src[1] == cur && + graph->nodes[s0 + 6]->ne[0] == r0 && graph->nodes[s0 + 11]->ne[0] == r0 && + graph->nodes[s0]->src[0]->type == graph->nodes[s0 + 5]->src[0]->type && + graph->nodes[s0 + 5]->src[0]->type == graph->nodes[s0 + 10]->src[0]->type && + graph->nodes[s0]->ne[0] > graph->nodes[s0 + 5]->ne[0] && + graph->nodes[s0 + 5]->ne[0] == graph->nodes[s0 + 10]->ne[0]) { + ggml_tensor * la_q = graph->nodes[s0 + 1], * add_q = graph->nodes[s0 + 4]; + ggml_tensor * la_k = graph->nodes[s0 + 6], * add_k = graph->nodes[s0 + 9]; + ggml_tensor * la_v = graph->nodes[s0 + 11], * add_v = graph->nodes[s0 + 14]; + dep(cur, add_v); + dep(la_q, add_q); + dep(la_k, add_v); + dep(la_v, add_v); + dep(add_k, add_v); + emit_node(s0 + 1); + emit_node(s0 + 6); + emit_node(s0 + 11); + emit_tail4(s0); + emit_tail4(s0 + 5); + emit_tail4(s0 + 10); + while (first_unused < graph->n_nodes && used[first_unused]) { first_unused++; } + continue; + } + + // Case B & C: 2-way paired [0, 1] + optional SWIGLU (11 or 10 nodes) + if (match_lora5(s0 + 5) && + graph->nodes[s0 + 5]->src[1] == cur && + graph->nodes[s0 + 6]->ne[0] == r0 && + graph->nodes[s0]->src[0]->type == graph->nodes[s0 + 5]->src[0]->type && + graph->nodes[s0]->src[0]->ne[0] == graph->nodes[s0 + 5]->src[0]->ne[0]) { + ggml_tensor * la_0 = graph->nodes[s0 + 1], * add_0 = graph->nodes[s0 + 4]; + ggml_tensor * la_1 = graph->nodes[s0 + 6], * add_1 = graph->nodes[s0 + 9]; + const bool has_glu = (s0 + 10 < graph->n_nodes) && !used[s0 + 10] && + graph->nodes[s0 + 10]->op == GGML_OP_GLU && + ggml_get_glu_op(graph->nodes[s0 + 10]) == GGML_GLU_OP_SWIGLU && + ((graph->nodes[s0 + 10]->src[0] == add_0 && graph->nodes[s0 + 10]->src[1] == add_1) || + (graph->nodes[s0 + 10]->src[0] == add_1 && graph->nodes[s0 + 10]->src[1] == add_0)); + if (has_glu) { + ggml_tensor * glu = graph->nodes[s0 + 10]; + dep(cur, glu); + dep(la_0, glu); + dep(la_1, glu); + emit_node(s0 + 1); + emit_node(s0 + 6); + emit_tail4(s0); + emit_tail4(s0 + 5); + emit_node(s0 + 10); + while (first_unused < graph->n_nodes && used[first_unused]) { first_unused++; } + continue; + } + const bool t1_feeds_add = (s0 + 10 < graph->n_nodes) && !used[s0 + 10] && + graph->nodes[s0 + 10]->op == GGML_OP_ADD && + (graph->nodes[s0 + 10]->src[0] == add_1 || graph->nodes[s0 + 10]->src[1] == add_1); + if (!t1_feeds_add && (graph->nodes[s0]->ne[0] & 7) == 0) { + dep(cur, add_1); + dep(la_0, add_1); + dep(la_1, add_1); + dep(add_0, add_1); + emit_node(s0 + 1); + emit_node(s0 + 6); + emit_tail4(s0); + emit_tail4(s0 + 5); + while (first_unused < graph->n_nodes && used[first_unused]) { first_unused++; } + continue; + } + } + + // Case D: Single LoRA + optional residual ADD (6 or 5 nodes) + ggml_tensor * la_0 = graph->nodes[s0 + 1]; + ggml_tensor * add_0 = graph->nodes[s0 + 4]; + ggml_tensor * radd = nullptr; + if (s0 + 5 < graph->n_nodes && !used[s0 + 5] && + graph->nodes[s0 + 5]->op == GGML_OP_ADD && + (graph->nodes[s0 + 5]->src[0] == add_0 || graph->nodes[s0 + 5]->src[1] == add_0)) { + ggml_tensor * bias = (graph->nodes[s0 + 5]->src[0] == add_0) + ? graph->nodes[s0 + 5]->src[1] : graph->nodes[s0 + 5]->src[0]; + if (bias && bias != add_0 && + (bias->op == GGML_OP_NONE || used_node_set.find(bias) != used_node_set.end())) { + radd = graph->nodes[s0 + 5]; + dep(bias, radd); + } + } + ggml_tensor * end_t = radd ? radd : add_0; + dep(cur, end_t); + dep(la_0, end_t); + emit_node(s0 + 1); + emit_tail4(s0); + if (radd) { + emit_node(s0 + 5); + } + while (first_unused < graph->n_nodes && used[first_unused]) { first_unused++; } + continue; + } + } + auto const &mm_softplus_gate_len = [&](int s) -> int { + if (!gen_fuse_enabled("mmgate") || s < 0 || s + 3 >= graph->n_nodes || used[s]) { + return 0; + } + ggml_tensor * mm = graph->nodes[s]; + if (mm->op != GGML_OP_MUL_MAT) { + return 0; + } + int off = 1; + ggml_tensor * mv = graph->nodes[s + 1]; + if ((mv->op == GGML_OP_RESHAPE || mv->op == GGML_OP_VIEW) && mv->view_src == mm) { + off = 2; + } + if (s + off + 2 >= graph->n_nodes) { + return 0; + } + for (int t = 1; t <= off + 2; ++t) { + if (used[s + t]) { + return 0; + } + } + ggml_tensor * v_or_mm = off == 2 ? mv : mm; + ggml_tensor * add = graph->nodes[s + off]; + ggml_tensor * sp = graph->nodes[s + off + 1]; + ggml_tensor * mul = graph->nodes[s + off + 2]; + if (add->op != GGML_OP_ADD || (add->src[0] != v_or_mm && add->src[1] != v_or_mm)) { + return 0; + } + ggml_tensor * dt = add->src[0] == v_or_mm ? add->src[1] : add->src[0]; + if (!dt || dt->op != GGML_OP_NONE) { + return 0; + } + if (sp->op != GGML_OP_UNARY || ggml_get_unary_op(sp) != GGML_UNARY_OP_SOFTPLUS || sp->src[0] != add) { + return 0; + } + if (mul->op != GGML_OP_MUL || (mul->src[0] != sp && mul->src[1] != sp)) { + return 0; + } + ggml_tensor * aw = mul->src[0] == sp ? mul->src[1] : mul->src[0]; + return (aw && aw->op == GGML_OP_NONE) ? (off + 3) : 0; + }; + auto const &mm_sigmoid_len = [&](int s) -> int { + if (!gen_fuse_enabled("mmgate") || s < 0 || s + 1 >= graph->n_nodes || used[s]) { + return 0; + } + ggml_tensor * mm = graph->nodes[s]; + if (mm->op != GGML_OP_MUL_MAT) { + return 0; + } + if (!used[s + 1] && graph->nodes[s + 1]->op == GGML_OP_UNARY && + ggml_get_unary_op(graph->nodes[s + 1]) == GGML_UNARY_OP_SIGMOID && + graph->nodes[s + 1]->src[0] == mm && + (getenv("GGML_VK_DISABLE_S18_TOPK_MOE") != nullptr || (!match_pattern(topk_moe_sigmoid_norm_bias, s + 1) && !match_pattern(topk_moe_sigmoid_norm_bias_eps, s + 1)))) { + return 2; + } + if (s + 2 < graph->n_nodes && !used[s + 1] && !used[s + 2] && + (graph->nodes[s + 1]->op == GGML_OP_RESHAPE || graph->nodes[s + 1]->op == GGML_OP_VIEW) && + graph->nodes[s + 1]->view_src == mm && + graph->nodes[s + 2]->op == GGML_OP_UNARY && + ggml_get_unary_op(graph->nodes[s + 2]) == GGML_UNARY_OP_SIGMOID && + graph->nodes[s + 2]->src[0] == graph->nodes[s + 1] && + !match_pattern(topk_moe_sigmoid_norm_bias, s + 2) && + !match_pattern(topk_moe_sigmoid_norm_bias_eps, s + 2)) { + return 3; + } + return 0; + }; + auto const &in_mm_epilogue_group = [&](int idx) -> bool { + for (int o = 0; o < 5; ++o) { + int len = mm_softplus_gate_len(idx - o); + if (len > o) { + return true; + } + } + for (int o = 0; o < 3; ++o) { + int len = mm_sigmoid_len(idx - o); + if (len > o) { + return true; + } + } + return false; + }; + auto const &match_rms_mul_silu = [&](int s, int out_idxs[5]) -> int { + if (!gen_fuse_enabled("s8") || !gen_fuse_enabled("gate") || s < 0 || s + 3 >= graph->n_nodes || used[s] || used[s + 1]) { + return 0; + } + ggml_tensor * rms = graph->nodes[s]; + ggml_tensor * mul = graph->nodes[s + 1]; + if (rms->op != GGML_OP_RMS_NORM || mul->op != GGML_OP_MUL || (mul->src[0] != rms && mul->src[1] != rms)) { + return 0; + } + int p = s + 2; + while (p < graph->n_nodes && p <= s + 5 && (used[p] || graph->nodes[p]->op == GGML_OP_MUL_MAT)) { + p++; + } + if (p + 1 >= graph->n_nodes) { + return 0; + } + int n = 0; + out_idxs[n++] = s; + out_idxs[n++] = s + 1; + ggml_tensor * maybe_view = nullptr; + if ((graph->nodes[p]->op == GGML_OP_RESHAPE || graph->nodes[p]->op == GGML_OP_VIEW) && !used[p] && p + 2 < graph->n_nodes) { + maybe_view = graph->nodes[p]; + out_idxs[n++] = p; + p++; + } + if (p + 1 >= graph->n_nodes || used[p] || used[p + 1]) { + return 0; + } + ggml_tensor * silu = graph->nodes[p]; + ggml_tensor * out = graph->nodes[p + 1]; + if (silu->op != GGML_OP_UNARY || ggml_get_unary_op(silu) != GGML_UNARY_OP_SILU || out->op != GGML_OP_MUL) { + return 0; + } + if (maybe_view && silu->src[0] != maybe_view) { + return 0; + } + if (!((out->src[0] == mul && out->src[1] == silu) || (out->src[0] == silu && out->src[1] == mul))) { + return 0; + } + out_idxs[n++] = p; + out_idxs[n++] = p + 1; + return n; + }; + auto const &cont_unary_mul_len = [&](int s) -> int { + if (!gen_fuse_enabled("s8") || s < 0 || s + 2 >= graph->n_nodes || used[s]) { + return 0; + } + ggml_tensor * cont = graph->nodes[s]; + if (cont->op != GGML_OP_CONT || !cont->src[0]) { + return 0; + } + int u_off = 1; + while (u_off <= 2 && s + u_off + 1 < graph->n_nodes && is_empty(graph->nodes[s + u_off]) && + graph->nodes[s + u_off]->op != GGML_OP_NONE && !used[s + u_off]) { + u_off++; + } + if (s + u_off + 1 >= graph->n_nodes || used[s + u_off] || used[s + u_off + 1]) { + return 0; + } + ggml_tensor * unary = graph->nodes[s + u_off]; + ggml_tensor * mul = graph->nodes[s + u_off + 1]; + if (unary->op != GGML_OP_UNARY || mul->op != GGML_OP_MUL || + ggml_vk_unary_mul_op_index(ggml_get_unary_op(unary)) < 0) { + return 0; + } + const bool unary_reads_cont = unary->src[0] == cont || + ((unary->src[0]->op == GGML_OP_RESHAPE || unary->src[0]->op == GGML_OP_VIEW) && unary->src[0]->view_src == cont); + if (!unary_reads_cont || (mul->src[0] != unary && mul->src[1] != unary)) { + return 0; + } + return u_off + 2; + }; + auto const &in_s8_protected_group = [&](int idx) -> bool { + int r_idxs[5]; + for (int o = 0; o <= 6; ++o) { + int nr = match_rms_mul_silu(idx - o, r_idxs); + for (int k = 0; k < nr; ++k) { + if (r_idxs[k] == idx) { + return true; + } + } + } + for (int o = 0; o < 5; ++o) { + if (cont_unary_mul_len(idx - o) > o) { + return true; + } + } + return false; + }; + auto const &idxs_srcs_ready = [&](const int * idxs, int len) -> bool { + for (int t = 0; t < len; ++t) { + ggml_tensor * n = graph->nodes[idxs[t]]; + for (uint32_t k = 0; k < GGML_MAX_SRC; ++k) { + ggml_tensor * src = n->src[k]; + if (!src || src->op == GGML_OP_NONE || used_node_set.find(src) != used_node_set.end()) { + continue; + } + bool in_group = false; + for (int p = 0; p < t; ++p) { + if (graph->nodes[idxs[p]] == src) { + in_group = true; + break; + } + } + if (!in_group) { + return false; + } + } + } + return true; + }; + auto const &group_srcs_ready = [&](int s, int len) -> bool { + int seq[8]; + for (int t = 0; t < len; ++t) { + seq[t] = s + t; + } + return idxs_srcs_ready(seq, len); + }; + if (is_gate_up_glu(first_unused)) { + keep_pattern({ graph->nodes[first_unused]->op, graph->nodes[first_unused + 1]->op, GGML_OP_GLU }); + continue; + } + { + int rms_idxs[5]; + int rms_len = match_rms_mul_silu(first_unused, rms_idxs); + if (rms_len > 0 && idxs_srcs_ready(rms_idxs, rms_len)) { + if (rms_len == 5) { + // Emit z_2d view before RMS_NORM so [RMS_NORM, MUL, UNARY, MUL] has no external-source view inside subgraph + new_order.push_back(graph->nodes[rms_idxs[2]]); + used_node_set.insert(graph->nodes[rms_idxs[2]]); + used[rms_idxs[2]] = true; + } + for (int t = 0; t < rms_len; ++t) { + if (rms_len == 5 && t == 2) { + continue; + } + new_order.push_back(graph->nodes[rms_idxs[t]]); + used_node_set.insert(graph->nodes[rms_idxs[t]]); + used[rms_idxs[t]] = true; + } + while (first_unused < graph->n_nodes && used[first_unused]) { + first_unused++; + } + continue; + } + } + if (int cum_len = cont_unary_mul_len(first_unused); cum_len > 0 && group_srcs_ready(first_unused, cum_len)) { + ggml_tensor * cont_node = graph->nodes[first_unused]; + for (int t = 1; t < cum_len - 2; ++t) { + ggml_tensor * ev = graph->nodes[first_unused + t]; + if (ev->view_src != cont_node) { + new_order.push_back(ev); + used_node_set.insert(ev); + used[first_unused + t] = true; + } + } + for (int t = 0; t < cum_len; ++t) { + if (!used[first_unused + t]) { + new_order.push_back(graph->nodes[first_unused + t]); + used_node_set.insert(graph->nodes[first_unused + t]); + used[first_unused + t] = true; + } + } + while (first_unused < graph->n_nodes && used[first_unused]) { + first_unused++; + } + continue; + } + if (int sp_len = mm_softplus_gate_len(first_unused)) { + for (int t = 0; t < sp_len; ++t) { + new_order.push_back(graph->nodes[first_unused + t]); + used_node_set.insert(graph->nodes[first_unused + t]); + used[first_unused + t] = true; + } + while (first_unused < graph->n_nodes && used[first_unused]) { + first_unused++; + } + continue; + } + if (int sg_len = mm_sigmoid_len(first_unused)) { + for (int t = 0; t < sg_len; ++t) { + new_order.push_back(graph->nodes[first_unused + t]); + used_node_set.insert(graph->nodes[first_unused + t]); + used[first_unused + t] = true; + } + while (first_unused < graph->n_nodes && used[first_unused]) { + first_unused++; + } + continue; + } + // Series 17: Keep MUL_MAT_ID + per-expert .scale [RESHAPE?, REPEAT?, GET_ROWS, MUL, MUL?] atomic across all N + if (graph->nodes[first_unused]->op == GGML_OP_MUL_MAT_ID) { + const ggml_tensor * mmid_n = graph->nodes[first_unused]; + int c = first_unused + 1; + if (c < graph->n_nodes && !used[c] && graph->nodes[c]->op == GGML_OP_RESHAPE) { + ++c; + } + if (c < graph->n_nodes && !used[c] && graph->nodes[c]->op == GGML_OP_REPEAT) { + ++c; + } + if (c + 1 < graph->n_nodes && !used[c] && !used[c + 1] && + graph->nodes[c]->op == GGML_OP_GET_ROWS && graph->nodes[c]->src[1] == mmid_n->src[2] && + graph->nodes[c + 1]->op == GGML_OP_MUL && graph->nodes[c + 1]->src[0] == mmid_n && + graph->nodes[c + 1]->src[1] == graph->nodes[c]) { + int ep_end = c + 2; + if (ep_end < graph->n_nodes && !used[ep_end] && + graph->nodes[ep_end]->op == GGML_OP_MUL && graph->nodes[ep_end]->src[0] == graph->nodes[c + 1]) { + ++ep_end; + } + const int ep_len = ep_end - first_unused; + if (ep_len <= 8 && group_srcs_ready(first_unused, ep_len)) { + for (int t = 0; t < ep_len; ++t) { + new_order.push_back(graph->nodes[first_unused + t]); + used_node_set.insert(graph->nodes[first_unused + t]); + used[first_unused + t] = true; + } + while (first_unused < graph->n_nodes && used[first_unused]) { + first_unused++; + } + continue; + } + } + } + + if (gen_fuse_enabled("s8") && is_empty(graph->nodes[first_unused]) && !in_s8_protected_group(first_unused) && + group_srcs_ready(first_unused, 1)) { + while (first_unused < graph->n_nodes) { + if (used[first_unused]) { + first_unused++; + continue; + } + if (!is_empty(graph->nodes[first_unused]) || in_s8_protected_group(first_unused) || !group_srcs_ready(first_unused, 1)) { + break; + } + new_order.push_back(graph->nodes[first_unused]); + used_node_set.insert(graph->nodes[first_unused]); + used[first_unused] = true; + first_unused++; + } + continue; + } + + // First, grab the next unused node. + current_set.push_back(first_unused); + + // gen (pairmm): pull [ffn_gate_inp_shexp, shared_gate_sigmoid] or sibling MUL_MAT (e.g. wqkv_gate) adjacent to mm0 + if (gen_fuse_enabled("pairmm") && graph->nodes[first_unused]->op == GGML_OP_MUL_MAT && + (graph->nodes[first_unused]->ne[0] & 7) == 0 && + gen_supports_pair_type(graph->nodes[first_unused]->src[0]->type)) { + ggml_tensor * mm0 = graph->nodes[first_unused]; + bool paired = false; + static const bool s18_pair_opt = getenv("GGML_VK_ENABLE_S19_PAIR_OPT") == nullptr || getenv("GGML_VK_DISABLE_PAIR_MM_SIGMOID") != nullptr; + const int pair_sig_win = (!s18_pair_opt && mm0->ne[1] <= 8) ? 128 : 48; + for (int k = first_unused + 1; k + 1 < std::min(first_unused + pair_sig_win, graph->n_nodes); ++k) { + if (used[k] || used[k + 1]) { + continue; + } + ggml_tensor * mm1 = graph->nodes[k]; + ggml_tensor * sig1 = graph->nodes[k + 1]; + if (mm1->op == GGML_OP_MUL_MAT && mm1->src[1] == mm0->src[1] && + mm1->src[0]->type == mm0->src[0]->type && + mm1->ne[1] == mm0->ne[1] && mm1->src[0]->ne[0] == mm0->src[0]->ne[0] && + (mm1->ne[0] == 1 || (!s18_pair_opt && mm0->ne[1] <= 8 && (mm1->ne[0] & 7) == 0)) && + sig1->op == GGML_OP_UNARY && ggml_get_unary_op(sig1) == GGML_UNARY_OP_SIGMOID && + sig1->src[0] == mm1 && + (mm1->src[0]->op == GGML_OP_NONE || used_node_set.find(mm1->src[0]) != used_node_set.end())) { + current_set.push_back(k); + current_set.push_back(k + 1); + paired = true; + if (gen_fuse_enabled("gateup")) { + for (int g = first_unused + 1; g + 2 < k; ++g) { + if (!used[g] && !used[g + 1] && !used[g + 2] && + is_gate_up_glu(g) && + graph->nodes[g]->op == GGML_OP_MUL_MAT && + graph->nodes[g]->src[1] == mm0->src[1] && + graph->nodes[g]->src[0]->op == GGML_OP_NONE && + graph->nodes[g + 1]->src[0]->op == GGML_OP_NONE) { + current_set.push_back(g); + current_set.push_back(g + 1); + current_set.push_back(g + 2); + break; + } + } + } + break; + } + } + auto const &mm_has_own_fusion = [&](int idx) -> bool { + if (is_gate_up_glu(idx) || is_gate_up_glu(idx - 1) || in_mm_epilogue_group(idx)) { + return true; + } + ggml_tensor * m = graph->nodes[idx]; + for (int u = idx + 1; u < std::min(idx + 12, graph->n_nodes); ++u) { + if (used[u]) { + continue; + } + ggml_tensor * n = graph->nodes[u]; + if ((n->op == GGML_OP_GLU || n->op == GGML_OP_ADD) && (n->src[0] == m || n->src[1] == m)) { + return true; + } + if (gen_fuse_enabled("shexp") && n->op == GGML_OP_MUL && (n->src[0] == m || n->src[1] == m)) { + ggml_tensor * g = n->src[0] == m ? n->src[1] : n->src[0]; + if (g && g->ne[0] == 1 && g->ne[1] == m->ne[1]) { + return true; + } + } + } + return false; + }; + if (!paired && mm0->src[0]->op == GGML_OP_NONE && !mm_has_own_fusion(first_unused)) { + std::vector cands; + static const bool s18_pair_mm_win = getenv("GGML_VK_ENABLE_S19_PAIR_OPT") == nullptr; + const int pair_mm_win = (!s18_pair_mm_win && mm0->ne[1] <= 8) ? 128 : 64; + for (int k = first_unused + 1; k < std::min(first_unused + pair_mm_win, graph->n_nodes); ++k) { + if (used[k]) { + continue; + } + ggml_tensor * mm1 = graph->nodes[k]; + if (mm1->op == GGML_OP_MUL_MAT && mm1->src[1] == mm0->src[1] && + mm1->src[0]->op == GGML_OP_NONE && mm1->src[0]->type == mm0->src[0]->type && + mm1->ne[1] == mm0->ne[1] && mm1->src[0]->ne[0] == mm0->src[0]->ne[0] && + !mm_has_own_fusion(k)) { + cands.push_back(k); + if (cands.size() >= 2) { + break; + } + } + } + // In [Q, K, V] with matching types (Q larger than K == V), emit [Q, K, V] together in one wave: + // Q runs standalone and [K, V] fuse into GEN_PAIR_MM in the same barrier-free wave. + const bool is_qkv_head = cands.size() >= 2 && + mm0->ne[0] > graph->nodes[cands[0]]->ne[0] && + graph->nodes[cands[0]]->ne[0] == graph->nodes[cands[1]]->ne[0]; + if (!cands.empty() && !is_qkv_head) { + current_set.push_back(cands[0]); + paired = true; + if (gen_fuse_enabled("s8")) { + for (int k = first_unused + 1; k < std::min(first_unused + 48, graph->n_nodes); ++k) { + if (used[k] || std::find(current_set.begin(), current_set.end(), k) != current_set.end()) { + continue; + } + int ep_len = mm_softplus_gate_len(k); + if (!ep_len) { + ep_len = mm_sigmoid_len(k); + } + if (ep_len > 0 && graph->nodes[k]->src[0]->op == GGML_OP_NONE && graph->nodes[k]->src[1] == mm0->src[1]) { + for (int t = 0; t < ep_len; ++t) { + current_set.push_back(k + t); + } + k += ep_len - 1; + } + } + } + } else if (is_qkv_head) { + current_set.push_back(cands[0]); + current_set.push_back(cands[1]); + paired = true; + } else if (gen_fuse_enabled("s8")) { + // Mixed-quant GDN layer (wqkv and z differ in quant type): still group z + ssm_alpha + ssm_beta with wqkv + bool has_gdn_ep = false; + for (int k = first_unused + 1; k < std::min(first_unused + 48, graph->n_nodes); ++k) { + if (!used[k] && (mm_softplus_gate_len(k) > 0 || mm_sigmoid_len(k) > 0) && + graph->nodes[k]->src[0]->op == GGML_OP_NONE && graph->nodes[k]->src[1] == mm0->src[1]) { + has_gdn_ep = true; + break; + } + } + if (has_gdn_ep) { + for (int k = first_unused + 1; k < std::min(first_unused + 48, graph->n_nodes); ++k) { + if (used[k]) { + continue; + } + int ep_len = mm_softplus_gate_len(k); + if (!ep_len) { + ep_len = mm_sigmoid_len(k); + } + if (ep_len > 0 && graph->nodes[k]->src[0]->op == GGML_OP_NONE && graph->nodes[k]->src[1] == mm0->src[1]) { + for (int t = 0; t < ep_len; ++t) { + current_set.push_back(k + t); + } + k += ep_len - 1; + paired = true; + } else if (graph->nodes[k]->op == GGML_OP_MUL_MAT && graph->nodes[k]->src[0]->op == GGML_OP_NONE && + graph->nodes[k]->src[1] == mm0->src[1] && !mm_has_own_fusion(k)) { + current_set.push_back(k); + paired = true; + } + } + } + } + } + if (paired) { + for (auto c : current_set) { + new_order.push_back(graph->nodes[c]); + used_node_set.insert(graph->nodes[c]); + used[c] = true; + } + while (first_unused < graph->n_nodes && used[first_unused]) { + first_unused++; + } + continue; + } + } + // Loop through the next N nodes. Grab any that don't depend on other nodes that // haven't already been run. Nodes that have already been run have used[i] set // to true. Allow nodes that depend on the previous node if it's a fusion pattern @@ -16191,11 +25942,78 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes. // The goal is to not interleave real and view nodes in a way that breaks fusion. const int NUM_TO_CHECK = 20; - for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) { + const auto pass1_limit = [&]() { + int lim = first_unused + NUM_TO_CHECK; + if (gen_fuse_enabled("s8") && !current_set.empty() && graph->nodes[first_unused]->op == GGML_OP_ADD) { + lim = std::max(lim, current_set.back() + NUM_TO_CHECK); + } + return std::min(lim, graph->n_nodes); + }; + for (int j = first_unused+1; j < pass1_limit(); ++j) { + if (ggml_nbytes(graph->nodes[first_unused]) >= (64ULL << 20)) { + break; + } if (used[j]) { continue; } - if (is_empty(graph->nodes[j])) { + if (is_empty(graph->nodes[j]) || ggml_nbytes(graph->nodes[j]) >= (64ULL << 20)) { + continue; + } + if (is_gate_up_glu(j - 1) || is_gate_up_glu(j - 2) || in_mm_epilogue_group(j) || in_s8_protected_group(j)) { + continue; + } + const bool is_zero_scale = graph->nodes[j]->op == GGML_OP_SCALE && + ggml_get_op_params_f32(graph->nodes[j], 0) == 0.0f; + if (gen_fuse_enabled("s8") && + ((graph->nodes[first_unused]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_GET_ROWS) || + (graph->nodes[first_unused]->op != GGML_OP_ADD && is_zero_scale))) { + continue; + } + if (gen_fuse_enabled("s8") && gen_fuse_enabled("pairmm") && + graph->nodes[first_unused]->op != GGML_OP_MUL_MAT && + graph->nodes[j]->op == GGML_OP_MUL_MAT && graph->nodes[j]->src[0]->op == GGML_OP_NONE && + (graph->nodes[j]->ne[0] & 7) == 0 && gen_supports_pair_type(graph->nodes[j]->src[0]->type)) { + continue; + } + if (gen_fuse_enabled("s8") && graph->nodes[current_set.back()]->op == GGML_OP_ADD && graph->nodes[j]->op != GGML_OP_ADD) { + ggml_tensor * last_add = graph->nodes[current_set.back()]; + bool more_add_ahead = false; + for (int a = j + 1; a < pass1_limit(); ++a) { + if (used[a] || graph->nodes[a]->op != GGML_OP_ADD) { + continue; + } + ggml_tensor * na = graph->nodes[a]; + if (na->src[0] != last_add && na->src[1] != last_add) { + continue; + } + ggml_tensor * other = (na->src[0] == last_add) ? na->src[1] : na->src[0]; + if (other && (other->op == GGML_OP_NONE || used_node_set.find(other) != used_node_set.end() || + (other->view_src && (other->view_src->op == GGML_OP_NONE || used_node_set.find(other->view_src) != used_node_set.end())))) { + more_add_ahead = true; + break; + } + } + if (more_add_ahead) { + continue; + } + } + if (is_gate_up_glu(j)) { + bool pair_ok = true; + for (int c = first_unused; c < j; ++c) { + if (!used[c] && std::find(current_set.begin(), current_set.end(), c) == current_set.end() && + (is_src_of(graph->nodes[j], graph->nodes[c]) || is_src_of(graph->nodes[j + 1], graph->nodes[c]))) { + pair_ok = false; + break; + } + } + if (pair_ok) { + current_set.push_back(j); + current_set.push_back(j + 1); + current_set.push_back(j + 2); + used[j] = true; + used[j + 1] = true; + used[j + 2] = true; + } continue; } // Protect every interior QSA node (not just the start): the mask branch is @@ -16210,6 +26028,7 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, }; if (match_pattern(topk_moe_early_softmax_norm, j) || match_pattern(topk_moe_sigmoid_norm_bias, j) || + match_pattern(topk_moe_sigmoid_norm_bias_eps, j) || match_pattern(topk_moe_sqrt_softplus_norm_bias, j) || match_pattern(topk_moe_early_softmax, j) || match_pattern(topk_moe_late_softmax, j) || @@ -16218,28 +26037,70 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, match_pattern(rms_norm_mul_add_mul_pattern, j) || match_pattern(rms_norm_mul_add_pattern, j) || match_pattern(rms_norm_mul_rope_view_set_rows_pattern, j) || + match_pattern(softcap_argmax_pattern, j) || + (match_pattern(inkling_clip_view_set_rows_pattern, j) && + ggml_get_op_params_i32(graph->nodes[j], 0) == 0 && + ggml_check_edges(graph, j, rms_norm_view_set_rows_edges)) || match_pattern(rms_norm_view_set_rows_pattern, j) || match_pattern(rope_view_set_rows_pattern, j) || - match_pattern(hc_post_gate_pattern, j)) { + match_pattern(hc_post_gate_pattern, j) || + (graph->nodes[j]->op == GGML_OP_FILL && !current_set.empty() && + (graph->nodes[current_set.back()]->op == GGML_OP_MUL_MAT_ID || + graph->nodes[current_set.back()]->op == GGML_OP_GET_ROWS || + graph->nodes[current_set.back()]->op == GGML_OP_REPEAT || + graph->nodes[current_set.back()]->op == GGML_OP_MUL || + graph->nodes[current_set.back()]->op == GGML_OP_GLU))) { continue; } bool ok = true; + std::vector pending_empty_deps; + const bool allow_empty_chain = gen_fuse_enabled("s8") && + graph->nodes[current_set.back()]->op == GGML_OP_ADD && + (is_zero_scale || graph->nodes[j]->op == GGML_OP_GET_ROWS); for (int c = first_unused; c < j; ++c) { if (!used[c] && - is_src_of(graph->nodes[j], graph->nodes[c]) && + is_src_of(graph->nodes[j], graph->nodes[c])) { + if (allow_empty_chain && is_empty(graph->nodes[c]) && !in_s8_protected_group(c)) { + bool emp_ok = true; + for (int e = first_unused; e < c; ++e) { + if (!used[e] && !is_empty(graph->nodes[e]) && + std::find(current_set.begin(), current_set.end(), e) == current_set.end() && + is_src_of(graph->nodes[c], graph->nodes[e])) { + emp_ok = false; + break; + } + } + if (emp_ok) { + pending_empty_deps.push_back(c); + continue; + } + } + if ( !(c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL && empty_or_scheduled_between(c+1, j)) && + // gen: keep mat-vec + SWIGLU adjacent for the GGML_GEN_FUSE=glu / gateup fusion + !((gen_fuse_enabled("glu") || gen_fuse_enabled("gateup")) && graph->nodes[j]->op == GGML_OP_GLU && + std::find(current_set.begin(), current_set.end(), c) != current_set.end() && + (graph->nodes[current_set.back()]->op == GGML_OP_MUL_MAT || graph->nodes[current_set.back()]->op == GGML_OP_MUL_MAT_ID) && + (graph->nodes[j]->src[0] == graph->nodes[current_set.back()] || graph->nodes[j]->src[1] == graph->nodes[current_set.back()])) && !(c == current_set.back() && graph->nodes[c]->op == GGML_OP_UNARY && graph->nodes[j]->op == GGML_OP_MUL && empty_or_scheduled_between(c+1, j)) && !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) && !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) && !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL) && - !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_ADD && graph->nodes[j]->op == GGML_OP_ADD) && + !((j == c+1 || (gen_fuse_enabled("s8") && empty_or_scheduled_between(c+1, j))) && c == current_set.back() && graph->nodes[c]->op == GGML_OP_ADD && graph->nodes[j]->op == GGML_OP_ADD) && !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_SSM_CONV && graph->nodes[j]->op == GGML_OP_ADD) && !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_SSM_CONV && graph->nodes[j]->op == GGML_OP_UNARY)) { - ok = false; - break; + ok = false; + break; + } } } if (ok) { + for (int ec : pending_empty_deps) { + if (!used[ec] && std::find(current_set.begin(), current_set.end(), ec) == current_set.end()) { + current_set.push_back(ec); + used[ec] = true; + } + } current_set.push_back(j); int rope_idx = j; @@ -16313,6 +26174,80 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, } } } + // gen (s8): overlap ffn_moe_down + ffn_moe_weighted with ready ffn_shexp + ffn_shexp_gated so all 9 ADDs fuse + if (gen_fuse_enabled("s8") && gen_fuse_enabled("shexp") && + current_set.size() >= 2 && graph->nodes[current_set.back()]->op == GGML_OP_MUL) { + const int prev_idx = current_set[current_set.size() - 2]; + const int mmid_idx = graph->nodes[prev_idx]->op == GGML_OP_MUL_MAT_ID ? prev_idx : + (current_set.size() >= 3 && graph->nodes[prev_idx]->op == GGML_OP_ADD_ID && + graph->nodes[current_set[current_set.size() - 3]]->op == GGML_OP_MUL_MAT_ID ? current_set[current_set.size() - 3] : -1); + if (mmid_idx >= 0) { + ggml_tensor * mmid_node = graph->nodes[mmid_idx]; + ggml_tensor * mmid_mul = graph->nodes[current_set.back()]; + const int scan_hi = std::min(current_set.back() + 28, graph->n_nodes); + for (int k = current_set.back() + 1; k < scan_hi; ++k) { + if (used[k] || graph->nodes[k]->op != GGML_OP_MUL_MAT) { + continue; + } + ggml_tensor * mm = graph->nodes[k]; + if (mm->src[0]->op != GGML_OP_NONE || !mm->src[1] || + !(mm->src[1]->op == GGML_OP_NONE || used_node_set.find(mm->src[1]) != used_node_set.end())) { + continue; + } + int found_mul = -1; + for (int m = k + 1; m < std::min(k + 6, graph->n_nodes); ++m) { + if (used[m] || !empty_or_scheduled_between(k + 1, m)) { + continue; + } + ggml_tensor * mul = graph->nodes[m]; + if (mul->op != GGML_OP_MUL || (mul->src[0] != mm && mul->src[1] != mm)) { + continue; + } + ggml_tensor * gate = (mul->src[0] == mm) ? mul->src[1] : mul->src[0]; + if (gate && gate->ne[0] == 1 && gate->ne[1] == mm->ne[1] && + (gate->op == GGML_OP_NONE || used_node_set.find(gate) != used_node_set.end())) { + found_mul = m; + } + break; + } + if (found_mul < 0) { + continue; + } + bool dep_ok = true; + for (int c = first_unused; c < found_mul; ++c) { + if (!used[c] && c != k && std::find(current_set.begin(), current_set.end(), c) == current_set.end() && + (is_src_of(mm, graph->nodes[c]) || is_src_of(graph->nodes[found_mul], graph->nodes[c]))) { + dep_ok = false; + break; + } + } + if (dep_ok) { + if (params && params->add_alloc_dep) { + ggml_tensor * shexp_outs[2] = { mm, graph->nodes[found_mul] }; + for (ggml_tensor * out_t : shexp_outs) { + if (mmid_node->src[1]) { + params->add_alloc_dep(params->user_data, mmid_node->src[1], out_t); + } + if (mmid_node->src[2]) { + params->add_alloc_dep(params->user_data, mmid_node->src[2], out_t); + } + if (mmid_mul->src[0]) { + params->add_alloc_dep(params->user_data, mmid_mul->src[0], out_t); + } + if (mmid_mul->src[1]) { + params->add_alloc_dep(params->user_data, mmid_mul->src[1], out_t); + } + } + } + current_set.push_back(k); + used[k] = true; + current_set.push_back(found_mul); + used[found_mul] = true; + break; + } + } + } + } // Look for MUL_MAT + ADD + ADD if (j > 0 && graph->nodes[j]->op == GGML_OP_ADD && @@ -16371,7 +26306,7 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, if (used[j]) { continue; } - if (!is_empty(graph->nodes[j])) { + if (!is_empty(graph->nodes[j]) || in_s8_protected_group(j)) { continue; } bool ok = true; @@ -16405,6 +26340,336 @@ void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, for (int i = 0; i < graph->n_nodes; ++i) { graph->nodes[i] = new_order[i]; } + if (params && params->add_alloc_dep) { + if (gen_fuse_enabled("gateup")) { + for (int i = 0; i + 2 < graph->n_nodes; ++i) { + ggml_tensor * n0 = graph->nodes[i]; + ggml_tensor * n1 = graph->nodes[i + 1]; + ggml_tensor * glu = graph->nodes[i + 2]; + if ((n0->op == GGML_OP_MUL_MAT || n0->op == GGML_OP_MUL_MAT_ID) && + n1->op == n0->op && n0->src[1] == n1->src[1] && + glu->op == GGML_OP_GLU && + ((glu->src[0] == n0 && glu->src[1] == n1) || (glu->src[0] == n1 && glu->src[1] == n0))) { + if (n0->src[1]) { + params->add_alloc_dep(params->user_data, n0->src[1], glu); + } + if (n0->src[2]) { + params->add_alloc_dep(params->user_data, n0->src[2], glu); + } + } + } + } + auto base_tensor_opt = [](ggml_tensor * t) -> ggml_tensor * { + while (t && t->view_src) { + t = t->view_src; + } + return t; + }; + auto add_dep_safe = [&](ggml_tensor * a, ggml_tensor * b) { + if (a && b && a != b) { + params->add_alloc_dep(params->user_data, a, b); + } + }; + if (gen_fuse_enabled("pairmm")) { + for (int i = 0; i + 1 < graph->n_nodes; ++i) { + ggml_tensor * n0 = graph->nodes[i]; + if (n0->op != GGML_OP_MUL_MAT) { + continue; + } + if (!s10_pair_gdn_disabled() && gen_fuse_enabled("mmgate") && i + 5 < graph->n_nodes) { + int pos = i + 1; + if (pos < graph->n_nodes && is_empty(graph->nodes[pos]) && graph->nodes[pos]->view_src == n0) { + pos++; + } + if (pos + 4 < graph->n_nodes && + graph->nodes[pos]->op == GGML_OP_ADD && + graph->nodes[pos + 1]->op == GGML_OP_UNARY && + ggml_get_unary_op(graph->nodes[pos + 1]) == GGML_UNARY_OP_SOFTPLUS && + graph->nodes[pos + 2]->op == GGML_OP_MUL && + graph->nodes[pos + 3]->op == GGML_OP_MUL_MAT && + graph->nodes[pos + 3]->src[1] == n0->src[1]) { + ggml_tensor * mul0 = graph->nodes[pos + 2]; + ggml_tensor * mm1 = graph->nodes[pos + 3]; + int pos1 = pos + 4; + if (pos1 < graph->n_nodes && is_empty(graph->nodes[pos1]) && graph->nodes[pos1]->view_src == mm1) { + pos1++; + } + if (pos1 < graph->n_nodes && graph->nodes[pos1]->op == GGML_OP_UNARY && + ggml_get_unary_op(graph->nodes[pos1]) == GGML_UNARY_OP_SIGMOID) { + ggml_tensor * sig1 = graph->nodes[pos1]; + add_dep_safe(base_tensor_opt(n0->src[1]), sig1); + add_dep_safe(mul0, sig1); + continue; + } + } + } + ggml_tensor * n1 = graph->nodes[i + 1]; + if (n1->op == GGML_OP_MUL_MAT && n0 != n1 && n0->src[1] == n1->src[1] && n0->src[0]->type == n1->src[0]->type) { + ggml_tensor * last_out = n1; + int s_pos = i + 2; + if (s_pos + 1 < graph->n_nodes && is_empty(graph->nodes[s_pos]) && graph->nodes[s_pos]->view_src == n1) { + s_pos++; + } + if (s_pos < graph->n_nodes && graph->nodes[s_pos]->op == GGML_OP_UNARY && + ggml_get_unary_op(graph->nodes[s_pos]) == GGML_UNARY_OP_SIGMOID && + base_tensor_opt(graph->nodes[s_pos]->src[0]) == n1) { + last_out = graph->nodes[s_pos]; + } + add_dep_safe(base_tensor_opt(n0->src[1]), last_out); + add_dep_safe(n0, last_out); + } + } + } + if (!s10_ssm_conv_disabled()) { + for (int i = 0; i < graph->n_nodes; ++i) { + ggml_tensor * n0 = graph->nodes[i]; + if (n0->op == GGML_OP_CONCAT && i + 3 < graph->n_nodes && + graph->nodes[i + 1]->op == GGML_OP_VIEW && + graph->nodes[i + 2]->op == GGML_OP_CPY && + graph->nodes[i + 3]->op == GGML_OP_SSM_CONV && + graph->nodes[i + 3]->src[0] == n0) { + ggml_tensor * cpy = graph->nodes[i + 2]; + ggml_tensor * dst = graph->nodes[i + 3]; + if (i + 4 < graph->n_nodes && graph->nodes[i + 4]->op == GGML_OP_UNARY && + ggml_get_unary_op(graph->nodes[i + 4]) == GGML_UNARY_OP_SILU && + graph->nodes[i + 4]->src[0] == dst) { + dst = graph->nodes[i + 4]; + } + add_dep_safe(base_tensor_opt(n0->src[0]), dst); + add_dep_safe(base_tensor_opt(n0->src[1]), dst); + add_dep_safe(base_tensor_opt(n0->src[1]), cpy); + add_dep_safe(base_tensor_opt(cpy), dst); + } else if (n0->op == GGML_OP_CPY && i + 1 < graph->n_nodes && + graph->nodes[i + 1]->op == GGML_OP_SSM_CONV && + n0->src[0] && n0->src[0]->view_src == graph->nodes[i + 1]->src[0]) { + ggml_tensor * dst = graph->nodes[i + 1]; + if (i + 2 < graph->n_nodes && graph->nodes[i + 2]->op == GGML_OP_UNARY && + ggml_get_unary_op(graph->nodes[i + 2]) == GGML_UNARY_OP_SILU && + graph->nodes[i + 2]->src[0] == dst) { + dst = graph->nodes[i + 2]; + } + add_dep_safe(base_tensor_opt(graph->nodes[i + 1]->src[0]), dst); + add_dep_safe(base_tensor_opt(n0), dst); + } else if (n0->op == GGML_OP_SSM_CONV && n0->src[0] && n0->src[0]->op == GGML_OP_CONCAT) { + ggml_tensor * concat = n0->src[0]; + ggml_tensor * dst = n0; + if (i + 1 < graph->n_nodes && graph->nodes[i + 1]->op == GGML_OP_UNARY && + ggml_get_unary_op(graph->nodes[i + 1]) == GGML_UNARY_OP_SILU && + graph->nodes[i + 1]->src[0] == dst) { + dst = graph->nodes[i + 1]; + } + add_dep_safe(base_tensor_opt(concat->src[0]), dst); + add_dep_safe(base_tensor_opt(concat->src[1]), dst); + add_dep_safe(base_tensor_opt(concat), dst); + for (int k = std::max(0, i - 24); k < i; ++k) { + ggml_tensor * sr = graph->nodes[k]; + if (sr->op == GGML_OP_SET_ROWS && sr->src[0] && sr->src[0]->view_src == concat) { + add_dep_safe(base_tensor_opt(sr), dst); + break; + } + } + } + } + } + if (gen_fuse_enabled("l2")) { + for (int i = 0; i < graph->n_nodes; ++i) { + ggml_tensor * rms0 = graph->nodes[i]; + if (rms0->op != GGML_OP_RMS_NORM || !rms0->src[0]) { + continue; + } + ggml_tensor * sc0 = nullptr; + int sc0_idx = -1; + for (int j = i + 1; j < std::min(graph->n_nodes, i + 24); ++j) { + if (graph->nodes[j]->op == GGML_OP_SCALE && graph->nodes[j]->src[0] == rms0) { + sc0 = graph->nodes[j]; + sc0_idx = j; + break; + } + } + if (!sc0) { + continue; + } + add_dep_safe(base_tensor_opt(rms0->src[0]), sc0); + for (int j = i + 1; j <= std::min(graph->n_nodes - 1, sc0_idx + 6); ++j) { + if (j == sc0_idx || graph->nodes[j]->op != GGML_OP_RMS_NORM || !graph->nodes[j]->src[0]) { + continue; + } + ggml_tensor * rms1 = graph->nodes[j]; + for (int k = j + 1; k <= std::min(graph->n_nodes - 1, sc0_idx + 8); ++k) { + if (graph->nodes[k]->op == GGML_OP_SCALE && graph->nodes[k]->src[0] == rms1 && k > sc0_idx) { + ggml_tensor * sc1 = graph->nodes[k]; + add_dep_safe(base_tensor_opt(rms0->src[0]), sc1); + add_dep_safe(base_tensor_opt(rms1->src[0]), sc1); + add_dep_safe(base_tensor_opt(sc0), sc1); + break; + } + } + break; + } + } + } + if (!s10_add_rms_disabled()) { + for (int i = 0; i < graph->n_nodes; ++i) { + if (graph->nodes[i]->op != GGML_OP_ADD) { + continue; + } + int end = i; + while (end + 1 < graph->n_nodes && graph->nodes[end + 1]->op == GGML_OP_ADD && end - i + 1 < MAX_FUSED_ADDS) { + end++; + } + if (end == i && i > 0) { + const ggml_tensor * prev_node = graph->nodes[i - 1]; + if ((prev_node->op == GGML_OP_MUL_MAT || prev_node->op == GGML_OP_MUL_MAT_ID) && + (graph->nodes[i]->src[0] == prev_node || graph->nodes[i]->src[1] == prev_node)) { + continue; + } + } + ggml_tensor * last_add = graph->nodes[end]; + int rms_idx = -1; + for (int j = end + 1; j < std::min(graph->n_nodes, end + 17); ++j) { + if (graph->nodes[j]->op == GGML_OP_RMS_NORM && graph->nodes[j]->src[0] == last_add) { + rms_idx = j; + break; + } + } + if (rms_idx >= 0) { + ggml_tensor * rms = graph->nodes[rms_idx]; + ggml_tensor * final_dst = rms; + int final_idx = rms_idx; + if (rms_idx + 1 < graph->n_nodes && graph->nodes[rms_idx + 1]->op == GGML_OP_MUL && + (graph->nodes[rms_idx + 1]->src[0] == rms || graph->nodes[rms_idx + 1]->src[1] == rms)) { + final_dst = graph->nodes[rms_idx + 1]; + final_idx = rms_idx + 1; + } + for (int a = i; a <= end; ++a) { + for (int s = 0; s < 2; ++s) { + add_dep_safe(base_tensor_opt(graph->nodes[a]->src[s]), final_dst); + } + } + add_dep_safe(base_tensor_opt(last_add), final_dst); + for (int k = end + 1; k < final_idx; ++k) { + if (k == rms_idx || is_empty(graph->nodes[k])) { + continue; + } + add_dep_safe(base_tensor_opt(graph->nodes[k]), final_dst); + for (int s = 0; s < GGML_MAX_SRC; ++s) { + add_dep_safe(base_tensor_opt(graph->nodes[k]->src[s]), final_dst); + } + } + i = end; + } + } + } + if (gen_fuse_enabled("mmgate")) { + for (int i = 0; i < graph->n_nodes; ++i) { + ggml_tensor * mm = graph->nodes[i]; + if (mm->op != GGML_OP_MUL_MAT || !mm->src[1]) { + continue; + } + auto same_mm = [&](const ggml_tensor * t) { + return t == mm || ((t->op == GGML_OP_RESHAPE || t->op == GGML_OP_VIEW) && t->view_src == mm); + }; + for (int j = i + 1; j < std::min(i + 32, graph->n_nodes); ++j) { + ggml_tensor * n = graph->nodes[j]; + if (n->op == GGML_OP_UNARY && ggml_get_unary_op(n) == GGML_UNARY_OP_SIGMOID && same_mm(n->src[0])) { + params->add_alloc_dep(params->user_data, mm->src[1], n); + break; + } + if (n->op == GGML_OP_ADD && j + 2 < graph->n_nodes && (same_mm(n->src[0]) || same_mm(n->src[1]))) { + ggml_tensor * sp = graph->nodes[j + 1]; + ggml_tensor * mul = graph->nodes[j + 2]; + if (sp->op == GGML_OP_UNARY && ggml_get_unary_op(sp) == GGML_UNARY_OP_SOFTPLUS && sp->src[0] == n && + mul->op == GGML_OP_MUL && (mul->src[0] == sp || mul->src[1] == sp)) { + params->add_alloc_dep(params->user_data, mm->src[1], mul); + } + break; + } + } + } + } + if (gen_fuse_enabled("shexp")) { + for (int i = 0; i < graph->n_nodes; ++i) { + ggml_tensor * mm = graph->nodes[i]; + if (mm->op != GGML_OP_MUL_MAT || !mm->src[1]) { + continue; + } + for (int j = i + 1; j < std::min(i + 16, graph->n_nodes); ++j) { + ggml_tensor * mul = graph->nodes[j]; + if (mul->op == GGML_OP_MUL && (mul->src[0] == mm || mul->src[1] == mm)) { + ggml_tensor * gate = (mul->src[0] == mm) ? mul->src[1] : mul->src[0]; + if (gate && gate->ne[0] == 1 && gate->ne[1] == mm->ne[1]) { + params->add_alloc_dep(params->user_data, mm->src[1], mul); + params->add_alloc_dep(params->user_data, gate, mul); + } + break; + } + } + } + } + if (gen_fuse_enabled("s8")) { + auto base_tensor = [](ggml_tensor * t) -> ggml_tensor * { + while (t && t->view_src) { + t = t->view_src; + } + return t; + }; + for (int i = 0; i < graph->n_nodes; ++i) { + ggml_tensor * n0 = graph->nodes[i]; + if (n0->op == GGML_OP_RMS_NORM && i + 3 < graph->n_nodes && graph->nodes[i + 1]->op == GGML_OP_MUL) { + int silu_off = 2; + if ((graph->nodes[i + 2]->op == GGML_OP_RESHAPE || graph->nodes[i + 2]->op == GGML_OP_VIEW) && i + 4 < graph->n_nodes) { + silu_off = 3; + } + ggml_tensor * silu = graph->nodes[i + silu_off]; + ggml_tensor * out = graph->nodes[i + silu_off + 1]; + if (silu->op == GGML_OP_UNARY && ggml_get_unary_op(silu) == GGML_UNARY_OP_SILU && + out->op == GGML_OP_MUL && (out->src[0] == silu || out->src[1] == silu)) { + if (ggml_tensor * b0 = base_tensor(n0->src[0])) { + params->add_alloc_dep(params->user_data, b0, out); + } + if (ggml_tensor * bz = base_tensor(silu->src[0])) { + params->add_alloc_dep(params->user_data, bz, out); + } + } + } + if (n0->op == GGML_OP_CONT && n0->src[0] && i + 2 < graph->n_nodes) { + int u_off = 1; + while (u_off <= 2 && i + u_off + 1 < graph->n_nodes && is_empty(graph->nodes[i + u_off]) && + graph->nodes[i + u_off]->op != GGML_OP_NONE) { + u_off++; + } + if (i + u_off + 1 < graph->n_nodes) { + ggml_tensor * unary = graph->nodes[i + u_off]; + ggml_tensor * mul = graph->nodes[i + u_off + 1]; + if (unary->op == GGML_OP_UNARY && mul->op == GGML_OP_MUL && + (mul->src[0] == unary || mul->src[1] == unary)) { + if (ggml_tensor * bg = base_tensor(n0->src[0])) { + params->add_alloc_dep(params->user_data, bg, mul); + } + } + } + } + if (n0->op == GGML_OP_ADD) { + int end = i; + while (end + 1 < graph->n_nodes && graph->nodes[end + 1]->op == GGML_OP_ADD && end - i + 1 < MAX_FUSED_ADDS) { + end++; + } + if (end - i + 1 >= 3) { + ggml_tensor * last_add = graph->nodes[end]; + for (int a = i; a <= end; ++a) { + for (int s = 0; s < 2; ++s) { + ggml_tensor * src = graph->nodes[a]->src[s]; + if (src && src->view_src) { + params->add_alloc_dep(params->user_data, src->view_src, last_add); + } + } + } + i = end; + } + } + } + } + } } static void ggml_backend_vk_event_record(ggml_backend_t backend, ggml_backend_event_t event) { @@ -16412,6 +26677,19 @@ static void ggml_backend_vk_event_record(ggml_backend_t backend, ggml_backend_ev ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; vk_event *vkev = (vk_event *)event->context; + const bool t_idle = !ctx->device->async_use_transfer_queue || + ctx->transfer_semaphore_last_submitted == ctx->transfer_semaphore.value; + if (ctx->compute_ctx.expired() && ctx->transfer_ctx.expired() && t_idle && + !ctx->almost_ready_fence_pending && + (ctx->fence_submitted || !ctx->submit_pending)) { + vkev->fence_ctx = ctx; + vkev->fence_ctx_alive = ctx->alive_token; + vkev->fence_target = ctx->fence_epoch + (ctx->fence_submitted ? 1ULL : 0ULL); + vkev->has_fence_ref = true; + return; + } + vkev->has_fence_ref = false; + ggml_vk_submit_transfer_ctx(ctx); vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); @@ -16450,17 +26728,57 @@ static void ggml_backend_vk_event_wait(ggml_backend_t backend, ggml_backend_even ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; vk_event *vkev = (vk_event *)event->context; - vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); + if (vkev->has_fence_ref) { + if (auto al = vkev->fence_ctx_alive.lock(); al && *al) { + if (vkev->fence_ctx->fence_epoch < vkev->fence_target) { + ggml_vk_synchronize(vkev->fence_ctx); + } + } + vkev->has_fence_ref = false; + return; + } - if (vkev->has_event) { - // Wait for latest event - ggml_vk_wait_events(compute_ctx, { vkev->event }); + if (!vkev->has_event) { + return; + } - if (ctx->device->async_use_transfer_queue) { - vk_context transfer_ctx = ggml_vk_get_transfer_ctx(ctx); - transfer_ctx->s->wait_semaphores.push_back(vkev->tl_semaphore); + // If the timeline semaphore has already signaled (or drains within 200 us while ctx is idle), + // avoid opening compute_ctx / transfer_ctx so direct UMA writes, active KV span detection, and + // single-CB graph replay remain active across speculative rounds. + if (ctx->compute_ctx.expired() && ctx->transfer_ctx.expired()) { + vk::Semaphore sem = vkev->tl_semaphore.s; + uint64_t val = vkev->tl_semaphore.value; + bool signaled = (ctx->device->device.getSemaphoreCounterValue(sem) >= val); + if (!signaled && !ctx->fence_submitted && !ctx->almost_ready_fence_pending) { + vk::SemaphoreWaitInfo swi{vk::SemaphoreWaitFlags{}, sem, val}; + signaled = (ctx->device->device.waitSemaphores(swi, 200000ULL) == vk::Result::eSuccess); + } + if (signaled) { + for (auto & ev : vkev->events_submitted) { + ctx->device->device.resetEvent(ev); + } + vkev->events_free.insert(vkev->events_free.end(), vkev->events_submitted.begin(), vkev->events_submitted.end()); + vkev->events_submitted.clear(); + if (vkev->cmd_buffer) { + if (vkev->cmd_buffer_use_counter == vkev->cmd_buffer->use_counter) { + vkev->cmd_buffer->in_use = false; + vkev->cmd_buffer->buf.reset(); + } + vkev->cmd_buffer = nullptr; + } + return; } } + + vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); + + // Wait for latest event + ggml_vk_wait_events(compute_ctx, { vkev->event }); + + if (ctx->device->async_use_transfer_queue) { + vk_context transfer_ctx = ggml_vk_get_transfer_ctx(ctx); + transfer_ctx->s->wait_semaphores.push_back(vkev->tl_semaphore); + } } static ggml_backend_i ggml_backend_vk_interface = { @@ -16706,13 +27024,42 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm }; // non-compute ops are never executed here; their size is bounded by the buffer allocation limit const bool non_compute = ggml_op_is_empty(op->op); - for (int i = 0; i < GGML_MAX_SRC; i++) { - if (op->src[i] && !non_compute && !tensor_size_supported(ggml_nbytes(op->src[i]))) { + if (!non_compute) { + if (ggml_vk_tensor_is_repack(op)) { + return false; + } + for (int i = 0; i < GGML_MAX_SRC; i++) { + const ggml_tensor * s = op->src[i]; + if (!s) { + continue; + } + if (ggml_vk_tensor_is_repack(s)) { + if (i != 0 || (op->op != GGML_OP_MUL_MAT && op->op != GGML_OP_MUL_MAT_ID)) { + return false; + } + const int ri = ggml_vk_repack_type_idx(s->type); + if (ri < 0 || ggml_vk_repack_alloc_bytes(s) == 0 || + !ggml_is_contiguous(s) || s->view_offs != 0) { + return false; + } + if (device->pipeline_dequant_mul_mat_vec_repack_f32_f32[ri][0] == nullptr || + (op->op == GGML_OP_MUL_MAT_ID && device->pipeline_dequant_mul_mat_vec_id_repack_f32[ri] == nullptr)) { + return false; + } + const size_t repack_bytes = ggml_vk_repack_alloc_bytes(s); + if (repack_bytes == 0 || !tensor_size_supported(repack_bytes)) { + return false; + } + if (op->op == GGML_OP_MUL_MAT && repack_bytes > device->properties.limits.maxStorageBufferRange) { + return false; + } + } else if (!tensor_size_supported(ggml_nbytes(s))) { + return false; + } + } + if (!tensor_size_supported(ggml_nbytes(op))) { return false; } - } - if (!non_compute && !tensor_size_supported(ggml_nbytes(op))) { - return false; } switch (op->op) { @@ -16753,6 +27100,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm case GGML_GLU_OP_GEGLU_ERF: case GGML_GLU_OP_GEGLU_QUICK: case GGML_GLU_OP_SWIGLU_CLAMP: + case GGML_GLU_OP_SITU: return ggml_vk_is_float_elementwise(op) && (!op->src[1] || op->src[1]->type == op->type); default: return false; @@ -16762,7 +27110,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm { ggml_type src0_type = op->src[0]->type; if (op->op == GGML_OP_MUL_MAT_ID) { - if (!ggml_vk_use_mul_mat_vec_id(op)) { + if (!ggml_vk_use_mul_mat_vec_id(op, device->mmv_id_max_tokens)) { const ggml_tensor * ids = op->src[2]; // Shaders store row IDs as uint16_t slot and token indices. if (ids->ne[0] > int64_t(UINT16_MAX) + 1 || ids->ne[1] > int64_t(UINT16_MAX) + 1) { @@ -16835,14 +27183,27 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } + const bool has_banded_bias = ggml_flash_attn_ext_has_banded_rel_bias(op); bool coopmat2 = device->coopmat2; + if (has_banded_bias && (coopmat2 || device->xe_fa_support || op->src[3] == nullptr)) { + return false; + } uint32_t HSK = op->src[1]->ne[0]; uint32_t HSV = op->src[2]->ne[0]; if ((HSK % 8) != 0 || (HSV % 8) != 0) { return false; } - if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) { - return false; + if (op->src[4]) { + if (op->src[4]->type != GGML_TYPE_F32) { + return false; + } + if (ggml_nrows(op->src[4]) > 1) { + if (coopmat2 || device->xe_fa_support || !ggml_is_contiguous(op->src[4]) || + op->src[4]->ne[1] != op->src[0]->ne[1] * op->src[0]->ne[3] || + op->src[4]->ne[2] != 1 || op->src[4]->ne[3] != 1) { + return false; + } + } } if (op->src[0]->type != GGML_TYPE_F32) { return false; @@ -17128,6 +27489,41 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm } return false; } + case GGML_OP_INKLING_FUSED: + { + const int32_t m = ggml_get_op_params_i32(op, 0); + const bool type_ok = (op->type == GGML_TYPE_F32) || (m == 2 && op->type == GGML_TYPE_F16); + if (m < 0 || m >= 16 || !type_ok || !ggml_is_contiguous(op) || + device->pipeline_inkling_fused[m] == nullptr) { + return false; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + if (op->src[s] == nullptr) continue; + const ggml_tensor * st_t = op->src[s]; + const bool allow_strided = + (m == 1 && s == 0 && st_t->ne[2] == 1 && st_t->ne[3] == 1 && + st_t->nb[0] == sizeof(float) && (st_t->nb[1] % sizeof(float) == 0)) || + (m == 12 && (s == 0 || s == 1) && st_t->ne[3] == 1 && + st_t->nb[0] == sizeof(float) && st_t->nb[1] == (size_t)st_t->ne[0] * sizeof(float) && + (st_t->nb[2] % sizeof(float) == 0)); + if (allow_strided) { + if (!tensor_size_supported(ggml_vk_tensor_byte_span(st_t))) return false; + } else if (!ggml_is_contiguous(st_t)) { + return false; + } + const ggml_type st = op->src[s]->type; + if ((m == 2 && s == 2) || (m == 1 && s == 6) || (m == 9 && s == 0) || (m == 10 && s == 6)) { + if (st != GGML_TYPE_I32) return false; + } else if (m == 2 && s == 3) { + if (st != GGML_TYPE_F16) return false; + } else if (m == 9 && (s == 1 || s == 5)) { + if (st != GGML_TYPE_BF16 && st != GGML_TYPE_F32) return false; + } else { + if (st != GGML_TYPE_F32) return false; + } + } + return true; + } case GGML_OP_DSV4_HC_COMB: case GGML_OP_DSV4_HC_PRE: case GGML_OP_DSV4_HC_POST: @@ -17363,7 +27759,8 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm } static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) { - if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) { + if (buft->iface.get_name != ggml_backend_vk_buffer_type_name && + buft->iface.get_name != ggml_backend_vk_repack_buffer_type_name) { return false; } @@ -17428,6 +27825,16 @@ static void ggml_backend_vk_device_event_synchronize(ggml_backend_dev_t dev, ggm auto device = ggml_vk_get_device(ctx->device); vk_event *vkev = (vk_event *)event->context; + if (vkev->has_fence_ref) { + if (auto al = vkev->fence_ctx_alive.lock(); al && *al) { + if (vkev->fence_ctx->fence_epoch < vkev->fence_target) { + ggml_vk_synchronize(vkev->fence_ctx); + } + } + vkev->has_fence_ref = false; + return; + } + // Only do something if the event has actually been used if (vkev->has_event) { vk::Semaphore sem = vkev->tl_semaphore.s; @@ -17536,6 +27943,11 @@ static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, return devices[device]; } +static ggml_backend_buffer_type_t * ggml_backend_vk_dev_get_extra_bufts(ggml_backend_dev_t dev) { + ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; + return ggml_vk_get_device(ctx->device)->extra_bufts.data(); +} + static void * ggml_backend_vk_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) { UNUSED(reg); #if !defined(_WIN32) @@ -17549,6 +27961,9 @@ static void * ggml_backend_vk_reg_get_proc_address(ggml_backend_reg_t reg, const return (void *) ggml_backend_vk_comm_allreduce_tensor; } #endif + if (strcmp(name, "ggml_backend_dev_get_extra_bufts") == 0) { + return (void *) ggml_backend_vk_dev_get_extra_bufts; + } if (strcmp(name, "ggml_backend_fusion_get") == 0) { return (void *) ggml_backend_vk_fusion_get; } @@ -17564,6 +27979,9 @@ static void * ggml_backend_vk_reg_get_proc_address(ggml_backend_reg_t reg, const if (strcmp(name, "ggml_backend_fusion_set_enabled") == 0) { return (void *) ggml_backend_vk_fusion_set_enabled; } + if (strcmp(name, "ggml_backend_get_cached_uma_ptr") == 0) { + return (void *) ggml_backend_vk_get_cached_uma_ptr; + } return nullptr; } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/argmax.comp b/ggml/src/ggml-vulkan/vulkan-shaders/argmax.comp index 7c128776710e..c80150f4235e 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/argmax.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/argmax.comp @@ -9,52 +9,117 @@ layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; -layout (binding = 0) readonly buffer A {A_TYPE data_a[];}; -layout (binding = 1) writeonly buffer D {D_TYPE data_d[];}; +layout (binding = 0) readonly buffer A { A_TYPE data_a[]; }; +layout (binding = 0) readonly buffer AV4 { vec4 data_a_v4[]; }; +layout (binding = 1) writeonly buffer D { D_TYPE data_d[]; }; +layout (binding = 2) readonly buffer B { A_TYPE data_b[]; }; +layout (binding = 2) readonly buffer BV4 { vec4 data_b_v4[]; }; -layout (constant_id = 0) const uint BLOCK_SIZE = 32; +layout (constant_id = 0) const uint BLOCK_SIZE = 512; -shared FLOAT_TYPE tmpmax[BLOCK_SIZE]; -shared uint tmp[BLOCK_SIZE]; +shared FLOAT_TYPE tmpmax[512]; +shared uint tmp[512]; + +void update_best(inout FLOAT_TYPE amax, inout uint acol, FLOAT_TYPE val, uint idx) { + if (val > amax || (val == amax && idx < acol)) { + amax = val; + acol = idx; + } +} + +FLOAT_TYPE apply_softcap(FLOAT_TYPE x) { + if (p.param1 == 0.0f) { + return x; + } + precise float s0 = float(x) * p.param1 + 0.0f; + precise float t = tanh(s0); + precise float s1 = t * p.param2 + 0.0f; + return FLOAT_TYPE(s1); +} void main() { const uint row = gl_WorkGroupID.z * 262144 + gl_WorkGroupID.y * 512 + gl_WorkGroupID.x; - const uint col = gl_LocalInvocationID.x; + const uint tid = gl_LocalInvocationID.x; if (row >= p.KY) { return; } - A_TYPE amax = -FLT_MAX; - uint acol = col; - - if (col < p.KX) { - amax = data_a[row*p.KX + col]; - } + FLOAT_TYPE amax = FLOAT_TYPE(uintBitsToFloat(0xFF800000u)); + uint acol = 0xFFFFFFFFu; + const uint a_misalign = uint(p.param3); + const uint p4_bits = floatBitsToUint(p.param4); + const bool is_packed4 = (p4_bits & 0xFF000000u) == 0x40000000u; + const uint d_misalign = is_packed4 ? (p4_bits & 0x3FFu) : uint(p.param4); + const uint b_misalign = is_packed4 ? ((p4_bits >> 10u) & 0x3FFu) : 0u; + const bool has_add = is_packed4 && (((p4_bits >> 20u) & 1u) != 0u); + const uint row_base = a_misalign + row * p.KX; - for (uint i = col + BLOCK_SIZE; i < p.KX; i += BLOCK_SIZE) { - A_TYPE val = data_a[row*p.KX + i]; - if (val > amax) { - amax = val; - acol = i; + if (!has_add) { + if ((row_base & 3u) == 0u) { + const uint kx4 = p.KX >> 2u; + const uint base4 = row_base >> 2u; + for (uint v4_i = tid; v4_i < kx4; v4_i += BLOCK_SIZE) { + const vec4 v = data_a_v4[base4 + v4_i]; + const uint c0 = v4_i << 2u; + update_best(amax, acol, apply_softcap(FLOAT_TYPE(v.x)), c0 + 0u); + update_best(amax, acol, apply_softcap(FLOAT_TYPE(v.y)), c0 + 1u); + update_best(amax, acol, apply_softcap(FLOAT_TYPE(v.z)), c0 + 2u); + update_best(amax, acol, apply_softcap(FLOAT_TYPE(v.w)), c0 + 3u); + } + const uint tail_start = kx4 << 2u; + for (uint i = tail_start + tid; i < p.KX; i += BLOCK_SIZE) { + update_best(amax, acol, apply_softcap(FLOAT_TYPE(data_a[row_base + i])), i); + } + } else { + for (uint i = tid; i < p.KX; i += BLOCK_SIZE) { + update_best(amax, acol, apply_softcap(FLOAT_TYPE(data_a[row_base + i])), i); + } + } + } else { + const uint row_b_base = b_misalign + row * p.KX; + if ((row_base & 3u) == 0u && (row_b_base & 3u) == 0u) { + const uint kx4 = p.KX >> 2u; + const uint base4 = row_base >> 2u; + const uint bbase4 = row_b_base >> 2u; + for (uint v4_i = tid; v4_i < kx4; v4_i += BLOCK_SIZE) { + const vec4 va = data_a_v4[base4 + v4_i]; + const vec4 vb = data_b_v4[bbase4 + v4_i]; + const uint c0 = v4_i << 2u; + precise float sx = va.x + vb.x; + precise float sy = va.y + vb.y; + precise float sz = va.z + vb.z; + precise float sw = va.w + vb.w; + update_best(amax, acol, apply_softcap(FLOAT_TYPE(sx)), c0 + 0u); + update_best(amax, acol, apply_softcap(FLOAT_TYPE(sy)), c0 + 1u); + update_best(amax, acol, apply_softcap(FLOAT_TYPE(sz)), c0 + 2u); + update_best(amax, acol, apply_softcap(FLOAT_TYPE(sw)), c0 + 3u); + } + const uint tail_start = kx4 << 2u; + for (uint i = tail_start + tid; i < p.KX; i += BLOCK_SIZE) { + precise float s = float(data_a[row_base + i]) + float(data_b[row_b_base + i]); + update_best(amax, acol, apply_softcap(FLOAT_TYPE(s)), i); + } + } else { + for (uint i = tid; i < p.KX; i += BLOCK_SIZE) { + precise float s = float(data_a[row_base + i]) + float(data_b[row_b_base + i]); + update_best(amax, acol, apply_softcap(FLOAT_TYPE(s)), i); + } } } - tmp[col] = acol; - tmpmax[col] = amax; - + tmp[tid] = acol; + tmpmax[tid] = amax; barrier(); - [[unroll]] for (int s = int(BLOCK_SIZE) / 2; s > 0; s >>= 1) { - if (col < s && col + s < p.KX) { - if (tmpmax[col] < tmpmax[col + s]) { - tmpmax[col] = tmpmax[col + s]; - tmp[col] = tmp[col + s]; - } + + [[unroll]] for (uint s = BLOCK_SIZE >> 1u; s > 0u; s >>= 1u) { + if (tid < s) { + update_best(tmpmax[tid], tmp[tid], tmpmax[tid + s], tmp[tid + s]); } barrier(); } - if (col == 0) { - data_d[row] = D_TYPE(tmp[0]); + if (tid == 0u) { + data_d[d_misalign + row] = D_TYPE(tmp[0]); } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/count_experts.comp b/ggml/src/ggml-vulkan/vulkan-shaders/count_experts.comp index c7c0ac3416e5..2998302f73db 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/count_experts.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/count_experts.comp @@ -91,7 +91,6 @@ void zero_skipped_rows() { void main() { const uint num_elements = p.ne00 * p.ne01; const uint tid = gl_LocalInvocationID.x; - const uint tile_shift = findLSB(p.row_tile_size); uint total_tiles = 0; uint local_skipped = 0; if (tid == 0) { @@ -127,7 +126,7 @@ void main() { for (uint e = gl_SubgroupInvocationID; e < n_experts_padded; e += gl_SubgroupSize) { const bool in_range = e < n_experts; const uint count = in_range ? vals[e] : 0; - const uint n_tiles = (count + p.row_tile_size - 1) >> tile_shift; + const uint n_tiles = (count + p.row_tile_size - 1) / p.row_tile_size; const uint tile_begin = base + subgroupExclusiveAdd(n_tiles); if (in_range) { offsets[e] = tile_begin * p.row_tile_size; @@ -144,7 +143,7 @@ void main() { if (tid == 0) { for (uint e = 0; e < n_experts; ++e) { const uint count = vals[e]; - const uint n_tiles = (count + p.row_tile_size - 1) >> tile_shift; + const uint n_tiles = (count + p.row_tile_size - 1) / p.row_tile_size; offsets[e] = total_tiles * p.row_tile_size; cursors[e] = 0; write_tiles(expert_base + e, count, total_tiles, n_tiles); diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs.glsl index 911ceac22cf6..027836ae9706 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs.glsl @@ -121,9 +121,9 @@ vec2 dequantize(uint ib, uint iqs, uint a_offset) { return vec2(int(data_a[a_offset + ib].qs[iqs]), int(data_a[a_offset + ib].qs[iqs + 1])); } vec4 dequantize4(uint ib, uint iqs, uint a_offset) { - const i8vec2 v0 = unpack8(int32_t(data_a_packed16[a_offset + ib].qs[iqs/2])).xy; // vec4 used due to #12147 - const i8vec2 v1 = unpack8(int32_t(data_a_packed16[a_offset + ib].qs[iqs/2 + 1])).xy; - return vec4(v0.x, v0.y, v1.x, v1.y); + return vec4(unpack8(pack32(i16vec2( + data_a_packed16[a_offset + ib].qs[iqs/2], + data_a_packed16[a_offset + ib].qs[iqs/2 + 1])))); } #endif @@ -495,7 +495,7 @@ vec2 dequantize(uint ib, uint iqs, uint a_offset) { #ifdef USE_OCP_FP4 return vec2(unpackFloat2xfe2m1EXT(uint8_t(vui))); #else - return vec2(kvalues_mxfp4[vui & 0xF], kvalues_mxfp4[vui >> 4]) * 0.5; + return vec2(float(mxfp4_kval(vui & 0xFu)), float(mxfp4_kval(vui >> 4u))) * 0.5f; #endif } vec4 dequantize4(uint ib, uint iqs, uint a_offset) { @@ -512,37 +512,77 @@ vec4 dequantize4(uint ib, uint iqs, uint a_offset) { #endif #if defined(DATA_A_NVFP4) +#if defined(REPACK_PLANAR) vec2 dequantize(uint ib, uint iqs, uint a_offset) { - const uint sub = iqs >> 4; + const uint sub = iqs >> 4u; + const uint j = iqs & 7u; + const uint shift = (iqs & 8u) >> 1u; +#ifdef MUL_MAT_ID + const uint s_blks = (p.ncols >> 6u) * p.stride_d; +#else + const uint s_blks = (p.ncols >> 6u) * ((GEN_GLU == 2u) ? p.pair_m0 : p.stride_d); +#endif + const uint slice_u32 = a_offset * 9u; + const uint d_u32 = data_a_repack_u32[slice_u32 + s_blks * 8u + ib]; + const float d = ue4m3_to_fp32(uint8_t((d_u32 >> (sub * 8u)) & 0xFFu)); + const uint q_word = data_a_repack_u32[slice_u32 + ib * 8u + sub * 2u + (j >> 2u)]; + const uint bsh = (j & 3u) * 8u; + const uint vui0 = (q_word >> bsh) & 0xFFu; + const uint vui1 = (q_word >> (bsh + 8u)) & 0xFFu; + const uint qs0 = (vui0 >> shift) & 0xFu; + const uint qs1 = (vui1 >> shift) & 0xFu; + return vec2(float(mxfp4_kval(qs0)), float(mxfp4_kval(qs1))) * (d * 0.5f); +} +vec4 dequantize4(uint ib, uint iqs, uint a_offset) { + const uint sub = iqs >> 4u; + const uint j = iqs & 7u; + const uint shift = (iqs & 8u) >> 1u; +#ifdef MUL_MAT_ID + const uint s_blks = (p.ncols >> 6u) * p.stride_d; +#else + const uint s_blks = (p.ncols >> 6u) * ((GEN_GLU == 2u) ? p.pair_m0 : p.stride_d); +#endif + const uint slice_u32 = a_offset * 9u; + const uint d_u32 = data_a_repack_u32[slice_u32 + s_blks * 8u + ib]; + const float d = ue4m3_to_fp32(uint8_t((d_u32 >> (sub * 8u)) & 0xFFu)); + const uint vui = data_a_repack_u32[slice_u32 + ib * 8u + (sub * 8u + j) / 4u]; + const u8vec4 qv = unpack8((vui >> shift) & 0x0F0F0F0Fu); + return vec4(float(mxfp4_kval(uint(qv.x))), float(mxfp4_kval(uint(qv.y))), + float(mxfp4_kval(uint(qv.z))), float(mxfp4_kval(uint(qv.w)))) * (d * 0.5f); +} +#else +vec2 dequantize(uint ib, uint iqs, uint a_offset) { + const uint sub = iqs >> 4u; const float d = ue4m3_to_fp32(data_a[a_offset + ib].d[sub]); - const uint j = iqs & 7; - const uint shift = (iqs & 8) >> 1; // 0 or 4 + const uint j = iqs & 7u; + const uint shift = (iqs & 8u) >> 1u; // 0 or 4 #ifdef USE_OCP_FP4 const uint vui = uint(data_a_packed16[a_offset + ib].qs[(sub * 8u + j) / 2u]); return vec2(bitcastExtractfe2m1EXT(unpack8(vui).xy, shift)) * d; #else const uint vui0 = uint(data_a[a_offset + ib].qs[sub * 8u + j]); - const uint vui1 = uint(data_a[a_offset + ib].qs[sub * 8u + j + 1]); - const uint qs0 = (vui0 >> shift) & 0xF; - const uint qs1 = (vui1 >> shift) & 0xF; - return vec2(float(kvalues_mxfp4[qs0]), float(kvalues_mxfp4[qs1])) * d * 0.5; + const uint vui1 = uint(data_a[a_offset + ib].qs[sub * 8u + j + 1u]); + const uint qs0 = (vui0 >> shift) & 0xFu; + const uint qs1 = (vui1 >> shift) & 0xFu; + return vec2(float(mxfp4_kval(qs0)), float(mxfp4_kval(qs1))) * (d * 0.5f); #endif } vec4 dequantize4(uint ib, uint iqs, uint a_offset) { -#ifdef USE_OCP_FP4 - const uint sub = iqs >> 4; + const uint sub = iqs >> 4u; const float d = ue4m3_to_fp32(data_a[a_offset + ib].d[sub]); - const uint j = iqs & 7; - const uint shift = (iqs & 8) >> 1; // 0 or 4 + const uint j = iqs & 7u; + const uint shift = (iqs & 8u) >> 1u; // 0 or 4 const uint vui = data_a_packed32[a_offset + ib].qs[(sub * 8u + j) / 4u]; +#ifdef USE_OCP_FP4 return vec4(bitcastExtractfe2m1EXT(unpack8(vui), shift)) * d; #else - const vec2 v0 = dequantize(ib, iqs, a_offset); - const vec2 v1 = dequantize(ib, iqs + 2u, a_offset); - return vec4(v0.x, v0.y, v1.x, v1.y); + const u8vec4 qv = unpack8((vui >> shift) & 0x0F0F0F0Fu); + return vec4(float(mxfp4_kval(uint(qv.x))), float(mxfp4_kval(uint(qv.y))), + float(mxfp4_kval(uint(qv.z))), float(mxfp4_kval(uint(qv.w)))) * (d * 0.5f); #endif } #endif +#endif #if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16) vec2 get_dm(uint ib, uint a_offset) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs_cm2.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs_cm2.glsl index ecea26672384..461a31080888 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs_cm2.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs_cm2.glsl @@ -1323,7 +1323,7 @@ float16_t dequantFuncMXFP4(const in decodeBufMXFP4 bl, const in uint blockCoords uint32_t qs = bl.block.qs[iqs]; qs >>= shift; qs &= 0xF; - float16_t ret = float16_t(kvalues_mxfp4[qs] * d * 0.5); + float16_t ret = float16_t(float(mxfp4_kval(qs)) * d * 0.5f); return ret; #endif } @@ -1351,10 +1351,10 @@ f16vec4 dequantFuncMXFP4_v(const in decodeBufMXFP4 bl, const in uint blockCoords uint(bl.block.qs[iqs + 3u])); qv = (qv >> shift) & 0xFu; const vec4 ret = vec4( - float(kvalues_mxfp4[qv.x]), - float(kvalues_mxfp4[qv.y]), - float(kvalues_mxfp4[qv.z]), - float(kvalues_mxfp4[qv.w])) * d * 0.5f; + float(mxfp4_kval(uint(qv.x))), + float(mxfp4_kval(uint(qv.y))), + float(mxfp4_kval(uint(qv.z))), + float(mxfp4_kval(uint(qv.w)))) * d * 0.5f; return f16vec4(ret); #endif } @@ -1382,7 +1382,7 @@ float16_t dequantFuncNVFP4(const in decodeBufNVFP4 bl, const in uint blockCoords const float d = ue4m3_to_fp32(bl.block.d[sub]); uint qs = uint(bl.block.qs[iqs]); qs = (qs >> shift) & 0xF; - return float16_t(kvalues_mxfp4[qs] * d * 0.5); + return float16_t(float(mxfp4_kval(qs)) * d * 0.5f); #endif } @@ -1403,10 +1403,10 @@ f16vec4 dequantFuncNVFP4_v(const in decodeBufNVFP4 bl, const in uint blockCoords const float d = ue4m3_to_fp32(bl.block.d[sub]); const u8vec4 qv = unpack8((qsw >> shift) & 0x0F0F0F0Fu); const vec4 ret = vec4( - float(kvalues_mxfp4[qv.x]), - float(kvalues_mxfp4[qv.y]), - float(kvalues_mxfp4[qv.z]), - float(kvalues_mxfp4[qv.w])) * d * 0.5f; + float(mxfp4_kval(uint(qv.x))), + float(mxfp4_kval(uint(qv.y))), + float(mxfp4_kval(uint(qv.z))), + float(mxfp4_kval(uint(qv.w)))) * d * 0.5f; return f16vec4(ret); #endif } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_mxfp4.comp b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_mxfp4.comp index 3194ba291f31..30fca89448e2 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_mxfp4.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_mxfp4.comp @@ -10,7 +10,7 @@ layout (binding = 1) writeonly buffer D {D_TYPE data_b[];}; void main() { const uint i = gl_WorkGroupID.x * 4 + gl_LocalInvocationID.x / 64; - init_iq_shmem(gl_WorkGroupSize); + const uint tid = gl_LocalInvocationID.x % 64; const uint il = tid/32; @@ -26,7 +26,7 @@ void main() { const float d = e8m0_to_fp32(data_a[ib].e); [[unroll]] for (uint l = 0; l < 8; ++l) { - data_b[b_idx + l + 0] = D_TYPE(d * 0.5 * float(kvalues_mxfp4[data_a[ib].qs[q_idx + l] & 0xF])); - data_b[b_idx + l + 16] = D_TYPE(d * 0.5 * float(kvalues_mxfp4[data_a[ib].qs[q_idx + l] >> 4])); + data_b[b_idx + l + 0] = D_TYPE(d * 0.5f * float(mxfp4_kval(uint(data_a[ib].qs[q_idx + l]) & 0xFu))); + data_b[b_idx + l + 16] = D_TYPE(d * 0.5f * float(mxfp4_kval(uint(data_a[ib].qs[q_idx + l]) >> 4u))); } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_nvfp4.comp b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_nvfp4.comp index 689089160b70..5b73c03cee2c 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_nvfp4.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_nvfp4.comp @@ -10,7 +10,7 @@ layout (binding = 1) writeonly buffer D {D_TYPE data_b[];}; void main() { const uint i = gl_WorkGroupID.x * 4 + gl_LocalInvocationID.x / 64; - init_iq_shmem(gl_WorkGroupSize); + const uint tid = gl_LocalInvocationID.x % 64; const uint sub = tid / 16; @@ -26,7 +26,7 @@ void main() { const float d = ue4m3_to_fp32(data_a[ib].d[sub]); [[unroll]] for (uint l = 0; l < 8; ++l) { - data_b[b_idx + l + 0] = D_TYPE(d * 0.5 * float(kvalues_mxfp4[data_a[ib].qs[q_idx + l] & 0xF])); - data_b[b_idx + l + 8] = D_TYPE(d * 0.5 * float(kvalues_mxfp4[data_a[ib].qs[q_idx + l] >> 4])); + data_b[b_idx + l + 0] = D_TYPE(d * 0.5f * float(mxfp4_kval(uint(data_a[ib].qs[q_idx + l]) & 0xFu))); + data_b[b_idx + l + 8] = D_TYPE(d * 0.5f * float(mxfp4_kval(uint(data_a[ib].qs[q_idx + l]) >> 4u))); } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/dequant_repack.comp b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_repack.comp new file mode 100644 index 000000000000..712b27ac407f --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/dequant_repack.comp @@ -0,0 +1,133 @@ +#version 450 + +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable + +#include "dequant_head.glsl" +#include "repack_planar.glsl" + +layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in; + +layout (binding = 0) readonly buffer A_U32 { uint data_a_u32[]; }; +layout (binding = 0) readonly buffer A_U4 { uvec4 data_a_u4[]; }; +layout (binding = 1) writeonly buffer D { D_TYPE data_b[]; }; + +void main() { +#if defined(DATA_A_NVFP4) + const uint s_blks = (p.K >> 6u) * p.M; + const uint n_blks = p.nel >> 6u; + const uint tid = gl_LocalInvocationID.x; + const uint sub = tid >> 3u; + const uint l = tid & 7u; + for (uint wgy = 0u; wgy < 1024u; ++wgy) { + const uint ib = gl_WorkGroupID.x * 1024u + wgy; + if (ib >= n_blks) { + return; + } + const uint e = ib / s_blks; + const uint b_in_slice = ib - e * s_blks; + const uint slice_u32 = e * s_blks * 9u; + const uint d_u32 = data_a_u32[slice_u32 + s_blks * 8u + b_in_slice]; + const float d = ue4m3_to_fp32(uint8_t((d_u32 >> (sub * 8u)) & 0xFFu)); + const uint q_word = data_a_u32[slice_u32 + b_in_slice * 8u + sub * 2u + (l >> 2u)]; + const uint q_byte = (q_word >> ((l & 3u) * 8u)) & 0xFFu; + const uint b_idx = ib * 64u + sub * 16u + l; + data_b[b_idx + 0u] = D_TYPE(d * 0.5f * float(mxfp4_kval(q_byte & 0xFu))); + data_b[b_idx + 8u] = D_TYPE(d * 0.5f * float(mxfp4_kval(q_byte >> 4u))); + } + return; +#endif +#if defined(DATA_A_Q4_K) + const uint sb_u4 = REPACK_Q4_K_SB_U4; +#elif defined(DATA_A_Q5_K) + const uint sb_u4 = REPACK_Q5_K_SB_U4; +#else + const uint sb_u4 = REPACK_Q6_K_SB_U4; +#endif + + [[unroll]] for (uint wgy = 0u; wgy < 256u; ++wgy) { + const uint ib = gl_WorkGroupID.x * 256u + wgy; + if (ib >= p.nel / 256u) { + return; + } + + const uint base_u4 = ib * sb_u4; + const uint base_u32 = base_u4 << 2u; + + const uint tid = gl_LocalInvocationID.x; // 0..31: sub_pair (0..3) * 8 + itid8 (0..7) + const uint sub_pair = tid >> 3u; + const uint itid8 = tid & 7u; + const uint y_idx = ib * 256u + sub_pair * 64u + 4u * itid8; + +#if defined(DATA_A_Q4_K) || defined(DATA_A_Q5_K) + const uvec4 hdr = data_a_u4[base_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const uint is0 = sub_pair * 2u + 0u; + const uint is1 = sub_pair * 2u + 1u; + uint sc0, m0, sc1, m1; + if (sub_pair < 2u) { + const uint sh0 = is0 * 8u; + const uint sh1 = is1 * 8u; + sc0 = (hdr.y >> sh0) & 63u; + m0 = (hdr.z >> sh0) & 63u; + sc1 = (hdr.y >> sh1) & 63u; + m1 = (hdr.z >> sh1) & 63u; + } else { + const uint sh0 = (is0 - 4u) * 8u; + const uint sh1 = (is1 - 4u) * 8u; + sc0 = ((hdr.w >> sh0) & 0xFu) | (((hdr.y >> sh0) >> 2u) & 0x30u); + m0 = ((hdr.w >> (sh0 + 4u)) & 0xFu) | (((hdr.z >> sh0) >> 2u) & 0x30u); + sc1 = ((hdr.w >> sh1) & 0xFu) | (((hdr.y >> sh1) >> 2u) & 0x30u); + m1 = ((hdr.w >> (sh1 + 4u)) & 0xFu) | (((hdr.z >> sh1) >> 2u) & 0x30u); + } + const float d0 = dm.x * float(sc0); + const float n0 = -dm.y * float(m0); + const float d1 = dm.x * float(sc1); + const float n1 = -dm.y * float(m1); + const uint qs_word = data_a_u32[((base_u4 + REPACK_QS_OFF_U4 + itid8) << 2u) + sub_pair]; +#if defined(DATA_A_Q4_K) + const vec4 q_lo = repack_magic_u4(qs_word); + const vec4 q_hi = repack_magic_u4(qs_word >> 4u); +#else + const uint qh_u32 = data_a_u32[base_u32 + REPACK_Q5_K_QH_OFF_U32 + itid8]; + const uint hb0_02 = (is0 <= 4u ? (qh_u32 << (4u - is0)) : (qh_u32 >> (is0 - 4u))) & 0x00100010u; + const uint hb0_13 = (qh_u32 >> (is0 + 4u)) & 0x00100010u; + const uint hb1_02 = (is1 <= 4u ? (qh_u32 << (4u - is1)) : (qh_u32 >> (is1 - 4u))) & 0x00100010u; + const uint hb1_13 = (qh_u32 >> (is1 + 4u)) & 0x00100010u; + const vec4 q_lo = repack_magic_u5((qs_word & 0x000F000Fu) | hb0_02, ((qs_word >> 8u) & 0x000F000Fu) | hb0_13); + const vec4 q_hi = repack_magic_u5(((qs_word >> 4u) & 0x000F000Fu) | hb1_02, ((qs_word >> 12u) & 0x000F000Fu) | hb1_13); +#endif + const vec4 r_lo = fma(vec4(d0), q_lo, vec4(n0)); + const vec4 r_hi = fma(vec4(d1), q_hi, vec4(n1)); + data_b[y_idx + 0u] = D_TYPE(r_lo.x); data_b[y_idx + 1u] = D_TYPE(r_lo.y); + data_b[y_idx + 2u] = D_TYPE(r_lo.z); data_b[y_idx + 3u] = D_TYPE(r_lo.w); + data_b[y_idx + 32u] = D_TYPE(r_hi.x); data_b[y_idx + 33u] = D_TYPE(r_hi.y); + data_b[y_idx + 34u] = D_TYPE(r_hi.z); data_b[y_idx + 35u] = D_TYPE(r_hi.w); +#else + const uint h = sub_pair >> 1u; + const uint sb_b = sub_pair & 1u; + const uvec4 q_all = data_a_u4[base_u4 + REPACK_Q6_K_QL_OFF_U4 + itid8]; + const uint ql_a = (h == 0u) ? q_all.x : q_all.z; + const uint ql_b = (h == 0u) ? q_all.y : q_all.w; + const uint qh = data_a_u32[base_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + h]; + const uint sh_n = sb_b * 4u; + const uint qh_a_02 = (sb_b == 0u) ? ((qh & 0x00030003u) << 4u) : (qh & 0x00300030u); + const uint qh_a_13 = (sb_b == 0u) ? ((qh & 0x03000300u) >> 4u) : ((qh & 0x30003000u) >> 8u); + const uint qh_b_02 = (sb_b == 0u) ? ((qh & 0x000C000Cu) << 2u) : ((qh & 0x00C000C0u) >> 2u); + const uint qh_b_13 = (sb_b == 0u) ? ((qh & 0x0C000C00u) >> 6u) : ((qh & 0xC000C000u) >> 10u); + const vec4 q_a = repack_magic_q6(((ql_a >> sh_n) & 0x000F000Fu) | qh_a_02, ((ql_a >> (sh_n + 8u)) & 0x000F000Fu) | qh_a_13); + const vec4 q_b = repack_magic_q6(((ql_b >> sh_n) & 0x000F000Fu) | qh_b_02, ((ql_b >> (sh_n + 8u)) & 0x000F000Fu) | qh_b_13); + const uint sc_sel = itid8 >> 2u; + const float d_f = unpackHalf2x16(data_a_u32[base_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uint sc_word = data_a_u32[base_u32 + REPACK_Q6_K_SC_OFF_U32 + 2u * h + sb_b]; + const float sc_a = d_f * float(bitfieldExtract(int(sc_word), int(sc_sel * 8u), 8)); + const float sc_b = d_f * float(bitfieldExtract(int(sc_word), int((sc_sel + 2u) * 8u), 8)); + const vec4 r_a = q_a * vec4(sc_a); + const vec4 r_b = q_b * vec4(sc_b); + const uint y6_idx = ib * 256u + 128u * h + 64u * sb_b + 4u * itid8; + data_b[y6_idx + 0u] = D_TYPE(r_a.x); data_b[y6_idx + 1u] = D_TYPE(r_a.y); + data_b[y6_idx + 2u] = D_TYPE(r_a.z); data_b[y6_idx + 3u] = D_TYPE(r_a.w); + data_b[y6_idx + 32u] = D_TYPE(r_b.x); data_b[y6_idx + 33u] = D_TYPE(r_b.y); + data_b[y6_idx + 34u] = D_TYPE(r_b.z); data_b[y6_idx + 35u] = D_TYPE(r_b.w); +#endif + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp index c1e4606cd916..950922647845 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp @@ -166,7 +166,7 @@ void main() { } // ALiBi - if (p.max_bias > 0.0f) { + if (!REL_BIAS_ENABLE && p.max_bias > 0.0f) { [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) { slope[r] = perElemOpComputeSlope(tile_row(r), col_tid, ACC_TYPE(0), iq2); } @@ -189,6 +189,31 @@ void main() { uint32_t mask_opt_idx = ~0; uint32_t mask_opt_bits = 0; + const uint32_t rel_t_len = FA_REL_PARAMS & 0xFFFFu; + const uint32_t rel_ext = FA_REL_PARAMS >> 16; + const uint32_t rel_t_off = FA_REL_OFFSETS & 0xFFFFu; + const uint32_t rel_p_off = FA_REL_OFFSETS >> 16; + const uint32_t rel_cp_off = rel_p_off + iq3 * KV; + const uint32_t rel_qp_off = rel_p_off + p.ne3 * KV + iq3 * p.ne2; + const uint32_t rel_tm_off = rel_p_off + p.ne3 * KV + p.ne3 * p.ne2 + iq3 * CEIL_DIV(KV, 64u) * 2u; + int32_t wg_q_min = 1073741824; + int32_t wg_q_max = -1073741824; + if (REL_BIAS_ENABLE) { + if (p.gqa_ratio > 1u) { + wg_q_min = data_rel_pos[rel_qp_off + gqa_iq1]; + wg_q_max = wg_q_min; + } else { + for (uint32_t rr = 0u; rr < Br; ++rr) { + const uint32_t qr = i * Br + rr; + if (qr < N && qr < p.ne2) { + const int32_t qp = data_rel_pos[rel_qp_off + qr]; + wg_q_min = min(wg_q_min, qp); + wg_q_max = max(wg_q_max, qp); + } + } + } + } + [[dont_unroll]] for (uint32_t j = start_j; j < end_j; ++j) { if (MASK_ENABLE) { @@ -462,6 +487,32 @@ void main() { } } + if (REL_BIAS_ENABLE) { + const uint32_t b64 = (j * Bc) >> 6u; + const int32_t tmin = data_rel_pos[rel_tm_off + b64 * 2u + 0u]; + const int32_t tmax = data_rel_pos[rel_tm_off + b64 * 2u + 1u]; + if (wg_q_max >= tmin && wg_q_min < tmax + int32_t(rel_ext)) { + [[unroll]] for (uint32_t c = 0; c < cols_per_thread; ++c) { + uint32_t kcol; + if (fa_kv_index(j * Bc + c * cols_per_iter + col_tid, kcol)) { + const int32_t k_p = data_rel_pos[rel_cp_off + kcol]; + [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) { + const uint32_t row = tile_row(r); + const uint32_t q_tok = (p.gqa_ratio > 1u) ? gqa_iq1 : (i * Br + row); + const uint32_t q_head = (p.gqa_ratio > 1u) ? (iq2 + row) : iq2; + if (((p.gqa_ratio > 1u) ? (row < N) : (q_tok < N)) && q_tok < p.ne2 && q_head < p.ne1) { + const int32_t q_p = (p.gqa_ratio > 1u) ? wg_q_min : data_rel_pos[rel_qp_off + q_tok]; + const int32_t d = q_p - k_p; + if (d >= 0 && uint32_t(d) < rel_ext && uint32_t(d) < rel_t_len) { + Sf[r][c] += ACC_TYPE(data_rel_table[rel_t_off + ((iq3 * p.ne2 + q_tok) * p.ne1 + q_head) * rel_t_len + uint32_t(d)]); + } + } + } + } + } + } + } + float eMf[rows_per_thread]; [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) { float rowmaxf = NEG_FLT_MAX_OVER_2; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl index 072edfa68cc7..cc4ad81680f9 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl @@ -30,6 +30,9 @@ const bool Q_IN_REGS = (Flags & 32) != 0; // coopmat1: subgroups own Q rows, O in coopmat accumulators. K/V staged in LDS, or loaded from global memory with FLIP_DIRECT. const bool FLIP = (Flags & 64) != 0; const bool FLIP_DIRECT = (Flags & 128) != 0; +const bool USE_LPT_GQA_SWIZZLE = (Flags & 256) != 0; +const bool GQA_VROW_PACK = (Flags & 512) != 0; +const bool REL_BIAS_ENABLE = (Flags & 2048) != 0; // Round up head sizes to a multiple of 16, for coopmat1/coopmat2 paths const uint32_t HSK_pad = (HSK + 15) & ~15; @@ -78,7 +81,15 @@ layout (push_constant) uniform parameter { uint32_t k_num; } p; +// When REL_BIAS_ENABLE is set, ALiBi (max_bias > 0) and LOGIT_SOFTCAP are unused, so max_bias/logit_softcap +// carry packed rel_params & rel_offsets while preserving m0/m1 for ACTIVE_SPAN_BIT / CONST_PREFIX_BIT. +#define FA_REL_PARAMS floatBitsToUint(p.max_bias) +#define FA_REL_OFFSETS floatBitsToUint(p.logit_softcap) + #define SINK_ENABLE_BIT (1<<24) +#define ACTIVE_SPAN_BIT (1u<<25) +#define CONST_PREFIX_BIT (1u<<26) +#define SINK_2D_BIT (1u<<27) #define N_LOG2_MASK 0xFFFF layout (binding = 4) readonly buffer S {float data_s[];}; @@ -90,6 +101,10 @@ layout (binding = 6) readonly buffer MO {uint32_t data_mask_opt[];}; layout (binding = 7) readonly buffer SP {int32_t data_sparse[];}; +layout (binding = 8) readonly buffer RT {float data_rel_table[];}; + +layout (binding = 9) readonly buffer RP {int32_t data_rel_pos[];}; + // Use -FLT_MAX/2 rather than -inf to reduce the possibility of NaNs, e.g. when computing Mold-M. #define NEG_FLT_MAX_OVER_2 uintBitsToFloat(0xFEFFFFFF) // Lowest finite f16, mask value for inactive sparse KV slots @@ -103,7 +118,7 @@ layout (binding = 7) readonly buffer SP {int32_t data_sparse[];}; #include "fa_types.glsl" -#if defined(BFLOAT16) +#if defined(BFLOAT16) || defined(COOPMAT_8X8) #define O_TYPE float #define O_TYPEV4 vec4 #else @@ -147,25 +162,44 @@ ACC_TYPE perElemOpComputeSlope(const in uint32_t r, const in uint32_t c, const i return ACC_TYPE(pow(base, ACC_TYPE(exph))); } -// Load the sink value, indexed by Q's dimension 2. +uint32_t i, N, KV, split_k_index, Tr, start_j, end_j, +#if defined(COOPMAT_8X8) + j_const_min, j_const_end, +#endif + gqa_iq1, iq2, iq3, rk2, rk3, rv2, rv3, ik2, ik3, iv2, iv3, + q_stride, k_stride, v_stride, m_stride, sparse_base; + +// Load the sink value, indexed by Q's dimension 2 (or 2D [n_head, n_tokens] when SINK_2D_BIT is set). ACC_TYPE perElemOpGetSink(const in uint32_t r, const in uint32_t c, const in ACC_TYPE elem, const in uint32_t iq2) { + if ((p.mask_n_head_log2 & SINK_2D_BIT) != 0u) { + uint32_t q_tok, h; + if (GQA_VROW_PACK) { + q_tok = r / p.gqa_ratio; + h = iq2 + (r - q_tok * p.gqa_ratio); + } else if (p.gqa_ratio > 1u) { + q_tok = gqa_iq1; + h = iq2 + r; + } else { + q_tok = i * Br + r; + h = iq2; + } + q_tok = min(q_tok, p.ne2 - 1u); + h = min(h, p.ne1 - 1u); + return ACC_TYPE(data_s[(iq3 * p.ne2 + q_tok) * p.ne1 + h]); + } const uint32_t h = iq2 + (r % p.gqa_ratio); return ACC_TYPE(data_s[h]); } -uint32_t i, N, KV, split_k_index, Tr, start_j, end_j, - gqa_iq1, iq2, iq3, rk2, rk3, rv2, rv3, ik2, ik3, iv2, iv3, - q_stride, k_stride, v_stride, m_stride, sparse_base; - void init_indices() { N = p.N; KV = p.KV; if (p.k_num > 1) { - if (p.gqa_ratio > 1) { + if (p.gqa_ratio > 1 && !GQA_VROW_PACK) { i = 0; // batch and split_k share gl_WorkGroupID.x gqa_iq1 = gl_WorkGroupID.x / p.k_num; @@ -175,7 +209,7 @@ void init_indices() split_k_index = gl_WorkGroupID.x % p.k_num; i = gl_WorkGroupID.x / p.k_num; } - } else if (p.gqa_ratio > 1) { + } else if (p.gqa_ratio > 1 && !GQA_VROW_PACK) { i = 0; gqa_iq1 = gl_WorkGroupID.x; split_k_index = 0; @@ -189,6 +223,26 @@ void init_indices() start_j = split_k_index * p.split_kv / Bc; end_j = CEIL_DIV(min(KV, (split_k_index + 1) * p.split_kv), Bc); +#if defined(COOPMAT_8X8) + j_const_min = 0u; + j_const_end = 0u; + if (!USE_SPARSE && (p.mask_n_head_log2 & ACTIVE_SPAN_BIT) != 0u) { + const uint32_t m0_u = floatBitsToUint(p.m0); + if ((p.mask_n_head_log2 & CONST_PREFIX_BIT) != 0u) { + j_const_min = m0_u & 0xFFFFu; + j_const_end = m0_u >> 16; + start_j = max(start_j, j_const_min); + } else { + start_j = max(start_j, m0_u); + } + end_j = min(end_j, floatBitsToUint(p.m1)); + } +#else + if (!USE_SPARSE && (p.mask_n_head_log2 & ACTIVE_SPAN_BIT) != 0u) { + start_j = max(start_j, floatBitsToUint(p.m0)); + end_j = min(end_j, floatBitsToUint(p.m1)); + } +#endif // When not using grouped query attention, all rows share the same iq2, equal to gl_WorkGroupID.y. // When using grouped query attention, each workgroup does gqa_ratio consecutive values of iq2. @@ -213,7 +267,7 @@ void init_indices() // nb?1 are already divided by the type size and are in units of elements. // When using grouped query attention, Q is indexed by iq2, so the stride // should be nb02 (which is in bytes). - q_stride = p.gqa_ratio > 1 ? (p.nb02 / 4) : p.nb01; + q_stride = (p.gqa_ratio > 1 && !GQA_VROW_PACK) ? (p.nb02 / 4) : p.nb01; k_stride = p.nb11; v_stride = p.nb21; // When using grouped query attention, all rows use the same mask (stride 0). @@ -222,6 +276,22 @@ void init_indices() // and breaking the alignment detection. m_stride = (p.gqa_ratio > 1) ? (p.gqa_ratio >> 16) : KV; + if (USE_LPT_GQA_SWIZZLE) { + if (!USE_SPARSE) { + if (p.k_num == 1u && p.gqa_ratio == 1u && p.nek2 == p.nev2 && rk2 > 1u && p.neq2 == p.nek2 * rk2) { + const uint32_t wg_lin = gl_WorkGroupID.y * Tr + gl_WorkGroupID.x; + const uint32_t h_sub = wg_lin % rk2; + const uint32_t tmp = wg_lin / rk2; + const uint32_t i_rev = tmp % Tr; + const uint32_t ik_lin = tmp / Tr; + i = (Tr - 1u) - i_rev; + iq2 = ik_lin * rk2 + h_sub; + ik2 = ik_lin; + iv2 = ik_lin; + } + } + } + // Sparse: the tile shares one mask row (gqa heads, or Br==1). split_k // partitions the n_kv_max blocks. if (USE_SPARSE) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp index ea945ed075dc..e4ee3b282961 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp @@ -18,14 +18,16 @@ #include "types.glsl" #include "flash_attn_base.glsl" -#if !defined(BFLOAT16) +#if !defined(BFLOAT16) && !defined(COOPMAT_8X8) #include "flash_attn_dequant.glsl" #endif // 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; +#if !defined(COOPMAT_8X8) || defined(BFLOAT16) const uint32_t q_tiles = Br / MatBr; +#endif const uint32_t rows_per_thread = Br / row_split; const uint32_t cols_per_iter = gl_WorkGroupSize.x / row_split; @@ -40,6 +42,762 @@ layout (binding = 2) readonly buffer V {FLOAT_TYPE data_v[];}; layout (binding = 2) readonly buffer VV4 {FLOAT_TYPEV4 data_vv4[];}; layout (binding = 3) readonly buffer M {float16_t data_m[];}; +#if defined(COOPMAT_8X8) && !defined(BFLOAT16) +struct fa_block_q8_0 { + float16_t d; + uint16_t qs[16]; +}; +layout (binding = 1) readonly buffer K_Q8 { fa_block_q8_0 data_k_q8[]; }; +layout (binding = 2) readonly buffer V_Q8 { fa_block_q8_0 data_v_q8[]; }; + +f16vec2 fa_q8_0_decode_f16x2(const uint16_t q16, const float16_t d) { + const uint32_t u = uint32_t(q16); + const uint32_t packed = (((u & 0x00FFu) | ((u & 0xFF00u) << 8u)) ^ 0x00800080u) | 0x64006400u; + precise const f16vec2 qf = unpackFloat2x16(packed) - f16vec2(1152.0); + return qf * d; +} + +// Series 13: 15,776-byte <= 16 KB COOPMAT_8X8 layout for 2-WG/core occupancy on Apple AGX G17P +// Supports both WG=128 (4 subgroups -> 256 threads/core) and WG=256 (8 subgroups -> 512 threads/core, +// halving per-thread OfMat/SfMat GPRs from 80 -> 40 half-GPRs for zero register spills!): +// - 8x8 block-packed transposed Qf_T (RowMajor f16vec2 loads, 0 bank conflicts) +// - RowMajor [Br][Bc+8] Psh_s (f16vec2 loads, 36-dword stride -> 0 bank conflicts) +// - Direct OfMat[num_hsv_tiles][2][2] register accumulation (eliminates pvsh + 9 barriers/iter) +// - Compact 1 KB kvsh[128] used only on partial tail blocks +const uint32_t num_sg = WorkGroupSize / SubGroupSize; +const uint32_t q_tiles = Br / 8u; +const uint32_t k_tiles_per_sg = Bc / (num_sg * 8u); +const uint32_t sm_sg = (num_sg < (Br / 4u)) ? num_sg : (Br / 4u); +const uint32_t sm_rows_per_th = Br / sm_sg; +const uint32_t sm_cols_per_th = Bc / 32u; + +shared float tmpsh[num_sg]; +shared float sh_eMf[Br]; +shared ACC_TYPE slope[Br]; +shared FLOAT_TYPE Qf_T[HSK_pad * Br]; +const uint32_t psh_s_stride = Bc + 8u; +shared FLOAT_TYPE Psh_s[Br * psh_s_stride]; +const uint32_t sfshstride = (Br == 16u && HSK <= 128u) ? (Br / 4u + 1u) : (Br / 4u); +const uint32_t osh_stride = 16u; +const uint32_t sfsh_elems = (Bc * sfshstride >= Br * osh_stride) ? (Bc * sfshstride) : (Br * osh_stride); +shared ACC_TYPEV4 sfsh[sfsh_elems]; +const uint32_t need_kvsh_k = (FaTypeK == GGML_TYPE_Q8_0) ? 0u : (SHMEM_STAGING | (Flags & 16u) | Clamp | (HSK & 15u)); +const uint32_t need_kvsh_v = (FaTypeV == GGML_TYPE_Q8_0) ? 0u : (SHMEM_STAGING | (Flags & 16u) | Clamp | (HSV % (MatBc * num_sg))); +shared FLOAT_TYPEV4 kvsh[((need_kvsh_k | need_kvsh_v) != 0u) ? 128u : 1u]; +shared int32_t sh_q_pos[REL_BIAS_ENABLE ? Br : 1u]; +shared int32_t sh_q_mm[REL_BIAS_ENABLE ? 2u : 1u]; + +void main() { + init_indices(); + + const uint32_t tid = gl_LocalInvocationIndex; + const uint32_t row_tid = tid / 32u; + const uint32_t col_tid = tid & 31u; + +#define tile_row(r) (row_tid * sm_rows_per_th + (r)) + + const uint32_t q_offset = gqa_iq1 * p.nb01 + (iq2 * p.nb02 + iq3 * p.nb03) / 4u; + + [[unroll]] for (uint32_t idx = 0u; idx < Br * HSK_pad / 4u; idx += WorkGroupSize) { + const uint32_t idx0 = idx + tid; + if (idx0 < Br * HSK_pad / 4u) { + const uint32_t d4 = idx0 % (HSK_pad / 4u); + const uint32_t r = idx0 / (HSK_pad / 4u); + vec4 qv = vec4(0.0); + if (i * Br + r < N && d4 * 4u < HSK) { + const uint32_t vrow = i * Br + r; + uint32_t q_elem; + if (GQA_VROW_PACK) { + const uint32_t q_tok = vrow / p.gqa_ratio; + const uint32_t q_head = iq2 + (vrow - q_tok * p.gqa_ratio); + q_elem = q_tok * p.nb01 + (q_head * p.nb02 + iq3 * p.nb03) / 4u + d4 * 4u; + } else { + q_elem = q_offset + vrow * q_stride + d4 * 4u; + } + if (!KV_bounds_check || (q_elem & 3u) == 0u) { + qv = data_qv4[q_elem >> 2u] * p.scale; + } else { + qv = vec4(data_q[q_elem + 0u], data_q[q_elem + 1u], + data_q[q_elem + 2u], data_q[q_elem + 3u]) * p.scale; + } + } + const uint32_t d8 = d4 >> 1u; + const uint32_t k_base = (d4 & 1u) * 4u; + const uint32_t n_blk = r >> 3u; + const uint32_t c_in = r & 7u; + const uint32_t blk = d8 * (Br / 8u) + n_blk; + [[unroll]] for (uint32_t t = 0u; t < 4u; ++t) { + Qf_T[((blk * 8u) + k_base + t) * 8u + c_in] = FLOAT_TYPE(qv[t]); + } + } + } + + const uint32_t mo_stride = CEIL_DIV(KV, 16u * Bc); + uint32_t mo_offset = mo_stride * i; + const uint32_t k_offset = (ik2 * p.nb12 + ik3 * p.nb13) / FaBlockBytesK; + const uint32_t v_offset = (iv2 * p.nb22 + iv3 * p.nb23) / FaBlockBytesV; + uint32_t m_offset = gqa_iq1 * KV; + if (p.nem2 != 1u || p.nem3 != 1u) { + m_offset += ((iq3 % p.nem3) * p.nem2 + (iq2 % p.nem2)) * p.nem1 * KV; + mo_offset += ((iq3 % p.nem3) * p.nem2 + (iq2 % p.nem2)) * CEIL_DIV(p.nem1, Br) * mo_stride; + } + + const bool has_const_prefix = MASK_ENABLE && !USE_SPARSE && !USE_MASK_OPT && + ((p.mask_n_head_log2 & CONST_PREFIX_BIT) != 0u); + if (tid < Br) { + if (has_const_prefix) { + const uint32_t kcol = j_const_min * Bc; + ACC_TYPE cm = ACC_TYPE(0.0); + if (GQA_VROW_PACK) { + const uint32_t vrow = i * Br + tid; + if (vrow < N) { + const uint32_t q_tok = vrow / p.gqa_ratio; + const uint32_t q_head = iq2 + (vrow - q_tok * p.gqa_ratio); + if (q_tok < p.nem1) { + const uint32_t m_b3 = (iq3 % p.nem3) * p.nem2; + cm = ACC_TYPE(data_m[((m_b3 + (q_head % p.nem2)) * p.nem1 + q_tok) * KV + kcol]); + } + } + } else { + const bool nem1_bc = !(p.gqa_ratio > 1u) && (p.nem1 % Br) != 0u; + if (!nem1_bc || i * Br + tid < p.nem1) { + cm = ACC_TYPE(data_m[m_offset + (i * Br + tid) * m_stride + kcol]); + } + } + slope[tid] = cm; + } else { + const uint32_t slope_r = GQA_VROW_PACK ? (i * Br + tid) : tid; + slope[tid] = (!REL_BIAS_ENABLE && p.max_bias > 0.0f) ? perElemOpComputeSlope(slope_r, col_tid, ACC_TYPE(0), iq2) : ACC_TYPE(1.0); + } + } + const uint32_t rel_t_len = FA_REL_PARAMS & 0xFFFFu; + const uint32_t rel_ext = FA_REL_PARAMS >> 16; + const uint32_t rel_t_off = FA_REL_OFFSETS & 0xFFFFu; + const uint32_t rel_p_off = FA_REL_OFFSETS >> 16; + const uint32_t rel_cp_off = rel_p_off + iq3 * KV; + const uint32_t rel_qp_off = rel_p_off + p.ne3 * KV + iq3 * p.ne2; + const uint32_t rel_tm_off = rel_p_off + p.ne3 * KV + p.ne3 * p.ne2 + iq3 * CEIL_DIV(KV, 64u) * 2u; + if (REL_BIAS_ENABLE && gl_SubgroupID == 0u) { + int32_t lmin = 1073741824; + int32_t lmax = -1073741824; + for (uint32_t r = gl_SubgroupInvocationID; r < Br; r += SubGroupSize) { + const uint32_t vrow = i * Br + r; + int32_t qp = -1073741824; + if (vrow < N) { + const uint32_t q_tok = GQA_VROW_PACK ? (vrow / p.gqa_ratio) : ((p.gqa_ratio > 1u) ? gqa_iq1 : vrow); + if (q_tok < p.ne2) { + qp = data_rel_pos[rel_qp_off + q_tok]; + lmin = min(lmin, qp); + lmax = max(lmax, qp); + } + } + sh_q_pos[r] = qp; + } + lmin = subgroupMin(lmin); + lmax = subgroupMax(lmax); + if (gl_SubgroupInvocationID == 0u) { + sh_q_mm[0] = lmin; + sh_q_mm[1] = lmax; + } + } + barrier(); + + const uint32_t num_hsv_tiles = (HSV + MatBc * num_sg - 1u) / (MatBc * num_sg); + coopmat OfMat[num_hsv_tiles][q_tiles][2]; + [[unroll]] for (uint32_t ht = 0u; ht < num_hsv_tiles; ++ht) { + [[unroll]] for (uint32_t m = 0u; m < q_tiles; ++m) { + [[unroll]] for (uint32_t n = 0u; n < 2u; ++n) { + OfMat[ht][m][n] = coopmat(0.0); + } + } + } + + float Lf[sm_rows_per_th], Mf[sm_rows_per_th]; + [[unroll]] for (uint32_t r = 0u; r < sm_rows_per_th; ++r) { + Lf[r] = 0.0f; + Mf[r] = NEG_FLT_MAX_OVER_2; + } + + uint32_t mask_opt = 0u; + uint32_t mask_opt_idx = ~0u; + + [[dont_unroll]] + for (uint32_t j = start_j; j < end_j; ++j) { + const bool is_const_mask_blk = has_const_prefix && (j >= j_const_min) && (j < j_const_end); + uint32_t mask_opt_bits = 0u; + if (MASK_ENABLE && !is_const_mask_blk) { + if (USE_MASK_OPT) { + if (mask_opt_idx != j / 16u) { + mask_opt_idx = j / 16u; + mask_opt = data_mask_opt[mo_offset + mask_opt_idx]; + } + const uint32_t rem_shift = (j & 15u) * 2u; + const uint32_t chunk_end = min(end_j, (j & ~15u) + 16u); + const uint32_t n_rem = chunk_end - j; + const uint32_t rem_mask = (n_rem >= 16u) ? 0xFFFFFFFFu : ((1u << (2u * n_rem)) - 1u); + if (((mask_opt >> rem_shift) & rem_mask) == (0x55555555u & rem_mask)) { + j = chunk_end - 1u; + continue; + } + mask_opt_bits = (mask_opt >> rem_shift) & 0x3u; + if (mask_opt_bits == MASK_OPT_ALL_NEG_INF) { + continue; + } + } else { + const bool nem1_bounds_check = !(p.gqa_ratio > 1u) && (p.nem1 % Br) != 0u; + float max_mask = NEG_FLT_MAX_OVER_2; + [[unroll]] for (uint32_t idx = 0u; idx < Bc * Br / 4u; idx += WorkGroupSize) { + const uint32_t idx0 = idx + tid; + if (idx0 < Bc * Br / 4u) { + const uint32_t c = idx0 / (Br / 4u); + const uint32_t r = idx0 % (Br / 4u); + uint32_t kcol; + if (fa_kv_index(j * Bc + c, kcol)) { + if (USE_SPARSE) { + max_mask = max(max_mask, float(data_m[m_offset + kcol])); + } else if (GQA_VROW_PACK) { + const uint32_t m_b3 = (iq3 % p.nem3) * p.nem2; + [[unroll]] for (uint32_t rr = 0u; rr < 4u; ++rr) { + const uint32_t vrow = i * Br + r * 4u + rr; + if (vrow < N) { + const uint32_t q_tok = vrow / p.gqa_ratio; + const uint32_t q_head = iq2 + (vrow - q_tok * p.gqa_ratio); + if (q_tok < p.nem1) { + const uint32_t m_idx = ((m_b3 + (q_head % p.nem2)) * p.nem1 + q_tok) * KV + kcol; + max_mask = max(max_mask, float(data_m[m_idx])); + } + } + } + } else { + [[unroll]] for (uint32_t rr = 0u; rr < 4u; ++rr) { + if (!nem1_bounds_check || i * Br + r * 4u + rr < p.nem1) { + max_mask = max(max_mask, float(data_m[m_offset + (i * Br + r * 4u + rr) * m_stride + kcol])); + } + } + } + } + } + } + const bool all_less = subgroupAll(max_mask <= NEG_FLT_MAX_OVER_2); + barrier(); + if (gl_SubgroupInvocationID == 0u) { + tmpsh[gl_SubgroupID] = all_less ? NEG_FLT_MAX_OVER_2 : 0.0f; + } + barrier(); + [[unroll]] for (uint32_t s = 0u; s < num_sg; ++s) { + max_mask = max(max_mask, tmpsh[s]); + } + if (max_mask <= NEG_FLT_MAX_OVER_2) { + continue; + } + } + } + + coopmat SfMat[k_tiles_per_sg][q_tiles]; + [[unroll]] for (uint32_t m = 0u; m < k_tiles_per_sg; ++m) { + [[unroll]] for (uint32_t n = 0u; n < q_tiles; ++n) { + SfMat[m][n] = coopmat(0.0); + } + } + coopmat KMatK[k_tiles_per_sg]; + coopmat KMatP[q_tiles]; + coopmat QMat[q_tiles]; + coopmat VMat[2]; + + if (FaTypeK == GGML_TYPE_Q8_0) { + const uint32_t k_lane = gl_SubgroupInvocationID; + const uint32_t k_cm_r = ((k_lane >> 1u) & 3u) | ((k_lane >> 2u) & 4u); + const uint32_t k_pair = (k_lane & 1u) | ((k_lane >> 2u) & 2u); + uint32_t k_row_blk[k_tiles_per_sg]; + bool k_row_ok[k_tiles_per_sg]; + [[unroll]] for (uint32_t m = 0u; m < k_tiles_per_sg; ++m) { + const uint32_t kv_local_row = (gl_SubgroupID * k_tiles_per_sg + m) * 8u + k_cm_r; + uint32_t kcol; + k_row_ok[m] = fa_kv_index(j * Bc + kv_local_row, kcol); + k_row_blk[m] = k_offset + kcol * k_stride; + } + [[unroll]] for (uint32_t d_blk = 0u; d_blk < HSK / 32u; ++d_blk) { + float16_t kd_arr[k_tiles_per_sg]; + [[unroll]] for (uint32_t m = 0u; m < k_tiles_per_sg; ++m) { + kd_arr[m] = k_row_ok[m] ? data_k_q8[k_row_blk[m] + d_blk].d : float16_t(0.0); + } + [[unroll]] for (uint32_t sub = 0u; sub < 4u; ++sub) { + [[unroll]] for (uint32_t m = 0u; m < k_tiles_per_sg; ++m) { + f16vec2 kv2 = f16vec2(0.0); + if (k_row_ok[m]) { + kv2 = fa_q8_0_decode_f16x2(data_k_q8[k_row_blk[m] + d_blk].qs[sub * 4u + k_pair], kd_arr[m]); + } + KMatK[m][0] = kv2.x; + KMatK[m][1] = kv2.y; + } + [[unroll]] for (uint32_t n = 0u; n < q_tiles; ++n) { + const uint32_t q_coord = ((d_blk * 4u + sub) * q_tiles + n) * 64u; + coopMatLoad(QMat[n], Qf_T, q_coord, 8u, gl_CooperativeMatrixLayoutRowMajor); + } + [[unroll]] for (uint32_t m = 0u; m < k_tiles_per_sg; ++m) { + [[unroll]] for (uint32_t n = 0u; n < q_tiles; ++n) { + SfMat[m][n] = coopMatMulAdd(KMatK[m], QMat[n], SfMat[m][n]); + } + } + } + } + } else { + const bool stage_k_block = (SHMEM_STAGING != 0u) || USE_SPARSE || + (KV_bounds_check && (j * Bc + Bc > KV || ((k_offset | k_stride) & 3u) != 0u)); + + [[unroll]] for (uint32_t d = 0u; d < HSK_pad / 16u; ++d) { + [[unroll]] for (uint32_t dk = 0u; dk < 2u; ++dk) { + const bool stage_k_now = stage_k_block || (d * 16u + dk * 8u + 8u > HSK); + if (stage_k_now) { + barrier(); + if (tid < 128u) { + const uint32_t row = tid >> 1u; + const uint32_t col_vec = tid & 1u; + FLOAT_TYPEV4 K_Tf = FLOAT_TYPEV4(0.0); + uint32_t kcol; + if (fa_kv_index(j * Bc + row, kcol) && (d * 16u + dk * 8u + col_vec * 4u < HSK)) { + const uint32_t elem_idx = k_offset + kcol * k_stride + d * 16u + dk * 8u + col_vec * 4u; + if ((elem_idx & 3u) == 0u) { + K_Tf = data_kv4[elem_idx >> 2u]; + } else { + K_Tf = FLOAT_TYPEV4(data_k[elem_idx + 0u], data_k[elem_idx + 1u], + data_k[elem_idx + 2u], data_k[elem_idx + 3u]); + } + } + kvsh[tid] = K_Tf; + } + barrier(); + } + [[unroll]] for (uint32_t m = 0u; m < k_tiles_per_sg; ++m) { + const uint32_t kv_local_row = (gl_SubgroupID * k_tiles_per_sg + m) * 8u; + if (!stage_k_now) { + const uint32_t coord = k_offset / 4u + (j * Bc + kv_local_row) * (k_stride / 4u) + d * 4u + dk * 2u; + coopMatLoad(KMatK[m], data_kv4, coord, k_stride / 4u, gl_CooperativeMatrixLayoutRowMajor); + } else { + const uint32_t coord = kv_local_row * 2u; + coopMatLoad(KMatK[m], kvsh, coord, 2u, gl_CooperativeMatrixLayoutRowMajor); + } + } + [[unroll]] for (uint32_t n = 0u; n < q_tiles; ++n) { + const uint32_t q_coord = ((d * 2u + dk) * q_tiles + n) * 64u; + coopMatLoad(QMat[n], Qf_T, q_coord, 8u, gl_CooperativeMatrixLayoutRowMajor); + } + [[unroll]] for (uint32_t m = 0u; m < k_tiles_per_sg; ++m) { + [[unroll]] for (uint32_t n = 0u; n < q_tiles; ++n) { + SfMat[m][n] = coopMatMulAdd(KMatK[m], QMat[n], SfMat[m][n]); + } + } + } + } + } + + [[unroll]] for (uint32_t m = 0u; m < k_tiles_per_sg; ++m) { + const uint32_t kv_local_row = (gl_SubgroupID * k_tiles_per_sg + m) * 8u; + [[unroll]] for (uint32_t n = 0u; n < q_tiles; ++n) { + const uint32_t coord = kv_local_row * sfshstride + n * 2u; + coopMatStore(SfMat[m][n], sfsh, coord, sfshstride, gl_CooperativeMatrixLayoutRowMajor); + } + } + barrier(); // Barrier #1: sfsh ready; prior j's Psh_s/sh_eMf reads finished + + if (LOGIT_SOFTCAP) { + [[unroll]] for (uint32_t idx = 0u; idx < Bc * Br / 4u; idx += WorkGroupSize) { + const uint32_t idx0 = idx + tid; + if (idx0 < Bc * Br / 4u) { + const uint32_t c = idx0 / (Br / 4u); + const uint32_t r = idx0 % (Br / 4u); + sfsh[c * sfshstride + r] = ACC_TYPEV4(p.logit_softcap * tanh(sfsh[c * sfshstride + r])); + } + } + barrier(); + } + + bool tile_has_rel = false; + if (REL_BIAS_ENABLE) { + const uint32_t b64 = (j * Bc) >> 6u; + const int32_t tmin = data_rel_pos[rel_tm_off + b64 * 2u + 0u]; + const int32_t tmax = data_rel_pos[rel_tm_off + b64 * 2u + 1u]; + tile_has_rel = (sh_q_mm[1] >= tmin) && (sh_q_mm[0] < tmax + int32_t(rel_ext)); + } + const bool need_mask_add = MASK_ENABLE && !is_const_mask_blk && mask_opt_bits != MASK_OPT_ALL_ZERO; + if (need_mask_add || tile_has_rel) { + const bool nem1_bounds_check = !(p.gqa_ratio > 1u) && (p.nem1 % Br) != 0u; + [[unroll]] for (uint32_t idx = 0u; idx < Bc * Br / 4u; idx += WorkGroupSize) { + const uint32_t idx0 = idx + tid; + if (idx0 < Bc * Br / 4u) { + const uint32_t c = idx0 / (Br / 4u); + const uint32_t r = idx0 % (Br / 4u); + uint32_t kcol; + const bool kv_active = fa_kv_index(j * Bc + c, kcol); + if (!KV_bounds_check || j * Bc + c < KV) { + ACC_TYPEV4 add_v = ACC_TYPEV4(0.0); + if (need_mask_add) { + ACC_TYPEV4 masks = ACC_TYPEV4(0.0); + if (kv_active) { + if (USE_SPARSE) { + masks = ACC_TYPEV4(float(data_m[m_offset + kcol])); + } else if (GQA_VROW_PACK) { + const uint32_t m_b3 = (iq3 % p.nem3) * p.nem2; + [[unroll]] for (uint32_t rr = 0u; rr < 4u; ++rr) { + const uint32_t vrow = i * Br + r * 4u + rr; + if (vrow < N) { + const uint32_t q_tok = vrow / p.gqa_ratio; + const uint32_t q_head = iq2 + (vrow - q_tok * p.gqa_ratio); + if (q_tok < p.nem1) { + const uint32_t m_idx = ((m_b3 + (q_head % p.nem2)) * p.nem1 + q_tok) * KV + kcol; + masks[rr] = ACC_TYPE(data_m[m_idx]); + } + } + } + } else { + [[unroll]] for (uint32_t rr = 0u; rr < 4u; ++rr) { + if (!nem1_bounds_check || i * Br + r * 4u + rr < p.nem1) { + masks[rr] = ACC_TYPE(data_m[m_offset + (i * Br + r * 4u + rr) * m_stride + kcol]); + } + } + } + } else if (USE_SPARSE) { + masks = ACC_TYPEV4(NEG_FLT_MAX_OVER_2); + } + const ACC_TYPEV4 slopes = has_const_prefix + ? ACC_TYPEV4(1.0) + : ACC_TYPEV4(slope[r * 4u], slope[r * 4u + 1u], slope[r * 4u + 2u], slope[r * 4u + 3u]); + add_v = slopes * masks; + } + if (tile_has_rel && kv_active) { + const int32_t k_p = data_rel_pos[rel_cp_off + kcol]; + [[unroll]] for (uint32_t rr = 0u; rr < 4u; ++rr) { + const uint32_t r_loc = r * 4u + rr; + const uint32_t vrow = i * Br + r_loc; + if (vrow < N) { + uint32_t q_tok, q_head; + if (GQA_VROW_PACK) { + q_tok = vrow / p.gqa_ratio; + q_head = iq2 + (vrow - q_tok * p.gqa_ratio); + } else if (p.gqa_ratio > 1u) { + q_tok = gqa_iq1; + q_head = iq2 + r_loc; + } else { + q_tok = vrow; + q_head = iq2; + } + if (q_tok < p.ne2 && q_head < p.ne1) { + const int32_t d = sh_q_pos[r_loc] - k_p; + if (d >= 0 && uint32_t(d) < rel_ext && uint32_t(d) < rel_t_len) { + add_v[rr] += ACC_TYPE(data_rel_table[rel_t_off + ((iq3 * p.ne2 + q_tok) * p.ne1 + q_head) * rel_t_len + uint32_t(d)]); + } + } + } + } + } + sfsh[c * sfshstride + r] += add_v; + } + } + } + barrier(); + } + + // Single-pass sfsh read -> online softmax -> Psh_s & sh_eMf write (first sm_sg subgroups) + if (gl_SubgroupID < sm_sg) { + [[unroll]] for (uint32_t r4 = 0u; r4 < sm_rows_per_th; r4 += 4u) { + const uint32_t base_row0 = tile_row(r4); + const uint32_t r_vec = base_row0 / 4u; + const vec4 cm_vec = is_const_mask_blk + ? vec4(slope[base_row0 + 0u], slope[base_row0 + 1u], slope[base_row0 + 2u], slope[base_row0 + 3u]) + : vec4(0.0); + vec4 sf_reg[sm_cols_per_th]; + vec4 rowmax4 = vec4(NEG_FLT_MAX_OVER_2); + [[unroll]] for (uint32_t c = 0u; c < sm_cols_per_th; ++c) { + const uint32_t col = c * 32u + col_tid; + if (!KV_bounds_check || j * Bc + col < KV) { + sf_reg[c] = vec4(sfsh[col * sfshstride + r_vec]); + if (is_const_mask_blk) { + sf_reg[c] += cm_vec; + } + rowmax4 = max(rowmax4, sf_reg[c]); + } else { + sf_reg[c] = vec4(0.0); + } + } + rowmax4 += vec4(FATTN_KQ_MAX_OFFSET); + [[unroll]] for (uint32_t v = 0u; v < 4u; ++v) { + const uint32_t r = r4 + v; + const float Moldf = Mf[r]; + const float rmax = subgroupMax(rowmax4[v]); + Mf[r] = max(rmax, Moldf); + const float eM = exp(Moldf - Mf[r]); + Lf[r] = eM * Lf[r]; + if (col_tid == 0u) { + sh_eMf[tile_row(r)] = eM; + } + } + const vec4 mfvec = vec4(Mf[r4], Mf[r4 + 1u], Mf[r4 + 2u], Mf[r4 + 3u]); + const uint32_t base_row = tile_row(r4); + [[unroll]] for (uint32_t c = 0u; c < sm_cols_per_th; ++c) { + const uint32_t col = c * 32u + col_tid; + FLOAT_TYPEV4 Pf = FLOAT_TYPEV4(0.0); + if (!KV_bounds_check || j * Bc + col < KV) { + Pf = FLOAT_TYPEV4(exp(sf_reg[c] - mfvec)); + [[unroll]] for (uint32_t v = 0u; v < 4u; ++v) { + Lf[r4 + v] += float(Pf[v]); + } + } + [[unroll]] for (uint32_t v = 0u; v < 4u; ++v) { + Psh_s[(base_row + v) * psh_s_stride + col] = Pf[v]; + } + } + } + } + barrier(); // Barrier #2: Psh_s & sh_eMf ready; sfsh reads finished for next j + + // Rescale OfMat directly in registers (both elements in lane belong to row cm_r) + const uint32_t lane = gl_SubgroupInvocationID; + const uint32_t cm_r = ((lane >> 1u) & 3u) | ((lane >> 2u) & 4u); + [[unroll]] for (uint32_t m = 0u; m < q_tiles; ++m) { + const float eM = sh_eMf[m * 8u + cm_r]; + [[unroll]] for (uint32_t ht = 0u; ht < num_hsv_tiles; ++ht) { + [[unroll]] for (uint32_t n = 0u; n < 2u; ++n) { + OfMat[ht][m][n][0] *= eM; + OfMat[ht][m][n][1] *= eM; + } + } + } + + if (FaTypeV == GGML_TYPE_Q8_0) { + const uint32_t cm_pair = (lane & 1u) | ((lane >> 2u) & 2u); + [[unroll]] for (uint32_t bc_chunk = 0u; bc_chunk < Bc / MatBc; ++bc_chunk) { + [[unroll]] for (uint32_t dk = 0u; dk < 2u; ++dk) { + [[unroll]] for (uint32_t m = 0u; m < q_tiles; ++m) { + coopMatLoad(KMatP[m], Psh_s, (m * 8u) * psh_s_stride + bc_chunk * MatBc + dk * 8u, psh_s_stride, gl_CooperativeMatrixLayoutRowMajor); + } + uint32_t v_row; + const bool v_ok = fa_kv_index(j * Bc + bc_chunk * MatBc + dk * 8u + cm_r, v_row); + const uint32_t v_row_blk = v_offset + v_row * v_stride; + [[unroll]] for (uint32_t hsv_tile = 0u; hsv_tile < num_hsv_tiles; ++hsv_tile) { + const uint32_t hsv_offset = (hsv_tile * num_sg + gl_SubgroupID) * 16u; + if (hsv_offset < HSV) { + f16vec2 vv0 = f16vec2(0.0); + f16vec2 vv1 = f16vec2(0.0); + if (v_ok) { + const uint32_t ib = v_row_blk + (hsv_offset >> 5u); + const float16_t vd = data_v_q8[ib].d; + const uint32_t qbase = ((hsv_offset >> 4u) & 1u) * 8u + cm_pair; + vv0 = fa_q8_0_decode_f16x2(data_v_q8[ib].qs[qbase + 0u], vd); + vv1 = fa_q8_0_decode_f16x2(data_v_q8[ib].qs[qbase + 4u], vd); + } + VMat[0][0] = vv0.x; + VMat[0][1] = vv0.y; + VMat[1][0] = vv1.x; + VMat[1][1] = vv1.y; + [[unroll]] for (uint32_t m = 0u; m < q_tiles; ++m) { + [[unroll]] for (uint32_t n = 0u; n < 2u; ++n) { + OfMat[hsv_tile][m][n] = coopMatMulAdd(KMatP[m], VMat[n], OfMat[hsv_tile][m][n]); + } + } + } + } + } + } + } else { + const bool stage_v_block = (SHMEM_STAGING != 0u) || USE_SPARSE || + (KV_bounds_check && (j * Bc + Bc > KV || ((v_offset | v_stride) & 3u) != 0u)); + const uint32_t n_sub_passes = (num_sg + 3u) / 4u; + + [[unroll]] for (uint32_t bc_chunk = 0u; bc_chunk < Bc / MatBc; ++bc_chunk) { + [[unroll]] for (uint32_t dk = 0u; dk < 2u; ++dk) { + [[unroll]] for (uint32_t m = 0u; m < q_tiles; ++m) { + coopMatLoad(KMatP[m], Psh_s, (m * 8u) * psh_s_stride + bc_chunk * MatBc + dk * 8u, psh_s_stride, gl_CooperativeMatrixLayoutRowMajor); + } + [[unroll]] for (uint32_t hsv_tile = 0u; hsv_tile < num_hsv_tiles; ++hsv_tile) { + const uint32_t hsv_offset = (hsv_tile * num_sg + gl_SubgroupID) * 16u; + const bool hsv_tile_partial = (hsv_tile * MatBc * num_sg + MatBc * num_sg) > HSV; + const bool stage_v_now = stage_v_block || hsv_tile_partial; + if (!stage_v_now) { + if (hsv_offset < HSV_pad) { + const uint32_t v_tile_row = j * Bc + bc_chunk * MatBc + dk * 8u; + [[unroll]] for (uint32_t n = 0u; n < 2u; ++n) { + const uint32_t v_tile_offset = v_offset / 4u + v_tile_row * (v_stride / 4u) + hsv_offset / 4u + n * 2u; + coopMatLoad(QMat[n], data_vv4, v_tile_offset, v_stride / 4u, gl_CooperativeMatrixLayoutRowMajor); + } + [[unroll]] for (uint32_t m = 0u; m < q_tiles; ++m) { + [[unroll]] for (uint32_t n = 0u; n < 2u; ++n) { + OfMat[hsv_tile][m][n] = coopMatMulAdd(KMatP[m], QMat[n], OfMat[hsv_tile][m][n]); + } + } + } + } else { + [[unroll]] for (uint32_t sp = 0u; sp < n_sub_passes; ++sp) { + barrier(); + if (tid < 128u) { + const uint32_t r8 = tid >> 4u; + const uint32_t c16 = tid & 15u; + const uint32_t v_col = (hsv_tile * num_sg + sp * 4u) * 16u + c16 * 4u; + FLOAT_TYPEV4 V_Tf = FLOAT_TYPEV4(0.0); + uint32_t v_row; + if (v_col < HSV && fa_kv_index(j * Bc + bc_chunk * MatBc + dk * 8u + r8, v_row)) { + const uint32_t elem_idx = v_offset + v_row * v_stride + v_col; + if ((elem_idx & 3u) == 0u) { + V_Tf = data_vv4[elem_idx >> 2u]; + } else { + V_Tf = FLOAT_TYPEV4(data_v[elem_idx + 0u], data_v[elem_idx + 1u], + data_v[elem_idx + 2u], data_v[elem_idx + 3u]); + } + } + kvsh[tid] = V_Tf; + } + barrier(); + if ((gl_SubgroupID / 4u) == sp && hsv_offset < HSV_pad) { + [[unroll]] for (uint32_t n = 0u; n < 2u; ++n) { + const uint32_t v_tile_offset = (gl_SubgroupID & 3u) * 4u + n * 2u; + coopMatLoad(QMat[n], kvsh, v_tile_offset, 16u, gl_CooperativeMatrixLayoutRowMajor); + } + [[unroll]] for (uint32_t m = 0u; m < q_tiles; ++m) { + [[unroll]] for (uint32_t n = 0u; n < 2u; ++n) { + OfMat[hsv_tile][m][n] = coopMatMulAdd(KMatP[m], QMat[n], OfMat[hsv_tile][m][n]); + } + } + } + } + } + } + } + } + } + } + + barrier(); + if (gl_SubgroupID < sm_sg) { + [[unroll]] for (uint32_t r = 0u; r < sm_rows_per_th; ++r) { + Lf[r] = subgroupAdd(Lf[r]); + } + + if (p.k_num > 1u) { + if (col_tid == 0u) { + [[unroll]] for (uint32_t r = 0u; r < sm_rows_per_th; ++r) { + sh_eMf[tile_row(r)] = 1.0f; + } + } + if (GQA_VROW_PACK) { + [[unroll]] for (uint32_t r = 0u; r < sm_rows_per_th; ++r) { + const uint32_t vrow = i * Br + tile_row(r); + if (vrow < N && col_tid == 0u) { + const uint32_t q_tok = vrow / p.gqa_ratio; + const uint32_t q_head = iq2 + (vrow - q_tok * p.gqa_ratio); + const uint32_t lm_offset = HSV * p.ne1 * p.k_num * p.ne2 * p.ne3 + p.ne1 * 2u * (split_k_index + p.k_num * (q_tok + p.ne2 * iq3)); + data_o[lm_offset + q_head] = D_TYPE(Lf[r]); + data_o[lm_offset + p.ne1 + q_head] = D_TYPE(Mf[r]); + } + } + } else if (p.gqa_ratio > 1u) { + const uint32_t lm_offset = HSV * p.ne1 * p.k_num * p.ne2 * p.ne3 + p.ne1 * 2u * (split_k_index + p.k_num * (gqa_iq1 + p.ne2 * iq3)); + [[unroll]] for (uint32_t r = 0u; r < sm_rows_per_th; ++r) { + if (tile_row(r) < N) { + perElemOpStoreCol0(tile_row(r), 0u, ACC_TYPE(Lf[r]), lm_offset, iq2, N); + perElemOpStoreCol0(tile_row(r), 0u, ACC_TYPE(Mf[r]), lm_offset + p.ne1, iq2, N); + } + } + } else { + [[unroll]] for (uint32_t r = 0u; r < sm_rows_per_th; ++r) { + const uint32_t global_row = i * Br + tile_row(r); + if (global_row < N && col_tid == 0u) { + const uint32_t lm_offset = HSV * p.ne1 * p.k_num * p.ne2 * p.ne3 + p.ne1 * 2u * (split_k_index + p.k_num * (global_row + p.ne2 * iq3)); + data_o[lm_offset + iq2] = D_TYPE(Lf[r]); + data_o[lm_offset + p.ne1 + iq2] = D_TYPE(Mf[r]); + } + } + } + } else { + [[unroll]] for (uint32_t r = 0u; r < sm_rows_per_th; ++r) { + float ms = 1.0f; + if ((p.mask_n_head_log2 & SINK_ENABLE_BIT) != 0u) { + const uint32_t sink_r = GQA_VROW_PACK ? (i * Br + tile_row(r)) : tile_row(r); + const float sink = perElemOpGetSink(sink_r, 0u, ACC_TYPE(0), iq2); + float vs = 1.0f; + if (sink > Mf[r]) { + ms = exp(Mf[r] - sink); + } else { + vs = exp(sink - Mf[r]); + } + Lf[r] = Lf[r] * ms + vs; + } + if (col_tid == 0u) { + sh_eMf[tile_row(r)] = (Lf[r] == 0.0f) ? 0.0f : (ms / Lf[r]); + } + } + } + } + + const uint32_t o_base_dense = (gqa_iq1 * p.ne1 * HSV + iq3 * p.ne2 * p.ne1 * HSV) / 4u; + const uint32_t o_base_sk_gqa = HSV * p.ne1 * (split_k_index + p.k_num * (gqa_iq1 + p.ne2 * iq3)) / 4u; + const uint32_t n_sub_passes = (num_sg + 3u) / 4u; + + [[unroll]] for (uint32_t hsv_tile = 0u; hsv_tile < num_hsv_tiles; ++hsv_tile) { + const uint32_t hsv_offset = (hsv_tile * num_sg + gl_SubgroupID) * 16u; + [[unroll]] for (uint32_t sp = 0u; sp < n_sub_passes; ++sp) { + barrier(); + if ((gl_SubgroupID / 4u) == sp && hsv_offset < HSV_pad) { + const uint32_t o_offset_sh = (gl_SubgroupID & 3u) * 4u; + [[unroll]] for (uint32_t m = 0u; m < q_tiles; ++m) { + [[unroll]] for (uint32_t n = 0u; n < 2u; ++n) { + coopMatStore(OfMat[hsv_tile][m][n], sfsh, o_offset_sh + m * 8u * osh_stride + n * 2u, osh_stride, gl_CooperativeMatrixLayoutRowMajor); + } + } + } + barrier(); + if (gl_SubgroupID < sm_sg && col_tid < 16u) { + const uint32_t d = (hsv_tile * num_sg + sp * 4u) * 4u + col_tid; + if (d < HSV / 4u) { + [[unroll]] for (uint32_t r = 0u; r < sm_rows_per_th; ++r) { + const uint32_t row = tile_row(r); + O_TYPEV4 out_v = sfsh[row * osh_stride + col_tid] * O_TYPE(sh_eMf[row]); +#if defined(FLOAT_TYPE_MAX) + if (p.k_num <= 1u) { + out_v = clamp(out_v, -O_TYPE(FLOAT_TYPE_MAX), O_TYPE(FLOAT_TYPE_MAX)); + } +#endif + if (GQA_VROW_PACK) { + const uint32_t vrow = i * Br + row; + if (vrow < N) { + const uint32_t q_tok = vrow / p.gqa_ratio; + const uint32_t q_head = iq2 + (vrow - q_tok * p.gqa_ratio); + if (p.k_num > 1u) { + const uint32_t o_off = HSV * p.ne1 * (split_k_index + p.k_num * (q_tok + p.ne2 * iq3)) / 4u; + data_ov4[o_off + q_head * (HSV / 4u) + d] = D_TYPEV4(out_v); + } else { + data_ov4[o_base_dense + (q_head * HSV + q_tok * p.ne1 * HSV) / 4u + d] = D_TYPEV4(out_v); + } + } + } else if (p.k_num > 1u) { + if (p.gqa_ratio > 1u) { + if (row < N) { + gqaStore(row, d, out_v, o_base_sk_gqa, iq2, N); + } + } else { + const uint32_t global_row = i * Br + row; + if (global_row < N) { + const uint32_t o_off = HSV * p.ne1 * (split_k_index + p.k_num * (global_row + p.ne2 * iq3)) / 4u; + data_ov4[o_off + iq2 * (HSV / 4u) + d] = D_TYPEV4(out_v); + } + } + } else if (p.gqa_ratio > 1u) { + if (row < N) { + gqaStore(row, d, out_v, o_base_dense, iq2, N); + } + } else { + const uint32_t global_row = i * Br + row; + if (global_row < N) { + data_ov4[o_base_dense + (iq2 * HSV + global_row * p.ne1 * HSV) / 4u + d] = D_TYPEV4(out_v); + } + } + } + } + } + } + } +} + +#else // !(defined(COOPMAT_8X8) && !defined(BFLOAT16)) + shared float tmpsh[row_split]; const uint32_t qstride = HSK_pad / 4 + 2; @@ -146,8 +904,8 @@ void main() { barrier(); } } else { - // Zero-initialize Qf when HSK is not a multiple of 16 (HSK_pad > HSK). - if ((HSK % 16) != 0) { + // Zero-initialize Qf when HSK is not a multiple of 16 (HSK_pad > HSK) or N is partial. + if ((HSK % 16) != 0 || i * Br + Br > N) { [[unroll]] for (uint ii = 0; ii < Br * qstride; ii += gl_WorkGroupSize.x) { if (ii + tid < Br * qstride) { Qf[ii + tid] = FLOAT_TYPEV4(0); @@ -328,21 +1086,32 @@ 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 +#ifdef COOPMAT_8X8 + coopmat SfMat[2][2]; + [[unroll]] for (uint32_t m = 0; m < 2; ++m) { + [[unroll]] for (uint32_t n = 0; n < 2; ++n) { + SfMat[m][n] = coopmat(0); + } + } + coopmat KMat[2]; + coopmat QMat[2]; +#else // No coopmat arrays: AMD's Windows compiler crashes on loop-indexed ones. q_tiles <= 2. coopmat SfMat0 = coopmat(0); coopmat SfMat1 = coopmat(0); coopmat KMat; coopmat QMat; +#endif [[unroll]] for (uint32_t d = 0; d < d_tiles; ++d) { // If SHMEM_STAGING is set, a Bc * HSK_pad size tile of K is loaded to shmem // If not, K is loaded directly from global memory if aligned, otherwise // staged through a Bc * MatBr size staging buffer. // If K is a quant type, then it is always staged for dequantization. + const bool stage_k = USE_DECODE_K || KV_bounds_check || USE_SPARSE || d * 16 + 16 > HSK; if (SHMEM_STAGING == 0) { // For quants we always need to dequant into kvsh; for f16/bf16 we can load // directly from global memory when alignment / bounds allow it. - const bool stage_k = USE_DECODE_K || KV_bounds_check || USE_SPARSE || d * 16 + 16 > HSK; if (stage_k) { barrier(); [[unroll]] for (uint32_t idx = 0; idx < Bc * MatBr / 4; idx += gl_WorkGroupSize.x) { @@ -371,7 +1140,33 @@ void main() { } barrier(); } - +#ifdef COOPMAT_8X8 + } + [[unroll]] for (uint32_t dk = 0; dk < 2; ++dk) { + [[unroll]] for (uint32_t m = 0; m < 2; ++m) { + if (SHMEM_STAGING == 0) { + if (stage_k) { + uint coord = (gl_SubgroupID * MatBc + m * 8) * kvsh_stride + dk * 2; + coopMatLoad(KMat[m], kvsh, coord, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor); + } else { + const uint coord = k_offset / 4 + (j * Bc + gl_SubgroupID * MatBc + m * 8) * (k_stride / 4) + d * 4 + dk * 2; + coopMatLoad(KMat[m], data_kv4, coord, k_stride / 4, gl_CooperativeMatrixLayoutRowMajor); + } + } else { + uint coord = (gl_SubgroupID * MatBc + m * 8) * kvsh_stride + d * 4 + dk * 2; + coopMatLoad(KMat[m], kvsh, coord, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor); + } + } + [[unroll]] for (uint32_t n = 0; n < 2; ++n) { + coopMatLoad(QMat[n], Qf, d * 4 + n * 8 * qstride + dk * 2, qstride, gl_CooperativeMatrixLayoutColumnMajor); + } + [[unroll]] for (uint32_t m = 0; m < 2; ++m) { + [[unroll]] for (uint32_t n = 0; n < 2; ++n) { + SfMat[m][n] = coopMatMulAdd(KMat[m], QMat[n], SfMat[m][n]); + } + } + } +#else if (stage_k) { uint coord = (gl_SubgroupID * MatBc) * kvsh_stride; coopMatLoad(KMat, kvsh, coord, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor); @@ -397,12 +1192,22 @@ void main() { SfMat1 = coopMatMulAdd(KMat, QMat, SfMat1); } } +#endif } +#ifdef COOPMAT_8X8 + [[unroll]] for (uint32_t m = 0; m < 2; ++m) { + [[unroll]] for (uint32_t n = 0; n < 2; ++n) { + uint coord = (gl_SubgroupID * MatBc + m * 8) * sfshstride + n * 2; + coopMatStore(SfMat[m][n], sfsh, coord, sfshstride, gl_CooperativeMatrixLayoutRowMajor); + } + } +#else 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); } +#endif barrier(); if (LOGIT_SOFTCAP) { @@ -519,8 +1324,17 @@ 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; +#ifdef COOPMAT_8X8 + coopmat PVMat[2][2]; + [[unroll]] for (uint32_t m = 0; m < 2; ++m) { + [[unroll]] for (uint32_t n = 0; n < 2; ++n) { + PVMat[m][n] = coopmat(0); + } + } +#else coopmat PVMat0 = coopmat(0); coopmat PVMat1 = coopmat(0); +#endif // Preload V tiles for [Bc, 16 * num subgroups] const uint v_rows = Bc; @@ -531,10 +1345,11 @@ void main() { // If not, V is loaded directly from global memory if aligned, otherwise // staged through a Bc * MatBr size staging buffer. // If V is a quant type, then it is always staged for dequantization. + const bool hsv_partial = (hsv_tile * MatBc * row_split + MatBc * row_split) > HSV; if (SHMEM_STAGING == 0) { // For quants we always preload via kvsh. For f16/bf16 we only preload when // alignment / bounds force it (otherwise we coopMatLoad direct from data_vv4). - const bool stage_v = USE_DECODE_V || KV_bounds_check || USE_SPARSE; + const bool stage_v = USE_DECODE_V || KV_bounds_check || USE_SPARSE || hsv_partial; if (stage_v) { [[unroll]] for (uint32_t i = 0; i < v_loads_per_thread; ++i) { const uint idx = i * gl_WorkGroupSize.x + tid; @@ -549,7 +1364,7 @@ void main() { const uint ib = coord / BLOCK_SIZE_V; const uint iqs = coord % BLOCK_SIZE_V; - if (USE_SPARSE ? (kv_active && v_col < HSV) : (!KV_bounds_check || (v_row < KV && v_col < HSV))) { + if (USE_SPARSE ? (kv_active && v_col < HSV) : (v_col < HSV && (!KV_bounds_check || v_row < KV))) { #if !defined(BFLOAT16) if (USE_DECODE_V) { kvsh[row * vsh_stride + col] = dequantize4(ib, iqs, v_offset, BINDING_IDX_V); @@ -569,9 +1384,43 @@ void main() { const uint o_offset = gl_SubgroupID * MatBr / 4; if (hsv_offset < HSV_pad) { +#ifdef COOPMAT_8X8 + [[unroll]] for (uint32_t bc_chunk = 0; bc_chunk < Bc / MatBc; ++bc_chunk) { + [[unroll]] for (uint32_t dk = 0; dk < 2; ++dk) { + [[unroll]] for (uint32_t m = 0; m < 2; ++m) { + coopMatLoad(KMat[m], Psh, (bc_chunk * MatBc + dk * 8) * psh_stride + m * 2, psh_stride, gl_CooperativeMatrixLayoutColumnMajor); + } + [[unroll]] for (uint32_t n = 0; n < 2; ++n) { + if (SHMEM_STAGING == 0) { + if (!USE_DECODE_V && !KV_bounds_check && !USE_SPARSE && !hsv_partial) { + const uint v_tile_row = j * Bc + bc_chunk * MatBc + dk * 8; + const uint v_tile_offset = v_offset / 4 + v_tile_row * (v_stride / 4) + hsv_offset / 4 + n * 2; + coopMatLoad(QMat[n], data_vv4, v_tile_offset, v_stride / 4, gl_CooperativeMatrixLayoutRowMajor); + } else { + const uint v_tile_offset = (bc_chunk * MatBr + dk * 8) * v_cols + gl_SubgroupID * (MatBc / 4) + n * 2; + coopMatLoad(QMat[n], kvsh, v_tile_offset, vsh_stride, gl_CooperativeMatrixLayoutRowMajor); + } + } else { + const uint v_tile_offset = (bc_chunk * MatBc + dk * 8) * kvsh_stride + (hsv_tile * row_split + gl_SubgroupID) * (MatBc / 4) + n * 2; + coopMatLoad(QMat[n], kvsh, v_tile_offset, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor); + } + } + [[unroll]] for (uint32_t m = 0; m < 2; ++m) { + [[unroll]] for (uint32_t n = 0; n < 2; ++n) { + PVMat[m][n] = coopMatMulAdd(KMat[m], QMat[n], PVMat[m][n]); + } + } + } + } + [[unroll]] for (uint32_t m = 0; m < 2; ++m) { + [[unroll]] for (uint32_t n = 0; n < 2; ++n) { + coopMatStore(PVMat[m][n], pvsh, o_offset + m * 8 * osh_stride + n * 2, osh_stride, gl_CooperativeMatrixLayoutRowMajor); + } + } +#else [[unroll]] for (uint32_t bc_chunk = 0; bc_chunk < Bc / MatBc; ++bc_chunk) { if (SHMEM_STAGING == 0) { - if (!USE_DECODE_V && !KV_bounds_check && !USE_SPARSE) { + if (!USE_DECODE_V && !KV_bounds_check && !USE_SPARSE && !hsv_partial) { // F16/BF16 values can be loaded directly from global memory const uint v_tile_row = j * Bc + bc_chunk * MatBc; const uint v_tile_offset = v_offset / 4 + v_tile_row * v_stride / 4 + hsv_offset / 4; @@ -599,6 +1448,7 @@ void main() { } else { coopMatStore(PVMat0, pvsh, o_offset, osh_stride, gl_CooperativeMatrixLayoutRowMajor); } +#endif } barrier(); @@ -715,7 +1565,7 @@ void main() { [[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) { Of[r][d_local] *= O_TYPE(Lfrcp[r]); #if defined(FLOAT_TYPE_MAX) - Of[r][d_local] = clamp(Of[r][d_local], -FLOAT_TYPE_MAX, FLOAT_TYPE_MAX); + Of[r][d_local] = clamp(Of[r][d_local], -O_TYPE(FLOAT_TYPE_MAX), O_TYPE(FLOAT_TYPE_MAX)); #endif } } @@ -746,3 +1596,4 @@ void main() { } } } +#endif // defined(COOPMAT_8X8) && !defined(BFLOAT16) diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_split_k_reduce.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_split_k_reduce.comp index 68917fc0bb02..81173aced22f 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_split_k_reduce.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_split_k_reduce.comp @@ -78,7 +78,7 @@ void main() { float sink; if (p.sinks != 0) { - sink = data_s[n]; + sink = (p.sinks > 1u) ? data_s[(i3 * p.ne2 + i2) * p.ne1 + n] : data_s[n]; float ms = 1.0f; float vs = 1.0f; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_vec_mhm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_vec_mhm.comp new file mode 100644 index 000000000000..79024a90b43e --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_vec_mhm.comp @@ -0,0 +1,443 @@ +#version 450 + +// S19.D W4.2: 0-ULP 88-GPR N=1 GQA=3 multi-head-mask FlashAttention kernel for Apple AGX (Borealis) +// Specializes HSK = HSV = 128, Br = 3, Bc = 64, WorkGroupSize = 128, SubGroupSize = 32, D_split = 8, row_split = 1: +// - Qf[3 * 33] staged in 1,584 B bank-conflict-free shared memory (-48 FP32 GPRs -> 88 GPRs total, 0 spills!) +// - Per-subhead mask indexing (q_head = iq2 + r) with 0 masksh shared memory and 0 inner-loop barriers +// - 2-column K/V register-paced [[dont_unroll]] inner loops keeping live GPRs <= 88 (0 dynamic array indexing) +// - Batched 2-barrier epilogue preserving exact D_split=8 & s=0..3 FP32/FP16 reduction order (100% 0-ULP) + +#extension GL_EXT_control_flow_attributes : enable +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require + +#ifdef FLOAT16 +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_subgroup_extended_types_float16 : require +#endif + +#extension GL_KHR_shader_subgroup_shuffle : enable +#extension GL_KHR_shader_subgroup_vote : enable + +#include "types.glsl" +#include "dot_product_funcs.glsl" +#include "flash_attn_base.glsl" + +struct fa_block_q8_0 { + float16_t d; + uint16_t qs[16]; +}; + +layout (binding = 0) readonly buffer Q { float data_q[]; }; +layout (binding = 0) readonly buffer QV4 { vec4 data_qv4[]; }; +layout (binding = 1) readonly buffer KV4 { f16vec4 data_kv4[]; }; +layout (binding = 1) readonly buffer K_Q8 { fa_block_q8_0 data_k_q8[]; }; +layout (binding = 2) readonly buffer VV4 { f16vec4 data_vv4[]; }; +layout (binding = 2) readonly buffer V_Q8 { fa_block_q8_0 data_v_q8[]; }; +layout (binding = 3) readonly buffer M { float16_t data_m[]; }; + +f16vec4 fa_q8_0_decode_f16x4(const uint16_t q0, const uint16_t q1, const float16_t d) { + const uint32_t u0 = uint32_t(q0); + const uint32_t u1 = uint32_t(q1); + const uint32_t p0 = (((u0 & 0x00FFu) | ((u0 & 0xFF00u) << 8u)) ^ 0x00800080u) | 0x64006400u; + const uint32_t p1 = (((u1 & 0x00FFu) | ((u1 & 0xFF00u) << 8u)) ^ 0x00800080u) | 0x64006400u; + precise const f16vec2 f0 = unpackFloat2x16(p0) - f16vec2(1152.0); + precise const f16vec2 f1 = unpackFloat2x16(p1) - f16vec2(1152.0); + return f16vec4(f0 * d, f1 * d); +} + +shared FLOAT_TYPEV4 Qf[3u * 33u]; +shared float tmpsh_m[3u * 32u]; +shared float tmpsh_l[3u * 32u]; +shared FLOAT_TYPEV4 tmpshv4[3u * 4u * 32u]; + +void main() { + init_indices(); + + const uint32_t tid = gl_LocalInvocationIndex; + const uint32_t d_tid = tid & 7u; + const uint32_t col_tid = tid >> 3u; + const uint32_t lane = gl_SubgroupInvocationID; + const uint32_t sg_id = gl_SubgroupID; + + const uint32_t q_base_elem = gqa_iq1 * p.nb01 + (iq2 * p.nb02 + iq3 * p.nb03) / 4u; + if (tid < 96u) { + const uint32_t qr = tid >> 5u; + const uint32_t qc = tid & 31u; + const uint32_t elem = q_base_elem + qr * q_stride + qc * 4u; + vec4 qv; + if ((elem & 3u) == 0u) { + qv = data_qv4[elem >> 2u]; + } else { + qv = vec4(data_q[elem + 0u], data_q[elem + 1u], data_q[elem + 2u], data_q[elem + 3u]); + } + Qf[qr * 33u + qc] = FLOAT_TYPEV4(qv * p.scale); + } + + FLOAT_TYPEV4 Of[3][4]; + float Lf[3], Mf[3]; + uint32_t m_row_off[3]; + const uint32_t m_b3 = (iq3 % p.nem3) * p.nem2; + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + Of[r][d] = FLOAT_TYPEV4(0.0); + } + Lf[r] = 0.0f; + Mf[r] = NEG_FLT_MAX_OVER_2; + const uint32_t q_head = iq2 + r; + m_row_off[r] = ((m_b3 + (q_head % p.nem2)) * p.nem1 + gqa_iq1) * KV; + } + barrier(); + + const uint32_t k_offset4 = ((ik2 * p.nb12 + ik3 * p.nb13) / 2u) >> 2u; + const uint32_t v_offset4 = ((iv2 * p.nb22 + iv3 * p.nb23) / 2u) >> 2u; + const uint32_t k_stride4 = k_stride >> 2u; + const uint32_t v_stride4 = v_stride >> 2u; + const uint32_t k_offset_q8 = (ik2 * p.nb12 + ik3 * p.nb13) / FaBlockBytesK; + const uint32_t v_offset_q8 = (iv2 * p.nb22 + iv3 * p.nb23) / FaBlockBytesV; + + const int32_t q_pos_val = REL_BIAS_ENABLE ? data_rel_pos[p.ne3 * KV + iq3 * p.ne2 + gqa_iq1 + (FA_REL_OFFSETS >> 16)] : 0; + const uint32_t rel_t_len = FA_REL_PARAMS & 0xFFFFu; + const uint32_t rel_ext = FA_REL_PARAMS >> 16; + const uint32_t rel_t_off = FA_REL_OFFSETS & 0xFFFFu; + const uint32_t rel_p_off = FA_REL_OFFSETS >> 16; + const uint32_t rel_cp_off = rel_p_off + iq3 * KV; + const uint32_t rel_tm_off = rel_p_off + p.ne3 * KV + p.ne3 * p.ne2 + iq3 * CEIL_DIV(KV, 64u) * 2u; + const uint32_t rel_tb_row = rel_t_off + ((iq3 * p.ne2 + gqa_iq1) * p.ne1 + iq2) * rel_t_len; + + [[dont_unroll]] + for (uint32_t j = start_j; j < end_j; ++j) { + const uint32_t j_col = j * 64u; + if (MASK_ENABLE) { + float sub_max = NEG_FLT_MAX_OVER_2; + const uint32_t kc0 = j_col + lane; + const uint32_t kc1 = kc0 + 32u; + if (p.nem2 == 1u) { + if (!KV_bounds_check || kc0 < KV) { + sub_max = max(sub_max, float(data_m[m_row_off[0] + kc0])); + } + if (!KV_bounds_check || kc1 < KV) { + sub_max = max(sub_max, float(data_m[m_row_off[0] + kc1])); + } + } else { + if (!KV_bounds_check || kc0 < KV) { + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + sub_max = max(sub_max, float(data_m[m_row_off[r] + kc0])); + } + } + if (!KV_bounds_check || kc1 < KV) { + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + sub_max = max(sub_max, float(data_m[m_row_off[r] + kc1])); + } + } + } + if (subgroupAll(sub_max <= NEG_FLT_MAX_OVER_2)) { + continue; + } + } + + ACC_TYPE Sf[3][4]; + [[dont_unroll]] + for (uint32_t c2 = 0u; c2 < 2u; ++c2) { + const uint32_t kcol0 = j_col + (c2 * 2u + 0u) * 16u + col_tid; + const uint32_t kcol1 = kcol0 + 16u; + ACC_TYPE s0_0 = ACC_TYPE(0.0), s1_0 = ACC_TYPE(0.0), s2_0 = ACC_TYPE(0.0); + ACC_TYPE s0_1 = ACC_TYPE(0.0), s1_1 = ACC_TYPE(0.0), s2_1 = ACC_TYPE(0.0); + if (!KV_bounds_check || kcol0 < KV) { + if (FaTypeK == GGML_TYPE_Q8_0) { + const uint32_t kb0_q8 = k_offset_q8 + kcol0 * k_stride; + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + const uint32_t qc = d * 8u + d_tid; + const uint32_t ib = kb0_q8 + d; + const FLOAT_TYPEV4 K_Tf = FLOAT_TYPEV4(fa_q8_0_decode_f16x4( + data_k_q8[ib].qs[2u * d_tid], data_k_q8[ib].qs[2u * d_tid + 1u], data_k_q8[ib].d)); + s0_0 = dot_product(Qf[0u * 33u + qc], K_Tf, s0_0); + s1_0 = dot_product(Qf[1u * 33u + qc], K_Tf, s1_0); + s2_0 = dot_product(Qf[2u * 33u + qc], K_Tf, s2_0); + } + } else { + const uint32_t kb0 = k_offset4 + kcol0 * k_stride4 + d_tid; + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + const uint32_t qc = d * 8u + d_tid; + const FLOAT_TYPEV4 K_Tf = FLOAT_TYPEV4(data_kv4[kb0 + d * 8u]); + s0_0 = dot_product(Qf[0u * 33u + qc], K_Tf, s0_0); + s1_0 = dot_product(Qf[1u * 33u + qc], K_Tf, s1_0); + s2_0 = dot_product(Qf[2u * 33u + qc], K_Tf, s2_0); + } + } + } + if (!KV_bounds_check || kcol1 < KV) { + if (FaTypeK == GGML_TYPE_Q8_0) { + const uint32_t kb1_q8 = k_offset_q8 + kcol1 * k_stride; + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + const uint32_t qc = d * 8u + d_tid; + const uint32_t ib = kb1_q8 + d; + const FLOAT_TYPEV4 K_Tf = FLOAT_TYPEV4(fa_q8_0_decode_f16x4( + data_k_q8[ib].qs[2u * d_tid], data_k_q8[ib].qs[2u * d_tid + 1u], data_k_q8[ib].d)); + s0_1 = dot_product(Qf[0u * 33u + qc], K_Tf, s0_1); + s1_1 = dot_product(Qf[1u * 33u + qc], K_Tf, s1_1); + s2_1 = dot_product(Qf[2u * 33u + qc], K_Tf, s2_1); + } + } else { + const uint32_t kb1 = k_offset4 + kcol1 * k_stride4 + d_tid; + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + const uint32_t qc = d * 8u + d_tid; + const FLOAT_TYPEV4 K_Tf = FLOAT_TYPEV4(data_kv4[kb1 + d * 8u]); + s0_1 = dot_product(Qf[0u * 33u + qc], K_Tf, s0_1); + s1_1 = dot_product(Qf[1u * 33u + qc], K_Tf, s1_1); + s2_1 = dot_product(Qf[2u * 33u + qc], K_Tf, s2_1); + } + } + } + if (c2 == 0u) { + Sf[0][0] = s0_0; Sf[1][0] = s1_0; Sf[2][0] = s2_0; + Sf[0][1] = s0_1; Sf[1][1] = s1_1; Sf[2][1] = s2_1; + } else { + Sf[0][2] = s0_0; Sf[1][2] = s1_0; Sf[2][2] = s2_0; + Sf[0][3] = s0_1; Sf[1][3] = s1_1; Sf[2][3] = s2_1; + } + } + + [[unroll]] for (uint32_t c = 0u; c < 4u; ++c) { + [[unroll]] for (uint s = 4u; s > 0u; s >>= 1u) { + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + Sf[r][c] += subgroupShuffleXor(Sf[r][c], s); + } + } + } + + if (MASK_ENABLE) { + [[unroll]] for (uint32_t c = 0u; c < 4u; ++c) { + const uint32_t kcol = j_col + c * 16u + col_tid; + const bool ok = !KV_bounds_check || kcol < KV; + if (p.nem2 == 1u) { + const ACC_TYPE mvf = ok ? ACC_TYPE(data_m[m_row_off[0] + kcol]) : ACC_TYPE(0.0); + Sf[0][c] += mvf; + Sf[1][c] += mvf; + Sf[2][c] += mvf; + } else { + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + const FLOAT_TYPE mvf = ok ? FLOAT_TYPE(data_m[m_row_off[r] + kcol]) : FLOAT_TYPE(0.0); + Sf[r][c] += ACC_TYPE(mvf); + } + } + } + } + + if (REL_BIAS_ENABLE) { + const uint32_t b64 = j_col >> 6u; + const int32_t tmin = data_rel_pos[rel_tm_off + b64 * 2u + 0u]; + const int32_t tmax = data_rel_pos[rel_tm_off + b64 * 2u + 1u]; + if (q_pos_val >= tmin && q_pos_val < tmax + int32_t(rel_ext)) { + [[unroll]] for (uint32_t c = 0u; c < 4u; ++c) { + const uint32_t kcol = j_col + c * 16u + col_tid; + if (!KV_bounds_check || kcol < KV) { + const int32_t d = q_pos_val - data_rel_pos[rel_cp_off + kcol]; + if (d >= 0 && uint32_t(d) < rel_ext && uint32_t(d) < rel_t_len) { + const uint32_t ud = uint32_t(d); + Sf[0][c] += ACC_TYPE(data_rel_table[rel_tb_row + 0u * rel_t_len + ud]); + Sf[1][c] += ACC_TYPE(data_rel_table[rel_tb_row + 1u * rel_t_len + ud]); + Sf[2][c] += ACC_TYPE(data_rel_table[rel_tb_row + 2u * rel_t_len + ud]); + } + } + } + } + } + + float eMf[3]; + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + float rowmaxf = NEG_FLT_MAX_OVER_2; + [[unroll]] for (uint32_t c = 0u; c < 4u; ++c) { + if (KV_bounds_check && j_col + c * 16u + col_tid >= KV) { + continue; + } + rowmaxf = max(rowmaxf, float(Sf[r][c])); + } + rowmaxf += FATTN_KQ_MAX_OFFSET; + const float Moldf = Mf[r]; + Mf[r] = max(rowmaxf, Moldf); + eMf[r] = exp(Moldf - Mf[r]); + Lf[r] = eMf[r] * Lf[r]; + } + + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + Of[r][d] = FLOAT_TYPE(eMf[r]) * Of[r][d]; + } + } + + [[dont_unroll]] + for (uint32_t c2 = 0u; c2 < 2u; ++c2) { + const uint32_t vcol0 = j_col + (c2 * 2u + 0u) * 16u + col_tid; + const uint32_t vcol1 = vcol0 + 16u; + const ACC_TYPE s0_0 = (c2 == 0u) ? Sf[0][0] : Sf[0][2]; + const ACC_TYPE s1_0 = (c2 == 0u) ? Sf[1][0] : Sf[1][2]; + const ACC_TYPE s2_0 = (c2 == 0u) ? Sf[2][0] : Sf[2][2]; + const ACC_TYPE s0_1 = (c2 == 0u) ? Sf[0][1] : Sf[0][3]; + const ACC_TYPE s1_1 = (c2 == 0u) ? Sf[1][1] : Sf[1][3]; + const ACC_TYPE s2_1 = (c2 == 0u) ? Sf[2][1] : Sf[2][3]; + + if (!KV_bounds_check || vcol0 < KV) { + const FLOAT_TYPE p0 = FLOAT_TYPE(exp(float(s0_0) - Mf[0])); + const FLOAT_TYPE p1 = FLOAT_TYPE(exp(float(s1_0) - Mf[1])); + const FLOAT_TYPE p2 = FLOAT_TYPE(exp(float(s2_0) - Mf[2])); + Lf[0] += float(p0); + Lf[1] += float(p1); + Lf[2] += float(p2); + if (FaTypeV == GGML_TYPE_Q8_0) { + const uint32_t vb0_q8 = v_offset_q8 + vcol0 * v_stride; + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + const uint32_t ib = vb0_q8 + d; + const FLOAT_TYPEV4 Vf = FLOAT_TYPEV4(fa_q8_0_decode_f16x4( + data_v_q8[ib].qs[2u * d_tid], data_v_q8[ib].qs[2u * d_tid + 1u], data_v_q8[ib].d)); + Of[0][d] += FLOAT_TYPEV4(p0 * Vf); + Of[1][d] += FLOAT_TYPEV4(p1 * Vf); + Of[2][d] += FLOAT_TYPEV4(p2 * Vf); + } + } else { + const uint32_t vb0 = v_offset4 + vcol0 * v_stride4 + d_tid; + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + const FLOAT_TYPEV4 Vf = FLOAT_TYPEV4(data_vv4[vb0 + d * 8u]); + Of[0][d] += FLOAT_TYPEV4(p0 * Vf); + Of[1][d] += FLOAT_TYPEV4(p1 * Vf); + Of[2][d] += FLOAT_TYPEV4(p2 * Vf); + } + } + } + if (!KV_bounds_check || vcol1 < KV) { + const FLOAT_TYPE p0 = FLOAT_TYPE(exp(float(s0_1) - Mf[0])); + const FLOAT_TYPE p1 = FLOAT_TYPE(exp(float(s1_1) - Mf[1])); + const FLOAT_TYPE p2 = FLOAT_TYPE(exp(float(s2_1) - Mf[2])); + Lf[0] += float(p0); + Lf[1] += float(p1); + Lf[2] += float(p2); + if (FaTypeV == GGML_TYPE_Q8_0) { + const uint32_t vb1_q8 = v_offset_q8 + vcol1 * v_stride; + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + const uint32_t ib = vb1_q8 + d; + const FLOAT_TYPEV4 Vf = FLOAT_TYPEV4(fa_q8_0_decode_f16x4( + data_v_q8[ib].qs[2u * d_tid], data_v_q8[ib].qs[2u * d_tid + 1u], data_v_q8[ib].d)); + Of[0][d] += FLOAT_TYPEV4(p0 * Vf); + Of[1][d] += FLOAT_TYPEV4(p1 * Vf); + Of[2][d] += FLOAT_TYPEV4(p2 * Vf); + } + } else { + const uint32_t vb1 = v_offset4 + vcol1 * v_stride4 + d_tid; + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + const FLOAT_TYPEV4 Vf = FLOAT_TYPEV4(data_vv4[vb1 + d * 8u]); + Of[0][d] += FLOAT_TYPEV4(p0 * Vf); + Of[1][d] += FLOAT_TYPEV4(p1 * Vf); + Of[2][d] += FLOAT_TYPEV4(p2 * Vf); + } + } + } + } + } + + // Batched 2-barrier workgroup reduction across all 3 sub-heads (exact D_split=8 & s=0..3 order) + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + float rowmaxf = Mf[r]; + rowmaxf = max(rowmaxf, subgroupShuffleXor(rowmaxf, 8u)); + rowmaxf = max(rowmaxf, subgroupShuffleXor(rowmaxf, 16u)); + if (lane == d_tid) { + tmpsh_m[(r * 4u + sg_id) * 8u + d_tid] = rowmaxf; + } + } + barrier(); + + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + float rowmaxf = tmpsh_m[r * 32u + d_tid]; + [[unroll]] for (uint32_t s = 1u; s < 4u; ++s) { + rowmaxf = max(rowmaxf, tmpsh_m[(r * 4u + s) * 8u + d_tid]); + } + const float Moldf = Mf[r]; + Mf[r] = max(rowmaxf, Moldf); + const float eMf = exp(Moldf - Mf[r]); + + Lf[r] = eMf * Lf[r]; + Lf[r] += subgroupShuffleXor(Lf[r], 8u); + Lf[r] += subgroupShuffleXor(Lf[r], 16u); + if (lane == d_tid) { + tmpsh_l[(r * 4u + sg_id) * 8u + d_tid] = Lf[r]; + } + + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + Of[r][d] = FLOAT_TYPE(eMf) * Of[r][d]; + Of[r][d] += subgroupShuffleXor(Of[r][d], 8u); + Of[r][d] += subgroupShuffleXor(Of[r][d], 16u); + if (lane == d_tid) { + tmpshv4[((r * 4u + d) * 4u + sg_id) * 8u + d_tid] = Of[r][d]; + } + } + } + barrier(); + + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + Lf[r] = tmpsh_l[r * 32u + d_tid]; + [[unroll]] for (uint32_t s = 1u; s < 4u; ++s) { + Lf[r] += tmpsh_l[(r * 4u + s) * 8u + d_tid]; + } + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + Of[r][d] = tmpshv4[(r * 4u + d) * 32u + d_tid]; + [[unroll]] for (uint32_t s = 1u; s < 4u; ++s) { + Of[r][d] += tmpshv4[((r * 4u + d) * 4u + s) * 8u + d_tid]; + } + } + } + + if (p.k_num > 1u) { + if (col_tid == 0u) { + const uint32_t o_offset = HSV * p.ne1 * (split_k_index + p.k_num * (gqa_iq1 + p.ne2 * iq3)) / 4u; + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + if (r < N) { + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + gqaStore(r, d * 8u + d_tid, Of[r][d], o_offset, iq2, N); + } + } + } + if (d_tid == 0u) { + const uint32_t lm_offset = HSV * p.ne1 * p.k_num * p.ne2 * p.ne3 + p.ne1 * 2u * (split_k_index + p.k_num * (gqa_iq1 + p.ne2 * iq3)); + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + if (r < N) { + data_o[lm_offset + iq2 + r] = D_TYPE(Lf[r]); + data_o[lm_offset + p.ne1 + iq2 + r] = D_TYPE(Mf[r]); + } + } + } + } + return; + } + + if ((p.mask_n_head_log2 & SINK_ENABLE_BIT) != 0u) { + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + const float sink = perElemOpGetSink(r, 0u, ACC_TYPE(0), iq2); + float ms = 1.0f; + float vs = 1.0f; + if (sink > Mf[r]) { + ms = exp(Mf[r] - sink); + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + Of[r][d] *= FLOAT_TYPE(ms); + } + } else { + vs = exp(sink - Mf[r]); + } + Lf[r] = Lf[r] * ms + vs; + } + } + + if (col_tid == 0u) { + const uint32_t o_offset = (gqa_iq1 * p.ne1 * HSV + iq3 * p.ne2 * p.ne1 * HSV) / 4u; + [[unroll]] for (uint32_t r = 0u; r < 3u; ++r) { + if (r < N) { + const float lrcp = (Lf[r] == 0.0f) ? 0.0f : (1.0f / Lf[r]); + [[unroll]] for (uint32_t d = 0u; d < 4u; ++d) { + FLOAT_TYPEV4 out_v = Of[r][d] * FLOAT_TYPE(lrcp); +#if defined(FLOAT_TYPE_MAX) + out_v = clamp(out_v, -FLOAT_TYPE_MAX, FLOAT_TYPE_MAX); +#endif + gqaStore(r, d * 8u + d_tid, out_v, o_offset, iq2, N); + } + } + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp index 75c32a067595..d8a13ed37c4c 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp @@ -17,8 +17,12 @@ layout(constant_id = 2) const uint SUBGROUP_SIZE = 32; layout(constant_id = 3) const uint LANES_PER_COLUMN = 32; layout(constant_id = 4) const bool PACKED_ROWS = false; layout(constant_id = 5) const uint REPLAY = 0; +layout(constant_id = 6) const uint COLS_PER_SUB = 1; +layout(constant_id = 7) const uint SUBGROUPS_PER_WG = 1; +layout(constant_id = 8) const uint CONTIG_VEC4 = 0; -const uint COLS_PER_WG = SUBGROUP_SIZE / LANES_PER_COLUMN; +const uint COLS_PER_SUB_STEP = SUBGROUP_SIZE / LANES_PER_COLUMN; +const uint COLS_PER_WG = COLS_PER_SUB_STEP * SUBGROUPS_PER_WG; const uint ROWS_PER_LANE = S_V / LANES_PER_COLUMN; uint row_index(uint r, uint lane) { @@ -29,7 +33,7 @@ uint row_index(uint r, uint lane) { return r * LANES_PER_COLUMN + lane; } -layout(local_size_x_id = 2, local_size_y = 1, local_size_z = 1) in; +layout(local_size_x_id = 2, local_size_y_id = 7, local_size_z = 1) in; layout(push_constant) uniform Parameters { uint H; @@ -47,21 +51,31 @@ layout(push_constant) uniform Parameters { uint spk1, spk2, spk3; uint spv1, spv2, spv3; uint spg1, spg2, spg3; + uint sout_nb2; }; layout(binding = 0) readonly buffer QBuf { FLOAT_TYPE data_q[]; }; +layout(binding = 0) readonly buffer QBufV4 { vec4 data_q_v4[]; }; layout(binding = 1) readonly buffer KBuf { FLOAT_TYPE data_k[]; }; +layout(binding = 1) readonly buffer KBufV4 { vec4 data_k_v4[]; }; layout(binding = 2) readonly buffer VBuf { FLOAT_TYPE data_v[]; }; -layout(binding = 3) readonly buffer GBuf { FLOAT_TYPE data_g[]; }; -layout(binding = 4) readonly buffer BetaBuf { FLOAT_TYPE data_beta[]; }; -layout(binding = 5) readonly buffer StateBuf { FLOAT_TYPE data_state[]; }; -layout(binding = 6) buffer DstBuf { FLOAT_TYPE data_dst[]; }; - +layout(binding = 2) readonly buffer VBufV4 { vec4 data_v_v4[]; }; +layout(binding = 3) readonly restrict buffer GBuf { FLOAT_TYPE data_g[]; }; +layout(binding = 4) readonly restrict buffer BetaBuf { FLOAT_TYPE data_beta[]; }; +layout(binding = 5) readonly buffer StateBuf { FLOAT_TYPE data_state[]; }; +layout(binding = 5) readonly buffer StateBufV4 { vec4 data_state_v4[]; }; +layout(binding = 6) writeonly buffer DstBuf { FLOAT_TYPE data_dst[]; }; +layout(binding = 6) writeonly buffer DstBufV4 { vec4 data_dst_v4[]; }; // replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext) layout(binding = 7) readonly buffer PKBuf { FLOAT_TYPE data_pk[]; }; layout(binding = 8) readonly buffer PVBuf { FLOAT_TYPE data_pv[]; }; layout(binding = 9) readonly buffer PGBBuf { FLOAT_TYPE data_pgb[]; }; layout(binding = 10) readonly buffer NRepBuf { int data_n_rep[]; }; +#if STATE_OUT +// gen: the final state goes straight to its destination (the recurrent cache row), not into dst +layout(binding = 11) buffer StateOutBuf { FLOAT_TYPE data_state_out[]; }; +layout(binding = 11) buffer StateOutBufV4 { vec4 data_state_out_v4[]; }; +#endif #if !USE_SUBGROUP_ADD && !USE_SUBGROUP_CLUSTERED shared FLOAT_TYPE temp[SUBGROUP_SIZE]; @@ -117,7 +131,7 @@ void main() { const uint head_id = gl_WorkGroupID.x; const uint seq_id = gl_WorkGroupID.y; const uint lane = gl_SubgroupInvocationID % LANES_PER_COLUMN; - const uint col = gl_WorkGroupID.z * COLS_PER_WG + (gl_SubgroupInvocationID / LANES_PER_COLUMN); + const uint col_base = (gl_WorkGroupID.z * COLS_PER_SUB) * COLS_PER_WG + gl_LocalInvocationID.y * COLS_PER_SUB_STEP + (gl_SubgroupInvocationID / LANES_PER_COLUMN); const uint iq1 = head_id % neq1; const uint iq3 = seq_id / rq3; @@ -128,10 +142,196 @@ void main() { // output state layout per slot: same per-(seq,head) offset as the single-slot case. const uint state_out_base = (seq_id * H + head_id) * state_size; const uint state_size_per_snap = state_size * H * n_seqs; + const bool zero_state = (K & 0x80000000u) != 0u; + const uint eff_K = K & 0x7FFFFFFFu; + +#if USE_SUBGROUP_ADD + if (REPLAY == 0u && CONTIG_VEC4 != 0u && KDA == 0u && ROWS_PER_LANE == 4u && LANES_PER_COLUMN == 32u && (COLS_PER_SUB == 4u || COLS_PER_SUB == 2u) && + sq1 == sk1 && sq2 == sk2 && sq3 == sk3) { + const bool qk_v4_ok = ((sq1 & 3u) == 0u) && ((sq2 & 3u) == 0u) && ((sq3 & 3u) == 0u); + const bool v_v4_ok = (COLS_PER_SUB == 4u) && (COLS_PER_WG == 1u) && ((sv1 & 3u) == 0u) && ((sv2 & 3u) == 0u) && ((sv3 & 3u) == 0u) && ((col_base & 3u) == 0u); + const bool st_v4_ok = ((sout_nb2 & 3u) == 0u) && ((s_off & 3u) == 0u); + vec4 s0 = vec4(0.0f), s1 = vec4(0.0f), s2 = vec4(0.0f), s3 = vec4(0.0f); + if (!zero_state) { + s0 = data_state_v4[((state_in_base + (col_base + 0u * COLS_PER_WG) * S_V) >> 2u) + lane]; + s1 = data_state_v4[((state_in_base + (col_base + 1u * COLS_PER_WG) * S_V) >> 2u) + lane]; + if (COLS_PER_SUB == 4u) { + s2 = data_state_v4[((state_in_base + (col_base + 2u * COLS_PER_WG) * S_V) >> 2u) + lane]; + s3 = data_state_v4[((state_in_base + (col_base + 3u * COLS_PER_WG) * S_V) >> 2u) + lane]; + } + } + + uint attn_off = (seq_id * n_tokens * H + head_id) * S_V; + uint q_off = iq3 * sq3 + iq1 * sq1; + uint v_off = seq_id * sv3 + head_id * sv1; + uint gb_off = seq_id * sb3 + head_id * sb1; + for (uint t = 0u; t < n_tokens; ++t) { + const float beta_val = data_beta[gb_off]; + const float g_val = exp(data_g[gb_off]); + + const vec4 k_vec = qk_v4_ok + ? data_k_v4[(q_off >> 2u) + lane] + : vec4(data_k[q_off + 4u * lane + 0u], data_k[q_off + 4u * lane + 1u], data_k[q_off + 4u * lane + 2u], data_k[q_off + 4u * lane + 3u]); + const vec4 q_vec = qk_v4_ok + ? data_q_v4[(q_off >> 2u) + lane] + : vec4(data_q[q_off + 4u * lane + 0u], data_q[q_off + 4u * lane + 1u], data_q[q_off + 4u * lane + 2u], data_q[q_off + 4u * lane + 3u]); + + if (COLS_PER_SUB == 4u) { + vec4 attn_cols; + if (CONTIG_VEC4 >= 2u) { + const vec4 kv_sh = vec4( + dot(s0, k_vec), + dot(s1, k_vec), + dot(s2, k_vec), + dot(s3, k_vec) + ) * g_val; + const vec4 sq_sh = vec4( + dot(s0, q_vec), + dot(s1, q_vec), + dot(s2, q_vec), + dot(s3, q_vec) + ); + const float kq_sh = dot(k_vec, q_vec); + const vec4 kv_cols = subgroupAdd(kv_sh); + const vec4 sq_cols = subgroupAdd(sq_sh); + const float kq_dot = subgroupAdd(kq_sh); + const vec4 v_cols = v_v4_ok + ? data_v_v4[(v_off + col_base) >> 2u] + : vec4(data_v[v_off + col_base], data_v[v_off + col_base + COLS_PER_WG], data_v[v_off + col_base + 2u * COLS_PER_WG], data_v[v_off + col_base + 3u * COLS_PER_WG]); + const vec4 delta = (v_cols - kv_cols) * beta_val; + attn_cols = fma(vec4(g_val), sq_cols, delta * kq_dot) * scale; + s0 = fma(vec4(g_val), s0, k_vec * delta.x); + s1 = fma(vec4(g_val), s1, k_vec * delta.y); + s2 = fma(vec4(g_val), s2, k_vec * delta.z); + s3 = fma(vec4(g_val), s3, k_vec * delta.w); + } else { + vec4 kv_sh = vec4( + dot(s0, k_vec), + dot(s1, k_vec), + dot(s2, k_vec), + dot(s3, k_vec) + ) * g_val; + const vec4 kv_cols = subgroupAdd(kv_sh); + const vec4 v_cols = v_v4_ok + ? data_v_v4[(v_off + col_base) >> 2u] + : vec4(data_v[v_off + col_base], data_v[v_off + col_base + COLS_PER_WG], data_v[v_off + col_base + 2u * COLS_PER_WG], data_v[v_off + col_base + 3u * COLS_PER_WG]); + const vec4 delta = (v_cols - kv_cols) * beta_val; + s0 = fma(vec4(g_val), s0, k_vec * delta.x); + s1 = fma(vec4(g_val), s1, k_vec * delta.y); + s2 = fma(vec4(g_val), s2, k_vec * delta.z); + s3 = fma(vec4(g_val), s3, k_vec * delta.w); + + attn_cols = subgroupAdd(vec4( + dot(s0, q_vec), + dot(s1, q_vec), + dot(s2, q_vec), + dot(s3, q_vec) + )) * scale; + } + if (COLS_PER_WG == 1u && ((col_base & 3u) == 0u)) { + if (lane == 0u) { + data_dst_v4[(attn_off + col_base) >> 2u] = attn_cols; + } + } else if (lane < 4u) { + data_dst[attn_off + col_base + lane * COLS_PER_WG] = attn_cols[lane]; + } + } else { + vec2 attn_cols; + if (CONTIG_VEC4 >= 2u) { + const vec2 kv_sh = vec2(dot(s0, k_vec), dot(s1, k_vec)) * g_val; + const vec2 sq_sh = vec2(dot(s0, q_vec), dot(s1, q_vec)); + const float kq_sh = dot(k_vec, q_vec); + const vec2 kv_cols = subgroupAdd(kv_sh); + const vec2 sq_cols = subgroupAdd(sq_sh); + const float kq_dot = subgroupAdd(kq_sh); + const vec2 v_cols = vec2(data_v[v_off + col_base], data_v[v_off + col_base + COLS_PER_WG]); + const vec2 delta = (v_cols - kv_cols) * beta_val; + attn_cols = fma(vec2(g_val), sq_cols, delta * kq_dot) * scale; + s0 = fma(vec4(g_val), s0, k_vec * delta.x); + s1 = fma(vec4(g_val), s1, k_vec * delta.y); + } else { + vec2 kv_sh = vec2(dot(s0, k_vec), dot(s1, k_vec)) * g_val; + const vec2 kv_cols = subgroupAdd(kv_sh); + const vec2 v_cols = vec2(data_v[v_off + col_base], data_v[v_off + col_base + COLS_PER_WG]); + const vec2 delta = (v_cols - kv_cols) * beta_val; + s0 = fma(vec4(g_val), s0, k_vec * delta.x); + s1 = fma(vec4(g_val), s1, k_vec * delta.y); + + attn_cols = subgroupAdd(vec2(dot(s0, q_vec), dot(s1, q_vec))) * scale; + } + if (lane < 2u) { + data_dst[attn_off + col_base + lane * COLS_PER_WG] = attn_cols[lane]; + } + } + + attn_off += S_V * H; + q_off += sq2; + v_off += sv2; + gb_off += sb2; + + if (eff_K > 1u) { + const int target_slot = int(n_tokens) - 1 - int(t); + if (target_slot >= 0 && target_slot < int(eff_K)) { + for (uint c = 0u; c < COLS_PER_SUB; ++c) { + const vec4 sv = (c == 0u) ? s0 : ((c == 1u) ? s1 : ((c == 2u) ? s2 : s3)); + const uint col = col_base + c * COLS_PER_WG; +#if STATE_OUT + const uint slot_base = uint(target_slot) * sout_nb2 + state_out_base; + if (st_v4_ok) { + data_state_out_v4[((slot_base + col * S_V) >> 2u) + lane] = sv; + } else { + const uint b = slot_base + col * S_V + 4u * lane; + data_state_out[b + 0u] = sv.x; data_state_out[b + 1u] = sv.y; + data_state_out[b + 2u] = sv.z; data_state_out[b + 3u] = sv.w; + } +#else + const uint slot_base = s_off + uint(target_slot) * state_size_per_snap + state_out_base; + if (st_v4_ok) { + data_dst_v4[((slot_base + col * S_V) >> 2u) + lane] = sv; + } else { + const uint b = slot_base + col * S_V + 4u * lane; + data_dst[b + 0u] = sv.x; data_dst[b + 1u] = sv.y; + data_dst[b + 2u] = sv.z; data_dst[b + 3u] = sv.w; + } +#endif + } + } + } + } + + if (eff_K == 1u) { + for (uint c = 0u; c < COLS_PER_SUB; ++c) { + const vec4 sv = (c == 0u) ? s0 : ((c == 1u) ? s1 : ((c == 2u) ? s2 : s3)); + const uint col = col_base + c * COLS_PER_WG; +#if STATE_OUT + data_state_out_v4[((state_out_base + col * S_V) >> 2u) + lane] = sv; +#else + if (st_v4_ok) { + data_dst_v4[((s_off + state_out_base + col * S_V) >> 2u) + lane] = sv; + } else { + const uint b = s_off + state_out_base + col * S_V + 4u * lane; + data_dst[b + 0u] = sv.x; data_dst[b + 1u] = sv.y; + data_dst[b + 2u] = sv.z; data_dst[b + 3u] = sv.w; + } +#endif + } + } + return; + } +#endif - FLOAT_TYPE s_shard[ROWS_PER_LANE]; - [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]); + FLOAT_TYPE s_shard[COLS_PER_SUB * ROWS_PER_LANE]; + if (zero_state) { + [[unroll]] for (uint idx_s = 0; idx_s < COLS_PER_SUB * ROWS_PER_LANE; idx_s++) { + s_shard[idx_s] = FLOAT_TYPE(0.0); + } + } else { + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint col = col_base + c * COLS_PER_WG; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + s_shard[c * ROWS_PER_LANE + r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]); + } + } } if (REPLAY != 0) { @@ -160,25 +360,32 @@ void main() { } } - const FLOAT_TYPE v_val = FLOAT_TYPE(data_pv[v_off + col]); + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint col = col_base + c * COLS_PER_WG; + const uint sb = c * ROWS_PER_LANE; + const FLOAT_TYPE v_val = FLOAT_TYPE(data_pv[v_off + col]); - // same update as below, without the attention output - FLOAT_TYPE kv_shard = 0.0; - [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - kv_shard += g_exp[r] * s_shard[r] * k_reg[r]; - } - FLOAT_TYPE kv_col = reduce_partial(kv_shard); + // same update as below, without the attention output + FLOAT_TYPE kv_shard = 0.0; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + kv_shard += g_exp[r] * s_shard[sb + r] * k_reg[r]; + } + FLOAT_TYPE kv_col = reduce_partial(kv_shard); - FLOAT_TYPE delta_col = (v_val - kv_col) * beta_val; + FLOAT_TYPE delta_col = (v_val - kv_col) * beta_val; - [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - s_shard[r] = g_exp[r] * s_shard[r] + k_reg[r] * delta_col; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + s_shard[sb + r] = g_exp[r] * s_shard[sb + r] + k_reg[r] * delta_col; + } } } if (keep != 0) { - [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r]; + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint col = col_base + c * COLS_PER_WG; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[c * ROWS_PER_LANE + r]; + } } } } @@ -196,65 +403,139 @@ void main() { const FLOAT_TYPE beta_val = FLOAT_TYPE(data_beta[gb_off]); FLOAT_TYPE k_reg[ROWS_PER_LANE]; - FLOAT_TYPE q_reg[ROWS_PER_LANE]; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { const uint i = row_index(r, lane); k_reg[r] = FLOAT_TYPE(data_k[k_off + i]); - q_reg[r] = FLOAT_TYPE(data_q[q_off + i]); } - FLOAT_TYPE g_exp[ROWS_PER_LANE]; if (KDA == 0) { const FLOAT_TYPE g_val = exp(FLOAT_TYPE(data_g[gb_off])); - [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - g_exp[r] = g_val; + FLOAT_TYPE kv_shards[COLS_PER_SUB]; + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint sb = c * ROWS_PER_LANE; + FLOAT_TYPE kv_shard = 0.0; + if (COLS_PER_SUB == 1u) { + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + kv_shard += g_val * s_shard[sb + r] * k_reg[r]; + } + kv_shards[c] = kv_shard; + } else { + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + kv_shard += s_shard[sb + r] * k_reg[r]; + } + kv_shards[c] = kv_shard * g_val; + } + } + FLOAT_TYPE kv_cols[COLS_PER_SUB]; + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + kv_cols[c] = reduce_partial(kv_shards[c]); + } + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint col = col_base + c * COLS_PER_WG; + const uint sb = c * ROWS_PER_LANE; + const FLOAT_TYPE delta_col = (FLOAT_TYPE(data_v[v_off + col]) - kv_cols[c]) * beta_val; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + s_shard[sb + r] = g_val * s_shard[sb + r] + k_reg[r] * delta_col; + } } } else { + FLOAT_TYPE g_exp[ROWS_PER_LANE]; const uint g_base = gb_off * S_V; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { const uint i = row_index(r, lane); g_exp[r] = exp(FLOAT_TYPE(data_g[g_base + i])); } - } + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint col = col_base + c * COLS_PER_WG; + const uint sb = c * ROWS_PER_LANE; + const FLOAT_TYPE v_val = FLOAT_TYPE(data_v[v_off + col]); - const FLOAT_TYPE v_val = FLOAT_TYPE(data_v[v_off + col]); + FLOAT_TYPE kv_shard = 0.0; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + kv_shard += g_exp[r] * s_shard[sb + r] * k_reg[r]; + } + FLOAT_TYPE kv_col = reduce_partial(kv_shard); + FLOAT_TYPE delta_col = (v_val - kv_col) * beta_val; - FLOAT_TYPE kv_shard = 0.0; - [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - kv_shard += g_exp[r] * s_shard[r] * k_reg[r]; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + s_shard[sb + r] = g_exp[r] * s_shard[sb + r] + k_reg[r] * delta_col; + } + } } - FLOAT_TYPE kv_col = reduce_partial(kv_shard); - FLOAT_TYPE delta_col = (v_val - kv_col) * beta_val; + if (COLS_PER_SUB == 1u) { + FLOAT_TYPE attn_partial = 0.0; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + const uint i = row_index(r, lane); + attn_partial += s_shard[r] * FLOAT_TYPE(data_q[q_off + i]); + } + FLOAT_TYPE attn_col = reduce_partial(attn_partial); - FLOAT_TYPE attn_partial = 0.0; - [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - s_shard[r] = g_exp[r] * s_shard[r] + k_reg[r] * delta_col; - attn_partial += s_shard[r] * q_reg[r]; - } - FLOAT_TYPE attn_col = reduce_partial(attn_partial); + if (lane == 0) { + data_dst[attn_off + col_base] = attn_col * scale; + } + } else { + FLOAT_TYPE q_reg[ROWS_PER_LANE]; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + const uint i = row_index(r, lane); + q_reg[r] = FLOAT_TYPE(data_q[q_off + i]); + } - if (lane == 0) { - data_dst[attn_off + col] = attn_col * scale; + FLOAT_TYPE attn_partials[COLS_PER_SUB]; + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint sb = c * ROWS_PER_LANE; + FLOAT_TYPE attn_partial = 0.0; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + attn_partial += s_shard[sb + r] * q_reg[r]; + } + attn_partials[c] = attn_partial; + } + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const FLOAT_TYPE attn_col = reduce_partial(attn_partials[c]); + if (lane == 0) { + const uint col = col_base + c * COLS_PER_WG; + data_dst[attn_off + col] = attn_col * scale; + } + } } attn_off += S_V * H; - if (K > 1u) { + if (eff_K > 1u) { const int target_slot = int(n_tokens) - 1 - int(t); - if (target_slot >= 0 && target_slot < int(K)) { + if (target_slot >= 0 && target_slot < int(eff_K)) { +#if STATE_OUT + const uint slot_base = uint(target_slot) * sout_nb2 + state_out_base; + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint col = col_base + c * COLS_PER_WG; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + data_state_out[slot_base + col * S_V + row_index(r, lane)] = s_shard[c * ROWS_PER_LANE + r]; + } + } +#else const uint slot_base = s_off + uint(target_slot) * state_size_per_snap + state_out_base; - [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - data_dst[slot_base + col * S_V + row_index(r, lane)] = s_shard[r]; + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint col = col_base + c * COLS_PER_WG; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + data_dst[slot_base + col * S_V + row_index(r, lane)] = s_shard[c * ROWS_PER_LANE + r]; + } } +#endif } } } // replay with keep: the state output is the state after the replay - if (K == 1u && !(REPLAY != 0 && keep != 0)) { - [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r]; + if (eff_K == 1u && !(REPLAY != 0 && keep != 0)) { + [[unroll]] for (uint c = 0; c < COLS_PER_SUB; c++) { + const uint col = col_base + c * COLS_PER_WG; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { +#if STATE_OUT + data_state_out[state_out_base + col * S_V + row_index(r, lane)] = s_shard[c * ROWS_PER_LANE + r]; +#else + data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[c * ROWS_PER_LANE + r]; +#endif + } } } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_conv.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_conv.comp new file mode 100644 index 000000000000..856ff719112a --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_conv.comp @@ -0,0 +1,83 @@ +#version 450 +#extension GL_EXT_control_flow_attributes : enable + +layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufCur { float data_cur[]; }; +layout(binding = 1) readonly buffer BufHist { float data_hist[]; }; +layout(binding = 2) readonly buffer BufW { float data_w[]; }; +layout(binding = 3) readonly buffer BufDyn { float data_dyn[]; }; +layout(binding = 4) writeonly buffer BufState { float data_state[]; }; +layout(binding = 5) writeonly buffer BufDst { float data_dst[]; }; +layout(binding = 6) readonly buffer BufRes { float data_res[]; }; + +layout(push_constant) uniform PushConstants { + uint n_channels; + uint n_seq_tokens; + uint n_seqs; + uint hist_sconv_ch; + uint ch_offset; + uint n_heads; + uint st_base_f32; + uint st_seq_stride; + uint st_slot_stride; + uint st_kw; + uint off_cur; + uint off_hist; + uint off_w; + uint off_dyn; + uint off_dst; + float scale_out; + uint has_res; + uint off_res; + uint cur_s1; +} p; + +float load_conv_x(uint seq, uint c, int pos) { + if (pos < 0) { + return data_hist[p.off_hist + (seq * p.hist_sconv_ch + (p.ch_offset + c)) * 3u + uint(pos + 3)]; + } + return data_cur[p.off_cur + (seq * p.n_seq_tokens + uint(pos)) * p.cur_s1 + c]; +} + +void main() { + const uint c = gl_GlobalInvocationID.x; + const uint t = gl_WorkGroupID.y; + const uint seq = gl_WorkGroupID.z; + if (c >= p.n_channels || t >= p.n_seq_tokens || seq >= p.n_seqs) { + return; + } + + const float x0 = load_conv_x(seq, c, int(t) - 3); + const float x1 = load_conv_x(seq, c, int(t) - 2); + const float x2 = load_conv_x(seq, c, int(t) - 1); + const float x3 = load_conv_x(seq, c, int(t)); + + const uint wb = p.off_w + c * 4u; + float sum = ((x0 * data_w[wb + 0u] + x1 * data_w[wb + 1u]) + x2 * data_w[wb + 2u]) + x3 * data_w[wb + 3u]; + + const uint tok_global = seq * p.n_seq_tokens + t; + if (p.n_heads > 0u) { + const uint head_dim = p.n_channels / p.n_heads; + const uint head = c / head_dim; + const uint db = p.off_dyn + (tok_global * p.n_heads + head) * 4u; + sum += x3 * data_dyn[db + 0u]; + sum += x2 * data_dyn[db + 1u]; + sum += x1 * data_dyn[db + 2u]; + sum += x0 * data_dyn[db + 3u]; + } + + const uint elem = tok_global * p.n_channels + c; + precise float pre_sum = x3 + sum; + precise float scaled = pre_sum * p.scale_out; + precise float out_val = (p.has_res != 0u) ? (data_res[p.off_res + elem] + scaled) : scaled; + data_dst[p.off_dst + elem] = out_val; + + const int target_slot = int(p.n_seq_tokens) - 1 - int(t); + if (target_slot >= 0 && uint(target_slot) < p.st_kw) { + const uint sb = p.st_base_f32 + uint(target_slot) * p.st_slot_stride + seq * p.st_seq_stride + c * 3u; + data_state[sb + 0u] = x1; + data_state[sb + 1u] = x2; + data_state[sb + 2u] = x3; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_conv_scopy.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_conv_scopy.comp new file mode 100644 index 000000000000..835f4dd22a01 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_conv_scopy.comp @@ -0,0 +1,112 @@ +#version 450 +#extension GL_EXT_control_flow_attributes : enable + +// S19 W6: Dedicated N<=16 WAR-free wg_y=1 ShortConv + n_exp MoE sum8 epilogue (supports both direct s_copy & build_rs history) +layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufCur { float data_cur[]; }; +layout(binding = 1) readonly buffer BufHist { float data_hist[]; }; +layout(binding = 2) readonly buffer BufW { float data_w[]; }; +layout(binding = 3) readonly buffer BufDyn { float data_dyn[]; }; +layout(binding = 4) buffer BufState { float data_state[]; }; +layout(binding = 5) writeonly buffer BufDst { float data_dst[]; }; +layout(binding = 6) readonly buffer BufRes { float data_res[]; }; +layout(binding = 7) readonly buffer BufSCopy { int data_scopy[]; }; + +layout(push_constant) uniform PushConstants { + uint n_channels; + uint n_seq_tokens; + uint n_seqs; + uint n_exp; + uint ch_offset; + uint n_heads; + uint st_base_f32; + uint st_seq_stride; + uint st_slot_stride; + uint st_kw; + uint off_cur; + uint off_w; + uint off_dyn; + uint off_dst; + float scale_out; + uint has_res; + uint off_res; + uint off_state; + uint off_scopy; + uint use_hist; + uint off_hist; + uint hist_sconv_ch; + uint cur_s1; +} p; + +void main() { + const uint c = gl_GlobalInvocationID.x; + const uint seq = gl_WorkGroupID.z; + if (c >= p.n_channels || seq >= p.n_seqs) { + return; + } + + const uint wb = p.off_w + c * 4u; + const float w0 = data_w[wb + 0u]; + const float w1 = data_w[wb + 1u]; + const float w2 = data_w[wb + 2u]; + const float w3 = data_w[wb + 3u]; + + float x0, x1, x2; + if (p.use_hist != 0u) { + const uint hb = p.off_hist + (seq * p.hist_sconv_ch + (p.ch_offset + c)) * 3u; + x0 = data_hist[hb + 0u]; + x1 = data_hist[hb + 1u]; + x2 = data_hist[hb + 2u]; + } else { + const uint src_cell = uint(data_scopy[p.off_scopy + seq]); + const uint hb = p.off_state + src_cell * p.st_seq_stride + (p.ch_offset + c) * 3u; + x0 = data_state[hb + 0u]; + x1 = data_state[hb + 1u]; + x2 = data_state[hb + 2u]; + } + + const uint head = (p.n_heads > 0u) ? (c / (p.n_channels / p.n_heads)) : 0u; + for (uint t = 0u; t < p.n_seq_tokens; ++t) { + const uint tok_global = seq * p.n_seq_tokens + t; + const uint elem = tok_global * p.n_channels + c; + float x3; + if (p.n_exp <= 1u) { + x3 = data_cur[p.off_cur + tok_global * p.cur_s1 + c]; + } else { + const uint base = p.off_cur + tok_global * (p.n_exp * p.n_channels) + c; + float s = data_cur[base]; + for (uint e = 1u; e < p.n_exp; ++e) { + precise float ns = s + data_cur[base + e * p.n_channels]; + s = ns; + } + x3 = s; + } + + float sum = ((x0 * w0 + x1 * w1) + x2 * w2) + x3 * w3; + if (p.n_heads > 0u) { + const uint db = p.off_dyn + (tok_global * p.n_heads + head) * 4u; + sum += x3 * data_dyn[db + 0u]; + sum += x2 * data_dyn[db + 1u]; + sum += x1 * data_dyn[db + 2u]; + sum += x0 * data_dyn[db + 3u]; + } + + precise float pre_sum = x3 + sum; + precise float scaled = pre_sum * p.scale_out; + precise float out_val = (p.has_res != 0u) ? (data_res[p.off_res + elem] + scaled) : scaled; + data_dst[p.off_dst + elem] = out_val; + + const int target_slot = int(p.n_seq_tokens) - 1 - int(t); + if (target_slot >= 0 && uint(target_slot) < p.st_kw) { + const uint sb = p.st_base_f32 + uint(target_slot) * p.st_slot_stride + seq * p.st_seq_stride + c * 3u; + data_state[sb + 0u] = x1; + data_state[sb + 1u] = x2; + data_state[sb + 2u] = x3; + } + + x0 = x1; + x1 = x2; + x2 = x3; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_ctrl_apply.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_ctrl_apply.comp new file mode 100644 index 000000000000..a0dc9aedfb75 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_ctrl_apply.comp @@ -0,0 +1,33 @@ +#version 450 + +layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufCur { float data_cur[]; }; +layout(binding = 1) readonly buffer BufMsg { float data_msg[]; }; +layout(binding = 2) readonly buffer BufGn { float data_gn[]; }; +layout(binding = 3) readonly buffer BufFg { float data_fg[]; }; +layout(binding = 4) writeonly buffer BufDst { float data_dst[]; }; + +layout(push_constant) uniform PushConstants { + uint ne; + uint off_cur; + uint off_msg; + uint off_gn; + uint off_fg; + uint off_dst; +} p; + +void main() { + const uint base = (gl_GlobalInvocationID.x + gl_WorkGroupID.y * (65535u * 256u)) * 4u; + if (base >= p.ne) { + return; + } + for (uint k = 0u; k < 4u && (base + k) < p.ne; ++k) { + const uint i = base + k; + const float c = data_cur[p.off_cur + i]; + const float m = data_msg[p.off_msg + i]; + const float gn = tanh(data_gn[p.off_gn + i]); + const float fg = tanh(data_fg[p.off_fg + i]); + data_dst[p.off_dst + i] = (c - fg * c) + gn * m; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_ctrl_apply_rms_mul.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_ctrl_apply_rms_mul.comp new file mode 100644 index 000000000000..c2c5b456470e --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_ctrl_apply_rms_mul.comp @@ -0,0 +1,87 @@ +#version 450 +// S19_WAVE3 (mode = 11): Batched [gain; forget] ctrl_apply + 0-ULP Borealis 512-tree RMS_NORM_MUL +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable +#extension GL_EXT_control_flow_attributes : enable +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require + +layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufCur { float data_cur[]; }; +layout(binding = 1) readonly buffer BufMsg { float data_msg[]; }; +layout(binding = 2) readonly buffer BufUp { float data_up[]; }; +layout(binding = 3) readonly buffer BufW { float data_w[]; }; +layout(binding = 4) writeonly buffer BufDst { float data_dst[]; }; +layout(binding = 5) writeonly buffer BufDst16 { float16_t data_dst16[]; }; + +layout(push_constant) uniform PushConstants { + uint n_embd; + uint n_tokens; + uint C; + uint off_cur; + uint off_msg; + uint off_up; + uint off_w; + uint off_dst; + uint cur_s2; + uint w_s1; + float eps; +} p; + +shared float sh_mix[2304]; +shared float sh_rms[16]; + +void main() { + const uint tok = gl_WorkGroupID.x + gl_WorkGroupID.y * 65535u; + const uint sl = gl_WorkGroupID.z; + const bool do_f16 = (p.C & 0x80000000u) != 0u; + const uint C_val = p.C & 0x7FFFFFFFu; + if (tok >= p.n_tokens || sl >= C_val) { + return; + } + const uint tid = gl_LocalInvocationID.x; + const uint cb = p.off_cur + sl * p.cur_s2 + tok * p.n_embd; + const uint mb = p.off_msg + (sl * p.n_tokens + tok) * p.n_embd; + const uint ub = p.off_up + (sl * p.n_tokens + tok) * (2u * p.n_embd); + const uint wb = p.off_w + sl * p.w_s1; + const uint db16 = (sl * p.n_tokens + tok) * p.n_embd; + const uint db = p.off_dst + db16; + + for (uint col = tid; col < p.n_embd; col += 512u) { + const float c = data_cur[cb + col]; + const float m = data_msg[mb + col]; + const float gn = tanh(data_up[ub + col]); + const float fg = tanh(data_up[ub + p.n_embd + col]); + sh_mix[col] = (c - fg * c) + gn * m; + } + barrier(); + + const uint num_blocks = (p.n_embd + 511u) >> 9u; + float sum = 0.0f; + [[dont_unroll]] for (uint col = tid, idx = 0u; idx < num_blocks; col += 512u, ++idx) { + float xi = 0.0f; + if (col < p.n_embd) { + xi = sh_mix[col]; + } + sum += xi * xi; + } + sum = subgroupAdd(sum); + if (gl_SubgroupInvocationID == 0u) { + sh_rms[gl_SubgroupID] = sum; + } + barrier(); + + float total = (gl_SubgroupInvocationID < 16u) ? sh_rms[gl_SubgroupInvocationID] : 0.0f; + total = subgroupAdd(total); + const float mean = total / float(p.n_embd); + const float scale = inversesqrt(mean + p.eps); + + for (uint col = tid; col < p.n_embd; col += 512u) { + const float val = scale * sh_mix[col] * data_w[wb + col]; + data_dst[db + col] = val; + if (do_f16) { + data_dst16[db16 + col] = float16_t(val); + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_depth_mix.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_depth_mix.comp new file mode 100644 index 000000000000..3018cce2518a --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_depth_mix.comp @@ -0,0 +1,254 @@ +#version 450 +// S19 W11d: Zero-spill (~36 GPRs, 16 B shmem) 0-ULP depth_mix matching s18 FMA & loop structure bit-for-bit +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable +#extension GL_EXT_control_flow_attributes : enable + +layout(local_size_x = 128, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufS0 { float s0[]; }; +layout(binding = 1) readonly buffer BufS1 { float s1[]; }; +layout(binding = 2) readonly buffer BufS2 { float s2[]; }; +layout(binding = 3) readonly buffer BufS3 { float s3[]; }; +layout(binding = 4) readonly buffer BufS4 { float s4[]; }; +layout(binding = 5) readonly buffer BufS5 { float s5[]; }; +layout(binding = 6) readonly buffer BufQ { float data_q[]; }; +layout(binding = 7) writeonly buffer BufD { float data_dst[]; }; + +layout(push_constant) uniform PushConstants { + uint n_embd; + uint n_tokens; + uint K; + uint Q; + uint off_s[6]; + uint off_q; + uint off_dst; + float eps; + float sm_scale; +} p; + +shared float sh_red[4]; + +float reduce_sum_128(float v) { + const float sg = subgroupAdd(v); + if (gl_SubgroupInvocationID == 0u) { + sh_red[gl_SubgroupID] = sg; + } + barrier(); + const float res = sh_red[0] + sh_red[1] + sh_red[2] + sh_red[3]; + barrier(); + return res; +} + +float load_state(uint b, uint idx) { + switch (b) { + case 0u: return s0[p.off_s[0] + idx]; + case 1u: return s1[p.off_s[1] + idx]; + case 2u: return s2[p.off_s[2] + idx]; + case 3u: return s3[p.off_s[3] + idx]; + case 4u: return s4[p.off_s[4] + idx]; + default: return s5[p.off_s[5] + idx]; + } +} + +void main() { + const uint tok = gl_WorkGroupID.x + gl_WorkGroupID.y * 65535u; + const uint q_beg = (gl_NumWorkGroups.z > 1u) ? gl_WorkGroupID.z : 0u; + const uint q_end = (gl_NumWorkGroups.z > 1u) ? (q_beg + 1u) : p.Q; + if (tok >= p.n_tokens || q_beg >= p.Q) { + return; + } + const uint n_embd = p.n_embd & 0x7FFFFFFFu; + const uint tid = gl_LocalInvocationID.x; + const uint tok_base = tok * n_embd; + const float inv_d = 1.0f / float(n_embd); + + if (n_embd == 1280u && p.K <= 6u) { + float v[6][10]; + for (uint b = 0u; b < p.K; ++b) { + float ss = 0.0f; + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + const float x = load_state(b, tok_base + tid + m * 128u); + v[b][m] = x; + ss += x * x; + } + const float rms_inv = 1.0f / sqrt(reduce_sum_128(ss) * inv_d + p.eps); + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + v[b][m] *= rms_inv; + } + } + for (uint q = q_beg; q < q_end; ++q) { + const uint qb = p.off_q + q * 1280u; + float qv[10]; + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + qv[m] = data_q[qb + tid + m * 128u]; + } + float scores[6]; + float mx = -3.402823466e+38f; + for (uint b = 0u; b < p.K; ++b) { + float dp = 0.0f; + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + dp += v[b][m] * qv[m]; + } + const float sc = reduce_sum_128(dp) * p.sm_scale; + scores[b] = sc; + mx = max(mx, sc); + } + float ex_sum = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + scores[b] = exp(scores[b] - mx); + ex_sum += scores[b]; + } + const float inv_ex = 1.0f / ex_sum; + for (uint b = 0u; b < p.K; ++b) { + scores[b] *= inv_ex; + } + const uint db = p.off_dst + (q * p.n_tokens + tok) * 1280u; + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + float acc = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + acc += v[b][m] * scores[b]; + } + data_dst[db + tid + m * 128u] = acc; + } + } + return; + } + + if (n_embd == 2304u && p.K <= 6u) { + float rms_inv[6]; + for (uint b = 0u; b < p.K; ++b) { + float ss = 0.0f; + switch (b) { + case 0u: { const uint sb = p.off_s[0] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s0[sb + m * 128u]; ss += x * x; } break; } + case 1u: { const uint sb = p.off_s[1] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s1[sb + m * 128u]; ss += x * x; } break; } + case 2u: { const uint sb = p.off_s[2] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s2[sb + m * 128u]; ss += x * x; } break; } + case 3u: { const uint sb = p.off_s[3] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s3[sb + m * 128u]; ss += x * x; } break; } + case 4u: { const uint sb = p.off_s[4] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s4[sb + m * 128u]; ss += x * x; } break; } + default: { const uint sb = p.off_s[5] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s5[sb + m * 128u]; ss += x * x; } break; } + } + rms_inv[b] = 1.0f / sqrt(reduce_sum_128(ss) * inv_d + p.eps); + } + for (uint q = q_beg; q < q_end; ++q) { + const uint qb = p.off_q + q * 2304u; + float qv[18]; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { + qv[m] = data_q[qb + tid + m * 128u]; + } + float scores[6]; + float mx = -3.402823466e+38f; + for (uint b = 0u; b < p.K; ++b) { + const float rinv = rms_inv[b]; + float dp = 0.0f; + switch (b) { + case 0u: { const uint sb = p.off_s[0] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s0[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + case 1u: { const uint sb = p.off_s[1] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s1[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + case 2u: { const uint sb = p.off_s[2] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s2[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + case 3u: { const uint sb = p.off_s[3] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s3[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + case 4u: { const uint sb = p.off_s[4] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s4[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + default: { const uint sb = p.off_s[5] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s5[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + } + const float sc = reduce_sum_128(dp) * p.sm_scale; + scores[b] = sc; + mx = max(mx, sc); + } + float ex_sum = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + scores[b] = exp(scores[b] - mx); + ex_sum += scores[b]; + } + const float inv_ex = 1.0f / ex_sum; + for (uint b = 0u; b < p.K; ++b) { + scores[b] *= inv_ex; + } + float acc[18]; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { + acc[m] = 0.0f; + } + for (uint b = 0u; b < p.K; ++b) { + const float rinv = rms_inv[b]; + const float sc = scores[b]; + switch (b) { + case 0u: { + const uint sb = p.off_s[0] + tok_base + tid; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s0[sb + m * 128u] * rinv; acc[m] += vn * sc; } + break; + } + case 1u: { + const uint sb = p.off_s[1] + tok_base + tid; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s1[sb + m * 128u] * rinv; acc[m] += vn * sc; } + break; + } + case 2u: { + const uint sb = p.off_s[2] + tok_base + tid; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s2[sb + m * 128u] * rinv; acc[m] += vn * sc; } + break; + } + case 3u: { + const uint sb = p.off_s[3] + tok_base + tid; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s3[sb + m * 128u] * rinv; acc[m] += vn * sc; } + break; + } + case 4u: { + const uint sb = p.off_s[4] + tok_base + tid; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s4[sb + m * 128u] * rinv; acc[m] += vn * sc; } + break; + } + default: { + const uint sb = p.off_s[5] + tok_base + tid; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s5[sb + m * 128u] * rinv; acc[m] += vn * sc; } + break; + } + } + } + const uint db = p.off_dst + (q * p.n_tokens + tok) * 2304u; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { + data_dst[db + tid + m * 128u] = acc[m]; + } + } + return; + } + + float rms_inv[6]; + for (uint b = 0u; b < p.K; ++b) { + float ss = 0.0f; + for (uint c = tid; c < n_embd; c += 128u) { + const float x = load_state(b, tok_base + c); + ss += x * x; + } + rms_inv[b] = 1.0f / sqrt(reduce_sum_128(ss) * inv_d + p.eps); + } + for (uint q = q_beg; q < q_end; ++q) { + const uint qb = p.off_q + q * n_embd; + float scores[6]; + float mx = -3.402823466e+38f; + for (uint b = 0u; b < p.K; ++b) { + float dp = 0.0f; + for (uint c = tid; c < n_embd; c += 128u) { + precise float vn = load_state(b, tok_base + c) * rms_inv[b]; + dp += vn * data_q[qb + c]; + } + const float sc = reduce_sum_128(dp) * p.sm_scale; + scores[b] = sc; + mx = max(mx, sc); + } + float ex_sum = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + scores[b] = exp(scores[b] - mx); + ex_sum += scores[b]; + } + const float inv_ex = 1.0f / ex_sum; + for (uint b = 0u; b < p.K; ++b) { + scores[b] *= inv_ex; + } + const uint db = p.off_dst + (q * p.n_tokens + tok) * n_embd; + for (uint c = tid; c < n_embd; c += 128u) { + float acc = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + precise float vn = load_state(b, tok_base + c) * rms_inv[b]; + acc += vn * scores[b]; + } + data_dst[db + c] = acc; + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_depth_mix_rms.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_depth_mix_rms.comp new file mode 100644 index 000000000000..5f5714d99f35 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_depth_mix_rms.comp @@ -0,0 +1,296 @@ +#version 450 +// S19 W11d: Zero-spill (~36 GPRs) 3D query-parallel depth_mix + 0-ULP 512-tree RMS_NORM_MUL epilogue +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable +#extension GL_EXT_control_flow_attributes : enable +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require + +layout(local_size_x = 128, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufS0 { float s0[]; }; +layout(binding = 1) readonly buffer BufS1 { float s1[]; }; +layout(binding = 2) readonly buffer BufS2 { float s2[]; }; +layout(binding = 3) readonly buffer BufS3 { float s3[]; }; +layout(binding = 4) readonly buffer BufS4 { float s4[]; }; +layout(binding = 5) readonly buffer BufS5 { float s5[]; }; +layout(binding = 6) readonly buffer BufQ { float data_q[]; }; +layout(binding = 7) writeonly buffer BufD { float data_dst[]; }; +layout(binding = 8) readonly buffer BufW { float data_w[]; }; +layout(binding = 9) writeonly buffer BufD16 { float16_t data_dst16[]; }; + +layout(push_constant) uniform PushConstants { + uint n_embd; + uint n_tokens; + uint K; + uint Q; + uint off_s[6]; + uint off_q; + uint off_dst; + float eps; + float sm_scale; + uint has_rms_w; + uint off_w; + uint w_s1; + float rms_eps; +} p; + +shared float sh_red[4]; +shared float sh_mix[2304]; +shared float sh_rms[16]; + +float reduce_sum_128(float v) { + const float sg = subgroupAdd(v); + if (gl_SubgroupInvocationID == 0u) { + sh_red[gl_SubgroupID] = sg; + } + barrier(); + const float res = sh_red[0] + sh_red[1] + sh_red[2] + sh_red[3]; + barrier(); + return res; +} + +float load_state(uint b, uint idx) { + switch (b) { + case 0u: return s0[p.off_s[0] + idx]; + case 1u: return s1[p.off_s[1] + idx]; + case 2u: return s2[p.off_s[2] + idx]; + case 3u: return s3[p.off_s[3] + idx]; + case 4u: return s4[p.off_s[4] + idx]; + default: return s5[p.off_s[5] + idx]; + } +} + +void epilogue_rms512_from_shmem(uint tid, uint q, uint db, uint db16, bool do_f16) { + barrier(); + const uint num_blocks = (p.n_embd + 511u) >> 9u; + [[unroll]] for (uint vsg = 0u; vsg < 4u; ++vsg) { + const uint tid512 = vsg * 128u + tid; + float sum = 0.0f; + [[dont_unroll]] for (uint col = tid512, idx = 0u; idx < num_blocks; col += 512u, ++idx) { + float xi = 0.0f; + if (col < p.n_embd) { + xi = sh_mix[col]; + } + sum += xi * xi; + } + sum = subgroupAdd(sum); + if (gl_SubgroupInvocationID == 0u) { + sh_rms[vsg * 4u + gl_SubgroupID] = sum; + } + } + barrier(); + float total = (gl_SubgroupInvocationID < 16u) ? sh_rms[gl_SubgroupInvocationID] : 0.0f; + total = subgroupAdd(total); + const float mean = total / float(p.n_embd); + const float scale = inversesqrt(mean + p.rms_eps); + const uint wb = p.off_w + q * p.w_s1; + for (uint col = tid; col < p.n_embd; col += 128u) { + const float val = scale * sh_mix[col] * data_w[wb + col]; + data_dst[db + col] = val; + if (do_f16) { + data_dst16[db16 + col] = float16_t(val); + } + } +} + +void main() { + const uint tok = gl_WorkGroupID.x + gl_WorkGroupID.y * 65535u; + const uint q = gl_WorkGroupID.z; + if (tok >= p.n_tokens || q >= p.Q) { + return; + } + const uint tid = gl_LocalInvocationID.x; + const uint tok_base = tok * p.n_embd; + const float inv_d = 1.0f / float(p.n_embd); + + if (p.n_embd == 1280u && p.K <= 6u) { + float v[6][10]; + for (uint b = 0u; b < p.K; ++b) { + float ss = 0.0f; + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + const float x = load_state(b, tok_base + tid + m * 128u); + v[b][m] = x; + ss += x * x; + } + const float rms_inv = 1.0f / sqrt(reduce_sum_128(ss) * inv_d + p.eps); + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + v[b][m] *= rms_inv; + } + } + const uint qb = p.off_q + q * 1280u; + float qv[10]; + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + qv[m] = data_q[qb + tid + m * 128u]; + } + float scores[6]; + float mx = -3.402823466e+38f; + for (uint b = 0u; b < p.K; ++b) { + float dp = 0.0f; + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + dp += v[b][m] * qv[m]; + } + const float sc = reduce_sum_128(dp) * p.sm_scale; + scores[b] = sc; + mx = max(mx, sc); + } + float ex_sum = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + scores[b] = exp(scores[b] - mx); + ex_sum += scores[b]; + } + const float inv_ex = 1.0f / ex_sum; + for (uint b = 0u; b < p.K; ++b) { + scores[b] *= inv_ex; + } + const uint db16 = (q * p.n_tokens + tok) * 1280u; + const uint db = p.off_dst + db16; + [[unroll]] for (uint m = 0u; m < 10u; ++m) { + float acc = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + acc += v[b][m] * scores[b]; + } + if (p.has_rms_w != 0u) { + sh_mix[tid + m * 128u] = acc; + } else { + data_dst[db + tid + m * 128u] = acc; + } + } + if (p.has_rms_w != 0u) { + epilogue_rms512_from_shmem(tid, q, db, db16, (p.has_rms_w & 2u) != 0u); + } + return; + } + + if (p.n_embd == 2304u && p.K <= 6u) { + float rms_inv[6]; + for (uint b = 0u; b < p.K; ++b) { + float ss = 0.0f; + switch (b) { + case 0u: { const uint sb = p.off_s[0] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s0[sb + m * 128u]; ss += x * x; } break; } + case 1u: { const uint sb = p.off_s[1] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s1[sb + m * 128u]; ss += x * x; } break; } + case 2u: { const uint sb = p.off_s[2] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s2[sb + m * 128u]; ss += x * x; } break; } + case 3u: { const uint sb = p.off_s[3] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s3[sb + m * 128u]; ss += x * x; } break; } + case 4u: { const uint sb = p.off_s[4] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s4[sb + m * 128u]; ss += x * x; } break; } + default: { const uint sb = p.off_s[5] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { const float x = s5[sb + m * 128u]; ss += x * x; } break; } + } + rms_inv[b] = 1.0f / sqrt(reduce_sum_128(ss) * inv_d + p.eps); + } + const uint qb = p.off_q + q * 2304u; + float qv[18]; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { + qv[m] = data_q[qb + tid + m * 128u]; + } + float scores[6]; + float mx = -3.402823466e+38f; + for (uint b = 0u; b < p.K; ++b) { + const float rinv = rms_inv[b]; + float dp = 0.0f; + switch (b) { + case 0u: { const uint sb = p.off_s[0] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s0[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + case 1u: { const uint sb = p.off_s[1] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s1[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + case 2u: { const uint sb = p.off_s[2] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s2[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + case 3u: { const uint sb = p.off_s[3] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s3[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + case 4u: { const uint sb = p.off_s[4] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s4[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + default: { const uint sb = p.off_s[5] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s5[sb + m * 128u] * rinv; dp += vn * qv[m]; } break; } + } + const float sc = reduce_sum_128(dp) * p.sm_scale; + scores[b] = sc; + mx = max(mx, sc); + } + float ex_sum = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + scores[b] = exp(scores[b] - mx); + ex_sum += scores[b]; + } + const float inv_ex = 1.0f / ex_sum; + for (uint b = 0u; b < p.K; ++b) { + scores[b] *= inv_ex; + } + float acc[18]; + [[unroll]] for (uint m = 0u; m < 18u; ++m) { + acc[m] = 0.0f; + } + for (uint b = 0u; b < p.K; ++b) { + const float rinv = rms_inv[b]; + const float sc = scores[b]; + switch (b) { + case 0u: { const uint sb = p.off_s[0] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s0[sb + m * 128u] * rinv; acc[m] += vn * sc; } break; } + case 1u: { const uint sb = p.off_s[1] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s1[sb + m * 128u] * rinv; acc[m] += vn * sc; } break; } + case 2u: { const uint sb = p.off_s[2] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s2[sb + m * 128u] * rinv; acc[m] += vn * sc; } break; } + case 3u: { const uint sb = p.off_s[3] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s3[sb + m * 128u] * rinv; acc[m] += vn * sc; } break; } + case 4u: { const uint sb = p.off_s[4] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s4[sb + m * 128u] * rinv; acc[m] += vn * sc; } break; } + default: { const uint sb = p.off_s[5] + tok_base + tid; [[unroll]] for (uint m = 0u; m < 18u; ++m) { precise float vn = s5[sb + m * 128u] * rinv; acc[m] += vn * sc; } break; } + } + } + const uint db16 = (q * p.n_tokens + tok) * 2304u; + const uint db = p.off_dst + db16; + if (p.has_rms_w != 0u) { + [[unroll]] for (uint m = 0u; m < 18u; ++m) { + sh_mix[tid + m * 128u] = acc[m]; + } + } else { + [[unroll]] for (uint m = 0u; m < 18u; ++m) { + data_dst[db + tid + m * 128u] = acc[m]; + } + } + if (p.has_rms_w != 0u) { + epilogue_rms512_from_shmem(tid, q, db, db16, (p.has_rms_w & 2u) != 0u); + } + return; + } + + float rms_inv[6]; + for (uint b = 0u; b < p.K; ++b) { + float ss = 0.0f; + for (uint c = tid; c < p.n_embd; c += 128u) { + const float x = load_state(b, tok_base + c); + ss += x * x; + } + rms_inv[b] = 1.0f / sqrt(reduce_sum_128(ss) * inv_d + p.eps); + } + const uint qb = p.off_q + q * p.n_embd; + float scores[6]; + float mx = -3.402823466e+38f; + for (uint b = 0u; b < p.K; ++b) { + float dp = 0.0f; + for (uint c = tid; c < p.n_embd; c += 128u) { + precise float vn = load_state(b, tok_base + c) * rms_inv[b]; + dp += vn * data_q[qb + c]; + } + const float sc = reduce_sum_128(dp) * p.sm_scale; + scores[b] = sc; + mx = max(mx, sc); + } + float ex_sum = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + scores[b] = exp(scores[b] - mx); + ex_sum += scores[b]; + } + const float inv_ex = 1.0f / ex_sum; + for (uint b = 0u; b < p.K; ++b) { + scores[b] *= inv_ex; + } + const uint db16 = (q * p.n_tokens + tok) * p.n_embd; + const uint db = p.off_dst + db16; + if (p.has_rms_w != 0u && p.n_embd <= 2304u) { + for (uint c = tid; c < p.n_embd; c += 128u) { + float acc = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + precise float vn = load_state(b, tok_base + c) * rms_inv[b]; + acc += vn * scores[b]; + } + sh_mix[c] = acc; + } + epilogue_rms512_from_shmem(tid, q, db, db16, (p.has_rms_w & 2u) != 0u); + } else { + for (uint c = tid; c < p.n_embd; c += 128u) { + float acc = 0.0f; + for (uint b = 0u; b < p.K; ++b) { + precise float vn = load_state(b, tok_base + c) * rms_inv[b]; + acc += vn * scores[b]; + } + data_dst[db + c] = acc; + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_concat4.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_concat4.comp new file mode 100644 index 000000000000..b234c7e3aa52 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_concat4.comp @@ -0,0 +1,36 @@ +#version 450 + +layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer Buf0 { float data_0[]; }; +layout(binding = 1) readonly buffer Buf1 { float data_1[]; }; +layout(binding = 2) readonly buffer Buf2 { float data_2[]; }; +layout(binding = 3) readonly buffer Buf3 { float data_3[]; }; +layout(binding = 4) writeonly buffer BufDst { float data_dst[]; }; + +layout(push_constant) uniform PushConstants { + uint n0, n1, n2, n3; + uint nb; + uint off0, off1, off2, off3, off_dst; +} p; + +void main() { + const uint total_cols = p.n0 + p.n1 + p.n2 + p.n3; + const uint idx = gl_GlobalInvocationID.x; + if (idx >= total_cols * p.nb) { + return; + } + const uint row = idx / total_cols; + const uint col = idx - row * total_cols; + float v; + if (col < p.n0) { + v = data_0[p.off0 + row * p.n0 + col]; + } else if (col < p.n0 + p.n1) { + v = data_1[p.off1 + row * p.n1 + (col - p.n0)]; + } else if (col < p.n0 + p.n1 + p.n2) { + v = data_2[p.off2 + row * p.n2 + (col - p.n0 - p.n1)]; + } else { + v = data_3[p.off3 + row * p.n3 + (col - p.n0 - p.n1 - p.n2)]; + } + data_dst[p.off_dst + idx] = v; +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_gru.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_gru.comp new file mode 100644 index 000000000000..99699027896f --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_gru.comp @@ -0,0 +1,45 @@ +#version 450 + +layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufJoint { float data_joint[]; }; +layout(binding = 1) readonly buffer BufState { float data_state[]; }; +layout(binding = 2) writeonly buffer BufDst { float data_dst[]; }; + +layout(push_constant) uniform PushConstants { + uint rank; + uint nb; + uint off_joint; + uint off_state; + uint off_dst; +} p; + +void main() { + const uint idx = gl_GlobalInvocationID.x; + const uint slice_elems = p.rank * p.nb; + if (idx >= slice_elems) { + return; + } + const uint row = idx / p.rank; + const uint col = idx - row * p.rank; + const uint j_base = p.off_joint + row * (3u * p.rank); + + const float j0 = data_joint[j_base + col]; + const float j1 = data_joint[j_base + p.rank + col]; + const float j2 = data_joint[j_base + 2u * p.rank + col]; + const float st = data_state[p.off_state + idx]; + + // Series 18 (0-ULP): exact IEEE-754 rounding sequence of sigmoid, tanh, sub, mul, add, tanh + precise float neg_j0 = -j0; + precise float exp_j0 = exp(neg_j0); + precise float den_j0 = 1.0f + exp_j0; + precise float gate = 1.0f / den_j0; + precise float cand = tanh(j1); + precise float diff = st - cand; + precise float prod = gate * diff; + precise float st_new = cand + prod; + precise float latent = tanh(j2); + + data_dst[p.off_dst + idx] = st_new; + data_dst[p.off_dst + slice_elems + idx] = latent; +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_inject_mix.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_inject_mix.comp new file mode 100644 index 000000000000..5ef6e930484f --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_inject_mix.comp @@ -0,0 +1,157 @@ +#version 450 +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable +#extension GL_EXT_control_flow_attributes : enable + +layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufFeat { float data_feat[]; }; +layout(binding = 1) readonly buffer BufFuse { float data_fuse[]; }; +layout(binding = 2) readonly buffer BufN0 { float norm0[]; }; +layout(binding = 3) readonly buffer BufN1 { float norm1[]; }; +layout(binding = 4) readonly buffer BufN2 { float norm2[]; }; +layout(binding = 5) readonly buffer BufN3 { float norm3[]; }; +layout(binding = 6) readonly buffer BufPos { int data_pos[]; }; +layout(binding = 7) buffer BufRing { float data_ring[]; }; +layout(binding = 8) writeonly buffer BufDst { float data_dst[]; }; + +layout(push_constant) uniform PushConstants { + uint n_embd; + uint n_tokens; + uint has_ring; + uint ring_seq_offset; + uint ring_rows; + float eps; + uint off_feat; + uint off_fuse; + uint off_n0; + uint off_n1; + uint off_n2; + uint off_n3; + uint off_pos; + uint off_ring; + uint off_dst; +} p; + +shared float sumsh[16]; + +float load_norm(uint row, uint col) { + switch (row) { + case 0u: return norm0[p.off_n0 + col]; + case 1u: return norm1[p.off_n1 + col]; + case 2u: return norm2[p.off_n2 + col]; + default: return norm3[p.off_n3 + col]; + } +} + +void main() { + const uint tok = gl_WorkGroupID.x + gl_WorkGroupID.z * 65535u; + const uint row = gl_WorkGroupID.y; + const uint tid = gl_LocalInvocationID.x; + if (tok >= p.n_tokens || row >= 4u) { + return; + } + + // 1. Exact 4-element softmax matching soft_max.comp shared-memory binary tree + const uint fb = p.off_fuse + row * 4u; + const float f0 = data_fuse[fb + 0u]; + const float f1 = data_fuse[fb + 1u]; + const float f2 = data_fuse[fb + 2u]; + const float f3 = data_fuse[fb + 3u]; + const float mx = max(max(f0, f1), max(f2, f3)); + const float e0 = exp(f0 - mx); + const float e1 = exp(f1 - mx); + const float e2 = exp(f2 - mx); + const float e3 = exp(f3 - mx); + precise float es02 = e0 + e2; + precise float es13 = e1 + e3; + precise float esum = es02 + es13; + const float rcp = 1.0f / esum; + const float w0 = e0 * rcp; + const float w1 = e1 * rcp; + const float w2 = e2 * rcp; + const float w3 = e3 * rcp; + + // 2. Weighted feature sum + 512-lane / 16-subgroup RMS_NORM_MUL matching sum_rows.comp & rms_norm.comp (0-ULP) + const uint feat_base = p.off_feat + tok * (4u * p.n_embd); + float y_reg[8]; + float ss = 0.0f; + const uint num_blocks = (p.n_embd + 511u) >> 9u; + + for (uint idx = 0u; idx < num_blocks; ++idx) { + const uint col = tid + idx * 512u; + float y = 0.0f; + if (col < p.n_embd) { + const float x0 = data_feat[feat_base + 0u * p.n_embd + col]; + const float x1 = data_feat[feat_base + 1u * p.n_embd + col]; + const float x2 = data_feat[feat_base + 2u * p.n_embd + col]; + const float x3 = data_feat[feat_base + 3u * p.n_embd + col]; + precise float m0 = x0 * w0; + precise float m1 = x1 * w1; + precise float m2 = x2 * w2; + precise float m3 = x3 * w3; + precise float s02 = m0 + m2; + precise float s13 = m1 + m3; + precise float s = s02 + s13; + y = s; + } + if (idx < 8u) { + y_reg[idx] = y; + } + ss += y * y; + } + + ss = subgroupAdd(ss); + if (subgroupElect()) { + sumsh[gl_SubgroupID] = ss; + } + barrier(); + ss = 0.0f; + for (uint i = gl_SubgroupInvocationID; i < gl_NumSubgroups; i += gl_SubgroupSize) { + ss += sumsh[i]; + } + ss = subgroupAdd(ss); + + const float scale = inversesqrt(ss / float(p.n_embd) + p.eps); + const uint dst_base = p.off_dst + (row * p.n_tokens + tok) * p.n_embd; + + const bool write_ring = (row == 3u) && (p.has_ring != 0u); + bool valid_ring_tok = false; + uint ring_base = 0u; + if (write_ring) { + const int pos_i = data_pos[p.off_pos + tok]; + if (pos_i >= 0) { + valid_ring_tok = true; + const uint slot = p.ring_seq_offset + (uint(pos_i) % p.ring_rows); + ring_base = p.off_ring + slot * p.n_embd; + } + } + + for (uint idx = 0u; idx < num_blocks; ++idx) { + const uint col = tid + idx * 512u; + if (col < p.n_embd) { + float y; + if (idx < 8u) { + y = y_reg[idx]; + } else { + const float x0 = data_feat[feat_base + 0u * p.n_embd + col]; + const float x1 = data_feat[feat_base + 1u * p.n_embd + col]; + const float x2 = data_feat[feat_base + 2u * p.n_embd + col]; + const float x3 = data_feat[feat_base + 3u * p.n_embd + col]; + precise float m0 = x0 * w0; + precise float m1 = x1 * w1; + precise float m2 = x2 * w2; + precise float m3 = x3 * w3; + precise float s02 = m0 + m2; + precise float s13 = m1 + m3; + precise float s = s02 + s13; + y = s; + } + const float out_v = (y * scale) * load_norm(row, col); + data_dst[dst_base + col] = out_v; + if (valid_ring_tok) { + data_ring[ring_base + col] = out_v; + } + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_joint_gru.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_joint_gru.comp new file mode 100644 index 000000000000..937405a35db0 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_dspark_joint_gru.comp @@ -0,0 +1,215 @@ +#version 450 +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable +#extension GL_EXT_control_flow_attributes : enable + +layout(local_size_x = 128, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufPrev { int data_prev[]; }; +layout(binding = 1) readonly buffer BufW1U32 { uint w1_u32[]; }; +layout(binding = 1) readonly buffer BufW1F32 { float w1_f32[]; }; +layout(binding = 2) readonly buffer BufState { float data_state[]; }; +layout(binding = 3) readonly buffer BufHidden { float data_hid[]; }; +layout(binding = 4) readonly buffer BufCtx { float data_ctx[]; }; +layout(binding = 5) readonly buffer BufJpU32 { uint jp_u32[]; }; +layout(binding = 5) readonly buffer BufJpF32 { float jp_f32[]; }; +layout(binding = 6) readonly buffer BufBias { float data_bias[]; }; +layout(binding = 7) writeonly buffer BufDst { float data_dst[]; }; + +layout(push_constant) uniform PushConstants { + uint rank; + uint n_embd; + uint nb; + uint flags; // bit0: w1_is_bf16, bit1: jp_is_bf16, bit2: has_bias + uint off_prev; + uint off_w1; // in elements (BF16 or F32) + uint off_state; + uint off_hid; + uint off_ctx; + uint off_jp; // in elements (BF16 or F32) + uint off_bias; + uint off_dst; +} p; + +float unpack_bf16_elem(uint u32_word, uint hi) { + return (hi == 0u) + ? uintBitsToFloat((u32_word & 0x0000FFFFu) << 16u) + : uintBitsToFloat( u32_word & 0xFFFF0000u); +} + +float load_w1_1(uint idx) { + if ((p.flags & 1u) != 0u) { + const uint pos = p.off_w1 + idx; + return unpack_bf16_elem(w1_u32[pos >> 1u], pos & 1u); + } + return w1_f32[p.off_w1 + idx]; +} + +vec4 load_w1_4(uint idx) { + if ((p.flags & 1u) != 0u) { + const uint pos = p.off_w1 + idx; + if ((pos & 1u) == 0u) { + const uint a = w1_u32[pos >> 1u]; + const uint b = w1_u32[(pos >> 1u) + 1u]; + return vec4( + uintBitsToFloat((a & 0x0000FFFFu) << 16u), + uintBitsToFloat( a & 0xFFFF0000u), + uintBitsToFloat((b & 0x0000FFFFu) << 16u), + uintBitsToFloat( b & 0xFFFF0000u) + ); + } + } + return vec4(load_w1_1(idx), load_w1_1(idx + 1u), load_w1_1(idx + 2u), load_w1_1(idx + 3u)); +} + +float load_jp_1(uint idx) { + if ((p.flags & 2u) != 0u) { + const uint pos = p.off_jp + idx; + return unpack_bf16_elem(jp_u32[pos >> 1u], pos & 1u); + } + return jp_f32[p.off_jp + idx]; +} + +vec4 load_jp_4(uint idx) { + if ((p.flags & 2u) != 0u) { + const uint pos = p.off_jp + idx; + if ((pos & 1u) == 0u) { + const uint a = jp_u32[pos >> 1u]; + const uint b = jp_u32[(pos >> 1u) + 1u]; + return vec4( + uintBitsToFloat((a & 0x0000FFFFu) << 16u), + uintBitsToFloat( a & 0xFFFF0000u), + uintBitsToFloat((b & 0x0000FFFFu) << 16u), + uintBitsToFloat( b & 0xFFFF0000u) + ); + } + } + return vec4(load_jp_1(idx), load_jp_1(idx + 1u), load_jp_1(idx + 2u), load_jp_1(idx + 3u)); +} + +float load_x_1(uint b_idx, uint prev_id, uint k) { + if (k < p.rank) { + return data_state[p.off_state + b_idx * p.rank + k]; + } + const uint k1 = k - p.rank; + if (k1 < p.rank) { + return load_w1_1(prev_id * p.rank + k1); + } + const uint k2 = k1 - p.rank; + if (k2 < p.n_embd) { + return data_hid[p.off_hid + b_idx * p.n_embd + k2]; + } + const uint k3 = k2 - p.n_embd; + return data_ctx[p.off_ctx + b_idx * p.n_embd + k3]; +} + +vec4 load_x_4(uint b_idx, uint prev_id, uint k) { + if ((p.rank & 3u) == 0u && (p.n_embd & 3u) == 0u) { + if (k < p.rank) { + const uint base = p.off_state + b_idx * p.rank + k; + return vec4(data_state[base], data_state[base + 1u], data_state[base + 2u], data_state[base + 3u]); + } + const uint k1 = k - p.rank; + if (k1 < p.rank) { + return load_w1_4(prev_id * p.rank + k1); + } + const uint k2 = k1 - p.rank; + if (k2 < p.n_embd) { + const uint base = p.off_hid + b_idx * p.n_embd + k2; + return vec4(data_hid[base], data_hid[base + 1u], data_hid[base + 2u], data_hid[base + 3u]); + } + const uint k3 = k2 - p.n_embd; + const uint base = p.off_ctx + b_idx * p.n_embd + k3; + return vec4(data_ctx[base], data_ctx[base + 1u], data_ctx[base + 2u], data_ctx[base + 3u]); + } + return vec4( + load_x_1(b_idx, prev_id, k + 0u), + load_x_1(b_idx, prev_id, k + 1u), + load_x_1(b_idx, prev_id, k + 2u), + load_x_1(b_idx, prev_id, k + 3u) + ); +} + +void main() { + const uint sg = gl_SubgroupID; + const uint lane = gl_SubgroupInvocationID; + const uint col = gl_WorkGroupID.x * 4u + sg; + const uint b_idx = gl_WorkGroupID.y; + if (col >= p.rank || b_idx >= p.nb) { + return; + } + + const uint prev_id = uint(data_prev[p.off_prev + b_idx]); + const uint K = 2u * p.rank + 2u * p.n_embd; + const uint r0 = col; + const uint r1 = p.rank + col; + const uint r2 = 2u * p.rank + col; + + // Exact BLOCK_SIZE=32, K_PER_ITER=4 accumulation matching mul_mat_vec.comp (0-ULP) + float acc0 = 0.0f; + float acc1 = 0.0f; + float acc2 = 0.0f; + + const uint full_iters = K / 128u; + for (uint it = 0u; it < full_iters; ++it) { + const uint k = it * 128u + 4u * lane; + const vec4 xv = load_x_4(b_idx, prev_id, k); + acc0 += dot(load_jp_4(r0 * K + k), xv); + acc1 += dot(load_jp_4(r1 * K + k), xv); + acc2 += dot(load_jp_4(r2 * K + k), xv); + } + const uint tail_k = full_iters * 128u + 4u * lane; + if (tail_k < K) { + const uint rem = K - tail_k; + if (rem >= 4u) { + const vec4 xv = load_x_4(b_idx, prev_id, tail_k); + acc0 += dot(load_jp_4(r0 * K + tail_k), xv); + acc1 += dot(load_jp_4(r1 * K + tail_k), xv); + acc2 += dot(load_jp_4(r2 * K + tail_k), xv); + } else if (rem == 3u) { + const vec3 xv = vec3(load_x_1(b_idx, prev_id, tail_k), load_x_1(b_idx, prev_id, tail_k + 1u), load_x_1(b_idx, prev_id, tail_k + 2u)); + acc0 += dot(vec3(load_jp_1(r0 * K + tail_k), load_jp_1(r0 * K + tail_k + 1u), load_jp_1(r0 * K + tail_k + 2u)), xv); + acc1 += dot(vec3(load_jp_1(r1 * K + tail_k), load_jp_1(r1 * K + tail_k + 1u), load_jp_1(r1 * K + tail_k + 2u)), xv); + acc2 += dot(vec3(load_jp_1(r2 * K + tail_k), load_jp_1(r2 * K + tail_k + 1u), load_jp_1(r2 * K + tail_k + 2u)), xv); + } else if (rem == 2u) { + const vec2 xv = vec2(load_x_1(b_idx, prev_id, tail_k), load_x_1(b_idx, prev_id, tail_k + 1u)); + acc0 += dot(vec2(load_jp_1(r0 * K + tail_k), load_jp_1(r0 * K + tail_k + 1u)), xv); + acc1 += dot(vec2(load_jp_1(r1 * K + tail_k), load_jp_1(r1 * K + tail_k + 1u)), xv); + acc2 += dot(vec2(load_jp_1(r2 * K + tail_k), load_jp_1(r2 * K + tail_k + 1u)), xv); + } else { + const float xv = load_x_1(b_idx, prev_id, tail_k); + acc0 = fma(load_jp_1(r0 * K + tail_k), xv, acc0); + acc1 = fma(load_jp_1(r1 * K + tail_k), xv, acc1); + acc2 = fma(load_jp_1(r2 * K + tail_k), xv, acc2); + } + } + + acc0 = subgroupAdd(acc0); + acc1 = subgroupAdd(acc1); + acc2 = subgroupAdd(acc2); + + if (lane == 0u) { + const bool has_b = (p.flags & 4u) != 0u; + precise float j0 = has_b ? (acc0 + data_bias[p.off_bias + r0]) : acc0; + precise float j1 = has_b ? (acc1 + data_bias[p.off_bias + r1]) : acc1; + precise float j2 = has_b ? (acc2 + data_bias[p.off_bias + r2]) : acc2; + + const uint idx = b_idx * p.rank + col; + const float st = data_state[p.off_state + idx]; + + // Exact IEEE-754 rounding sequence matching inkling_dspark_gru.comp (0-ULP) + precise float neg_j0 = -j0; + precise float exp_j0 = exp(neg_j0); + precise float den_j0 = 1.0f + exp_j0; + precise float gate = 1.0f / den_j0; + precise float cand = tanh(j1); + precise float diff = st - cand; + precise float prod = gate * diff; + precise float st_new = cand + prod; + precise float latent = tanh(j2); + + const uint slice_elems = p.rank * p.nb; + data_dst[p.off_dst + idx] = st_new; + data_dst[p.off_dst + slice_elems + idx] = latent; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_l2_clip.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_l2_clip.comp new file mode 100644 index 000000000000..dd5b3cd867a2 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_l2_clip.comp @@ -0,0 +1,116 @@ +#version 450 +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable +#extension GL_KHR_shader_subgroup_shuffle : enable +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require + +layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in; + +struct block_q8_0_u16 { + float16_t d; + uint16_t qs16[16]; +}; + +layout(binding = 0) readonly buffer BufCur { float data_cur[]; }; +layout(binding = 1) readonly buffer BufScale { float data_scale[]; }; +layout(binding = 2) readonly buffer BufTau { float data_tau[]; }; +layout(binding = 3) writeonly buffer BufDst { float data_dst[]; }; +layout(binding = 3) writeonly buffer BufDst16 { float16_t data_dst16[]; }; +layout(binding = 3) writeonly buffer BufDstQ8 { block_q8_0_u16 data_dst_q8[]; }; +layout(binding = 4) readonly buffer BufIdx { uvec2 data_idx[]; }; + +layout(push_constant) uniform PushConstants { + uint ne0; + uint ne1; + uint ne2; + uint flags; // bit 0: has_scale, bit 1: has_tau, bit 2: set_rows, bit 3: dst_f16, bit 4: dst_q8_0 + uint off_cur; + uint off_scale; + uint off_tau; + uint off_dst; + float threshold; + float eps; + uint off_idx; + uint set_rows_nb1; +} p; + +void main() { + const uint row = gl_WorkGroupID.x + gl_WorkGroupID.y * 65535u; + if (row >= p.ne1 * p.ne2) { + return; + } + const uint lane = gl_LocalInvocationID.x; + const uint cur_base = p.off_cur + row * p.ne0; + const uint head = row % p.ne1; + const uint tok = row / p.ne1; + const uint sc_base = p.off_scale + head * p.ne0; + const bool has_sc = (p.flags & 1u) != 0u; + const bool has_tau = (p.flags & 2u) != 0u; + const bool do_sr = (p.flags & 4u) != 0u; + const bool dst_f16 = (p.flags & 8u) != 0u; + const bool dst_q8 = (p.flags & 16u) != 0u; + + const uint dst_base = do_sr + ? (p.off_dst + data_idx[p.off_idx + tok].x * p.set_rows_nb1 + head * (dst_q8 ? (p.ne0 >> 5u) : p.ne0)) + : (p.off_dst + row * p.ne0); + + float ss = 0.0f; + for (uint c = lane; c < p.ne0; c += 32u) { + float x = data_cur[cur_base + c]; + if (has_sc) { + x *= data_scale[sc_base + c]; + } + ss += x * x; + } + ss = subgroupAdd(ss); + const float norm = sqrt(ss) + p.eps; + const float factor = clamp(p.threshold / norm, 0.0f, 1.0f); + const float tau_v = has_tau ? data_tau[p.off_tau + tok] : 1.0f; + + if (dst_q8) { + const uint n_blks = p.ne0 >> 5u; + for (uint b = 0u; b < n_blks; ++b) { + const uint c = (b << 5u) + lane; + float x = data_cur[cur_base + c]; + if (has_sc) { + x *= data_scale[sc_base + c]; + } + float out_v = x * factor; + if (has_tau) { + out_v *= tau_v; + } + const float amax = subgroupMax(abs(out_v)); + const float d = amax / 127.0f; + const float id = (d != 0.0f) ? (1.0f / d) : 0.0f; + const uint qlo = uint(int(round(out_v * id))) & 0xFFu; + const uint qhi = subgroupShuffleXor(qlo, 1u); + const uint bi = dst_base + b; + if (lane == 0u) { + data_dst_q8[bi].d = float16_t(d); + } + if ((lane & 1u) == 0u) { + data_dst_q8[bi].qs16[lane >> 1u] = uint16_t(qlo | (qhi << 8u)); + } + } + return; + } + + for (uint c = lane; c < p.ne0; c += 32u) { + float x = data_cur[cur_base + c]; + if (has_sc) { + x *= data_scale[sc_base + c]; + } + float out_v = x * factor; + if (has_tau) { + out_v *= tau_v; + } + if (dst_f16) { + data_dst16[dst_base + c] = float16_t(out_v); + } else { + data_dst[dst_base + c] = out_v; + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_l2_clip_qr.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_l2_clip_qr.comp new file mode 100644 index 000000000000..67235795cccf --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_l2_clip_qr.comp @@ -0,0 +1,78 @@ +#version 450 +// S19_WAVE3 (mode = 12): Heterogeneous Q [q_ne0, n_head, N] + R [r_ne0, n_head, N] L2 clip in 1 dispatch +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable + +layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufQCur { float data_q[]; }; +layout(binding = 1) readonly buffer BufRCur { float data_r[]; }; +layout(binding = 2) readonly buffer BufQScale { float data_qs[]; }; +layout(binding = 3) readonly buffer BufRScale { float data_rs[]; }; +layout(binding = 4) readonly buffer BufTau { float data_tau[]; }; +layout(binding = 5) writeonly buffer BufDst { float data_dst[]; }; + +layout(push_constant) uniform PushConstants { + uint q_ne0; + uint r_ne0; + uint n_head; + uint n_tokens; + uint flags; // bit 0: has_q_scale, bit 1: has_r_scale, bit 2: has_tau + uint off_q; + uint off_r; + uint off_qs; + uint off_rs; + uint off_tau; + uint off_dst; + float q_threshold; + float r_threshold; + float eps; + uint q_tok_s; + uint r_tok_s; +} p; + +void main() { + const uint row = gl_WorkGroupID.x + gl_WorkGroupID.y * 65535u; + const uint q_rows = p.n_head * p.n_tokens; + if (row >= 2u * q_rows) { + return; + } + const uint lane = gl_LocalInvocationID.x; + const bool is_r = row >= q_rows; + const uint sub_row = is_r ? (row - q_rows) : row; + const uint head = sub_row % p.n_head; + const uint tok = sub_row / p.n_head; + const uint ne0 = is_r ? p.r_ne0 : p.q_ne0; + const bool has_sc = is_r ? ((p.flags & 2u) != 0u) : ((p.flags & 1u) != 0u); + const bool has_tau = (p.flags & 4u) != 0u; + const float thresh = is_r ? p.r_threshold : p.q_threshold; + const uint cur_b = is_r ? (p.off_r + tok * p.r_tok_s + head * p.r_ne0) + : (p.off_q + tok * p.q_tok_s + head * p.q_ne0); + const uint sc_b = (is_r ? p.off_rs : p.off_qs) + head * ne0; + const uint dst_b = p.off_dst + (is_r ? (q_rows * p.q_ne0 + sub_row * p.r_ne0) : (sub_row * p.q_ne0)); + + float ss = 0.0f; + for (uint c = lane; c < ne0; c += 32u) { + float x = is_r ? data_r[cur_b + c] : data_q[cur_b + c]; + if (has_sc) { + x *= is_r ? data_rs[sc_b + c] : data_qs[sc_b + c]; + } + ss += x * x; + } + ss = subgroupAdd(ss); + const float norm = sqrt(ss) + p.eps; + const float factor = clamp(thresh / norm, 0.0f, 1.0f); + const float tau_v = has_tau ? data_tau[p.off_tau + tok] : 1.0f; + + for (uint c = lane; c < ne0; c += 32u) { + float x = is_r ? data_r[cur_b + c] : data_q[cur_b + c]; + if (has_sc) { + x *= is_r ? data_rs[sc_b + c] : data_qs[sc_b + c]; + } + float out_v = x * factor; + if (has_tau) { + out_v *= tau_v; + } + data_dst[dst_b + c] = out_v; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_rel_gather.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_rel_gather.comp new file mode 100644 index 000000000000..d74bdc5e9e07 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_rel_gather.comp @@ -0,0 +1,90 @@ +#version 450 +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable + +layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufTable { float data_table[]; }; +layout(binding = 1) readonly buffer BufSinks { float data_sinks[]; }; +layout(binding = 2) readonly buffer BufRelPos { int data_rel_pos[]; }; +layout(binding = 3) readonly buffer BufMaskF16 { float16_t data_mask_f16[]; }; +layout(binding = 4) writeonly buffer BufDstF32 { float data_dst[]; }; +layout(binding = 4) writeonly buffer BufDstF16 { float16_t data_dst_f16[]; }; + +layout(push_constant) uniform PushConstants { + uint n_kv; + uint nr; + uint n_head; + uint n_stream; + uint n_seq_tokens; + uint r0; + uint table_len; + uint extent; + uint off_table; + uint off_sinks; + uint off_rel; + uint off_dst; + uint flags; // bit 0: out_f16, bit 1: has_mask, bit 2: span_compact, bit 3: span_neg_inf, bit 4: const_prefix + uint off_mask; // in f16 elements + uint mask_r0; + uint mask_ne1; + uint mask_ne2; + uint mask_ne3; + uint kv_min; + uint kv_limit; + uint kv_const_end; +} p; + +void main() { + const uint idx = gl_GlobalInvocationID.x + gl_WorkGroupID.y * (65535u * 256u); + const bool span_compact = (p.flags & 4u) != 0u; + const bool const_prefix = (p.flags & 16u) != 0u; + const uint span = const_prefix ? (1u + (p.kv_limit - p.kv_const_end)) + : (span_compact ? (p.kv_limit - p.kv_min) : p.n_kv); + const uint total = span * p.nr * p.n_head * p.n_stream; + if (idx >= total) { + return; + } + const uint s_idx = idx % span; + const uint kv_i = const_prefix ? ((s_idx == 0u) ? p.kv_min : (p.kv_const_end + (s_idx - 1u))) + : (span_compact ? (p.kv_min + s_idx) : s_idx); + const uint t1 = idx / span; + const uint dst_i = (span_compact || const_prefix) ? (t1 * p.n_kv + kv_i) : idx; + + if ((p.flags & 8u) != 0u && (kv_i < p.kv_min || kv_i >= p.kv_limit)) { + if ((p.flags & 1u) != 0u) { + data_dst_f16[p.off_dst + dst_i] = unpackFloat2x16(0xFC00FC00u).x; + } else { + data_dst[p.off_dst + dst_i] = uintBitsToFloat(0xFF800000u); + } + return; + } + const uint tok_r = t1 % p.nr; + const uint t2 = t1 / p.nr; + const uint h = t2 % p.n_head; + const uint s = t2 / p.n_head; + + const uint tok_seq = p.r0 + tok_r; + const uint tok_global = s * p.n_seq_tokens + tok_seq; + const int r = data_rel_pos[p.off_rel + tok_global * p.n_kv + kv_i]; + const float tval = (r >= 0 && uint(r) < p.extent && uint(r) < p.table_len) + ? data_table[p.off_table + (tok_global * p.n_head + h) * p.table_len + uint(r)] + : 0.0f; + const float sval = data_sinks[p.off_sinks + tok_global * p.n_head + h]; + precise float b = tval - sval; + + if ((p.flags & 2u) != 0u) { + const uint m2 = (p.mask_ne2 > 1u) ? (h % p.mask_ne2) : 0u; + const uint m3 = (p.mask_ne3 > 1u) ? (s % p.mask_ne3) : 0u; + const uint midx = p.off_mask + (((m3 * p.mask_ne2 + m2) * p.mask_ne1 + (p.mask_r0 + tok_r)) * p.n_kv + kv_i); + precise float mv = float(data_mask_f16[midx]); + precise float sum = b + mv; + b = sum; + } + + if ((p.flags & 1u) != 0u) { + data_dst_f16[p.off_dst + dst_i] = float16_t(b); + } else { + data_dst[p.off_dst + dst_i] = b; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_rms2_concat.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_rms2_concat.comp new file mode 100644 index 000000000000..20ed2cbf5198 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_rms2_concat.comp @@ -0,0 +1,60 @@ +#version 450 +// S19_WAVE3: multi-slice C=1|3 (gl_WorkGroupID.z = sl) with optional cur broadcast (cur_s2 = 0 on SWA) +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable + +layout(local_size_x = 128, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufCur { float data_cur[]; }; +layout(binding = 1) readonly buffer BufMsg { float data_msg[]; }; +layout(binding = 2) writeonly buffer BufDst { float data_dst[]; }; + +layout(push_constant) uniform PushConstants { + uint n_embd; + uint n_tokens; + uint off_cur; + uint off_msg; + uint off_dst; + float eps; + uint C; + uint cur_s2; + uint msg_s2; +} p; + +shared float sh_red[4][2]; + +void main() { + const uint tok = gl_WorkGroupID.x + gl_WorkGroupID.y * 65535u; + const uint sl = gl_WorkGroupID.z; + if (tok >= p.n_tokens || sl >= p.C) { + return; + } + const uint tid = gl_LocalInvocationID.x; + const uint cb = p.off_cur + sl * p.cur_s2 + tok * p.n_embd; + const uint mb = p.off_msg + sl * p.msg_s2 + tok * p.n_embd; + const uint db = p.off_dst + (sl * p.n_tokens + tok) * (2u * p.n_embd); + + float ss0 = 0.0f; + float ss1 = 0.0f; + for (uint c = tid; c < p.n_embd; c += 128u) { + const float x0 = data_cur[cb + c]; + const float x1 = data_msg[mb + c]; + ss0 += x0 * x0; + ss1 += x1 * x1; + } + ss0 = subgroupAdd(ss0); + ss1 = subgroupAdd(ss1); + if (gl_SubgroupInvocationID == 0u) { + sh_red[gl_SubgroupID][0] = ss0; + sh_red[gl_SubgroupID][1] = ss1; + } + barrier(); + const float inv_d = 1.0f / float(p.n_embd); + const float r0_inv = 1.0f / sqrt((sh_red[0][0] + sh_red[1][0] + sh_red[2][0] + sh_red[3][0]) * inv_d + p.eps); + const float r1_inv = 1.0f / sqrt((sh_red[0][1] + sh_red[1][1] + sh_red[2][1] + sh_red[3][1]) * inv_d + p.eps); + + for (uint c = tid; c < p.n_embd; c += 128u) { + data_dst[db + c] = data_cur[cb + c] * r0_inv; + data_dst[db + p.n_embd + c] = data_msg[mb + c] * r1_inv; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/inkling_softcap.comp b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_softcap.comp new file mode 100644 index 000000000000..285960ea9bf1 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/inkling_softcap.comp @@ -0,0 +1,53 @@ +#version 450 + +layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer BufSrc { float data_src[]; }; +layout(binding = 0) readonly buffer BufSrcV4 { vec4 data_src_v4[]; }; +layout(binding = 1) writeonly buffer BufDst { float data_dst[]; }; +layout(binding = 1) writeonly buffer BufDstV4 { vec4 data_dst_v4[]; }; + +layout(push_constant) uniform PushConstants { + uint total; + uint off_src; + uint off_dst; + float inv_cap; + float cap; + uint pad; +} p; + +float exact_softcap(float x) { + precise float s0 = x * p.inv_cap + 0.0f; + precise float t = tanh(s0); + precise float s1 = t * p.cap + 0.0f; + return s1; +} + +void main() { + const uint wg_id = gl_WorkGroupID.y * 65535u + gl_WorkGroupID.x; + const uint tid = gl_LocalInvocationID.x; + + if ((p.off_src & 3u) == 0u && (p.off_dst & 3u) == 0u) { + const uint n4 = p.total >> 2u; + const uint i4 = wg_id * 256u + tid; + if (i4 < n4) { + const vec4 v = data_src_v4[(p.off_src >> 2u) + i4]; + data_dst_v4[(p.off_dst >> 2u) + i4] = vec4( + exact_softcap(v.x), + exact_softcap(v.y), + exact_softcap(v.z), + exact_softcap(v.w) + ); + } else { + const uint i = (n4 << 2u) + (i4 - n4); + if (i < p.total) { + data_dst[p.off_dst + i] = exact_softcap(data_src[p.off_src + i]); + } + } + } else { + const uint idx = wg_id * 256u + tid; + if (idx < p.total) { + data_dst[p.off_dst + idx] = exact_softcap(data_src[p.off_src + idx]); + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec.comp index 34be1f72ba7b..d00c67ed7517 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec.comp @@ -1,11 +1,18 @@ #version 450 #extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#if defined(DATA_A_Q8_0) || defined(DATA_A_NVFP4) +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#endif #include "mul_mat_vec_base.glsl" #include "dequant_funcs.glsl" +#if defined(USE_SUBGROUP_ADD_NO_SHMEM) && !defined(NEEDS_INIT_IQ_SHMEM) +layout(local_size_x_id = 0, local_size_y_id = 4, local_size_z = 1) in; +#else layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; +#endif #if !defined(DATA_A_F32) && !defined(DATA_A_F16) && !defined(DATA_A_BF16) #define K_PER_ITER 8 @@ -36,9 +43,11 @@ vec4 load_b(const uint j, const uint iybs, const uint iqs, const bool lastiter, return vec4(FLOAT_TYPE(data_b[j*p.batch_stride_b + b_offset + iybs + iqs]), FLOAT_TYPE(data_b[j*p.batch_stride_b + b_offset + iybs + iqs + y_offset]), 0, 0); - } else { + } else if (!lastiter || iybs + iqs < p.ncols) { return vec4(FLOAT_TYPE(data_b[j*p.batch_stride_b + b_offset + iybs + iqs]), 0, 0, 0); + } else { + return vec4(0); } } @@ -69,14 +78,15 @@ void iter(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const const vec4 b = load_b(j, iybs, iqs, lastiter, OOB_y, OOB_z, OOB_w); #endif uint ibi = first_row*p.ncols; - [[unroll]] for (uint n = 0; n < num_rows; ++n) { - const uint ib = (ibi + col)/QUANT_K; // block index - ibi += p.ncols; + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = (ibi + rn*p.ncols + col)/QUANT_K; // block index #if K_PER_ITER == 8 vec4 v = dequantize4(ib, iqs, a_offset); vec4 v2 = dequantize4(ib, iqs+(4/QUANT_R), a_offset); +#if defined(DATA_A_Q4_1) || defined(DATA_A_Q5_1) const vec2 dm = get_dm(ib, a_offset); if (dm.y != 0) { // quant has min component v = v * dm.x + dm.y; @@ -89,6 +99,14 @@ void iter(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const if (dm.y == 0) rowtmp *= dm.x; +#elif defined(DATA_A_NVFP4) + FLOAT_TYPE rowtmp = dot(bv0, v); + rowtmp += dot(bv1, v2); +#else + FLOAT_TYPE rowtmp = dot(bv0, v); + rowtmp += dot(bv1, v2); + rowtmp *= get_dm(ib, a_offset).x; +#endif temp[j][n] += rowtmp; #else @@ -115,33 +133,642 @@ void iter(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const } #if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16) -void iter_aligned_nonquant(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const uint num_rows, const uint tid, const uint i) +vec4 dequantize4_2aligned_a2(uint ib, uint a_offset) { +#if defined(DATA_A_F32) + const vec2 a = data_a2_packed64[(a_offset + ib)/2]; + const vec2 b = data_a2_packed64[(a_offset + ib)/2 + 1]; + return vec4(a, b); +#elif defined(DATA_A_F16) + const vec2 a = data_a2_packed32[(a_offset + ib)/2]; + const vec2 b = data_a2_packed32[(a_offset + ib)/2 + 1]; + return vec4(a, b); +#else + const uint a = data_a2_packed32[(a_offset + ib)/2]; + const uint b = data_a2_packed32[(a_offset + ib)/2 + 1]; + return vec4(uintBitsToFloat((a & 0x0000ffff) << 16), + uintBitsToFloat( a & 0xffff0000), + uintBitsToFloat((b & 0x0000ffff) << 16), + uintBitsToFloat( b & 0xffff0000)); +#endif +} + +void iter_aligned_nonquant_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint first_row, const uint num_rows, const uint tid, const uint i) { - [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - const uint col = i*BLOCK_SIZE + K_PER_ITER*tid; - const uint iqs = 0; // quant index - const uint iybs = col; // y block start index + const uint col = i*BLOCK_SIZE + K_PER_ITER*tid; + uint ibi = first_row*p.ncols; + if (NUM_COLS <= 8) { + vec4 b_arr[8]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + b_arr[j] = data_b_v4[(j*p.batch_stride_b + b_offset + col) / 4]; + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = (ibi + rn*p.ncols + col)/QUANT_K; + const vec4 v = dequantize4_2aligned(ib, 0, a_offset); + vec4 u = vec4(0.0); + if (GEN_GLU == 3) { + u = dequantize4_2aligned_a2(ib, a_offset); + } + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + temp[j][n] += dot(v, b_arr[j]); + if (GEN_GLU == 3) { + temp2[j][n] += dot(u, b_arr[j]); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = (ibi + rn*p.ncols + col)/QUANT_K; + const vec4 v = dequantize4_2aligned(ib, 0, a_offset); + vec4 u = vec4(0.0); + if (GEN_GLU == 3) { + u = dequantize4_2aligned_a2(ib, a_offset); + } + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const vec4 b = data_b_v4[(j*p.batch_stride_b + b_offset + col) / 4]; + temp[j][n] += dot(v, b); + if (GEN_GLU == 3) { + temp2[j][n] += dot(u, b); + } + } + } + } +} - const vec4 b = data_b_v4[(j*p.batch_stride_b + b_offset + iybs + iqs) / 4]; +void iter_aligned_nonquant_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const uint num_rows, const uint tid, const uint i) +{ + const uint col = i*BLOCK_SIZE + K_PER_ITER*tid; + uint ibi = first_row*p.ncols; + if (NUM_COLS <= 4) { + vec4 b_arr[4]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + b_arr[j] = data_b_v4[(j*p.batch_stride_b + b_offset + col) / 4]; + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = (ibi + rn*p.ncols + col)/QUANT_K; + const vec4 v = dequantize4_2aligned_a2(ib, a_offset); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + temp[j][n] += dot(v, b_arr[j]); + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = (ibi + rn*p.ncols + col)/QUANT_K; + const vec4 v = dequantize4_2aligned_a2(ib, a_offset); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const vec4 b = data_b_v4[(j*p.batch_stride_b + b_offset + col) / 4]; + temp[j][n] += dot(v, b); + } + } + } +} +#endif - uint ibi = first_row*p.ncols; - [[unroll]] for (uint n = 0; n < num_rows; ++n) { - const uint ib = (ibi + col)/QUANT_K; // block index - ibi += p.ncols; +#if defined(DATA_A_NVFP4) && !defined(USE_OCP_FP4) +vec4 nvfp4_decode_nibs(const uint qs_shifted) { + const f16vec2 ev = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(qs_shifted)); + const f16vec2 od = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(qs_shifted >> 8u)); + return vec4(ev.x, od.x, ev.y, od.y); +} - const vec4 v = dequantize4_2aligned(ib, iqs, a_offset); +float nvfp4_decode_scale(const uint d_u32, const uint sub) { + const uint du = (d_u32 >> (sub * 8u)) & 0xFFu; + return ue4m3_to_fp32_build(du); +} - // matrix multiplication - temp[j][n] += dot(v, b); +#ifdef REPACK_PLANAR +void nvfp4_load_planar_a(const uint b_in_slice, const uint sub, const uint shift, out float da, out vec4 v0, out vec4 v1) { +#ifdef MUL_MAT_ID + const uint s_blks = p.batch_stride_a >> 6u; +#else + const uint s_blks = (p.ncols >> 6u) * ((GEN_GLU == 2u) ? p.pair_m0 : p.stride_d); +#endif + const uint slice_u32 = a_offset * 9u; + const uint slice_u2 = slice_u32 >> 1u; + da = nvfp4_decode_scale(data_a_repack_u32[slice_u32 + s_blks * 8u + b_in_slice], sub); + const uvec2 q01 = data_a_repack_u2[slice_u2 + b_in_slice * 4u + sub]; + v0 = nvfp4_decode_nibs(q01.x >> shift); + v1 = nvfp4_decode_nibs(q01.y >> shift); +} + +void nvfp4_load_planar_a2(const uint b_in_slice, const uint sub, const uint shift, out float da, out vec4 v0, out vec4 v1) { +#ifdef MUL_MAT_ID + const uint s_blks = p.batch_stride_a >> 6u; +#else + const uint s_blks = (p.ncols >> 6u) * ((GEN_GLU == 2u) ? p.stride_d2 : p.stride_d); +#endif + const uint slice_u32 = a_offset * 9u; + const uint slice_u2 = slice_u32 >> 1u; + da = nvfp4_decode_scale(data_a2_repack_u32[slice_u32 + s_blks * 8u + b_in_slice], sub); + const uvec2 q01 = data_a2_repack_u2[slice_u2 + b_in_slice * 4u + sub]; + v0 = nvfp4_decode_nibs(q01.x >> shift); + v1 = nvfp4_decode_nibs(q01.y >> shift); +} +#endif + +void iter_aligned_nvfp4_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint row_base, const uint num_rows, const uint tid, const uint iter_idx) { + const uint b_col4 = iter_idx * (2u * BLOCK_SIZE) + 2u * tid; + const uint lane8 = tid & 7u; + const uint sub = lane8 >> 1u; + const uint shift = (lane8 & 1u) * 4u; + const uint ib_col = iter_idx * (BLOCK_SIZE >> 3u) + (tid >> 3u); + const uint blocks_per_row = p.ncols >> 6u; + + if (NUM_COLS <= 4) { + vec4 bv0_arr[NUM_COLS]; + vec4 bv1_arr[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2u; + bv0_arr[j] = vec4(data_b_v4[b4 + b_col4]); + bv1_arr[j] = vec4(data_b_v4[b4 + b_col4 + 1u]); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0u || n < num_rows) ? n : 0u; +#ifdef REPACK_PLANAR + const uint b_in_slice = (row_base + rn) * blocks_per_row + ib_col; + float da; vec4 v0, v1; + nvfp4_load_planar_a(b_in_slice, sub, shift, da, v0, v1); +#else + const uint ib = a_offset + (row_base + rn) * blocks_per_row + ib_col; + const float da = nvfp4_decode_scale(data_a_packed32[ib].d[0], sub); + const vec4 v0 = nvfp4_decode_nibs(data_a_packed32[ib].qs[2u * sub + 0u] >> shift); + const vec4 v1 = nvfp4_decode_nibs(data_a_packed32[ib].qs[2u * sub + 1u] >> shift); +#endif + vec4 u0 = vec4(0.0), u1 = vec4(0.0); + float da2 = 0.0f; + if (GEN_GLU == 3) { +#ifdef MUL_MAT_ID + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u) { +#ifdef REPACK_PLANAR + nvfp4_load_planar_a(b_in_slice + p.stride_d * blocks_per_row, sub, shift, da2, u0, u1); +#else + const uint ib_u = ib + p.stride_d * blocks_per_row; + da2 = nvfp4_decode_scale(data_a_packed32[ib_u].d[0], sub); + u0 = nvfp4_decode_nibs(data_a_packed32[ib_u].qs[2u * sub + 0u] >> shift); + u1 = nvfp4_decode_nibs(data_a_packed32[ib_u].qs[2u * sub + 1u] >> shift); +#endif + } else +#endif + { +#ifdef REPACK_PLANAR + nvfp4_load_planar_a2(b_in_slice, sub, shift, da2, u0, u1); +#else + da2 = nvfp4_decode_scale(data_a2_packed32[ib].d[0], sub); + u0 = nvfp4_decode_nibs(data_a2_packed32[ib].qs[2u * sub + 0u] >> shift); + u1 = nvfp4_decode_nibs(data_a2_packed32[ib].qs[2u * sub + 1u] >> shift); +#endif + } + } + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + temp[j][n] += FLOAT_TYPE((dot(bv0_arr[j], v0) + dot(bv1_arr[j], v1)) * da); + if (GEN_GLU == 3) { + temp2[j][n] += FLOAT_TYPE((dot(bv0_arr[j], u0) + dot(bv1_arr[j], u1)) * da2); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0u || n < num_rows) ? n : 0u; +#ifdef REPACK_PLANAR + const uint b_in_slice = (row_base + rn) * blocks_per_row + ib_col; + float da; vec4 v0, v1; + nvfp4_load_planar_a(b_in_slice, sub, shift, da, v0, v1); +#else + const uint ib = a_offset + (row_base + rn) * blocks_per_row + ib_col; + const float da = nvfp4_decode_scale(data_a_packed32[ib].d[0], sub); + const vec4 v0 = nvfp4_decode_nibs(data_a_packed32[ib].qs[2u * sub + 0u] >> shift); + const vec4 v1 = nvfp4_decode_nibs(data_a_packed32[ib].qs[2u * sub + 1u] >> shift); +#endif + vec4 u0 = vec4(0.0), u1 = vec4(0.0); + float da2 = 0.0f; + if (GEN_GLU == 3) { +#ifdef MUL_MAT_ID + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u) { +#ifdef REPACK_PLANAR + nvfp4_load_planar_a(b_in_slice + p.stride_d * blocks_per_row, sub, shift, da2, u0, u1); +#else + const uint ib_u = ib + p.stride_d * blocks_per_row; + da2 = nvfp4_decode_scale(data_a_packed32[ib_u].d[0], sub); + u0 = nvfp4_decode_nibs(data_a_packed32[ib_u].qs[2u * sub + 0u] >> shift); + u1 = nvfp4_decode_nibs(data_a_packed32[ib_u].qs[2u * sub + 1u] >> shift); +#endif + } else +#endif + { +#ifdef REPACK_PLANAR + nvfp4_load_planar_a2(b_in_slice, sub, shift, da2, u0, u1); +#else + da2 = nvfp4_decode_scale(data_a2_packed32[ib].d[0], sub); + u0 = nvfp4_decode_nibs(data_a2_packed32[ib].qs[2u * sub + 0u] >> shift); + u1 = nvfp4_decode_nibs(data_a2_packed32[ib].qs[2u * sub + 1u] >> shift); +#endif + } + } + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2u; + const vec4 bv0 = vec4(data_b_v4[b4 + b_col4]); + const vec4 bv1 = vec4(data_b_v4[b4 + b_col4 + 1u]); + temp[j][n] += FLOAT_TYPE((dot(bv0, v0) + dot(bv1, v1)) * da); + if (GEN_GLU == 3) { + temp2[j][n] += FLOAT_TYPE((dot(bv0, u0) + dot(bv1, u1)) * da2); + } + } + } + } +} + +void iter_aligned_nvfp4_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint row_base, const uint num_rows, const uint tid, const uint iter_idx) { + const uint b_col4 = iter_idx * (2u * BLOCK_SIZE) + 2u * tid; + const uint lane8 = tid & 7u; + const uint sub = lane8 >> 1u; + const uint shift = (lane8 & 1u) * 4u; + const uint ib_col = iter_idx * (BLOCK_SIZE >> 3u) + (tid >> 3u); + const uint blocks_per_row = p.ncols >> 6u; + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0u || n < num_rows) ? n : 0u; +#ifdef REPACK_PLANAR + const uint b_in_slice = (row_base + rn) * blocks_per_row + ib_col; + float da; vec4 v0, v1; + nvfp4_load_planar_a2(b_in_slice, sub, shift, da, v0, v1); +#else + const uint ib = a_offset + (row_base + rn) * blocks_per_row + ib_col; + const float da = nvfp4_decode_scale(data_a2_packed32[ib].d[0], sub); + const vec4 v0 = nvfp4_decode_nibs(data_a2_packed32[ib].qs[2u * sub + 0u] >> shift); + const vec4 v1 = nvfp4_decode_nibs(data_a2_packed32[ib].qs[2u * sub + 1u] >> shift); +#endif + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2u; + const vec4 bv0 = vec4(data_b_v4[b4 + b_col4]); + const vec4 bv1 = vec4(data_b_v4[b4 + b_col4 + 1u]); + temp[j][n] += FLOAT_TYPE((dot(bv0, v0) + dot(bv1, v1)) * da); } } } #endif +#if defined(DATA_A_Q8_0) +vec4 q8_0_decode_magic(const i16vec2 qh) +{ + const uint biased = pack32(qh) ^ 0x80808080u; + const f16vec2 ev = unpackFloat2x16((biased & 0x00FF00FFu) | 0x64006400u) - f16vec2(1152.0); + const f16vec2 od = unpackFloat2x16(((biased >> 8u) & 0x00FF00FFu) | 0x64006400u) - f16vec2(1152.0); + return vec4(ev.x, od.x, ev.y, od.y); +} + +void iter_aligned_q8_0_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint row_base, const uint num_rows, const uint tid, const uint iter_idx) +{ + const uint b_col4 = iter_idx * (2 * BLOCK_SIZE) + 2 * tid; + const uint iqs_h = 4 * (tid & 3); + const uint ib_col = iter_idx * (BLOCK_SIZE >> 2) + (tid >> 2); + const uint blocks_per_row = p.ncols >> 5; + + if (NUM_COLS <= 4) { + vec4 bv0_arr[NUM_COLS]; + vec4 bv1_arr[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + bv0_arr[j] = vec4(data_b_v4[b4 + b_col4]); + bv1_arr[j] = vec4(data_b_v4[b4 + b_col4 + 1]); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (row_base + rn) * blocks_per_row + ib_col; + const vec4 v = q8_0_decode_magic(i16vec2(data_a_packed16[ib].qs[iqs_h ], data_a_packed16[ib].qs[iqs_h + 1])); + const vec4 v2 = q8_0_decode_magic(i16vec2(data_a_packed16[ib].qs[iqs_h + 2], data_a_packed16[ib].qs[iqs_h + 3])); + const FLOAT_TYPE da = float(data_a_packed16[ib].d); + vec4 u = vec4(0.0), u2 = vec4(0.0); + FLOAT_TYPE da2 = FLOAT_TYPE(0); + if (GEN_GLU == 3) { +#ifdef MUL_MAT_ID + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u) { + const uint ib_u = ib + p.stride_d * blocks_per_row; + u = q8_0_decode_magic(i16vec2(data_a_packed16[ib_u].qs[iqs_h ], data_a_packed16[ib_u].qs[iqs_h + 1])); + u2 = q8_0_decode_magic(i16vec2(data_a_packed16[ib_u].qs[iqs_h + 2], data_a_packed16[ib_u].qs[iqs_h + 3])); + da2 = float(data_a_packed16[ib_u].d); + } else +#endif + { + u = q8_0_decode_magic(i16vec2(data_a2_packed16[ib].qs[iqs_h ], data_a2_packed16[ib].qs[iqs_h + 1])); + u2 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib].qs[iqs_h + 2], data_a2_packed16[ib].qs[iqs_h + 3])); + da2 = float(data_a2_packed16[ib].d); + } + } + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE rowtmp = (dot(bv0_arr[j], v) + dot(bv1_arr[j], v2)) * da; + temp[j][n] += rowtmp; + if (GEN_GLU == 3) { + const FLOAT_TYPE rowtmp2 = (dot(bv0_arr[j], u) + dot(bv1_arr[j], u2)) * da2; + temp2[j][n] += rowtmp2; + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (row_base + rn) * blocks_per_row + ib_col; + const vec4 v = q8_0_decode_magic(i16vec2(data_a_packed16[ib].qs[iqs_h ], data_a_packed16[ib].qs[iqs_h + 1])); + const vec4 v2 = q8_0_decode_magic(i16vec2(data_a_packed16[ib].qs[iqs_h + 2], data_a_packed16[ib].qs[iqs_h + 3])); + const FLOAT_TYPE da = float(data_a_packed16[ib].d); + vec4 u = vec4(0.0), u2 = vec4(0.0); + FLOAT_TYPE da2 = FLOAT_TYPE(0); + if (GEN_GLU == 3) { +#ifdef MUL_MAT_ID + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u) { + const uint ib_u = ib + p.stride_d * blocks_per_row; + u = q8_0_decode_magic(i16vec2(data_a_packed16[ib_u].qs[iqs_h ], data_a_packed16[ib_u].qs[iqs_h + 1])); + u2 = q8_0_decode_magic(i16vec2(data_a_packed16[ib_u].qs[iqs_h + 2], data_a_packed16[ib_u].qs[iqs_h + 3])); + da2 = float(data_a_packed16[ib_u].d); + } else +#endif + { + u = q8_0_decode_magic(i16vec2(data_a2_packed16[ib].qs[iqs_h ], data_a2_packed16[ib].qs[iqs_h + 1])); + u2 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib].qs[iqs_h + 2], data_a2_packed16[ib].qs[iqs_h + 3])); + da2 = float(data_a2_packed16[ib].d); + } + } + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + const vec4 bv0 = vec4(data_b_v4[b4 + b_col4]); + const vec4 bv1 = vec4(data_b_v4[b4 + b_col4 + 1]); + const FLOAT_TYPE rowtmp = (dot(bv0, v) + dot(bv1, v2)) * da; + temp[j][n] += rowtmp; + if (GEN_GLU == 3) { + const FLOAT_TYPE rowtmp2 = (dot(bv0, u) + dot(bv1, u2)) * da2; + temp2[j][n] += rowtmp2; + } + } + } + } +} + +void iter_aligned_q8_0_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint row_base, const uint num_rows, const uint tid, const uint iter_idx) +{ + const uint b_col4 = iter_idx * (2 * BLOCK_SIZE) + 2 * tid; + const uint iqs_h = 4 * (tid & 3); + const uint ib_col = iter_idx * (BLOCK_SIZE >> 2) + (tid >> 2); + const uint blocks_per_row = p.ncols >> 5; + + if (NUM_COLS <= 4) { + vec4 bv0_arr[NUM_COLS]; + vec4 bv1_arr[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + bv0_arr[j] = vec4(data_b_v4[b4 + b_col4]); + bv1_arr[j] = vec4(data_b_v4[b4 + b_col4 + 1]); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (row_base + rn) * blocks_per_row + ib_col; + const vec4 v = q8_0_decode_magic(i16vec2(data_a2_packed16[ib].qs[iqs_h ], data_a2_packed16[ib].qs[iqs_h + 1])); + const vec4 v2 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib].qs[iqs_h + 2], data_a2_packed16[ib].qs[iqs_h + 3])); + const FLOAT_TYPE da = float(data_a2_packed16[ib].d); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE rowtmp = (dot(bv0_arr[j], v) + dot(bv1_arr[j], v2)) * da; + temp[j][n] += rowtmp; + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (row_base + rn) * blocks_per_row + ib_col; + const vec4 v = q8_0_decode_magic(i16vec2(data_a2_packed16[ib].qs[iqs_h ], data_a2_packed16[ib].qs[iqs_h + 1])); + const vec4 v2 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib].qs[iqs_h + 2], data_a2_packed16[ib].qs[iqs_h + 3])); + const FLOAT_TYPE da = float(data_a2_packed16[ib].d); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + const vec4 bv0 = vec4(data_b_v4[b4 + b_col4]); + const vec4 bv1 = vec4(data_b_v4[b4 + b_col4 + 1]); + const FLOAT_TYPE rowtmp = (dot(bv0, v) + dot(bv1, v2)) * da; + temp[j][n] += rowtmp; + } + } + } +} + +void iter2_aligned_q8_0_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint row_base, const uint num_rows, const uint tid, const uint iter_idx) +{ + const uint b_col4_0 = iter_idx * (2 * BLOCK_SIZE) + 2 * tid; + const uint b_col4_1 = b_col4_0 + (2 * BLOCK_SIZE); + const uint iqs_h = 4 * (tid & 3); + const uint ib_col_0 = iter_idx * (BLOCK_SIZE >> 2) + (tid >> 2); + const uint ib_col_1 = ib_col_0 + (BLOCK_SIZE >> 2); + const uint blocks_per_row = p.ncols >> 5; + + if (NUM_ROWS == 1 && NUM_COLS > 1 && NUM_COLS <= 4) { + const uint row_off = a_offset + row_base * blocks_per_row; + const uint ib0 = row_off + ib_col_0; + const vec4 v0_0 = q8_0_decode_magic(i16vec2(data_a_packed16[ib0].qs[iqs_h ], data_a_packed16[ib0].qs[iqs_h + 1])); + const vec4 v1_0 = q8_0_decode_magic(i16vec2(data_a_packed16[ib0].qs[iqs_h + 2], data_a_packed16[ib0].qs[iqs_h + 3])); + const FLOAT_TYPE da0 = float(data_a_packed16[ib0].d); + vec4 w0_0 = vec4(0.0), w1_0 = vec4(0.0); + FLOAT_TYPE du0 = FLOAT_TYPE(0); + if (GEN_GLU == 3) { +#ifdef MUL_MAT_ID + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u) { + const uint ib0_u = ib0 + p.stride_d * blocks_per_row; + w0_0 = q8_0_decode_magic(i16vec2(data_a_packed16[ib0_u].qs[iqs_h ], data_a_packed16[ib0_u].qs[iqs_h + 1])); + w1_0 = q8_0_decode_magic(i16vec2(data_a_packed16[ib0_u].qs[iqs_h + 2], data_a_packed16[ib0_u].qs[iqs_h + 3])); + du0 = float(data_a_packed16[ib0_u].d); + } else +#endif + { + w0_0 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib0].qs[iqs_h ], data_a2_packed16[ib0].qs[iqs_h + 1])); + w1_0 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib0].qs[iqs_h + 2], data_a2_packed16[ib0].qs[iqs_h + 3])); + du0 = float(data_a2_packed16[ib0].d); + } + } + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + const vec4 bv0 = vec4(data_b_v4[b4 + b_col4_0]); + const vec4 bv1 = vec4(data_b_v4[b4 + b_col4_0 + 1]); + temp[j][0] += (dot(bv0, v0_0) + dot(bv1, v1_0)) * da0; + if (GEN_GLU == 3) { + temp2[j][0] += (dot(bv0, w0_0) + dot(bv1, w1_0)) * du0; + } + } + + const uint ib1 = row_off + ib_col_1; + const vec4 v0_1 = q8_0_decode_magic(i16vec2(data_a_packed16[ib1].qs[iqs_h ], data_a_packed16[ib1].qs[iqs_h + 1])); + const vec4 v1_1 = q8_0_decode_magic(i16vec2(data_a_packed16[ib1].qs[iqs_h + 2], data_a_packed16[ib1].qs[iqs_h + 3])); + const FLOAT_TYPE da1 = float(data_a_packed16[ib1].d); + vec4 w0_1 = vec4(0.0), w1_1 = vec4(0.0); + FLOAT_TYPE du1 = FLOAT_TYPE(0); + if (GEN_GLU == 3) { +#ifdef MUL_MAT_ID + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u) { + const uint ib1_u = ib1 + p.stride_d * blocks_per_row; + w0_1 = q8_0_decode_magic(i16vec2(data_a_packed16[ib1_u].qs[iqs_h ], data_a_packed16[ib1_u].qs[iqs_h + 1])); + w1_1 = q8_0_decode_magic(i16vec2(data_a_packed16[ib1_u].qs[iqs_h + 2], data_a_packed16[ib1_u].qs[iqs_h + 3])); + du1 = float(data_a_packed16[ib1_u].d); + } else +#endif + { + w0_1 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib1].qs[iqs_h ], data_a2_packed16[ib1].qs[iqs_h + 1])); + w1_1 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib1].qs[iqs_h + 2], data_a2_packed16[ib1].qs[iqs_h + 3])); + du1 = float(data_a2_packed16[ib1].d); + } + } + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + const vec4 bv0 = vec4(data_b_v4[b4 + b_col4_1]); + const vec4 bv1 = vec4(data_b_v4[b4 + b_col4_1 + 1]); + temp[j][0] += (dot(bv0, v0_1) + dot(bv1, v1_1)) * da1; + if (GEN_GLU == 3) { + temp2[j][0] += (dot(bv0, w0_1) + dot(bv1, w1_1)) * du1; + } + } + } else if (NUM_COLS <= 4) { + vec4 bv0_0[NUM_COLS], bv1_0[NUM_COLS]; + vec4 bv0_1[NUM_COLS], bv1_1[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + bv0_0[j] = vec4(data_b_v4[b4 + b_col4_0]); + bv1_0[j] = vec4(data_b_v4[b4 + b_col4_0 + 1]); + bv0_1[j] = vec4(data_b_v4[b4 + b_col4_1]); + bv1_1[j] = vec4(data_b_v4[b4 + b_col4_1 + 1]); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint row_off = a_offset + (row_base + rn) * blocks_per_row; + const uint ib0 = row_off + ib_col_0; + const uint ib1 = row_off + ib_col_1; + const vec4 v0_0 = q8_0_decode_magic(i16vec2(data_a_packed16[ib0].qs[iqs_h ], data_a_packed16[ib0].qs[iqs_h + 1])); + const vec4 v1_0 = q8_0_decode_magic(i16vec2(data_a_packed16[ib0].qs[iqs_h + 2], data_a_packed16[ib0].qs[iqs_h + 3])); + const FLOAT_TYPE da0 = float(data_a_packed16[ib0].d); + const vec4 v0_1 = q8_0_decode_magic(i16vec2(data_a_packed16[ib1].qs[iqs_h ], data_a_packed16[ib1].qs[iqs_h + 1])); + const vec4 v1_1 = q8_0_decode_magic(i16vec2(data_a_packed16[ib1].qs[iqs_h + 2], data_a_packed16[ib1].qs[iqs_h + 3])); + const FLOAT_TYPE da1 = float(data_a_packed16[ib1].d); + + vec4 w0_0 = vec4(0.0), w1_0 = vec4(0.0), w0_1 = vec4(0.0), w1_1 = vec4(0.0); + FLOAT_TYPE du0 = FLOAT_TYPE(0), du1 = FLOAT_TYPE(0); + if (GEN_GLU == 3) { +#ifdef MUL_MAT_ID + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u) { + const uint ib0_u = ib0 + p.stride_d * blocks_per_row; + const uint ib1_u = ib1 + p.stride_d * blocks_per_row; + w0_0 = q8_0_decode_magic(i16vec2(data_a_packed16[ib0_u].qs[iqs_h ], data_a_packed16[ib0_u].qs[iqs_h + 1])); + w1_0 = q8_0_decode_magic(i16vec2(data_a_packed16[ib0_u].qs[iqs_h + 2], data_a_packed16[ib0_u].qs[iqs_h + 3])); + du0 = float(data_a_packed16[ib0_u].d); + w0_1 = q8_0_decode_magic(i16vec2(data_a_packed16[ib1_u].qs[iqs_h ], data_a_packed16[ib1_u].qs[iqs_h + 1])); + w1_1 = q8_0_decode_magic(i16vec2(data_a_packed16[ib1_u].qs[iqs_h + 2], data_a_packed16[ib1_u].qs[iqs_h + 3])); + du1 = float(data_a_packed16[ib1_u].d); + } else +#endif + { + w0_0 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib0].qs[iqs_h ], data_a2_packed16[ib0].qs[iqs_h + 1])); + w1_0 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib0].qs[iqs_h + 2], data_a2_packed16[ib0].qs[iqs_h + 3])); + du0 = float(data_a2_packed16[ib0].d); + w0_1 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib1].qs[iqs_h ], data_a2_packed16[ib1].qs[iqs_h + 1])); + w1_1 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib1].qs[iqs_h + 2], data_a2_packed16[ib1].qs[iqs_h + 3])); + du1 = float(data_a2_packed16[ib1].d); + } + } + + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE d0 = (dot(bv0_0[j], v0_0) + dot(bv1_0[j], v1_0)) * da0; + const FLOAT_TYPE d1 = (dot(bv0_1[j], v0_1) + dot(bv1_1[j], v1_1)) * da1; + temp[j][n] = (temp[j][n] + d0) + d1; + if (GEN_GLU == 3) { + const FLOAT_TYPE e0 = (dot(bv0_0[j], w0_0) + dot(bv1_0[j], w1_0)) * du0; + const FLOAT_TYPE e1 = (dot(bv0_1[j], w0_1) + dot(bv1_1[j], w1_1)) * du1; + temp2[j][n] = (temp2[j][n] + e0) + e1; + } + } + } + } else { + iter_aligned_q8_0_a(temp, temp2, row_base, num_rows, tid, iter_idx); + iter_aligned_q8_0_a(temp, temp2, row_base, num_rows, tid, iter_idx + 1); + } +} + +void iter2_aligned_q8_0_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint row_base, const uint num_rows, const uint tid, const uint iter_idx) +{ + const uint b_col4_0 = iter_idx * (2 * BLOCK_SIZE) + 2 * tid; + const uint b_col4_1 = b_col4_0 + (2 * BLOCK_SIZE); + const uint iqs_h = 4 * (tid & 3); + const uint ib_col_0 = iter_idx * (BLOCK_SIZE >> 2) + (tid >> 2); + const uint ib_col_1 = ib_col_0 + (BLOCK_SIZE >> 2); + const uint blocks_per_row = p.ncols >> 5; + + if (NUM_ROWS == 1 && NUM_COLS > 1 && NUM_COLS <= 4) { + const uint row_off = a_offset + row_base * blocks_per_row; + const uint ib0 = row_off + ib_col_0; + const vec4 v0_0 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib0].qs[iqs_h ], data_a2_packed16[ib0].qs[iqs_h + 1])); + const vec4 v1_0 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib0].qs[iqs_h + 2], data_a2_packed16[ib0].qs[iqs_h + 3])); + const FLOAT_TYPE da0 = float(data_a2_packed16[ib0].d); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + const vec4 bv0 = vec4(data_b_v4[b4 + b_col4_0]); + const vec4 bv1 = vec4(data_b_v4[b4 + b_col4_0 + 1]); + temp[j][0] += (dot(bv0, v0_0) + dot(bv1, v1_0)) * da0; + } + + const uint ib1 = row_off + ib_col_1; + const vec4 v0_1 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib1].qs[iqs_h ], data_a2_packed16[ib1].qs[iqs_h + 1])); + const vec4 v1_1 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib1].qs[iqs_h + 2], data_a2_packed16[ib1].qs[iqs_h + 3])); + const FLOAT_TYPE da1 = float(data_a2_packed16[ib1].d); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + const vec4 bv0 = vec4(data_b_v4[b4 + b_col4_1]); + const vec4 bv1 = vec4(data_b_v4[b4 + b_col4_1 + 1]); + temp[j][0] += (dot(bv0, v0_1) + dot(bv1, v1_1)) * da1; + } + } else if (NUM_COLS <= 4) { + vec4 bv0_0[NUM_COLS], bv1_0[NUM_COLS]; + vec4 bv0_1[NUM_COLS], bv1_1[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset) >> 2; + bv0_0[j] = vec4(data_b_v4[b4 + b_col4_0]); + bv1_0[j] = vec4(data_b_v4[b4 + b_col4_0 + 1]); + bv0_1[j] = vec4(data_b_v4[b4 + b_col4_1]); + bv1_1[j] = vec4(data_b_v4[b4 + b_col4_1 + 1]); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint row_off = a_offset + (row_base + rn) * blocks_per_row; + const uint ib0 = row_off + ib_col_0; + const uint ib1 = row_off + ib_col_1; + const vec4 v0_0 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib0].qs[iqs_h ], data_a2_packed16[ib0].qs[iqs_h + 1])); + const vec4 v1_0 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib0].qs[iqs_h + 2], data_a2_packed16[ib0].qs[iqs_h + 3])); + const FLOAT_TYPE da0 = float(data_a2_packed16[ib0].d); + const vec4 v0_1 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib1].qs[iqs_h ], data_a2_packed16[ib1].qs[iqs_h + 1])); + const vec4 v1_1 = q8_0_decode_magic(i16vec2(data_a2_packed16[ib1].qs[iqs_h + 2], data_a2_packed16[ib1].qs[iqs_h + 3])); + const FLOAT_TYPE da1 = float(data_a2_packed16[ib1].d); + + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE d0 = (dot(bv0_0[j], v0_0) + dot(bv1_0[j], v1_0)) * da0; + const FLOAT_TYPE d1 = (dot(bv0_1[j], v0_1) + dot(bv1_1[j], v1_1)) * da1; + temp[j][n] = (temp[j][n] + d0) + d1; + } + } + } else { + iter_aligned_q8_0_a2(temp, row_base, num_rows, tid, iter_idx); + iter_aligned_q8_0_a2(temp, row_base, num_rows, tid, iter_idx + 1); + } +} +#endif + void compute_outputs(const uint32_t first_row, const uint32_t num_rows) { +#if defined(USE_SUBGROUP_ADD_NO_SHMEM) && !defined(NEEDS_INIT_IQ_SHMEM) + const uint tid = gl_SubgroupInvocationID; +#else const uint tid = gl_LocalInvocationID.x; +#endif get_offsets(a_offset, b_offset, d_offset); +#ifndef MUL_MAT_ID + const bool use_a2 = (GEN_GLU == 2) && (first_row >= p.pair_m0); + const uint row_base = use_a2 ? (first_row - p.pair_m0) : first_row; + const uint eff_rows = (!use_a2 && GEN_GLU == 2) ? min(num_rows, p.pair_m0 - first_row) : num_rows; +#else + const bool use_a2 = false; + const uint row_base = first_row; + const uint eff_rows = num_rows; +#endif + const bool is_aligned_nonquant = p.batch_stride_b % 4 == 0 && p.ncols % 4 == 0 && a_offset % 4 == 0 && b_offset % 4 == 0 && @@ -150,115 +777,179 @@ void compute_outputs(const uint32_t first_row, const uint32_t num_rows) { y_offset = QUANT_R == 1 ? 1 : QUANT_K/2; FLOAT_TYPE temp[NUM_COLS][NUM_ROWS]; + FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS]; [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { [[unroll]] for (uint i = 0; i < NUM_ROWS; ++i) { temp[j][i] = FLOAT_TYPE(0); + if (GEN_GLU == 3) { + temp2[j][i] = FLOAT_TYPE(0); + } } } - uint num_iters = p.ncols / (K_PER_ITER * BLOCK_SIZE); - if (num_iters * K_PER_ITER * BLOCK_SIZE + K_PER_ITER*tid < p.ncols) { - num_iters++; +#if defined(DATA_A_NVFP4) && !defined(USE_OCP_FP4) + if ((p.ncols & 63u) == 0u && (p.batch_stride_b & 3u) == 0u && (b_offset & 3u) == 0u && (BLOCK_SIZE & 7u) == 0u) { + if (eff_rows == 0u) { + return; + } + const uint full_iters = p.ncols / (8u * BLOCK_SIZE); + const bool has_tail = (full_iters * (8u * BLOCK_SIZE) + 8u * tid < p.ncols); + if (GEN_GLU == 2 && use_a2) { + for (uint it = 0u; it < full_iters; ++it) { + iter_aligned_nvfp4_a2(temp, row_base, eff_rows, tid, it); + } + if (has_tail) { + iter_aligned_nvfp4_a2(temp, row_base, eff_rows, tid, full_iters); + } + } else { + for (uint it = 0u; it < full_iters; ++it) { + iter_aligned_nvfp4_a(temp, temp2, row_base, eff_rows, tid, it); + } + if (has_tail) { + iter_aligned_nvfp4_a(temp, temp2, row_base, eff_rows, tid, full_iters); + } + } + if (GEN_GLU == 3) { + reduce_pair_glu(temp, temp2, d_offset, first_row, eff_rows, tid); + } +#ifndef MUL_MAT_ID + else if (GEN_GLU == 2 && use_a2) { + reduce_result_d2(temp, row_base, eff_rows, tid); + } +#endif + else { + reduce_result(temp, d_offset, first_row, eff_rows, tid); + } + return; } - int unroll_count = 4; - uint unrolled_iters = num_iters & ~(unroll_count - 1); - - uint i = 0; +#endif -#if K_PER_ITER == 4 - // If the K dimension is odd, we need lastiter==true on the last iteration - // so OOB is computed correctly. Skip some unrolling to make that happen. - if ((p.ncols & 3) != 0 && - unrolled_iters == num_iters && - unrolled_iters > 0) { - unrolled_iters -= unroll_count; - } - if (is_aligned_nonquant) { - while (i < unrolled_iters) { - // Manually partially unroll the loop - [[unroll]] for (uint k = 0; k < unroll_count; ++k) { - iter_aligned_nonquant(temp, first_row, num_rows, tid, i*K_PER_ITER); - i++; +#if defined(DATA_A_Q8_0) + if ((p.ncols & 31) == 0 && (p.batch_stride_b & 3) == 0 && (b_offset & 3) == 0 && (BLOCK_SIZE & 3) == 0) { + if (eff_rows == 0) { + return; + } + const uint full_iters = p.ncols / (8 * BLOCK_SIZE); + const bool has_tail = (full_iters * (8 * BLOCK_SIZE) + 8 * tid < p.ncols); + uint it = 0; + if (GEN_GLU == 2 && use_a2) { + if (NUM_ROWS == 1 && NUM_COLS <= 4) { + for (; it + 1 < full_iters; it += 2) { + iter2_aligned_q8_0_a2(temp, row_base, eff_rows, tid, it); + } + } + for (; it < full_iters; ++it) { + iter_aligned_q8_0_a2(temp, row_base, eff_rows, tid, it); + } + if (has_tail) { + iter_aligned_q8_0_a2(temp, row_base, eff_rows, tid, full_iters); + } + } else { + if (NUM_ROWS == 1 && NUM_COLS <= 4) { + for (; it + 1 < full_iters; it += 2) { + iter2_aligned_q8_0_a(temp, temp2, row_base, eff_rows, tid, it); + } + } + for (; it < full_iters; ++it) { + iter_aligned_q8_0_a(temp, temp2, row_base, eff_rows, tid, it); + } + if (has_tail) { + iter_aligned_q8_0_a(temp, temp2, row_base, eff_rows, tid, full_iters); } } - } else { + if (GEN_GLU == 3) { + reduce_pair_glu(temp, temp2, d_offset, first_row, eff_rows, tid); + } +#ifndef MUL_MAT_ID + else if (GEN_GLU == 2 && use_a2) { + reduce_result_d2(temp, row_base, eff_rows, tid); + } #endif - while (i < unrolled_iters) { - // Manually partially unroll the loop - [[unroll]] for (uint k = 0; k < unroll_count; ++k) { - iter(temp, first_row, num_rows, tid, i*K_PER_ITER, false); - i++; + else { + reduce_result(temp, d_offset, first_row, eff_rows, tid); } - } -#if K_PER_ITER == 4 + return; } #endif - unroll_count = 2; - unrolled_iters = num_iters & ~(unroll_count - 1); + if (eff_rows == 0) { + return; + } -#if K_PER_ITER == 4 - if ((p.ncols & 3) != 0 && - unrolled_iters == num_iters && - unrolled_iters > 0) { - unrolled_iters -= unroll_count; + uint num_iters = p.ncols / (K_PER_ITER * BLOCK_SIZE); + if (num_iters * K_PER_ITER * BLOCK_SIZE + K_PER_ITER*tid < p.ncols) { + num_iters++; } +#if K_PER_ITER == 4 && (defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16)) if (is_aligned_nonquant) { - while (i < unrolled_iters && is_aligned_nonquant) { - // Manually partially unroll the loop - [[unroll]] for (uint k = 0; k < unroll_count; ++k) { - iter_aligned_nonquant(temp, first_row, num_rows, tid, i*K_PER_ITER); - i++; + if (GEN_GLU == 2 && use_a2) { + for (uint it = 0; it < num_iters; ++it) { + iter_aligned_nonquant_a2(temp, row_base, eff_rows, tid, it*K_PER_ITER); + } + } else { + for (uint it = 0; it < num_iters; ++it) { + iter_aligned_nonquant_a(temp, temp2, row_base, eff_rows, tid, it*K_PER_ITER); } } - } else { + if (GEN_GLU == 3) { + reduce_pair_glu(temp, temp2, d_offset, first_row, eff_rows, tid); + } +#ifndef MUL_MAT_ID + else if (GEN_GLU == 2 && use_a2) { + reduce_result_d2(temp, row_base, eff_rows, tid); + } #endif - while (i < unrolled_iters) { - // Manually partially unroll the loop - [[unroll]] for (uint k = 0; k < unroll_count; ++k) { - iter(temp, first_row, num_rows, tid, i*K_PER_ITER, false); - i++; + else { + reduce_result(temp, d_offset, first_row, eff_rows, tid); } - } -#if K_PER_ITER == 4 + return; } #endif + uint unrolled_iters = num_iters; #if K_PER_ITER == 4 - if (is_aligned_nonquant) { - while (i < num_iters) { - iter_aligned_nonquant(temp, first_row, num_rows, tid, i*K_PER_ITER); - i++; - } - } else { + if ((p.ncols & 3) != 0 && unrolled_iters > 0) { + unrolled_iters--; + } #endif + uint i = 0; + while (i < unrolled_iters) { + iter(temp, row_base, eff_rows, tid, i*K_PER_ITER, false); + i++; + } while (i < num_iters) { - iter(temp, first_row, num_rows, tid, i*K_PER_ITER, true); + iter(temp, row_base, eff_rows, tid, i*K_PER_ITER, true); i++; } -#if K_PER_ITER == 4 + + if (GEN_GLU == 3) { + reduce_pair_glu(temp, temp2, d_offset, first_row, eff_rows, tid); + } +#ifndef MUL_MAT_ID + else if (GEN_GLU == 2 && use_a2) { + reduce_result_d2(temp, row_base, eff_rows, tid); } #endif - - reduce_result(temp, d_offset, first_row, num_rows, tid); + else { + reduce_result(temp, d_offset, first_row, eff_rows, tid); + } } void main() { +#if defined(USE_SUBGROUP_ADD_NO_SHMEM) && !defined(NEEDS_INIT_IQ_SHMEM) + const uint first_row = NUM_ROWS * (NUM_SUBGROUPS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z) + gl_SubgroupID); +#else const uint first_row = NUM_ROWS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z); +#endif #ifdef NEEDS_INIT_IQ_SHMEM init_iq_shmem(gl_WorkGroupSize); #endif - // do NUM_ROWS at a time, unless there aren't enough remaining rows - if (first_row + NUM_ROWS <= p.stride_d) { - compute_outputs(first_row, NUM_ROWS); - } else { - if (first_row >= p.stride_d) { - return; - } - compute_outputs(first_row, min(NUM_ROWS, p.stride_d - first_row)); + if (first_row >= p.stride_d) { + return; } + compute_outputs(first_row, min(NUM_ROWS, p.stride_d - first_row)); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_base.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_base.glsl index 12d9cbf6b7cd..3bf27982ddfe 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_base.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_base.glsl @@ -13,6 +13,43 @@ #include "mul_mat_vec_iface.glsl" +#define MAT_VEC_FUSION_FLAGS_PAIR_GLU 0x400 +#define MAT_VEC_FUSION_FLAGS_PAIR_MM 0x800 +#define MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1 0x1000 +#define MAT_VEC_FUSION_FLAGS_SCALE0_TOK 0x2000 +#define MAT_VEC_FUSION_FLAGS_SCALE1_TOK 0x4000 +#define MAT_VEC_FUSION_FLAGS_COL_SPLIT 0x8000 +#define MAT_VEC_FUSION_FLAGS_LORA0 0x80000 +#define MAT_VEC_FUSION_FLAGS_LORA1 0x100000 +#define MAT_VEC_FUSION_FLAGS_SITU_MERGED 0x400000 + +layout (binding = 3) readonly buffer A2 {A_TYPE data_a2[];}; +#if defined(A_TYPEV4) +layout (binding = 3) readonly buffer A2V4 {A_TYPEV4 data_a2_v4[];}; +#endif +#if defined(A_TYPE_PACKED16) +layout (binding = 3) readonly buffer A2_PACKED16 {A_TYPE_PACKED16 data_a2_packed16[];}; +#endif +#if defined(A_TYPE_PACKED32) +layout (binding = 3) readonly buffer A2_PACKED32 {A_TYPE_PACKED32 data_a2_packed32[];}; +#endif +#if defined(A_TYPE_PACKED64) +layout (binding = 3) readonly buffer A2_PACKED64 {A_TYPE_PACKED64 data_a2_packed64[];}; +#endif +#if defined(DATA_A_NVFP4) && defined(REPACK_PLANAR) +layout (binding = 3) readonly buffer A2_REPACK_U32 {uint data_a2_repack_u32[];}; +layout (binding = 3) readonly buffer A2_REPACK_U2 {uvec2 data_a2_repack_u2[];}; +#endif + +#ifndef MUL_MAT_ID +layout (binding = 5) writeonly buffer D2 {D_TYPE data_d2[];}; +layout (binding = 6) readonly buffer Fuse2 {D_TYPE data_fuse2[];}; +layout (binding = 7) readonly buffer LoRAB0 {float data_lora_b0[];}; +layout (binding = 8) readonly buffer LoRAH0 {float data_lora_h0[];}; +layout (binding = 9) readonly buffer LoRAB1 {float data_lora_b1[];}; +layout (binding = 10) readonly buffer LoRAH1 {float data_lora_h1[];}; +#endif + layout (push_constant) uniform parameter { uint ncols; @@ -31,30 +68,60 @@ layout (push_constant) uniform parameter uint ne11; uint expert_i1; uint nbi1; + float glu_alpha; + float glu_limit; #else uint base_work_group_y; uint ne02; uint ne12; uint broadcast2; uint broadcast3; + uint pair_m0; + uint stride_d2; + uint batch_stride_d2; + uint lora_r; + float lora_scale0; + float lora_scale1; #endif } p; #ifdef MUL_MAT_ID uint expert_id; bool expert_skip; // an id of -1 skips the slot, the result row is zeroed + +// gen: the expert slot and the token of this workgroup (one dispatch per token, or all tokens in y with GEN_TOKY) +uint gen_expert_i0() { return (p.fusion_flags & MAT_VEC_FUSION_FLAGS_GEN_TOKY) != 0 ? gl_WorkGroupID.y % p.nei0 : gl_WorkGroupID.y; } +uint gen_expert_i1() { return (p.fusion_flags & MAT_VEC_FUSION_FLAGS_GEN_TOKY) != 0 ? gl_WorkGroupID.y / p.nei0 : p.expert_i1; } #endif +layout (constant_id = 0) const uint BLOCK_SIZE = 32; +layout (constant_id = 1) const uint NUM_ROWS = 1; +layout (constant_id = 2) const uint NUM_COLS = 1; +// gen: 0 = plain, 1 = single-op epilogue (glu/mmgate/shexp), 2 = PAIR_MM, 3 = PAIR_GLU +layout (constant_id = 3) const uint GEN_GLU = 0; +// gen: independent subgroups per workgroup in SHADER_REDUCTION_MODE_SUBGROUP (row-split) +layout (constant_id = 4) const uint NUM_SUBGROUPS = 1; +// gen: K-quant fast reduction mode (0 = strict 0-ULP upstream layout, 1 = 16-lane vec4/packed32, 2 = 8-lane/superblock) +layout (constant_id = 5) const uint GEN_FAST_KQ = 0; +layout (constant_id = 6) const uint GEN_LORA = 0; + +#define MMV_HAS_LORA0 (GEN_LORA != 0 && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_LORA0) != 0) +#define MMV_HAS_LORA1 (GEN_LORA != 0 && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_LORA1) != 0) +#define MMV_HAS_ANY_LORA (GEN_LORA != 0 && (p.fusion_flags & (MAT_VEC_FUSION_FLAGS_LORA0 | MAT_VEC_FUSION_FLAGS_LORA1)) != 0) + void get_offsets(out uint a_offset, out uint b_offset, out uint d_offset) { #ifdef MUL_MAT_ID - const uint expert_i0 = gl_WorkGroupID.y; + const uint expert_i0 = gen_expert_i0(); + const uint expert_i1 = gen_expert_i1(); #else - const uint batch_idx = gl_WorkGroupID.y + p.base_work_group_y; + const bool col_split = (p.fusion_flags & MAT_VEC_FUSION_FLAGS_COL_SPLIT) != 0; + const uint batch_idx = col_split ? (gl_WorkGroupID.y * NUM_COLS + p.base_work_group_y) + : (gl_WorkGroupID.y + p.base_work_group_y); #endif #ifndef MUL_MAT_ID uint batch_idx_a = 0; - if (batch_idx != 0) { + if (!col_split && batch_idx != 0) { const uint i13 = batch_idx / p.ne12; const uint i12 = batch_idx % p.ne12; @@ -64,7 +131,7 @@ void get_offsets(out uint a_offset, out uint b_offset, out uint d_offset) { batch_idx_a = i03 * p.ne02 + i02; } #else - const int expert = data_ids[expert_i0 + p.expert_i1 * p.nbi1]; + const int expert = data_ids[expert_i0 + expert_i1 * p.nbi1]; expert_skip = expert == -1; expert_id = expert_skip ? 0 : uint(expert); // clamp, so that the offsets below stay in range #endif @@ -75,46 +142,168 @@ void get_offsets(out uint a_offset, out uint b_offset, out uint d_offset) { #else batch_idx_a * (p.batch_stride_a / QUANT_K); #endif + // S19_WAVE3: support NUM_COLS > 1 with ne12 > 1 (batched F32 dmmv at N <= 8, C = 3) b_offset = #ifdef MUL_MAT_ID - (expert_i0 % p.ne11) * p.stride_b + p.expert_i1 * p.batch_stride_b; + (expert_i0 % p.ne11) * p.stride_b + expert_i1 * p.batch_stride_b; #else - batch_idx * p.batch_stride_b; + (col_split ? batch_idx : batch_idx * NUM_COLS) * p.batch_stride_b; #endif d_offset = #ifdef MUL_MAT_ID - expert_i0 * p.stride_d + p.expert_i1 * p.batch_stride_d; + expert_i0 * p.stride_d + expert_i1 * p.batch_stride_d; #else - batch_idx * p.batch_stride_d; + (col_split ? batch_idx : batch_idx * NUM_COLS) * p.batch_stride_d; #endif } -layout (constant_id = 0) const uint BLOCK_SIZE = 32; -layout (constant_id = 1) const uint NUM_ROWS = 1; -layout (constant_id = 2) const uint NUM_COLS = 1; +#ifdef MUL_MAT_ID +float mmv_apply_id_pair_glu(float g, float u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0) { + const float esc = float(data_fuse0[expert_id]); + precise float g_s = g * esc; + precise float u_s = u * esc; + g = g_s; + u = u_s; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0) { + const float beta = p.glu_alpha; + const float lb = p.glu_limit; + const float act = (tanh(g * (1.0f / beta)) * beta) * (1.0f / (1.0f + exp(-g))); + const float u_c = (lb > 0.0f) ? (tanh(u * (1.0f / lb)) * lb) : u; + return act * u_c; + } + return (g / (1.0f + exp(-g))) * u; +} +#else +FLOAT_TYPE gen_apply_mm_epilogue(FLOAT_TYPE val, const uint j, const uint first_row, const uint n) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SIGMOID) != 0) { + precise float gen_x = float(D_TYPE(val)); + precise float gen_y = 1.0f / (1.0f + exp(-gen_x)); + return FLOAT_TYPE(gen_y); + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE) != 0) { + precise float gen_x = float(D_TYPE(val)) + float(data_fuse0[first_row + n]); + precise float gen_sp = (gen_x > 20.0f) ? gen_x : log(1.0f + exp(gen_x)); + precise float gen_y = gen_sp * float(data_fuse1[first_row + n]); + return FLOAT_TYPE(gen_y); + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_ROW_SCALE0) != 0) { + const uint col_j = (p.fusion_flags & MAT_VEC_FUSION_FLAGS_COL_SPLIT) != 0 + ? (gl_WorkGroupID.y * NUM_COLS + p.base_work_group_y + j) : j; + precise float gen_x = float(D_TYPE(val)); + precise float gen_g = float(data_fuse0[col_j]); + precise float gen_y = gen_x * gen_g; + return FLOAT_TYPE(gen_y); + } + return val; +} + +FLOAT_TYPE gen_apply_pair_mm0_epilogue(FLOAT_TYPE val, const uint first_row, const uint n) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE) != 0) { + precise float gen_x = float(D_TYPE(val)) + float(data_fuse1[first_row + n]); + precise float gen_sp = (gen_x > 20.0f) ? gen_x : log(1.0f + exp(gen_x)); + precise float gen_y = gen_sp * float(data_fuse2[first_row + n]); + return FLOAT_TYPE(gen_y); + } + return val; +} + +uint mmv_tok_j(const uint j) { + return (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_COL_SPLIT) != 0) + ? (gl_WorkGroupID.y * NUM_COLS + p.base_work_group_y) + : (gl_WorkGroupID.y + p.base_work_group_y)) + j; +} + +float mmv_eval_lora0_scalar(const uint row, const uint col_j) { + if (GEN_LORA == 0) { return 0.0f; } + float acc = 0.0f; + const uint b_off = row * p.lora_r; + const uint h_off = col_j * p.lora_r; + for (uint k = 0; k < p.lora_r; ++k) { + acc = fma(data_lora_b0[b_off + k], data_lora_h0[h_off + k], acc); + } + return acc * p.lora_scale0; +} + +float mmv_eval_lora1_scalar(const uint row, const uint col_j) { + if (GEN_LORA == 0) { return 0.0f; } + float acc = 0.0f; + const uint b_off = row * p.lora_r; + const uint h_off = col_j * p.lora_r; + for (uint k = 0; k < p.lora_r; ++k) { + acc = fma(data_lora_b1[b_off + k], data_lora_h1[h_off + k], acc); + } + return acc * p.lora_scale1; +} + +#if USE_SUBGROUP_ADD || USE_SUBGROUP_ADD_NO_SHMEM +float mmv_eval_lora0_sg(const uint row, const uint col_j) { + if (GEN_LORA == 0) { return 0.0f; } + float acc = 0.0f; + const uint b_off = row * p.lora_r; + const uint h_off = col_j * p.lora_r; + for (uint k = gl_SubgroupInvocationID; k < p.lora_r; k += gl_SubgroupSize) { + acc = fma(data_lora_b0[b_off + k], data_lora_h0[h_off + k], acc); + } + return subgroupAdd(acc) * p.lora_scale0; +} + +float mmv_eval_lora1_sg(const uint row, const uint col_j) { + if (GEN_LORA == 0) { return 0.0f; } + float acc = 0.0f; + const uint b_off = row * p.lora_r; + const uint h_off = col_j * p.lora_r; + for (uint k = gl_SubgroupInvocationID; k < p.lora_r; k += gl_SubgroupSize) { + acc = fma(data_lora_b1[b_off + k], data_lora_h1[h_off + k], acc); + } + return subgroupAdd(acc) * p.lora_scale1; +} +#endif +#endif #ifdef USE_SUBGROUP_ADD_NO_SHMEM void reduce_result(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offset, const in uint32_t first_row, const in uint32_t num_rows, const in uint32_t tid) { [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - [[unroll]] for (uint n = 0; n < num_rows; ++n) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { temp[j][n] = subgroupAdd(temp[j][n]); } } +#ifndef MUL_MAT_ID + if (GEN_GLU != 0 && MMV_HAS_LORA0 && num_rows > 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint tok_j = mmv_tok_j(j); + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const float lv = mmv_eval_lora0_sg(first_row + rn, tok_j); + if (n < num_rows) { + temp[j][n] += FLOAT_TYPE(lv); + } + } + } + } +#endif if (tid == 0) { [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - [[unroll]] for (uint n = 0; n < num_rows; ++n) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + if (n >= num_rows) { + continue; + } #ifdef MUL_MAT_ID if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) { temp[j][n] += FLOAT_TYPE(data_fuse0[expert_id*p.stride_d + first_row + n]); } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0) { + temp[j][n] *= FLOAT_TYPE(data_fuse0[expert_id]); + } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0) != 0) { - const uint expert_i0 = gl_GlobalInvocationID.y; - temp[j][n] *= FLOAT_TYPE(data_fuse0[expert_i0]); + const uint s0_idx = gen_expert_i0() + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0_TOK) != 0 ? gen_expert_i1() * p.nei0 : 0u); + temp[j][n] *= FLOAT_TYPE(data_fuse0[s0_idx]); } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1) != 0) { - const uint expert_i0 = gl_GlobalInvocationID.y; - temp[j][n] *= FLOAT_TYPE(data_fuse1[expert_i0]); + const uint s1_idx = gen_expert_i0() + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1_TOK) != 0 ? gen_expert_i1() * p.nei0 : 0u); + temp[j][n] *= FLOAT_TYPE(data_fuse1[s1_idx]); } if (expert_skip) { temp[j][n] = FLOAT_TYPE(0); @@ -126,14 +315,117 @@ void reduce_result(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS1) != 0) { temp[j][n] += FLOAT_TYPE(data_fuse1[j*p.batch_stride_d + d_offset + first_row + n]); } + if (GEN_GLU == 1 && (p.fusion_flags & (MAT_VEC_FUSION_FLAGS_SIGMOID | MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE | MAT_VEC_FUSION_FLAGS_ROW_SCALE0)) != 0) { + temp[j][n] = gen_apply_mm_epilogue(temp[j][n], j, first_row, n); + } + if (GEN_GLU == 2 && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE) != 0) { + temp[j][n] = gen_apply_pair_mm0_epilogue(temp[j][n], first_row, n); + } #endif + if (GEN_GLU == 1 && (p.fusion_flags & (MAT_VEC_FUSION_FLAGS_GLU_A | MAT_VEC_FUSION_FLAGS_GLU_B)) != 0) { + // gen: same expression as swiglu.comp op(a, b) = a / (1 + exp(-a)) * b + const float glu_o = float(data_fuse0[j*p.batch_stride_d + d_offset + first_row + n]); + const float glu_r = float(temp[j][n]); + temp[j][n] = FLOAT_TYPE((p.fusion_flags & MAT_VEC_FUSION_FLAGS_GLU_A) != 0 ? + glu_r / (1.0f + exp(-glu_r)) * glu_o : glu_o / (1.0f + exp(-glu_o)) * glu_r); + } data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(temp[j][n]); } } } } + +void reduce_pair_glu(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const in uint32_t d_offset, const in uint32_t first_row, const in uint32_t num_rows, const in uint32_t tid) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + temp[j][n] = subgroupAdd(temp[j][n]); + temp2[j][n] = subgroupAdd(temp2[j][n]); + } + } +#ifndef MUL_MAT_ID + if (MMV_HAS_ANY_LORA && num_rows > 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint tok_j = mmv_tok_j(j); + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + if (MMV_HAS_LORA0) { + const float lv0 = mmv_eval_lora0_sg(first_row + rn, tok_j); + if (n < num_rows) { temp[j][n] += FLOAT_TYPE(lv0); } + } + if (MMV_HAS_LORA1) { + const float lv1 = mmv_eval_lora1_sg(first_row + rn, tok_j); + if (n < num_rows) { temp2[j][n] += FLOAT_TYPE(lv1); } + } + } + } + } +#endif + if (tid == 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + if (n >= num_rows) { + continue; + } +#ifdef MUL_MAT_ID + if (expert_skip) { + data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(0); + continue; + } + data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(FLOAT_TYPE(mmv_apply_id_pair_glu(float(D_TYPE(temp[j][n])), float(D_TYPE(temp2[j][n]))))); +#else + const float glu_g = float(D_TYPE(temp[j][n])); + const float glu_u = float(D_TYPE(temp2[j][n])); + data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(FLOAT_TYPE(glu_g / (1.0f + exp(-glu_g)) * glu_u)); +#endif + } + } + } +} + +#ifndef MUL_MAT_ID +void reduce_result_d2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t first_row, const in uint32_t num_rows, const in uint32_t tid) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + temp[j][n] = subgroupAdd(temp[j][n]); + } + } + if (MMV_HAS_LORA1 && num_rows > 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint tok_j = mmv_tok_j(j); + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const float lv1 = mmv_eval_lora1_sg(first_row + rn, tok_j); + if (n < num_rows) { temp[j][n] += FLOAT_TYPE(lv1); } + } + } + } + if (tid == 0) { + const uint d2_offset = (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_COL_SPLIT) != 0) + ? (gl_WorkGroupID.y * NUM_COLS + p.base_work_group_y) + : (gl_WorkGroupID.y + p.base_work_group_y)) * p.batch_stride_d2; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + if (n >= num_rows) { + continue; + } + FLOAT_TYPE val = temp[j][n]; + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1) != 0) { + precise float gen_x = float(D_TYPE(val)); + precise float gen_y = 1.0f / (1.0f + exp(-gen_x)); + val = FLOAT_TYPE(gen_y); + } + data_d2[j*p.batch_stride_d2 + d2_offset + first_row + n] = D_TYPE(val); + } + } + } +} +#endif +#else +#if USE_SUBGROUP_ADD +shared FLOAT_TYPE tmpsh[NUM_COLS][NUM_ROWS][2 * (BLOCK_SIZE / 8) + 2]; #else shared FLOAT_TYPE tmpsh[NUM_COLS][NUM_ROWS][BLOCK_SIZE]; +#endif void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offset, const in uint32_t first_row, const in uint32_t num_rows, const in uint32_t tid) { // subgroupAdd is probably faster on devices that support it, @@ -141,7 +433,7 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs #if USE_SUBGROUP_ADD // sum up partial sums within a subgroup [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - [[unroll]] for (uint n = 0; n < num_rows; ++n) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { temp[j][n] = subgroupAdd(temp[j][n]); } } @@ -149,15 +441,30 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs // Go through shared memory to sum partials across subgroups if (gl_SubgroupInvocationID == 0) { [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - [[unroll]] for (uint n = 0; n < num_rows; ++n) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { tmpsh[j][n][gl_SubgroupID] = temp[j][n]; } } } barrier(); +#ifndef MUL_MAT_ID + FLOAT_TYPE lora0_acc[NUM_COLS][NUM_ROWS]; + if (GEN_GLU != 0 && MMV_HAS_LORA0 && gl_SubgroupID == 0 && num_rows > 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint tok_j = mmv_tok_j(j); + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + lora0_acc[j][n] = FLOAT_TYPE(mmv_eval_lora0_sg(first_row + rn, tok_j)); + } + } + } +#endif if (tid == 0) { [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - [[unroll]] for (uint n = 0; n < num_rows; ++n) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + if (n >= num_rows) { + continue; + } temp[j][n] = FLOAT_TYPE(0); [[unroll]] for (uint s = 0; s < gl_NumSubgroups; ++s) { temp[j][n] += tmpsh[j][n][s]; @@ -166,25 +473,44 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) { temp[j][n] += FLOAT_TYPE(data_fuse0[expert_id*p.stride_d + first_row + n]); } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0) { + temp[j][n] *= FLOAT_TYPE(data_fuse0[expert_id]); + } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0) != 0) { - const uint expert_i0 = gl_GlobalInvocationID.y; - temp[j][n] *= FLOAT_TYPE(data_fuse0[expert_i0]); + const uint s0_idx = gen_expert_i0() + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0_TOK) != 0 ? gen_expert_i1() * p.nei0 : 0u); + temp[j][n] *= FLOAT_TYPE(data_fuse0[s0_idx]); } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1) != 0) { - const uint expert_i0 = gl_GlobalInvocationID.y; - temp[j][n] *= FLOAT_TYPE(data_fuse1[expert_i0]); + const uint s1_idx = gen_expert_i0() + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1_TOK) != 0 ? gen_expert_i1() * p.nei0 : 0u); + temp[j][n] *= FLOAT_TYPE(data_fuse1[s1_idx]); } if (expert_skip) { temp[j][n] = FLOAT_TYPE(0); } #else + if (GEN_GLU != 0 && MMV_HAS_LORA0) { + temp[j][n] += lora0_acc[j][n]; + } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) { temp[j][n] += FLOAT_TYPE(data_fuse0[j*p.batch_stride_d + d_offset + first_row + n]); } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS1) != 0) { temp[j][n] += FLOAT_TYPE(data_fuse1[j*p.batch_stride_d + d_offset + first_row + n]); } + if (GEN_GLU == 1 && (p.fusion_flags & (MAT_VEC_FUSION_FLAGS_SIGMOID | MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE | MAT_VEC_FUSION_FLAGS_ROW_SCALE0)) != 0) { + temp[j][n] = gen_apply_mm_epilogue(temp[j][n], j, first_row, n); + } + if (GEN_GLU == 2 && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE) != 0) { + temp[j][n] = gen_apply_pair_mm0_epilogue(temp[j][n], first_row, n); + } #endif + if (GEN_GLU == 1 && (p.fusion_flags & (MAT_VEC_FUSION_FLAGS_GLU_A | MAT_VEC_FUSION_FLAGS_GLU_B)) != 0) { + // gen: same expression as swiglu.comp op(a, b) = a / (1 + exp(-a)) * b + const float glu_o = float(data_fuse0[j*p.batch_stride_d + d_offset + first_row + n]); + const float glu_r = float(temp[j][n]); + temp[j][n] = FLOAT_TYPE((p.fusion_flags & MAT_VEC_FUSION_FLAGS_GLU_A) != 0 ? + glu_r / (1.0f + exp(-glu_r)) * glu_o : glu_o / (1.0f + exp(-glu_o)) * glu_r); + } data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(temp[j][n]); } } @@ -192,7 +518,7 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs #else // sum up partial sums and write back result [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - [[unroll]] for (uint n = 0; n < num_rows; ++n) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { tmpsh[j][n][tid] = temp[j][n]; } } @@ -200,7 +526,7 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs [[unroll]] for (uint s = BLOCK_SIZE/2; s > 0; s >>= 1) { if (tid < s) { [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - [[unroll]] for (uint n = 0; n < num_rows; ++n) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { tmpsh[j][n][tid] += tmpsh[j][n][tid + s]; } } @@ -209,34 +535,286 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs } if (tid == 0) { [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - [[unroll]] for (uint n = 0; n < num_rows; ++n) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + if (n >= num_rows) { + continue; + } #ifdef MUL_MAT_ID if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) { tmpsh[j][n][0] += FLOAT_TYPE(data_fuse0[expert_id*p.stride_d + first_row + n]); } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0) { + tmpsh[j][n][0] *= FLOAT_TYPE(data_fuse0[expert_id]); + } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0) != 0) { - const uint expert_i0 = gl_GlobalInvocationID.y; - tmpsh[j][n][0] *= FLOAT_TYPE(data_fuse0[expert_i0]); + const uint s0_idx = gen_expert_i0() + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0_TOK) != 0 ? gen_expert_i1() * p.nei0 : 0u); + tmpsh[j][n][0] *= FLOAT_TYPE(data_fuse0[s0_idx]); } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1) != 0) { - const uint expert_i0 = gl_GlobalInvocationID.y; - tmpsh[j][n][0] *= FLOAT_TYPE(data_fuse1[expert_i0]); + const uint s1_idx = gen_expert_i0() + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1_TOK) != 0 ? gen_expert_i1() * p.nei0 : 0u); + tmpsh[j][n][0] *= FLOAT_TYPE(data_fuse1[s1_idx]); } if (expert_skip) { tmpsh[j][n][0] = FLOAT_TYPE(0); } #else + if (GEN_GLU != 0 && MMV_HAS_LORA0) { + tmpsh[j][n][0] += FLOAT_TYPE(mmv_eval_lora0_scalar(first_row + n, mmv_tok_j(j))); + } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) { tmpsh[j][n][0] += FLOAT_TYPE(data_fuse0[j*p.batch_stride_d + d_offset + first_row + n]); } if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS1) != 0) { tmpsh[j][n][0] += FLOAT_TYPE(data_fuse1[j*p.batch_stride_d + d_offset + first_row + n]); } + if (GEN_GLU == 1 && (p.fusion_flags & (MAT_VEC_FUSION_FLAGS_SIGMOID | MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE | MAT_VEC_FUSION_FLAGS_ROW_SCALE0)) != 0) { + tmpsh[j][n][0] = gen_apply_mm_epilogue(tmpsh[j][n][0], j, first_row, n); + } + if (GEN_GLU == 2 && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE) != 0) { + tmpsh[j][n][0] = gen_apply_pair_mm0_epilogue(tmpsh[j][n][0], first_row, n); + } #endif + if (GEN_GLU == 1 && (p.fusion_flags & (MAT_VEC_FUSION_FLAGS_GLU_A | MAT_VEC_FUSION_FLAGS_GLU_B)) != 0) { + // gen: same expression as swiglu.comp op(a, b) = a / (1 + exp(-a)) * b + const float glu_o = float(data_fuse0[j*p.batch_stride_d + d_offset + first_row + n]); + const float glu_r = float(tmpsh[j][n][0]); + tmpsh[j][n][0] = FLOAT_TYPE((p.fusion_flags & MAT_VEC_FUSION_FLAGS_GLU_A) != 0 ? + glu_r / (1.0f + exp(-glu_r)) * glu_o : glu_o / (1.0f + exp(-glu_o)) * glu_r); + } data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(tmpsh[j][n][0]); } } } #endif } + +void reduce_pair_glu(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const in uint32_t d_offset, const in uint32_t first_row, const in uint32_t num_rows, const in uint32_t tid) { +#if USE_SUBGROUP_ADD + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + temp[j][n] = subgroupAdd(temp[j][n]); + temp2[j][n] = subgroupAdd(temp2[j][n]); + } + } + if (gl_SubgroupInvocationID == 0) { + const uint sg_u = gl_NumSubgroups + gl_SubgroupID; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + tmpsh[j][n][gl_SubgroupID] = temp[j][n]; + tmpsh[j][n][sg_u] = temp2[j][n]; + } + } + } + barrier(); +#ifndef MUL_MAT_ID + FLOAT_TYPE lora0_acc[NUM_COLS][NUM_ROWS]; + FLOAT_TYPE lora1_acc[NUM_COLS][NUM_ROWS]; + if (MMV_HAS_ANY_LORA && gl_SubgroupID == 0 && num_rows > 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint tok_j = mmv_tok_j(j); + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + if (MMV_HAS_LORA0) { + lora0_acc[j][n] = FLOAT_TYPE(mmv_eval_lora0_sg(first_row + rn, tok_j)); + } + if (MMV_HAS_LORA1) { + lora1_acc[j][n] = FLOAT_TYPE(mmv_eval_lora1_sg(first_row + rn, tok_j)); + } + } + } + } +#endif + if (tid == 0) { + const uint sg_base_u = gl_NumSubgroups; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + if (n >= num_rows) { + continue; + } + FLOAT_TYPE acc = FLOAT_TYPE(0); + FLOAT_TYPE acc2 = FLOAT_TYPE(0); + [[unroll]] for (uint s = 0; s < gl_NumSubgroups; ++s) { + acc += tmpsh[j][n][s]; + acc2 += tmpsh[j][n][sg_base_u + s]; + } +#ifdef MUL_MAT_ID + if (expert_skip) { + data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(0); + continue; + } + data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(FLOAT_TYPE(mmv_apply_id_pair_glu(float(D_TYPE(acc)), float(D_TYPE(acc2))))); +#else + if (MMV_HAS_LORA0) { + acc += lora0_acc[j][n]; + } + if (MMV_HAS_LORA1) { + acc2 += lora1_acc[j][n]; + } + const float glu_g = float(D_TYPE(acc)); + const float glu_u = float(D_TYPE(acc2)); + data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(FLOAT_TYPE(glu_g / (1.0f + exp(-glu_g)) * glu_u)); +#endif + } + } + } +#else + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + tmpsh[j][n][tid] = temp[j][n]; + } + } + barrier(); + [[unroll]] for (uint s = BLOCK_SIZE/2; s > 0; s >>= 1) { + if (tid < s) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + tmpsh[j][n][tid] += tmpsh[j][n][tid + s]; + } + } + } + barrier(); + } + if (tid == 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + temp[j][n] = tmpsh[j][n][0]; + } + } + } + barrier(); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + tmpsh[j][n][tid] = temp2[j][n]; + } + } + barrier(); + [[unroll]] for (uint s = BLOCK_SIZE/2; s > 0; s >>= 1) { + if (tid < s) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + tmpsh[j][n][tid] += tmpsh[j][n][tid + s]; + } + } + } + barrier(); + } + if (tid == 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + if (n >= num_rows) { + continue; + } +#ifdef MUL_MAT_ID + if (expert_skip) { + data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(0); + continue; + } + data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(FLOAT_TYPE(mmv_apply_id_pair_glu(float(D_TYPE(temp[j][n])), float(D_TYPE(tmpsh[j][n][0]))))); +#else + if (MMV_HAS_LORA0) { + temp[j][n] += FLOAT_TYPE(mmv_eval_lora0_scalar(first_row + n, mmv_tok_j(j))); + } + if (MMV_HAS_LORA1) { + tmpsh[j][n][0] += FLOAT_TYPE(mmv_eval_lora1_scalar(first_row + n, mmv_tok_j(j))); + } + const float glu_g = float(D_TYPE(temp[j][n])); + const float glu_u = float(D_TYPE(tmpsh[j][n][0])); + data_d[j*p.batch_stride_d + d_offset + first_row + n] = D_TYPE(FLOAT_TYPE(glu_g / (1.0f + exp(-glu_g)) * glu_u)); +#endif + } + } + } +#endif +} + +#ifndef MUL_MAT_ID +void reduce_result_d2(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t first_row, const in uint32_t num_rows, const in uint32_t tid) { + const uint d2_offset = (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_COL_SPLIT) != 0) + ? (gl_WorkGroupID.y * NUM_COLS + p.base_work_group_y) + : (gl_WorkGroupID.y + p.base_work_group_y)) * p.batch_stride_d2; +#if USE_SUBGROUP_ADD + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + temp[j][n] = subgroupAdd(temp[j][n]); + } + } + if (gl_SubgroupInvocationID == 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + tmpsh[j][n][gl_SubgroupID] = temp[j][n]; + } + } + } + barrier(); + FLOAT_TYPE lora1_acc[NUM_COLS][NUM_ROWS]; + if (MMV_HAS_LORA1 && gl_SubgroupID == 0 && num_rows > 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint tok_j = mmv_tok_j(j); + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + lora1_acc[j][n] = FLOAT_TYPE(mmv_eval_lora1_sg(first_row + rn, tok_j)); + } + } + } + if (tid == 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + if (n >= num_rows) { + continue; + } + FLOAT_TYPE val = FLOAT_TYPE(0); + [[unroll]] for (uint s = 0; s < gl_NumSubgroups; ++s) { + val += tmpsh[j][n][s]; + } + if (MMV_HAS_LORA1) { + val += lora1_acc[j][n]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1) != 0) { + precise float gen_x = float(D_TYPE(val)); + precise float gen_y = 1.0f / (1.0f + exp(-gen_x)); + val = FLOAT_TYPE(gen_y); + } + data_d2[j*p.batch_stride_d2 + d2_offset + first_row + n] = D_TYPE(val); + } + } + } +#else + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + tmpsh[j][n][tid] = temp[j][n]; + } + } + barrier(); + [[unroll]] for (uint s = BLOCK_SIZE/2; s > 0; s >>= 1) { + if (tid < s) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + tmpsh[j][n][tid] += tmpsh[j][n][tid + s]; + } + } + } + barrier(); + } + if (tid == 0) { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + if (n >= num_rows) { + continue; + } + FLOAT_TYPE val = tmpsh[j][n][0]; + if (MMV_HAS_LORA1) { + val += FLOAT_TYPE(mmv_eval_lora1_scalar(first_row + n, mmv_tok_j(j))); + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1) != 0) { + precise float gen_x = float(D_TYPE(val)); + precise float gen_y = 1.0f / (1.0f + exp(-gen_x)); + val = FLOAT_TYPE(gen_y); + } + data_d2[j*p.batch_stride_d2 + d2_offset + first_row + n] = D_TYPE(val); + } + } + } +#endif +} +#endif #endif diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_iface.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_iface.glsl index a2b7cef64906..23d2056ada94 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_iface.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_iface.glsl @@ -4,6 +4,17 @@ #define MAT_VEC_FUSION_FLAGS_BIAS1 0x2 #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4 #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8 +// gen: SWIGLU epilogue, this result is the gate (A) or the up operand (B); the other comes from fuse0 +#define MAT_VEC_FUSION_FLAGS_GLU_A 0x10 +#define MAT_VEC_FUSION_FLAGS_GLU_B 0x20 +// gen: MUL_MAT_ID with all tokens in one dispatch: workgroup y = expert slot + nei0 * token +#define MAT_VEC_FUSION_FLAGS_GEN_TOKY 0x40 +// gen: dense mat-vec epilogues (GGML_GEN_FUSE=mmgate,shexp), compiled into the GEN_GLU=1 twin +#define MAT_VEC_FUSION_FLAGS_SIGMOID 0x80 +#define MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE 0x100 +#define MAT_VEC_FUSION_FLAGS_ROW_SCALE0 0x200 +#define MAT_VEC_FUSION_FLAGS_SRC1_SCALE 0x4000000 +#define MAT_VEC_FUSION_FLAGS_EXP_SCALE0 0x200000 layout (binding = 0) readonly buffer A {A_TYPE data_a[];}; #if defined(A_TYPEV4) @@ -18,6 +29,10 @@ layout (binding = 0) readonly buffer A_PACKED32 {A_TYPE_PACKED32 data_a_packed32 #if defined(A_TYPE_PACKED64) layout (binding = 0) readonly buffer A_PACKED64 {A_TYPE_PACKED64 data_a_packed64[];}; #endif +#if defined(DATA_A_NVFP4) && defined(REPACK_PLANAR) +layout (binding = 0) readonly buffer A_REPACK_U32 {uint data_a_repack_u32[];}; +layout (binding = 0) readonly buffer A_REPACK_U2 {uvec2 data_a_repack_u2[];}; +#endif layout (binding = 1) readonly buffer B {B_TYPE data_b[];}; #ifdef B_TYPEV2 diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_iq4_xs.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_iq4_xs.comp index a2b99d9ab16c..bee9bd102180 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_iq4_xs.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_iq4_xs.comp @@ -14,8 +14,9 @@ FLOAT_TYPE temp[NUM_COLS][NUM_ROWS]; void calc_superblock(const uint a_offset, const uint b_offset, const uint ib32, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { const uint y_idx = i * QUANT_K + 32 * ib32; - uint ibi = a_offset + first_row * num_blocks_per_row + i; - [[unroll]] for (uint n = 0; n < num_rows; ++n) { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ibi = a_offset + (first_row + rn) * num_blocks_per_row + i; const float d = float(data_a[ibi].d); const uint sl = (data_a[ibi].scales_l[ib32/2] >> (4 * (ib32 & 1))) & 0xF; const uint sh = (data_a[ibi].scales_h >> (2 * ib32)) & 3; @@ -50,8 +51,6 @@ void calc_superblock(const uint a_offset, const uint b_offset, const uint ib32, [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { temp[j][n] = fma(dscale, sum[j], temp[j][n]); } - - ibi += num_blocks_per_row; } } @@ -74,7 +73,7 @@ void compute_outputs(const uint32_t first_row, const uint32_t num_rows) { } } - [[unroll]] for (uint i = ix; i < num_blocks_per_row; i += blocks_per_wg) + for (uint i = ix; i < num_blocks_per_row; i += blocks_per_wg) calc_superblock(a_offset, b_offset, itid, i, num_blocks_per_row, first_row, num_rows); reduce_result(temp, d_offset, first_row, num_rows, tid); @@ -85,13 +84,8 @@ void main() { init_iq_shmem(gl_WorkGroupSize); - // do NUM_ROWS at a time, unless there aren't enough remaining rows - if (first_row + NUM_ROWS <= p.stride_d) { - compute_outputs(first_row, NUM_ROWS); - } else { - if (first_row >= p.stride_d) { - return; - } - compute_outputs(first_row, p.stride_d - first_row); + if (first_row >= p.stride_d) { + return; } + compute_outputs(first_row, min(NUM_ROWS, p.stride_d - first_row)); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q2_k.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q2_k.comp index 975cec8013f2..2ce5a1e58935 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q2_k.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q2_k.comp @@ -14,8 +14,9 @@ uint csel = 0; void calc_superblock(const uint a_offset, const uint b_offset, const uint itid, const uint v_im, const uint ix, const uint q_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows, const bool all_threads) { const uint y_idx = i * QUANT_K + y_offset; - [[unroll]] for (uint n = 0; n < num_rows; ++n) { - const uint ib0 = a_offset + (first_row+n)*num_blocks_per_row; + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row+rn)*num_blocks_per_row; csel ^= 1; if (!all_threads) { // when we don't have enough blocks to use all threads @@ -106,7 +107,7 @@ void compute_outputs(const uint32_t first_row, const uint32_t num_rows) { const uint nbr_par_th = num_blocks_per_row%it_size; const uint nbr_all_th = num_blocks_per_row - nbr_par_th; uint i0 = 0; - [[unroll]] for (; i0 < nbr_all_th; i0 += it_size) + for (; i0 < nbr_all_th; i0 += it_size) calc_superblock(a_offset, b_offset, itid, v_im, ix, q_offset, y_offset, i0 + ix, num_blocks_per_row, first_row, num_rows, true); calc_superblock(a_offset, b_offset, itid, v_im, ix, q_offset, y_offset, i0 + ix, num_blocks_per_row, first_row, num_rows, false); @@ -116,13 +117,8 @@ void compute_outputs(const uint32_t first_row, const uint32_t num_rows) { void main() { const uint first_row = NUM_ROWS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z); - // do NUM_ROWS at a time, unless there aren't enough remaining rows - if (first_row + NUM_ROWS <= p.stride_d) { - compute_outputs(first_row, NUM_ROWS); - } else { - if (first_row >= p.stride_d) { - return; - } - compute_outputs(first_row, p.stride_d - first_row); + if (first_row >= p.stride_d) { + return; } + compute_outputs(first_row, min(NUM_ROWS, p.stride_d - first_row)); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q3_k.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q3_k.comp index 93e48b790122..2fb61538384e 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q3_k.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q3_k.comp @@ -13,8 +13,9 @@ uint csel = 0; void calc_superblock(const uint a_offset, const uint b_offset, const uint ix, const uint itid8, const uint v_im, const uint v_im4, const uint v_in, const uint32_t hm_m[4], const uint q_offset, const uint y_offset, const uint s_shift, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows, const bool all_threads) { const uint y_idx = i * QUANT_K + y_offset; - [[unroll]] for (uint n = 0; n < num_rows; ++n) { - const uint ib0 = a_offset + (first_row+n)*num_blocks_per_row; + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row+rn)*num_blocks_per_row; csel ^= 1; if (!all_threads) { // when we don't have enough blocks to use all threads @@ -110,7 +111,7 @@ void compute_outputs(const uint32_t first_row, const uint32_t num_rows) { const uint nbr_par_th = num_blocks_per_row%it_size; const uint nbr_all_th = num_blocks_per_row - nbr_par_th; uint i0 = 0; - [[unroll]] for (; i0 < nbr_all_th; i0 += it_size) + for (; i0 < nbr_all_th; i0 += it_size) calc_superblock(a_offset, b_offset, ix, itid8, v_im, v_im4, v_in, hm_m, q_offset, y_offset, s_shift, i0 + ix, num_blocks_per_row, first_row, num_rows, true); calc_superblock(a_offset, b_offset, ix, itid8, v_im, v_im4, v_in, hm_m, q_offset, y_offset, s_shift, i0 + ix, num_blocks_per_row, first_row, num_rows, false); @@ -120,13 +121,8 @@ void compute_outputs(const uint32_t first_row, const uint32_t num_rows) { void main() { const uint first_row = NUM_ROWS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z); - // do NUM_ROWS at a time, unless there aren't enough remaining rows - if (first_row + NUM_ROWS <= p.stride_d) { - compute_outputs(first_row, NUM_ROWS); - } else { - if (first_row >= p.stride_d) { - return; - } - compute_outputs(first_row, p.stride_d - first_row); + if (first_row >= p.stride_d) { + return; } + compute_outputs(first_row, min(NUM_ROWS, p.stride_d - first_row)); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q4_k.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q4_k.comp index 93fbacc6282c..3e71549fb98a 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q4_k.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q4_k.comp @@ -1,85 +1,340 @@ #version 450 #extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#ifdef REPACK_PLANAR +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable +#endif #include "mul_mat_vec_base.glsl" +#ifdef REPACK_PLANAR +#include "repack_planar.glsl" +layout (binding = 0) readonly buffer A_U32 { uint data_a_u32[]; }; +layout (binding = 0) readonly buffer A_U4 { uvec4 data_a_u4[]; }; +layout (binding = 3) readonly buffer A2_U32 { uint data_a2_u32[]; }; +layout (binding = 3) readonly buffer A2_U4 { uvec4 data_a2_u4[]; }; +#endif + +#ifdef USE_SUBGROUP_ADD_NO_SHMEM +layout(local_size_x_id = 0, local_size_y_id = 4, local_size_z = 1) in; +#else layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; +#endif + +#define LOAD_Q4_K_16(PFX, ARR_A, ARR_P16, ARR_P32) \ + const FLOAT_TYPEV2 PFX##_dm = FLOAT_TYPEV2(ARR_A[ib0 + i].dm); \ + const uint32_t PFX##_scale0_u32 = ARR_P16[ib0 + i].scales[v_im ]; \ + const uint32_t PFX##_scale4_u32 = ARR_P16[ib0 + i].scales[v_im + 2]; \ + const uint32_t PFX##_scale8_u32 = ARR_P16[ib0 + i].scales[v_im + 4]; \ + const uint32_t PFX##_scale_0_4_l = (PFX##_scale4_u32 << 16) | PFX##_scale0_u32; \ + const uint32_t PFX##_scale_0_4_h = (PFX##_scale_0_4_l & 0xC0C0C0C0u) >> 2; \ + const vec4 PFX##_sc03 = vec4(unpack8(PFX##_scale_0_4_l & 0x3F3F3F3Fu)); \ + const vec4 PFX##_sc47 = vec4(unpack8((((PFX##_scale8_u32 << 12) | PFX##_scale8_u32) & 0x0F0F0F0Fu) | PFX##_scale_0_4_h)); \ + const uint32_t PFX##_qs0_u32 = ARR_P32[ib0 + i].qs[q_offset / 4]; \ + const uint32_t PFX##_qs64_u32 = ARR_P32[ib0 + i].qs[q_offset / 4 + 16]; \ + const vec4 PFX##_qs0_lo4 = vec4(unpack8(PFX##_qs0_u32 & 0x0F0F0F0Fu)); \ + const vec4 PFX##_qs64_lo4 = vec4(unpack8(PFX##_qs64_u32 & 0x0F0F0F0Fu)); \ + const vec4 PFX##_qs0_hi4 = vec4(unpack8((PFX##_qs0_u32 >> 4) & 0x0F0F0F0Fu)); \ + const vec4 PFX##_qs64_hi4 = vec4(unpack8((PFX##_qs64_u32 >> 4) & 0x0F0F0F0Fu)) -FLOAT_TYPE temp[NUM_COLS][NUM_ROWS]; +#define DOT_Q4_K_16_WITH_BY(PFX, DST_TEMP, BY10, BY132, BY20, BY232, SY10, SY132, SY20, SY232) do { \ + const FLOAT_TYPE sc0 = PFX##_sc03.x, sc1 = PFX##_sc03.y, sc2 = PFX##_sc03.z, sc3 = PFX##_sc03.w; \ + const FLOAT_TYPE sc4 = PFX##_sc47.x, sc5 = PFX##_sc47.y, sc6 = PFX##_sc47.z, sc7 = PFX##_sc47.w; \ + const FLOAT_TYPE sx = fma(FLOAT_TYPE((BY10).x), PFX##_qs0_lo4.x, fma(FLOAT_TYPE((BY10).y), PFX##_qs0_lo4.y, fma(FLOAT_TYPE((BY10).z), PFX##_qs0_lo4.z, FLOAT_TYPE((BY10).w) * PFX##_qs0_lo4.w))); \ + const FLOAT_TYPE sy = fma(FLOAT_TYPE((BY132).x), PFX##_qs0_hi4.x, fma(FLOAT_TYPE((BY132).y), PFX##_qs0_hi4.y, fma(FLOAT_TYPE((BY132).z), PFX##_qs0_hi4.z, FLOAT_TYPE((BY132).w) * PFX##_qs0_hi4.w))); \ + const FLOAT_TYPE sz = fma(FLOAT_TYPE((BY20).x), PFX##_qs64_lo4.x, fma(FLOAT_TYPE((BY20).y), PFX##_qs64_lo4.y, fma(FLOAT_TYPE((BY20).z), PFX##_qs64_lo4.z, FLOAT_TYPE((BY20).w) * PFX##_qs64_lo4.w))); \ + const FLOAT_TYPE sw = fma(FLOAT_TYPE((BY232).x), PFX##_qs64_hi4.x, fma(FLOAT_TYPE((BY232).y), PFX##_qs64_hi4.y, fma(FLOAT_TYPE((BY232).z), PFX##_qs64_hi4.z, FLOAT_TYPE((BY232).w) * PFX##_qs64_hi4.w))); \ + FLOAT_TYPE smin; \ + if (GEN_FAST_KQ == 0) { \ + smin = \ + fma(FLOAT_TYPE((BY10).x), sc2, fma(FLOAT_TYPE((BY132).x), sc3, fma(FLOAT_TYPE((BY20).x), sc6, fma(FLOAT_TYPE((BY232).x), sc7, \ + fma(FLOAT_TYPE((BY10).y), sc2, fma(FLOAT_TYPE((BY132).y), sc3, fma(FLOAT_TYPE((BY20).y), sc6, fma(FLOAT_TYPE((BY232).y), sc7, \ + fma(FLOAT_TYPE((BY10).z), sc2, fma(FLOAT_TYPE((BY132).z), sc3, fma(FLOAT_TYPE((BY20).z), sc6, fma(FLOAT_TYPE((BY232).z), sc7, \ + fma(FLOAT_TYPE((BY10).w), sc2, fma(FLOAT_TYPE((BY132).w), sc3, fma(FLOAT_TYPE((BY20).w), sc6, FLOAT_TYPE((BY232).w) * sc7))))))))))))))); \ + } else { \ + smin = fma(SY10, sc2, fma(SY132, sc3, fma(SY20, sc6, (SY232) * sc7))); \ + } \ + DST_TEMP[j][n] = fma(PFX##_dm.x, fma(sx, sc0, fma(sy, sc1, fma(sz, sc4, sw * sc5))), fma(-PFX##_dm.y, smin, DST_TEMP[j][n])); \ +} while (false) + +void calc_superblock_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint v_im, const uint q_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y1_idx = i * QUANT_K + y_offset; + const uint y2_idx = y1_idx + 128; + + if (NUM_COLS <= 4) { + vec4 by10_a[NUM_COLS], by132_a[NUM_COLS], by20_a[NUM_COLS], by232_a[NUM_COLS]; + FLOAT_TYPE sy10_a[NUM_COLS], sy132_a[NUM_COLS], sy20_a[NUM_COLS], sy232_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 4; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 4; + by10_a[j] = vec4(data_b_v4[b4_1 ]); + by132_a[j] = vec4(data_b_v4[b4_1 + 8]); + by20_a[j] = vec4(data_b_v4[b4_2 ]); + by232_a[j] = vec4(data_b_v4[b4_2 + 8]); + sy10_a[j] = FLOAT_TYPE(0); sy132_a[j] = FLOAT_TYPE(0); sy20_a[j] = FLOAT_TYPE(0); sy232_a[j] = FLOAT_TYPE(0); + if (GEN_FAST_KQ != 0) { + sy10_a[j] = (FLOAT_TYPE(by10_a[j].x) + FLOAT_TYPE(by10_a[j].y)) + (FLOAT_TYPE(by10_a[j].z) + FLOAT_TYPE(by10_a[j].w)); + sy132_a[j] = (FLOAT_TYPE(by132_a[j].x) + FLOAT_TYPE(by132_a[j].y)) + (FLOAT_TYPE(by132_a[j].z) + FLOAT_TYPE(by132_a[j].w)); + sy20_a[j] = (FLOAT_TYPE(by20_a[j].x) + FLOAT_TYPE(by20_a[j].y)) + (FLOAT_TYPE(by20_a[j].z) + FLOAT_TYPE(by20_a[j].w)); + sy232_a[j] = (FLOAT_TYPE(by232_a[j].x) + FLOAT_TYPE(by232_a[j].y)) + (FLOAT_TYPE(by232_a[j].z) + FLOAT_TYPE(by232_a[j].w)); + } + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q4_K_16(a1, data_a, data_a_packed16, data_a_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q4_K_16_WITH_BY(a1, temp, by10_a[j], by132_a[j], by20_a[j], by232_a[j], sy10_a[j], sy132_a[j], sy20_a[j], sy232_a[j]); + } + if (GEN_GLU == 3) { + LOAD_Q4_K_16(a2, data_a2, data_a2_packed16, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q4_K_16_WITH_BY(a2, temp2, by10_a[j], by132_a[j], by20_a[j], by232_a[j], sy10_a[j], sy132_a[j], sy20_a[j], sy232_a[j]); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q4_K_16(a1, data_a, data_a_packed16, data_a_packed32); + if (GEN_GLU == 3) { + LOAD_Q4_K_16(a2, data_a2, data_a2_packed16, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 4; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 4; + const vec4 by10 = vec4(data_b_v4[b4_1 ]); + const vec4 by132 = vec4(data_b_v4[b4_1 + 8]); + const vec4 by20 = vec4(data_b_v4[b4_2 ]); + const vec4 by232 = vec4(data_b_v4[b4_2 + 8]); + FLOAT_TYPE sumy10 = FLOAT_TYPE(0), sumy132 = FLOAT_TYPE(0), sumy20 = FLOAT_TYPE(0), sumy232 = FLOAT_TYPE(0); + if (GEN_FAST_KQ != 0) { + sumy10 = (FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y)) + (FLOAT_TYPE(by10.z) + FLOAT_TYPE(by10.w)); + sumy132 = (FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y)) + (FLOAT_TYPE(by132.z) + FLOAT_TYPE(by132.w)); + sumy20 = (FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y)) + (FLOAT_TYPE(by20.z) + FLOAT_TYPE(by20.w)); + sumy232 = (FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y)) + (FLOAT_TYPE(by232.z) + FLOAT_TYPE(by232.w)); + } + DOT_Q4_K_16_WITH_BY(a1, temp, by10, by132, by20, by232, sumy10, sumy132, sumy20, sumy232); + DOT_Q4_K_16_WITH_BY(a2, temp2, by10, by132, by20, by232, sumy10, sumy132, sumy20, sumy232); + } + } else { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 4; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 4; + const vec4 by10 = vec4(data_b_v4[b4_1 ]); + const vec4 by132 = vec4(data_b_v4[b4_1 + 8]); + const vec4 by20 = vec4(data_b_v4[b4_2 ]); + const vec4 by232 = vec4(data_b_v4[b4_2 + 8]); + FLOAT_TYPE sumy10 = FLOAT_TYPE(0), sumy132 = FLOAT_TYPE(0), sumy20 = FLOAT_TYPE(0), sumy232 = FLOAT_TYPE(0); + if (GEN_FAST_KQ != 0) { + sumy10 = (FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y)) + (FLOAT_TYPE(by10.z) + FLOAT_TYPE(by10.w)); + sumy132 = (FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y)) + (FLOAT_TYPE(by132.z) + FLOAT_TYPE(by132.w)); + sumy20 = (FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y)) + (FLOAT_TYPE(by20.z) + FLOAT_TYPE(by20.w)); + sumy232 = (FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y)) + (FLOAT_TYPE(by232.z) + FLOAT_TYPE(by232.w)); + } + DOT_Q4_K_16_WITH_BY(a1, temp, by10, by132, by20, by232, sumy10, sumy132, sumy20, sumy232); + } + } + } + } +} -void calc_superblock(const uint a_offset, const uint b_offset, const uint v_im, const uint q_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { +void calc_superblock_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint v_im, const uint q_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { const uint y1_idx = i * QUANT_K + y_offset; const uint y2_idx = y1_idx + 128; - [[unroll]] for (uint n = 0; n < num_rows; ++n) { - const uint ib0 = a_offset + (first_row+n)*num_blocks_per_row; - const FLOAT_TYPEV2 dm = FLOAT_TYPEV2(data_a[ib0 + i].dm); - - const uint32_t scale0_u32 = data_a_packed16[ib0 + i].scales[v_im ]; - const uint32_t scale4_u32 = data_a_packed16[ib0 + i].scales[v_im + 2]; - const uint32_t scale8_u32 = data_a_packed16[ib0 + i].scales[v_im + 4]; - - const uint32_t scale_0_4_l = (scale4_u32 << 16) | scale0_u32; - const uint32_t scale_0_4_h = (scale_0_4_l & 0xC0C0C0C0) >> 2; - const vec4 scale_0_4_l_f = vec4(unpack8(scale_0_4_l & 0x3F3F3F3F)); - const vec4 scale8_f = vec4(unpack8((((scale8_u32 << 12) | scale8_u32) & 0x0F0F0F0F) | scale_0_4_h)); - - const FLOAT_TYPE sc0 = scale_0_4_l_f.x; - const FLOAT_TYPE sc1 = scale_0_4_l_f.y; - const FLOAT_TYPE sc2 = scale_0_4_l_f.z; - const FLOAT_TYPE sc3 = scale_0_4_l_f.w; - const FLOAT_TYPE sc4 = scale8_f.x; - const FLOAT_TYPE sc5 = scale8_f.y; - const FLOAT_TYPE sc6 = scale8_f.z; - const FLOAT_TYPE sc7 = scale8_f.w; - - const uint32_t qs0_u32 = data_a_packed32[ib0 + i].qs[q_offset / 4]; - const uint32_t qs64_u32 = data_a_packed32[ib0 + i].qs[q_offset / 4 + 16]; - - const uint32_t qs0_u32_lo4 = qs0_u32 & 0x0F0F0F0F; - const uint32_t qs0_u32_hi4 = (qs0_u32 >> 4) & 0x0F0F0F0F; - const uint32_t qs64_u32_lo4 = qs64_u32 & 0x0F0F0F0F; - const uint32_t qs64_u32_hi4 = (qs64_u32 >> 4) & 0x0F0F0F0F; - - const vec4 qs0_lo4 = vec4(unpack8(qs0_u32_lo4)); - const vec4 qs64_lo4 = vec4(unpack8(qs64_u32_lo4)); - const vec4 qs0_hi4 = vec4(unpack8(qs0_u32_hi4)); - const vec4 qs64_hi4 = vec4(unpack8(qs64_u32_hi4)); - - const FLOAT_TYPE q4_0 = qs0_lo4.x; - const FLOAT_TYPE q4_1 = qs0_lo4.y; - const FLOAT_TYPE q4_2 = qs0_lo4.z; - const FLOAT_TYPE q4_3 = qs0_lo4.w; - const FLOAT_TYPE q4_4 = qs0_hi4.x; - const FLOAT_TYPE q4_5 = qs0_hi4.y; - const FLOAT_TYPE q4_6 = qs0_hi4.z; - const FLOAT_TYPE q4_7 = qs0_hi4.w; - const FLOAT_TYPE q4_8 = qs64_lo4.x; - const FLOAT_TYPE q4_9 = qs64_lo4.y; - const FLOAT_TYPE q4_10 = qs64_lo4.z; - const FLOAT_TYPE q4_11 = qs64_lo4.w; - const FLOAT_TYPE q4_12 = qs64_hi4.x; - const FLOAT_TYPE q4_13 = qs64_hi4.y; - const FLOAT_TYPE q4_14 = qs64_hi4.z; - const FLOAT_TYPE q4_15 = qs64_hi4.w; + if (NUM_COLS <= 4) { + vec4 by10_a[NUM_COLS], by132_a[NUM_COLS], by20_a[NUM_COLS], by232_a[NUM_COLS]; + FLOAT_TYPE sy10_a[NUM_COLS], sy132_a[NUM_COLS], sy20_a[NUM_COLS], sy232_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 4; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 4; + by10_a[j] = vec4(data_b_v4[b4_1 ]); + by132_a[j] = vec4(data_b_v4[b4_1 + 8]); + by20_a[j] = vec4(data_b_v4[b4_2 ]); + by232_a[j] = vec4(data_b_v4[b4_2 + 8]); + sy10_a[j] = FLOAT_TYPE(0); sy132_a[j] = FLOAT_TYPE(0); sy20_a[j] = FLOAT_TYPE(0); sy232_a[j] = FLOAT_TYPE(0); + if (GEN_FAST_KQ != 0) { + sy10_a[j] = (FLOAT_TYPE(by10_a[j].x) + FLOAT_TYPE(by10_a[j].y)) + (FLOAT_TYPE(by10_a[j].z) + FLOAT_TYPE(by10_a[j].w)); + sy132_a[j] = (FLOAT_TYPE(by132_a[j].x) + FLOAT_TYPE(by132_a[j].y)) + (FLOAT_TYPE(by132_a[j].z) + FLOAT_TYPE(by132_a[j].w)); + sy20_a[j] = (FLOAT_TYPE(by20_a[j].x) + FLOAT_TYPE(by20_a[j].y)) + (FLOAT_TYPE(by20_a[j].z) + FLOAT_TYPE(by20_a[j].w)); + sy232_a[j] = (FLOAT_TYPE(by232_a[j].x) + FLOAT_TYPE(by232_a[j].y)) + (FLOAT_TYPE(by232_a[j].z) + FLOAT_TYPE(by232_a[j].w)); + } + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q4_K_16(a2, data_a2, data_a2_packed16, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q4_K_16_WITH_BY(a2, temp, by10_a[j], by132_a[j], by20_a[j], by232_a[j], sy10_a[j], sy132_a[j], sy20_a[j], sy232_a[j]); + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q4_K_16(a2, data_a2, data_a2_packed16, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 4; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 4; + const vec4 by10 = vec4(data_b_v4[b4_1 ]); + const vec4 by132 = vec4(data_b_v4[b4_1 + 8]); + const vec4 by20 = vec4(data_b_v4[b4_2 ]); + const vec4 by232 = vec4(data_b_v4[b4_2 + 8]); + FLOAT_TYPE sumy10 = FLOAT_TYPE(0), sumy132 = FLOAT_TYPE(0), sumy20 = FLOAT_TYPE(0), sumy232 = FLOAT_TYPE(0); + if (GEN_FAST_KQ != 0) { + sumy10 = (FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y)) + (FLOAT_TYPE(by10.z) + FLOAT_TYPE(by10.w)); + sumy132 = (FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y)) + (FLOAT_TYPE(by132.z) + FLOAT_TYPE(by132.w)); + sumy20 = (FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y)) + (FLOAT_TYPE(by20.z) + FLOAT_TYPE(by20.w)); + sumy232 = (FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y)) + (FLOAT_TYPE(by232.z) + FLOAT_TYPE(by232.w)); + } + DOT_Q4_K_16_WITH_BY(a2, temp, by10, by132, by20, by232, sumy10, sumy132, sumy20, sumy232); + } + } + } +} +#define LOAD_Q4_K_8(PFX, ARR_P32) \ + const FLOAT_TYPEV2 PFX##_dm = FLOAT_TYPEV2(ARR_P32[ib].dm); \ + const uint32_t PFX##_s0 = ARR_P32[ib].scales[0]; \ + const uint32_t PFX##_s1 = ARR_P32[ib].scales[1]; \ + const uint32_t PFX##_s2 = ARR_P32[ib].scales[2]; \ + const vec4 PFX##_sc03 = vec4(unpack8(PFX##_s0 & 0x3F3F3F3Fu)); \ + const vec4 PFX##_m03 = vec4(unpack8(PFX##_s1 & 0x3F3F3F3Fu)); \ + const vec4 PFX##_sc47 = vec4(unpack8((PFX##_s2 & 0x0F0F0F0Fu) | ((PFX##_s0 >> 2) & 0x30303030u))); \ + const vec4 PFX##_m47 = vec4(unpack8(((PFX##_s2 >> 4) & 0x0F0F0F0Fu) | ((PFX##_s1 >> 2) & 0x30303030u))); \ + const uint32_t PFX##_q0 = ARR_P32[ib].qs[itid8 ]; \ + const uint32_t PFX##_q1 = ARR_P32[ib].qs[itid8 + 8]; \ + const uint32_t PFX##_q2 = ARR_P32[ib].qs[itid8 + 16]; \ + const uint32_t PFX##_q3 = ARR_P32[ib].qs[itid8 + 24]; \ + const vec4 PFX##_q0_lo = vec4(unpack8(PFX##_q0 & 0x0F0F0F0Fu)); \ + const vec4 PFX##_q0_hi = vec4(unpack8((PFX##_q0 >> 4) & 0x0F0F0F0Fu)); \ + const vec4 PFX##_q1_lo = vec4(unpack8(PFX##_q1 & 0x0F0F0F0Fu)); \ + const vec4 PFX##_q1_hi = vec4(unpack8((PFX##_q1 >> 4) & 0x0F0F0F0Fu)); \ + const vec4 PFX##_q2_lo = vec4(unpack8(PFX##_q2 & 0x0F0F0F0Fu)); \ + const vec4 PFX##_q2_hi = vec4(unpack8((PFX##_q2 >> 4) & 0x0F0F0F0Fu)); \ + const vec4 PFX##_q3_lo = vec4(unpack8(PFX##_q3 & 0x0F0F0F0Fu)); \ + const vec4 PFX##_q3_hi = vec4(unpack8((PFX##_q3 >> 4) & 0x0F0F0F0Fu)) + +#define DOT_Q4_K_8_BY(PFX, DST_TEMP, BY0, BY1, BY2, BY3, BY4, BY5, BY6, BY7, SY0, SY1, SY2, SY3, SY4, SY5, SY6, SY7) do { \ + const FLOAT_TYPE d0 = dot(BY0, PFX##_q0_lo) * PFX##_sc03.x + dot(BY1, PFX##_q0_hi) * PFX##_sc03.y; \ + const FLOAT_TYPE d1 = dot(BY2, PFX##_q1_lo) * PFX##_sc03.z + dot(BY3, PFX##_q1_hi) * PFX##_sc03.w; \ + const FLOAT_TYPE d2 = dot(BY4, PFX##_q2_lo) * PFX##_sc47.x + dot(BY5, PFX##_q2_hi) * PFX##_sc47.y; \ + const FLOAT_TYPE d3 = dot(BY6, PFX##_q3_lo) * PFX##_sc47.z + dot(BY7, PFX##_q3_hi) * PFX##_sc47.w; \ + const FLOAT_TYPE sm = (SY0 * PFX##_m03.x + SY1 * PFX##_m03.y) + (SY2 * PFX##_m03.z + SY3 * PFX##_m03.w) + \ + (SY4 * PFX##_m47.x + SY5 * PFX##_m47.y) + (SY6 * PFX##_m47.z + SY7 * PFX##_m47.w); \ + DST_TEMP[j][n] = fma(PFX##_dm.x, (d0 + d1) + (d2 + d3), fma(-PFX##_dm.y, sm, DST_TEMP[j][n])); \ +} while (false) + +#define DOT_Q4_K_8(PFX, DST_TEMP) do { \ + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; \ + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8]); \ + const vec4 by2 = vec4(data_b_v4[b4 + 16]), by3 = vec4(data_b_v4[b4 + 24]); \ + const vec4 by4 = vec4(data_b_v4[b4 + 32]), by5 = vec4(data_b_v4[b4 + 40]); \ + const vec4 by6 = vec4(data_b_v4[b4 + 48]), by7 = vec4(data_b_v4[b4 + 56]); \ + const FLOAT_TYPE sy0 = (FLOAT_TYPE(by0.x) + FLOAT_TYPE(by0.y)) + (FLOAT_TYPE(by0.z) + FLOAT_TYPE(by0.w)); \ + const FLOAT_TYPE sy1 = (FLOAT_TYPE(by1.x) + FLOAT_TYPE(by1.y)) + (FLOAT_TYPE(by1.z) + FLOAT_TYPE(by1.w)); \ + const FLOAT_TYPE sy2 = (FLOAT_TYPE(by2.x) + FLOAT_TYPE(by2.y)) + (FLOAT_TYPE(by2.z) + FLOAT_TYPE(by2.w)); \ + const FLOAT_TYPE sy3 = (FLOAT_TYPE(by3.x) + FLOAT_TYPE(by3.y)) + (FLOAT_TYPE(by3.z) + FLOAT_TYPE(by3.w)); \ + const FLOAT_TYPE sy4 = (FLOAT_TYPE(by4.x) + FLOAT_TYPE(by4.y)) + (FLOAT_TYPE(by4.z) + FLOAT_TYPE(by4.w)); \ + const FLOAT_TYPE sy5 = (FLOAT_TYPE(by5.x) + FLOAT_TYPE(by5.y)) + (FLOAT_TYPE(by5.z) + FLOAT_TYPE(by5.w)); \ + const FLOAT_TYPE sy6 = (FLOAT_TYPE(by6.x) + FLOAT_TYPE(by6.y)) + (FLOAT_TYPE(by6.z) + FLOAT_TYPE(by6.w)); \ + const FLOAT_TYPE sy7 = (FLOAT_TYPE(by7.x) + FLOAT_TYPE(by7.y)) + (FLOAT_TYPE(by7.z) + FLOAT_TYPE(by7.w)); \ + DOT_Q4_K_8_BY(PFX, DST_TEMP, by0, by1, by2, by3, by4, by5, by6, by7, sy0, sy1, sy2, sy3, sy4, sy5, sy6, sy7); \ +} while (false) + +void calc_superblock_8_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint itid8, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y_idx = i * QUANT_K + 4 * itid8; + if (NUM_COLS <= 4 && NUM_ROWS > 1) { + vec4 by0_a[NUM_COLS], by1_a[NUM_COLS], by2_a[NUM_COLS], by3_a[NUM_COLS]; + vec4 by4_a[NUM_COLS], by5_a[NUM_COLS], by6_a[NUM_COLS], by7_a[NUM_COLS]; + FLOAT_TYPE sy0_a[NUM_COLS], sy1_a[NUM_COLS], sy2_a[NUM_COLS], sy3_a[NUM_COLS]; + FLOAT_TYPE sy4_a[NUM_COLS], sy5_a[NUM_COLS], sy6_a[NUM_COLS], sy7_a[NUM_COLS]; [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - vec4 by10 = vec4(data_b_v4[(j*p.batch_stride_b + b_offset + y1_idx) / 4 ]); - vec4 by132 = vec4(data_b_v4[(j*p.batch_stride_b + b_offset + y1_idx) / 4 + 8]); - vec4 by20 = vec4(data_b_v4[(j*p.batch_stride_b + b_offset + y2_idx) / 4 ]); - vec4 by232 = vec4(data_b_v4[(j*p.batch_stride_b + b_offset + y2_idx) / 4 + 8]); - - const FLOAT_TYPE sx = fma(FLOAT_TYPE(by10.x), q4_0, fma(FLOAT_TYPE(by10.y), q4_1, fma(FLOAT_TYPE(by10.z), q4_2, FLOAT_TYPE(by10.w) * q4_3))); - const FLOAT_TYPE sy = fma(FLOAT_TYPE(by132.x), q4_4, fma(FLOAT_TYPE(by132.y), q4_5, fma(FLOAT_TYPE(by132.z), q4_6, FLOAT_TYPE(by132.w) * q4_7))); - const FLOAT_TYPE sz = fma(FLOAT_TYPE(by20.x), q4_8, fma(FLOAT_TYPE(by20.y), q4_9, fma(FLOAT_TYPE(by20.z), q4_10, FLOAT_TYPE(by20.w) * q4_11))); - const FLOAT_TYPE sw = fma(FLOAT_TYPE(by232.x), q4_12, fma(FLOAT_TYPE(by232.y), q4_13, fma(FLOAT_TYPE(by232.z), q4_14, FLOAT_TYPE(by232.w) * q4_15))); - const FLOAT_TYPE smin = - fma(FLOAT_TYPE(by10.x), sc2, fma(FLOAT_TYPE(by132.x), sc3, fma(FLOAT_TYPE(by20.x), sc6, fma(FLOAT_TYPE(by232.x), sc7, - fma(FLOAT_TYPE(by10.y), sc2, fma(FLOAT_TYPE(by132.y), sc3, fma(FLOAT_TYPE(by20.y), sc6, fma(FLOAT_TYPE(by232.y), sc7, - fma(FLOAT_TYPE(by10.z), sc2, fma(FLOAT_TYPE(by132.z), sc3, fma(FLOAT_TYPE(by20.z), sc6, fma(FLOAT_TYPE(by232.z), sc7, - fma(FLOAT_TYPE(by10.w), sc2, fma(FLOAT_TYPE(by132.w), sc3, fma(FLOAT_TYPE(by20.w), sc6, FLOAT_TYPE(by232.w) * sc7))))))))))))))); - temp[j][n] = fma(dm.x, fma(sx, sc0, fma(sy, sc1, fma(sz, sc4, sw * sc5))), fma(-dm.y, smin, temp[j][n])); + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; + by0_a[j] = vec4(data_b_v4[b4 ]); by1_a[j] = vec4(data_b_v4[b4 + 8]); + by2_a[j] = vec4(data_b_v4[b4 + 16]); by3_a[j] = vec4(data_b_v4[b4 + 24]); + by4_a[j] = vec4(data_b_v4[b4 + 32]); by5_a[j] = vec4(data_b_v4[b4 + 40]); + by6_a[j] = vec4(data_b_v4[b4 + 48]); by7_a[j] = vec4(data_b_v4[b4 + 56]); + sy0_a[j] = (FLOAT_TYPE(by0_a[j].x) + FLOAT_TYPE(by0_a[j].y)) + (FLOAT_TYPE(by0_a[j].z) + FLOAT_TYPE(by0_a[j].w)); + sy1_a[j] = (FLOAT_TYPE(by1_a[j].x) + FLOAT_TYPE(by1_a[j].y)) + (FLOAT_TYPE(by1_a[j].z) + FLOAT_TYPE(by1_a[j].w)); + sy2_a[j] = (FLOAT_TYPE(by2_a[j].x) + FLOAT_TYPE(by2_a[j].y)) + (FLOAT_TYPE(by2_a[j].z) + FLOAT_TYPE(by2_a[j].w)); + sy3_a[j] = (FLOAT_TYPE(by3_a[j].x) + FLOAT_TYPE(by3_a[j].y)) + (FLOAT_TYPE(by3_a[j].z) + FLOAT_TYPE(by3_a[j].w)); + sy4_a[j] = (FLOAT_TYPE(by4_a[j].x) + FLOAT_TYPE(by4_a[j].y)) + (FLOAT_TYPE(by4_a[j].z) + FLOAT_TYPE(by4_a[j].w)); + sy5_a[j] = (FLOAT_TYPE(by5_a[j].x) + FLOAT_TYPE(by5_a[j].y)) + (FLOAT_TYPE(by5_a[j].z) + FLOAT_TYPE(by5_a[j].w)); + sy6_a[j] = (FLOAT_TYPE(by6_a[j].x) + FLOAT_TYPE(by6_a[j].y)) + (FLOAT_TYPE(by6_a[j].z) + FLOAT_TYPE(by6_a[j].w)); + sy7_a[j] = (FLOAT_TYPE(by7_a[j].x) + FLOAT_TYPE(by7_a[j].y)) + (FLOAT_TYPE(by7_a[j].z) + FLOAT_TYPE(by7_a[j].w)); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + LOAD_Q4_K_8(a1, data_a_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q4_K_8_BY(a1, temp, by0_a[j], by1_a[j], by2_a[j], by3_a[j], by4_a[j], by5_a[j], by6_a[j], by7_a[j], sy0_a[j], sy1_a[j], sy2_a[j], sy3_a[j], sy4_a[j], sy5_a[j], sy6_a[j], sy7_a[j]); + } + if (GEN_GLU == 3) { + LOAD_Q4_K_8(a2, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q4_K_8_BY(a2, temp2, by0_a[j], by1_a[j], by2_a[j], by3_a[j], by4_a[j], by5_a[j], by6_a[j], by7_a[j], sy0_a[j], sy1_a[j], sy2_a[j], sy3_a[j], sy4_a[j], sy5_a[j], sy6_a[j], sy7_a[j]); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + LOAD_Q4_K_8(a1, data_a_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q4_K_8(a1, temp); + } + if (GEN_GLU == 3) { + LOAD_Q4_K_8(a2, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q4_K_8(a2, temp2); + } + } + } + } +} + +void calc_superblock_8_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint itid8, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y_idx = i * QUANT_K + 4 * itid8; + if (NUM_COLS <= 4 && NUM_ROWS > 1) { + vec4 by0_a[NUM_COLS], by1_a[NUM_COLS], by2_a[NUM_COLS], by3_a[NUM_COLS]; + vec4 by4_a[NUM_COLS], by5_a[NUM_COLS], by6_a[NUM_COLS], by7_a[NUM_COLS]; + FLOAT_TYPE sy0_a[NUM_COLS], sy1_a[NUM_COLS], sy2_a[NUM_COLS], sy3_a[NUM_COLS]; + FLOAT_TYPE sy4_a[NUM_COLS], sy5_a[NUM_COLS], sy6_a[NUM_COLS], sy7_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; + by0_a[j] = vec4(data_b_v4[b4 ]); by1_a[j] = vec4(data_b_v4[b4 + 8]); + by2_a[j] = vec4(data_b_v4[b4 + 16]); by3_a[j] = vec4(data_b_v4[b4 + 24]); + by4_a[j] = vec4(data_b_v4[b4 + 32]); by5_a[j] = vec4(data_b_v4[b4 + 40]); + by6_a[j] = vec4(data_b_v4[b4 + 48]); by7_a[j] = vec4(data_b_v4[b4 + 56]); + sy0_a[j] = (FLOAT_TYPE(by0_a[j].x) + FLOAT_TYPE(by0_a[j].y)) + (FLOAT_TYPE(by0_a[j].z) + FLOAT_TYPE(by0_a[j].w)); + sy1_a[j] = (FLOAT_TYPE(by1_a[j].x) + FLOAT_TYPE(by1_a[j].y)) + (FLOAT_TYPE(by1_a[j].z) + FLOAT_TYPE(by1_a[j].w)); + sy2_a[j] = (FLOAT_TYPE(by2_a[j].x) + FLOAT_TYPE(by2_a[j].y)) + (FLOAT_TYPE(by2_a[j].z) + FLOAT_TYPE(by2_a[j].w)); + sy3_a[j] = (FLOAT_TYPE(by3_a[j].x) + FLOAT_TYPE(by3_a[j].y)) + (FLOAT_TYPE(by3_a[j].z) + FLOAT_TYPE(by3_a[j].w)); + sy4_a[j] = (FLOAT_TYPE(by4_a[j].x) + FLOAT_TYPE(by4_a[j].y)) + (FLOAT_TYPE(by4_a[j].z) + FLOAT_TYPE(by4_a[j].w)); + sy5_a[j] = (FLOAT_TYPE(by5_a[j].x) + FLOAT_TYPE(by5_a[j].y)) + (FLOAT_TYPE(by5_a[j].z) + FLOAT_TYPE(by5_a[j].w)); + sy6_a[j] = (FLOAT_TYPE(by6_a[j].x) + FLOAT_TYPE(by6_a[j].y)) + (FLOAT_TYPE(by6_a[j].z) + FLOAT_TYPE(by6_a[j].w)); + sy7_a[j] = (FLOAT_TYPE(by7_a[j].x) + FLOAT_TYPE(by7_a[j].y)) + (FLOAT_TYPE(by7_a[j].z) + FLOAT_TYPE(by7_a[j].w)); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + LOAD_Q4_K_8(a2, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q4_K_8_BY(a2, temp, by0_a[j], by1_a[j], by2_a[j], by3_a[j], by4_a[j], by5_a[j], by6_a[j], by7_a[j], sy0_a[j], sy1_a[j], sy2_a[j], sy3_a[j], sy4_a[j], sy5_a[j], sy6_a[j], sy7_a[j]); + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + LOAD_Q4_K_8(a2, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q4_K_8(a2, temp); + } } } } @@ -87,48 +342,244 @@ void calc_superblock(const uint a_offset, const uint b_offset, const uint v_im, void compute_outputs(const uint32_t first_row, const uint32_t num_rows) { uint a_offset, b_offset, d_offset; get_offsets(a_offset, b_offset, d_offset); +#ifndef MUL_MAT_ID + const bool use_a2 = (GEN_GLU == 2) && (first_row >= p.pair_m0); + const uint row_base = use_a2 ? (first_row - p.pair_m0) : first_row; + const uint eff_rows = (!use_a2 && GEN_GLU == 2) ? min(num_rows, p.pair_m0 - first_row) : num_rows; +#else + const bool use_a2 = false; + const uint row_base = first_row; + const uint eff_rows = num_rows; +#endif const uint num_blocks_per_row = p.ncols / QUANT_K; - // 16 threads are used to process each block - const uint it_size = gl_WorkGroupSize.x/16; +#ifdef USE_SUBGROUP_ADD_NO_SHMEM + const uint tid = gl_SubgroupInvocationID; +#else const uint tid = gl_LocalInvocationID.x; - const uint itid = tid%16; // 0...15 - const uint ix = tid/16; - - const uint il = itid/4; // 0...3 - const uint ir = itid - 4*il; // 0...3 - const uint n = 4; - - const uint v_im = il / 2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224 - const uint v_in = il % 2; +#endif - const uint l0 = n * (2 * ir + v_in); // 0...15 - const uint q_offset = 32*v_im + l0; - const uint y_offset = 64*v_im + l0; + FLOAT_TYPE temp[NUM_COLS][NUM_ROWS]; + FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS]; [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { [[unroll]] for (uint i = 0; i < NUM_ROWS; ++i) { temp[j][i] = FLOAT_TYPE(0); + if (GEN_GLU == 3) { + temp2[j][i] = FLOAT_TYPE(0); + } } } - [[unroll]] for (uint i = ix; i < num_blocks_per_row; i += it_size) - calc_superblock(a_offset, b_offset, v_im, q_offset, y_offset, i, num_blocks_per_row, first_row, num_rows); +#ifdef REPACK_PLANAR + const uint it_size8 = gl_WorkGroupSize.x >> 3u; + const uint itid8 = tid & 7u; + const uint ix8 = tid >> 3u; + for (uint i = ix8; i < num_blocks_per_row; i += it_size8) { + const uint y_idx = i * QUANT_K + 4u * itid8; + if (NUM_COLS <= 2) { + vec4 by0_a[NUM_COLS], by1_a[NUM_COLS], by2_a[NUM_COLS], by3_a[NUM_COLS]; + vec4 by4_a[NUM_COLS], by5_a[NUM_COLS], by6_a[NUM_COLS], by7_a[NUM_COLS]; + FLOAT_TYPE sy0_a[NUM_COLS], sy1_a[NUM_COLS], sy2_a[NUM_COLS], sy3_a[NUM_COLS]; + FLOAT_TYPE sy4_a[NUM_COLS], sy5_a[NUM_COLS], sy6_a[NUM_COLS], sy7_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) >> 2u; + by0_a[j] = vec4(data_b_v4[b4 ]); by1_a[j] = vec4(data_b_v4[b4 + 8u]); + by2_a[j] = vec4(data_b_v4[b4 + 16u]); by3_a[j] = vec4(data_b_v4[b4 + 24u]); + by4_a[j] = vec4(data_b_v4[b4 + 32u]); by5_a[j] = vec4(data_b_v4[b4 + 40u]); + by6_a[j] = vec4(data_b_v4[b4 + 48u]); by7_a[j] = vec4(data_b_v4[b4 + 56u]); + sy0_a[j] = (FLOAT_TYPE(by0_a[j].x) + FLOAT_TYPE(by0_a[j].y)) + (FLOAT_TYPE(by0_a[j].z) + FLOAT_TYPE(by0_a[j].w)); + sy1_a[j] = (FLOAT_TYPE(by1_a[j].x) + FLOAT_TYPE(by1_a[j].y)) + (FLOAT_TYPE(by1_a[j].z) + FLOAT_TYPE(by1_a[j].w)); + sy2_a[j] = (FLOAT_TYPE(by2_a[j].x) + FLOAT_TYPE(by2_a[j].y)) + (FLOAT_TYPE(by2_a[j].z) + FLOAT_TYPE(by2_a[j].w)); + sy3_a[j] = (FLOAT_TYPE(by3_a[j].x) + FLOAT_TYPE(by3_a[j].y)) + (FLOAT_TYPE(by3_a[j].z) + FLOAT_TYPE(by3_a[j].w)); + sy4_a[j] = (FLOAT_TYPE(by4_a[j].x) + FLOAT_TYPE(by4_a[j].y)) + (FLOAT_TYPE(by4_a[j].z) + FLOAT_TYPE(by4_a[j].w)); + sy5_a[j] = (FLOAT_TYPE(by5_a[j].x) + FLOAT_TYPE(by5_a[j].y)) + (FLOAT_TYPE(by5_a[j].z) + FLOAT_TYPE(by5_a[j].w)); + sy6_a[j] = (FLOAT_TYPE(by6_a[j].x) + FLOAT_TYPE(by6_a[j].y)) + (FLOAT_TYPE(by6_a[j].z) + FLOAT_TYPE(by6_a[j].w)); + sy7_a[j] = (FLOAT_TYPE(by7_a[j].x) + FLOAT_TYPE(by7_a[j].y)) + (FLOAT_TYPE(by7_a[j].z) + FLOAT_TYPE(by7_a[j].w)); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q4_K_SB_U4; + { + const uvec4 hdr = use_a2 ? data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4] : data_a_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const vec4 sc03 = vec4(unpack8(hdr.y & 0x3F3F3F3Fu)); + const vec4 m03 = vec4(unpack8(hdr.z & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((hdr.w & 0x0F0F0F0Fu) | ((hdr.y >> 2u) & 0x30303030u))); + const vec4 m47 = vec4(unpack8(((hdr.w >> 4u) & 0x0F0F0F0Fu) | ((hdr.z >> 2u) & 0x30303030u))); + const uvec4 q = use_a2 ? data_a2_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8] : data_a_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE d0 = dot(by0_a[j], repack_magic_u4(q.x)) * sc03.x + dot(by1_a[j], repack_magic_u4(q.x >> 4u)) * sc03.y; + const FLOAT_TYPE d1 = dot(by2_a[j], repack_magic_u4(q.y)) * sc03.z + dot(by3_a[j], repack_magic_u4(q.y >> 4u)) * sc03.w; + const FLOAT_TYPE d2 = dot(by4_a[j], repack_magic_u4(q.z)) * sc47.x + dot(by5_a[j], repack_magic_u4(q.z >> 4u)) * sc47.y; + const FLOAT_TYPE d3 = dot(by6_a[j], repack_magic_u4(q.w)) * sc47.z + dot(by7_a[j], repack_magic_u4(q.w >> 4u)) * sc47.w; + const FLOAT_TYPE sm = (sy0_a[j] * m03.x + sy1_a[j] * m03.y) + (sy2_a[j] * m03.z + sy3_a[j] * m03.w) + + (sy4_a[j] * m47.x + sy5_a[j] * m47.y) + (sy6_a[j] * m47.z + sy7_a[j] * m47.w); + temp[j][n] = fma(dm.x, (d0 + d1) + (d2 + d3), fma(-dm.y, sm, temp[j][n])); + } + } + if (GEN_GLU == 3) { + const uvec4 hdr = data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const vec4 sc03 = vec4(unpack8(hdr.y & 0x3F3F3F3Fu)); + const vec4 m03 = vec4(unpack8(hdr.z & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((hdr.w & 0x0F0F0F0Fu) | ((hdr.y >> 2u) & 0x30303030u))); + const vec4 m47 = vec4(unpack8(((hdr.w >> 4u) & 0x0F0F0F0Fu) | ((hdr.z >> 2u) & 0x30303030u))); + const uvec4 q = data_a2_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE d0 = dot(by0_a[j], repack_magic_u4(q.x)) * sc03.x + dot(by1_a[j], repack_magic_u4(q.x >> 4u)) * sc03.y; + const FLOAT_TYPE d1 = dot(by2_a[j], repack_magic_u4(q.y)) * sc03.z + dot(by3_a[j], repack_magic_u4(q.y >> 4u)) * sc03.w; + const FLOAT_TYPE d2 = dot(by4_a[j], repack_magic_u4(q.z)) * sc47.x + dot(by5_a[j], repack_magic_u4(q.z >> 4u)) * sc47.y; + const FLOAT_TYPE d3 = dot(by6_a[j], repack_magic_u4(q.w)) * sc47.z + dot(by7_a[j], repack_magic_u4(q.w >> 4u)) * sc47.w; + const FLOAT_TYPE sm = (sy0_a[j] * m03.x + sy1_a[j] * m03.y) + (sy2_a[j] * m03.z + sy3_a[j] * m03.w) + + (sy4_a[j] * m47.x + sy5_a[j] * m47.y) + (sy6_a[j] * m47.z + sy7_a[j] * m47.w); + temp2[j][n] = fma(dm.x, (d0 + d1) + (d2 + d3), fma(-dm.y, sm, temp2[j][n])); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q4_K_SB_U4; + { + const uvec4 hdr = use_a2 ? data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4] : data_a_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const vec4 sc03 = vec4(unpack8(hdr.y & 0x3F3F3F3Fu)); + const vec4 m03 = vec4(unpack8(hdr.z & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((hdr.w & 0x0F0F0F0Fu) | ((hdr.y >> 2u) & 0x30303030u))); + const vec4 m47 = vec4(unpack8(((hdr.w >> 4u) & 0x0F0F0F0Fu) | ((hdr.z >> 2u) & 0x30303030u))); + const uvec4 q = use_a2 ? data_a2_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8] : data_a_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8]; + const vec4 q0_lo = repack_magic_u4(q.x), q0_hi = repack_magic_u4(q.x >> 4u); + const vec4 q1_lo = repack_magic_u4(q.y), q1_hi = repack_magic_u4(q.y >> 4u); + const vec4 q2_lo = repack_magic_u4(q.z), q2_hi = repack_magic_u4(q.z >> 4u); + const vec4 q3_lo = repack_magic_u4(q.w), q3_hi = repack_magic_u4(q.w >> 4u); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) >> 2u; + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8u]); + const vec4 by2 = vec4(data_b_v4[b4 + 16u]), by3 = vec4(data_b_v4[b4 + 24u]); + const vec4 by4 = vec4(data_b_v4[b4 + 32u]), by5 = vec4(data_b_v4[b4 + 40u]); + const vec4 by6 = vec4(data_b_v4[b4 + 48u]), by7 = vec4(data_b_v4[b4 + 56u]); + const FLOAT_TYPE sy0 = (FLOAT_TYPE(by0.x) + FLOAT_TYPE(by0.y)) + (FLOAT_TYPE(by0.z) + FLOAT_TYPE(by0.w)); + const FLOAT_TYPE sy1 = (FLOAT_TYPE(by1.x) + FLOAT_TYPE(by1.y)) + (FLOAT_TYPE(by1.z) + FLOAT_TYPE(by1.w)); + const FLOAT_TYPE sy2 = (FLOAT_TYPE(by2.x) + FLOAT_TYPE(by2.y)) + (FLOAT_TYPE(by2.z) + FLOAT_TYPE(by2.w)); + const FLOAT_TYPE sy3 = (FLOAT_TYPE(by3.x) + FLOAT_TYPE(by3.y)) + (FLOAT_TYPE(by3.z) + FLOAT_TYPE(by3.w)); + const FLOAT_TYPE sy4 = (FLOAT_TYPE(by4.x) + FLOAT_TYPE(by4.y)) + (FLOAT_TYPE(by4.z) + FLOAT_TYPE(by4.w)); + const FLOAT_TYPE sy5 = (FLOAT_TYPE(by5.x) + FLOAT_TYPE(by5.y)) + (FLOAT_TYPE(by5.z) + FLOAT_TYPE(by5.w)); + const FLOAT_TYPE sy6 = (FLOAT_TYPE(by6.x) + FLOAT_TYPE(by6.y)) + (FLOAT_TYPE(by6.z) + FLOAT_TYPE(by6.w)); + const FLOAT_TYPE sy7 = (FLOAT_TYPE(by7.x) + FLOAT_TYPE(by7.y)) + (FLOAT_TYPE(by7.z) + FLOAT_TYPE(by7.w)); + const FLOAT_TYPE d0 = dot(by0, q0_lo) * sc03.x + dot(by1, q0_hi) * sc03.y; + const FLOAT_TYPE d1 = dot(by2, q1_lo) * sc03.z + dot(by3, q1_hi) * sc03.w; + const FLOAT_TYPE d2 = dot(by4, q2_lo) * sc47.x + dot(by5, q2_hi) * sc47.y; + const FLOAT_TYPE d3 = dot(by6, q3_lo) * sc47.z + dot(by7, q3_hi) * sc47.w; + const FLOAT_TYPE sm = (sy0 * m03.x + sy1 * m03.y) + (sy2 * m03.z + sy3 * m03.w) + + (sy4 * m47.x + sy5 * m47.y) + (sy6 * m47.z + sy7 * m47.w); + temp[j][n] = fma(dm.x, (d0 + d1) + (d2 + d3), fma(-dm.y, sm, temp[j][n])); + } + } + if (GEN_GLU == 3) { + const uvec4 hdr = data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const vec4 sc03 = vec4(unpack8(hdr.y & 0x3F3F3F3Fu)); + const vec4 m03 = vec4(unpack8(hdr.z & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((hdr.w & 0x0F0F0F0Fu) | ((hdr.y >> 2u) & 0x30303030u))); + const vec4 m47 = vec4(unpack8(((hdr.w >> 4u) & 0x0F0F0F0Fu) | ((hdr.z >> 2u) & 0x30303030u))); + const uvec4 q = data_a2_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8]; + const vec4 q0_lo = repack_magic_u4(q.x), q0_hi = repack_magic_u4(q.x >> 4u); + const vec4 q1_lo = repack_magic_u4(q.y), q1_hi = repack_magic_u4(q.y >> 4u); + const vec4 q2_lo = repack_magic_u4(q.z), q2_hi = repack_magic_u4(q.z >> 4u); + const vec4 q3_lo = repack_magic_u4(q.w), q3_hi = repack_magic_u4(q.w >> 4u); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) >> 2u; + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8u]); + const vec4 by2 = vec4(data_b_v4[b4 + 16u]), by3 = vec4(data_b_v4[b4 + 24u]); + const vec4 by4 = vec4(data_b_v4[b4 + 32u]), by5 = vec4(data_b_v4[b4 + 40u]); + const vec4 by6 = vec4(data_b_v4[b4 + 48u]), by7 = vec4(data_b_v4[b4 + 56u]); + const FLOAT_TYPE sy0 = (FLOAT_TYPE(by0.x) + FLOAT_TYPE(by0.y)) + (FLOAT_TYPE(by0.z) + FLOAT_TYPE(by0.w)); + const FLOAT_TYPE sy1 = (FLOAT_TYPE(by1.x) + FLOAT_TYPE(by1.y)) + (FLOAT_TYPE(by1.z) + FLOAT_TYPE(by1.w)); + const FLOAT_TYPE sy2 = (FLOAT_TYPE(by2.x) + FLOAT_TYPE(by2.y)) + (FLOAT_TYPE(by2.z) + FLOAT_TYPE(by2.w)); + const FLOAT_TYPE sy3 = (FLOAT_TYPE(by3.x) + FLOAT_TYPE(by3.y)) + (FLOAT_TYPE(by3.z) + FLOAT_TYPE(by3.w)); + const FLOAT_TYPE sy4 = (FLOAT_TYPE(by4.x) + FLOAT_TYPE(by4.y)) + (FLOAT_TYPE(by4.z) + FLOAT_TYPE(by4.w)); + const FLOAT_TYPE sy5 = (FLOAT_TYPE(by5.x) + FLOAT_TYPE(by5.y)) + (FLOAT_TYPE(by5.z) + FLOAT_TYPE(by5.w)); + const FLOAT_TYPE sy6 = (FLOAT_TYPE(by6.x) + FLOAT_TYPE(by6.y)) + (FLOAT_TYPE(by6.z) + FLOAT_TYPE(by6.w)); + const FLOAT_TYPE sy7 = (FLOAT_TYPE(by7.x) + FLOAT_TYPE(by7.y)) + (FLOAT_TYPE(by7.z) + FLOAT_TYPE(by7.w)); + const FLOAT_TYPE d0 = dot(by0, q0_lo) * sc03.x + dot(by1, q0_hi) * sc03.y; + const FLOAT_TYPE d1 = dot(by2, q1_lo) * sc03.z + dot(by3, q1_hi) * sc03.w; + const FLOAT_TYPE d2 = dot(by4, q2_lo) * sc47.x + dot(by5, q2_hi) * sc47.y; + const FLOAT_TYPE d3 = dot(by6, q3_lo) * sc47.z + dot(by7, q3_hi) * sc47.w; + const FLOAT_TYPE sm = (sy0 * m03.x + sy1 * m03.y) + (sy2 * m03.z + sy3 * m03.w) + + (sy4 * m47.x + sy5 * m47.y) + (sy6 * m47.z + sy7 * m47.w); + temp2[j][n] = fma(dm.x, (d0 + d1) + (d2 + d3), fma(-dm.y, sm, temp2[j][n])); + } + } + } + } + } +#else + if (GEN_FAST_KQ >= 2) { + const uint it_size8 = gl_WorkGroupSize.x / 8; + const uint itid8 = tid & 7; + const uint ix8 = tid >> 3; + if (GEN_GLU == 2 && use_a2) { + for (uint i = ix8; i < num_blocks_per_row; i += it_size8) { + calc_superblock_8_a2(temp, a_offset, b_offset, itid8, i, num_blocks_per_row, row_base, eff_rows); + } + } else { + for (uint i = ix8; i < num_blocks_per_row; i += it_size8) { + calc_superblock_8_a(temp, temp2, a_offset, b_offset, itid8, i, num_blocks_per_row, row_base, eff_rows); + } + } + } else { + // 16 threads are used to process each block + const uint it_size = gl_WorkGroupSize.x/16; + const uint itid = tid%16; // 0...15 + const uint ix = tid/16; + + const uint il = itid/4; // 0...3 + const uint ir = itid - 4*il; // 0...3 + const uint n = 4; + + const uint v_im = il / 2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224 + const uint v_in = il % 2; + + const uint l0 = n * (2 * ir + v_in); // 0...15 + const uint q_offset = 32*v_im + l0; + const uint y_offset = 64*v_im + l0; + + if (GEN_GLU == 2 && use_a2) { + for (uint i = ix; i < num_blocks_per_row; i += it_size) { + calc_superblock_a2(temp, a_offset, b_offset, v_im, q_offset, y_offset, i, num_blocks_per_row, row_base, eff_rows); + } + } else { + for (uint i = ix; i < num_blocks_per_row; i += it_size) { + calc_superblock_a(temp, temp2, a_offset, b_offset, v_im, q_offset, y_offset, i, num_blocks_per_row, row_base, eff_rows); + } + } + } +#endif - reduce_result(temp, d_offset, first_row, num_rows, tid); + if (GEN_GLU == 3) { + reduce_pair_glu(temp, temp2, d_offset, first_row, eff_rows, tid); + } +#ifndef MUL_MAT_ID + else if (GEN_GLU == 2 && use_a2) { + reduce_result_d2(temp, row_base, eff_rows, tid); + } +#endif + else { + reduce_result(temp, d_offset, first_row, eff_rows, tid); + } } void main() { +#ifdef USE_SUBGROUP_ADD_NO_SHMEM + const uint first_row = NUM_ROWS * (NUM_SUBGROUPS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z) + gl_SubgroupID); +#else const uint first_row = NUM_ROWS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z); +#endif - // do NUM_ROWS at a time, unless there aren't enough remaining rows - if (first_row + NUM_ROWS <= p.stride_d) { - compute_outputs(first_row, NUM_ROWS); - } else { - if (first_row >= p.stride_d) { - return; - } - compute_outputs(first_row, p.stride_d - first_row); + if (first_row >= p.stride_d) { + return; } + compute_outputs(first_row, min(NUM_ROWS, p.stride_d - first_row)); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q5_k.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q5_k.comp index 54d7e1bcdca6..bcf485d3a2bc 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q5_k.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q5_k.comp @@ -1,117 +1,421 @@ #version 450 #extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#ifdef REPACK_PLANAR +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable +#endif #include "mul_mat_vec_base.glsl" +#ifdef REPACK_PLANAR +#include "repack_planar.glsl" +layout (binding = 0) readonly buffer A_U32 { uint data_a_u32[]; }; +layout (binding = 0) readonly buffer A_U4 { uvec4 data_a_u4[]; }; +layout (binding = 3) readonly buffer A2_U32 { uint data_a2_u32[]; }; +layout (binding = 3) readonly buffer A2_U4 { uvec4 data_a2_u4[]; }; +#endif + +#ifdef USE_SUBGROUP_ADD_NO_SHMEM +layout(local_size_x_id = 0, local_size_y_id = 4, local_size_z = 1) in; +#else layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; +#endif + +#define LOAD_Q5_K_0ULP(PFX, ARR_A, ARR_P16) \ + const FLOAT_TYPEV2 PFX##_dm = FLOAT_TYPEV2(ARR_A[ib0 + i].dm); \ + const uint32_t PFX##_scale0_u32 = ARR_P16[ib0 + i].scales[v_im ]; \ + const uint32_t PFX##_scale4_u32 = ARR_P16[ib0 + i].scales[v_im + 2]; \ + const uint32_t PFX##_scale8_u32 = ARR_P16[ib0 + i].scales[v_im + 4]; \ + const uint32_t PFX##_scale_0_4_l = (PFX##_scale4_u32 << 16) | PFX##_scale0_u32; \ + const uint32_t PFX##_scale_0_4_h = (PFX##_scale_0_4_l & 0xC0C0C0C0u) >> 2; \ + const vec4 PFX##_sc03 = vec4(unpack8(PFX##_scale_0_4_l & 0x3F3F3F3Fu)); \ + const vec4 PFX##_sc47 = vec4(unpack8((((PFX##_scale8_u32 << 12) | PFX##_scale8_u32) & 0x0F0F0F0Fu) | PFX##_scale_0_4_h)); \ + const uint32_t PFX##_qs0_16_u32 = uint32_t(ARR_P16[ib0 + i].qs[q_offset / 2]) | (uint32_t(ARR_P16[ib0 + i].qs[q_offset / 2 + 8]) << 16); \ + const uint32_t PFX##_qs64_80_u32 = uint32_t(ARR_P16[ib0 + i].qs[q_offset / 2 + 32]) | (uint32_t(ARR_P16[ib0 + i].qs[q_offset / 2 + 40]) << 16); \ + const uint32_t PFX##_qh = pack32(u16vec2(ARR_P16[ib0 + i].qh[l0 / 2], ARR_P16[ib0 + i].qh[l0 / 2 + 8])); \ + const vec4 PFX##_qs0_16_lo4 = vec4(unpack8((PFX##_qs0_16_u32 & 0x0F0F0F0Fu) + (((PFX##_qh >> (2*v_im)) & 0x01010101u) << 4))); \ + const vec4 PFX##_qs0_16_hi4 = vec4(unpack8(((PFX##_qs0_16_u32 >> 4) & 0x0F0F0F0Fu) + (((PFX##_qh >> (2*v_im)) & 0x02020202u) << 3))); \ + const vec4 PFX##_qs64_80_lo4 = vec4(unpack8((PFX##_qs64_80_u32 & 0x0F0F0F0Fu) + ((PFX##_qh >> (2*v_im)) & 0x10101010u))); \ + const vec4 PFX##_qs64_80_hi4 = vec4(unpack8(((PFX##_qs64_80_u32 >> 4) & 0x0F0F0F0Fu) + (((PFX##_qh >> (2*v_im)) & 0x20202020u) >> 1))) + +#define DOT_Q5_K_0ULP_WITH_BY(PFX, DST_TEMP, BY10, BY116, BY132, BY148, BY20, BY216, BY232, BY248, SY0, SY1, SY2, SY3) do { \ + const FLOAT_TYPE sx = fma(FLOAT_TYPE((BY10).x), PFX##_qs0_16_lo4.x, fma(FLOAT_TYPE((BY10).y), PFX##_qs0_16_lo4.y, fma(FLOAT_TYPE((BY116).x), PFX##_qs0_16_lo4.z, FLOAT_TYPE((BY116).y) * PFX##_qs0_16_lo4.w))); \ + const FLOAT_TYPE sy = fma(FLOAT_TYPE((BY132).x), PFX##_qs0_16_hi4.x, fma(FLOAT_TYPE((BY132).y), PFX##_qs0_16_hi4.y, fma(FLOAT_TYPE((BY148).x), PFX##_qs0_16_hi4.z, FLOAT_TYPE((BY148).y) * PFX##_qs0_16_hi4.w))); \ + const FLOAT_TYPE sz = fma(FLOAT_TYPE((BY20).x), PFX##_qs64_80_lo4.x, fma(FLOAT_TYPE((BY20).y), PFX##_qs64_80_lo4.y, fma(FLOAT_TYPE((BY216).x), PFX##_qs64_80_lo4.z, FLOAT_TYPE((BY216).y) * PFX##_qs64_80_lo4.w))); \ + const FLOAT_TYPE sw = fma(FLOAT_TYPE((BY232).x), PFX##_qs64_80_hi4.x, fma(FLOAT_TYPE((BY232).y), PFX##_qs64_80_hi4.y, fma(FLOAT_TYPE((BY248).x), PFX##_qs64_80_hi4.z, FLOAT_TYPE((BY248).y) * PFX##_qs64_80_hi4.w))); \ + const FLOAT_TYPE smin = fma(SY0, PFX##_sc03.z, fma(SY1, PFX##_sc03.w, fma(SY2, PFX##_sc47.z, (SY3) * PFX##_sc47.w))); \ + DST_TEMP[j][n] = fma(PFX##_dm.x, fma(sx, PFX##_sc03.x, fma(sy, PFX##_sc03.y, fma(sz, PFX##_sc47.x, sw * PFX##_sc47.y))), fma(-PFX##_dm.y, smin, DST_TEMP[j][n])); \ +} while (false) + +void calc_superblock_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint v_im, const uint l0, const uint q_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y1_idx = i * QUANT_K + y_offset; + const uint y2_idx = y1_idx + 128; + + if (NUM_COLS <= 4) { + vec2 by10_a[4], by116_a[4], by132_a[4], by148_a[4]; + vec2 by20_a[4], by216_a[4], by232_a[4], by248_a[4]; + FLOAT_TYPE sy0_a[4], sy1_a[4], sy2_a[4], sy3_a[4]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b2_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 2; + const uint b2_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 2; + by10_a[j] = vec2(data_b_v2[b2_1 ]); by116_a[j] = vec2(data_b_v2[b2_1 + 8]); + by132_a[j] = vec2(data_b_v2[b2_1 + 16]); by148_a[j] = vec2(data_b_v2[b2_1 + 24]); + by20_a[j] = vec2(data_b_v2[b2_2 ]); by216_a[j] = vec2(data_b_v2[b2_2 + 8]); + by232_a[j] = vec2(data_b_v2[b2_2 + 16]); by248_a[j] = vec2(data_b_v2[b2_2 + 24]); + sy0_a[j] = FLOAT_TYPE(by10_a[j].x) + FLOAT_TYPE(by10_a[j].y) + FLOAT_TYPE(by116_a[j].x) + FLOAT_TYPE(by116_a[j].y); + sy1_a[j] = FLOAT_TYPE(by132_a[j].x) + FLOAT_TYPE(by132_a[j].y) + FLOAT_TYPE(by148_a[j].x) + FLOAT_TYPE(by148_a[j].y); + sy2_a[j] = FLOAT_TYPE(by20_a[j].x) + FLOAT_TYPE(by20_a[j].y) + FLOAT_TYPE(by216_a[j].x) + FLOAT_TYPE(by216_a[j].y); + sy3_a[j] = FLOAT_TYPE(by232_a[j].x) + FLOAT_TYPE(by232_a[j].y) + FLOAT_TYPE(by248_a[j].x) + FLOAT_TYPE(by248_a[j].y); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q5_K_0ULP(a1, data_a, data_a_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_0ULP_WITH_BY(a1, temp, by10_a[j], by116_a[j], by132_a[j], by148_a[j], by20_a[j], by216_a[j], by232_a[j], by248_a[j], sy0_a[j], sy1_a[j], sy2_a[j], sy3_a[j]); + } + if (GEN_GLU == 3) { + LOAD_Q5_K_0ULP(a2, data_a2, data_a2_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_0ULP_WITH_BY(a2, temp2, by10_a[j], by116_a[j], by132_a[j], by148_a[j], by20_a[j], by216_a[j], by232_a[j], by248_a[j], sy0_a[j], sy1_a[j], sy2_a[j], sy3_a[j]); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q5_K_0ULP(a1, data_a, data_a_packed16); + if (GEN_GLU == 3) { + LOAD_Q5_K_0ULP(a2, data_a2, data_a2_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b2_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 2; + const uint b2_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 2; + const vec2 by10 = vec2(data_b_v2[b2_1 ]), by116 = vec2(data_b_v2[b2_1 + 8]); + const vec2 by132 = vec2(data_b_v2[b2_1 + 16]), by148 = vec2(data_b_v2[b2_1 + 24]); + const vec2 by20 = vec2(data_b_v2[b2_2 ]), by216 = vec2(data_b_v2[b2_2 + 8]); + const vec2 by232 = vec2(data_b_v2[b2_2 + 16]), by248 = vec2(data_b_v2[b2_2 + 24]); + const FLOAT_TYPE sumy0 = FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y) + FLOAT_TYPE(by116.x) + FLOAT_TYPE(by116.y); + const FLOAT_TYPE sumy1 = FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y) + FLOAT_TYPE(by148.x) + FLOAT_TYPE(by148.y); + const FLOAT_TYPE sumy2 = FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y) + FLOAT_TYPE(by216.x) + FLOAT_TYPE(by216.y); + const FLOAT_TYPE sumy3 = FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y) + FLOAT_TYPE(by248.x) + FLOAT_TYPE(by248.y); + DOT_Q5_K_0ULP_WITH_BY(a1, temp, by10, by116, by132, by148, by20, by216, by232, by248, sumy0, sumy1, sumy2, sumy3); + DOT_Q5_K_0ULP_WITH_BY(a2, temp2, by10, by116, by132, by148, by20, by216, by232, by248, sumy0, sumy1, sumy2, sumy3); + } + } else { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b2_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 2; + const uint b2_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 2; + const vec2 by10 = vec2(data_b_v2[b2_1 ]), by116 = vec2(data_b_v2[b2_1 + 8]); + const vec2 by132 = vec2(data_b_v2[b2_1 + 16]), by148 = vec2(data_b_v2[b2_1 + 24]); + const vec2 by20 = vec2(data_b_v2[b2_2 ]), by216 = vec2(data_b_v2[b2_2 + 8]); + const vec2 by232 = vec2(data_b_v2[b2_2 + 16]), by248 = vec2(data_b_v2[b2_2 + 24]); + const FLOAT_TYPE sumy0 = FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y) + FLOAT_TYPE(by116.x) + FLOAT_TYPE(by116.y); + const FLOAT_TYPE sumy1 = FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y) + FLOAT_TYPE(by148.x) + FLOAT_TYPE(by148.y); + const FLOAT_TYPE sumy2 = FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y) + FLOAT_TYPE(by216.x) + FLOAT_TYPE(by216.y); + const FLOAT_TYPE sumy3 = FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y) + FLOAT_TYPE(by248.x) + FLOAT_TYPE(by248.y); + DOT_Q5_K_0ULP_WITH_BY(a1, temp, by10, by116, by132, by148, by20, by216, by232, by248, sumy0, sumy1, sumy2, sumy3); + } + } + } + } +} + +void calc_superblock_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint v_im, const uint l0, const uint q_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y1_idx = i * QUANT_K + y_offset; + const uint y2_idx = y1_idx + 128; -FLOAT_TYPE temp[NUM_COLS][NUM_ROWS]; + if (NUM_COLS <= 4) { + vec2 by10_a[4], by116_a[4], by132_a[4], by148_a[4]; + vec2 by20_a[4], by216_a[4], by232_a[4], by248_a[4]; + FLOAT_TYPE sy0_a[4], sy1_a[4], sy2_a[4], sy3_a[4]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b2_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 2; + const uint b2_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 2; + by10_a[j] = vec2(data_b_v2[b2_1 ]); by116_a[j] = vec2(data_b_v2[b2_1 + 8]); + by132_a[j] = vec2(data_b_v2[b2_1 + 16]); by148_a[j] = vec2(data_b_v2[b2_1 + 24]); + by20_a[j] = vec2(data_b_v2[b2_2 ]); by216_a[j] = vec2(data_b_v2[b2_2 + 8]); + by232_a[j] = vec2(data_b_v2[b2_2 + 16]); by248_a[j] = vec2(data_b_v2[b2_2 + 24]); + sy0_a[j] = FLOAT_TYPE(by10_a[j].x) + FLOAT_TYPE(by10_a[j].y) + FLOAT_TYPE(by116_a[j].x) + FLOAT_TYPE(by116_a[j].y); + sy1_a[j] = FLOAT_TYPE(by132_a[j].x) + FLOAT_TYPE(by132_a[j].y) + FLOAT_TYPE(by148_a[j].x) + FLOAT_TYPE(by148_a[j].y); + sy2_a[j] = FLOAT_TYPE(by20_a[j].x) + FLOAT_TYPE(by20_a[j].y) + FLOAT_TYPE(by216_a[j].x) + FLOAT_TYPE(by216_a[j].y); + sy3_a[j] = FLOAT_TYPE(by232_a[j].x) + FLOAT_TYPE(by232_a[j].y) + FLOAT_TYPE(by248_a[j].x) + FLOAT_TYPE(by248_a[j].y); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q5_K_0ULP(a2, data_a2, data_a2_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_0ULP_WITH_BY(a2, temp, by10_a[j], by116_a[j], by132_a[j], by148_a[j], by20_a[j], by216_a[j], by232_a[j], by248_a[j], sy0_a[j], sy1_a[j], sy2_a[j], sy3_a[j]); + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q5_K_0ULP(a2, data_a2, data_a2_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b2_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 2; + const uint b2_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 2; + const vec2 by10 = vec2(data_b_v2[b2_1 ]), by116 = vec2(data_b_v2[b2_1 + 8]); + const vec2 by132 = vec2(data_b_v2[b2_1 + 16]), by148 = vec2(data_b_v2[b2_1 + 24]); + const vec2 by20 = vec2(data_b_v2[b2_2 ]), by216 = vec2(data_b_v2[b2_2 + 8]); + const vec2 by232 = vec2(data_b_v2[b2_2 + 16]), by248 = vec2(data_b_v2[b2_2 + 24]); + const FLOAT_TYPE sumy0 = FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y) + FLOAT_TYPE(by116.x) + FLOAT_TYPE(by116.y); + const FLOAT_TYPE sumy1 = FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y) + FLOAT_TYPE(by148.x) + FLOAT_TYPE(by148.y); + const FLOAT_TYPE sumy2 = FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y) + FLOAT_TYPE(by216.x) + FLOAT_TYPE(by216.y); + const FLOAT_TYPE sumy3 = FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y) + FLOAT_TYPE(by248.x) + FLOAT_TYPE(by248.y); + DOT_Q5_K_0ULP_WITH_BY(a2, temp, by10, by116, by132, by148, by20, by216, by232, by248, sumy0, sumy1, sumy2, sumy3); + } + } + } +} + +#define LOAD_Q5_K_16_VEC4(PFX, ARR_A, ARR_P16, ARR_P32) \ + const FLOAT_TYPEV2 PFX##_dm = FLOAT_TYPEV2(ARR_A[ib0 + i].dm); \ + const uint32_t PFX##_scale0_u32 = ARR_P16[ib0 + i].scales[v_im ]; \ + const uint32_t PFX##_scale4_u32 = ARR_P16[ib0 + i].scales[v_im + 2]; \ + const uint32_t PFX##_scale8_u32 = ARR_P16[ib0 + i].scales[v_im + 4]; \ + const uint32_t PFX##_scale_0_4_l = (PFX##_scale4_u32 << 16) | PFX##_scale0_u32; \ + const uint32_t PFX##_scale_0_4_h = (PFX##_scale_0_4_l & 0xC0C0C0C0u) >> 2; \ + const vec4 PFX##_sc03 = vec4(unpack8(PFX##_scale_0_4_l & 0x3F3F3F3Fu)); \ + const vec4 PFX##_sc47 = vec4(unpack8((((PFX##_scale8_u32 << 12) | PFX##_scale8_u32) & 0x0F0F0F0Fu) | PFX##_scale_0_4_h)); \ + const uint32_t PFX##_qs0_u32 = ARR_P32[ib0 + i].qs[q_offset / 4]; \ + const uint32_t PFX##_qs64_u32 = ARR_P32[ib0 + i].qs[q_offset / 4 + 16]; \ + const uint32_t PFX##_qh_s = ARR_P32[ib0 + i].qh[l0 / 4] >> (2 * v_im); \ + const vec4 PFX##_q0_lo = vec4(unpack8((PFX##_qs0_u32 & 0x0F0F0F0Fu) | ((PFX##_qh_s & 0x01010101u) << 4))); \ + const vec4 PFX##_q0_hi = vec4(unpack8(((PFX##_qs0_u32 >> 4) & 0x0F0F0F0Fu) | ((PFX##_qh_s & 0x02020202u) << 3))); \ + const vec4 PFX##_q2_lo = vec4(unpack8((PFX##_qs64_u32 & 0x0F0F0F0Fu) | (PFX##_qh_s & 0x10101010u))); \ + const vec4 PFX##_q2_hi = vec4(unpack8(((PFX##_qs64_u32 >> 4) & 0x0F0F0F0Fu) | ((PFX##_qh_s & 0x20202020u) >> 1))) + +#define DOT_Q5_K_16_VEC4(PFX, DST_TEMP) do { \ + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 4; \ + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 4; \ + const vec4 by10 = vec4(data_b_v4[b4_1 ]), by132 = vec4(data_b_v4[b4_1 + 8]); \ + const vec4 by20 = vec4(data_b_v4[b4_2 ]), by232 = vec4(data_b_v4[b4_2 + 8]); \ + const FLOAT_TYPE sumy10 = (FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y)) + (FLOAT_TYPE(by10.z) + FLOAT_TYPE(by10.w)); \ + const FLOAT_TYPE sumy132 = (FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y)) + (FLOAT_TYPE(by132.z) + FLOAT_TYPE(by132.w)); \ + const FLOAT_TYPE sumy20 = (FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y)) + (FLOAT_TYPE(by20.z) + FLOAT_TYPE(by20.w)); \ + const FLOAT_TYPE sumy232 = (FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y)) + (FLOAT_TYPE(by232.z) + FLOAT_TYPE(by232.w)); \ + const FLOAT_TYPE sx = dot(by10, PFX##_q0_lo); \ + const FLOAT_TYPE sy = dot(by132, PFX##_q0_hi); \ + const FLOAT_TYPE sz = dot(by20, PFX##_q2_lo); \ + const FLOAT_TYPE sw = dot(by232, PFX##_q2_hi); \ + const FLOAT_TYPE smin = fma(sumy10, PFX##_sc03.z, fma(sumy132, PFX##_sc03.w, fma(sumy20, PFX##_sc47.z, sumy232 * PFX##_sc47.w))); \ + DST_TEMP[j][n] = fma(PFX##_dm.x, fma(sx, PFX##_sc03.x, fma(sy, PFX##_sc03.y, fma(sz, PFX##_sc47.x, sw * PFX##_sc47.y))), fma(-PFX##_dm.y, smin, DST_TEMP[j][n])); \ +} while (false) + +#define DOT_Q5_K_16_VEC4_BY(PFX, DST_TEMP, BY10, BY132, BY20, BY232, SY10, SY132, SY20, SY232) do { \ + const FLOAT_TYPE sx = dot(BY10, PFX##_q0_lo); \ + const FLOAT_TYPE sy = dot(BY132, PFX##_q0_hi); \ + const FLOAT_TYPE sz = dot(BY20, PFX##_q2_lo); \ + const FLOAT_TYPE sw = dot(BY232, PFX##_q2_hi); \ + const FLOAT_TYPE smin = fma(SY10, PFX##_sc03.z, fma(SY132, PFX##_sc03.w, fma(SY20, PFX##_sc47.z, (SY232) * PFX##_sc47.w))); \ + DST_TEMP[j][n] = fma(PFX##_dm.x, fma(sx, PFX##_sc03.x, fma(sy, PFX##_sc03.y, fma(sz, PFX##_sc47.x, sw * PFX##_sc47.y))), fma(-PFX##_dm.y, smin, DST_TEMP[j][n])); \ +} while (false) + +void calc_superblock_vec4_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint v_im, const uint l0, const uint q_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y1_idx = i * QUANT_K + y_offset; + const uint y2_idx = y1_idx + 128; + + if (GEN_FAST_KQ > 0) { + if (NUM_COLS <= 4) { + vec4 by10_a[NUM_COLS], by132_a[NUM_COLS], by20_a[NUM_COLS], by232_a[NUM_COLS]; + FLOAT_TYPE sy10_a[NUM_COLS], sy132_a[NUM_COLS], sy20_a[NUM_COLS], sy232_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 4; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 4; + by10_a[j] = vec4(data_b_v4[b4_1 ]); by132_a[j] = vec4(data_b_v4[b4_1 + 8]); + by20_a[j] = vec4(data_b_v4[b4_2 ]); by232_a[j] = vec4(data_b_v4[b4_2 + 8]); + sy10_a[j] = (FLOAT_TYPE(by10_a[j].x) + FLOAT_TYPE(by10_a[j].y)) + (FLOAT_TYPE(by10_a[j].z) + FLOAT_TYPE(by10_a[j].w)); + sy132_a[j] = (FLOAT_TYPE(by132_a[j].x) + FLOAT_TYPE(by132_a[j].y)) + (FLOAT_TYPE(by132_a[j].z) + FLOAT_TYPE(by132_a[j].w)); + sy20_a[j] = (FLOAT_TYPE(by20_a[j].x) + FLOAT_TYPE(by20_a[j].y)) + (FLOAT_TYPE(by20_a[j].z) + FLOAT_TYPE(by20_a[j].w)); + sy232_a[j] = (FLOAT_TYPE(by232_a[j].x) + FLOAT_TYPE(by232_a[j].y)) + (FLOAT_TYPE(by232_a[j].z) + FLOAT_TYPE(by232_a[j].w)); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q5_K_16_VEC4(a1, data_a, data_a_packed16, data_a_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_16_VEC4_BY(a1, temp, by10_a[j], by132_a[j], by20_a[j], by232_a[j], sy10_a[j], sy132_a[j], sy20_a[j], sy232_a[j]); + } + if (GEN_GLU == 3) { + LOAD_Q5_K_16_VEC4(a2, data_a2, data_a2_packed16, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_16_VEC4_BY(a2, temp2, by10_a[j], by132_a[j], by20_a[j], by232_a[j], sy10_a[j], sy132_a[j], sy20_a[j], sy232_a[j]); + } + } + } + return; + } + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q5_K_16_VEC4(a1, data_a, data_a_packed16, data_a_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_16_VEC4(a1, temp); + } + if (GEN_GLU == 3) { + LOAD_Q5_K_16_VEC4(a2, data_a2, data_a2_packed16, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_16_VEC4(a2, temp2); + } + } + } +} -void calc_superblock(const uint a_offset, const uint b_offset, const uint v_im, const uint l0, const uint q_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { +void calc_superblock_vec4_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint v_im, const uint l0, const uint q_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { const uint y1_idx = i * QUANT_K + y_offset; const uint y2_idx = y1_idx + 128; - [[unroll]] for (uint n = 0; n < num_rows; ++n) { - const uint ib0 = a_offset + (first_row+n)*num_blocks_per_row; - const FLOAT_TYPEV2 dm = FLOAT_TYPEV2(data_a[ib0 + i].dm); - - const uint32_t scale0_u32 = data_a_packed16[ib0 + i].scales[v_im ]; - const uint32_t scale4_u32 = data_a_packed16[ib0 + i].scales[v_im + 2]; - const uint32_t scale8_u32 = data_a_packed16[ib0 + i].scales[v_im + 4]; - - const uint32_t scale_0_4_l = (scale4_u32 << 16) | scale0_u32; - const uint32_t scale_0_4_h = (scale_0_4_l & 0xC0C0C0C0) >> 2; - const vec4 scale_0_4_l_f = vec4(unpack8(scale_0_4_l & 0x3F3F3F3F)); - const vec4 scale8_f = vec4(unpack8((((scale8_u32 << 12) | scale8_u32) & 0x0F0F0F0F) | scale_0_4_h)); - - const FLOAT_TYPE sc0 = scale_0_4_l_f.x; - const FLOAT_TYPE sc1 = scale_0_4_l_f.y; - const FLOAT_TYPE sc2 = scale_0_4_l_f.z; - const FLOAT_TYPE sc3 = scale_0_4_l_f.w; - const FLOAT_TYPE sc4 = scale8_f.x; - const FLOAT_TYPE sc5 = scale8_f.y; - const FLOAT_TYPE sc6 = scale8_f.z; - const FLOAT_TYPE sc7 = scale8_f.w; - - const uint32_t qs0_16_u32 = uint32_t(data_a_packed16[ib0 + i].qs[q_offset / 2]) | (uint32_t(data_a_packed16[ib0 + i].qs[q_offset / 2 + 8]) << 16); - const uint32_t qs64_80_u32 = uint32_t(data_a_packed16[ib0 + i].qs[q_offset / 2 + 32]) | (uint32_t(data_a_packed16[ib0 + i].qs[q_offset / 2 + 40]) << 16); - - uint32_t qs0_16_u32_lo4 = qs0_16_u32 & 0x0F0F0F0F; - uint32_t qs0_16_u32_hi4 = (qs0_16_u32 >> 4) & 0x0F0F0F0F; - uint32_t qs64_80_u32_lo4 = qs64_80_u32 & 0x0F0F0F0F; - uint32_t qs64_80_u32_hi4 = (qs64_80_u32 >> 4) & 0x0F0F0F0F; - - const uint32_t qh = pack32(u16vec2(data_a_packed16[ib0 + i].qh[l0 / 2], data_a_packed16[ib0 + i].qh[l0 / 2 + 8])); - - const uint32_t qs0_16_lo4_offset16 = ((qh >> (2*v_im)) & 0x01010101) << 4; - const uint32_t qs0_16_hi4_offset16 = ((qh >> (2*v_im)) & 0x02020202) << 3; - const uint32_t qs64_80_lo4_offset16 = ((qh >> (2*v_im)) & 0x10101010); - const uint32_t qs64_80_hi4_offset16 = ((qh >> (2*v_im)) & 0x20202020) >> 1; - - qs0_16_u32_lo4 += qs0_16_lo4_offset16; - qs0_16_u32_hi4 += qs0_16_hi4_offset16; - qs64_80_u32_lo4 += qs64_80_lo4_offset16; - qs64_80_u32_hi4 += qs64_80_hi4_offset16; - - const vec4 qs0_16_lo4 = vec4(unpack8(qs0_16_u32_lo4)); - const vec4 qs64_80_lo4 = vec4(unpack8(qs64_80_u32_lo4)); - const vec4 qs0_16_hi4 = vec4(unpack8(qs0_16_u32_hi4)); - const vec4 qs64_80_hi4 = vec4(unpack8(qs64_80_u32_hi4)); - - const FLOAT_TYPE q4_0 = qs0_16_lo4.x; - const FLOAT_TYPE q4_1 = qs0_16_lo4.y; - const FLOAT_TYPE q4_2 = qs0_16_lo4.z; - const FLOAT_TYPE q4_3 = qs0_16_lo4.w; - const FLOAT_TYPE q4_4 = qs0_16_hi4.x; - const FLOAT_TYPE q4_5 = qs0_16_hi4.y; - const FLOAT_TYPE q4_6 = qs0_16_hi4.z; - const FLOAT_TYPE q4_7 = qs0_16_hi4.w; - const FLOAT_TYPE q4_8 = qs64_80_lo4.x; - const FLOAT_TYPE q4_9 = qs64_80_lo4.y; - const FLOAT_TYPE q4_10 = qs64_80_lo4.z; - const FLOAT_TYPE q4_11 = qs64_80_lo4.w; - const FLOAT_TYPE q4_12 = qs64_80_hi4.x; - const FLOAT_TYPE q4_13 = qs64_80_hi4.y; - const FLOAT_TYPE q4_14 = qs64_80_hi4.z; - const FLOAT_TYPE q4_15 = qs64_80_hi4.w; + if (GEN_FAST_KQ > 0) { + if (NUM_COLS <= 4) { + vec4 by10_a[NUM_COLS], by132_a[NUM_COLS], by20_a[NUM_COLS], by232_a[NUM_COLS]; + FLOAT_TYPE sy10_a[NUM_COLS], sy132_a[NUM_COLS], sy20_a[NUM_COLS], sy232_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) / 4; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) / 4; + by10_a[j] = vec4(data_b_v4[b4_1 ]); by132_a[j] = vec4(data_b_v4[b4_1 + 8]); + by20_a[j] = vec4(data_b_v4[b4_2 ]); by232_a[j] = vec4(data_b_v4[b4_2 + 8]); + sy10_a[j] = (FLOAT_TYPE(by10_a[j].x) + FLOAT_TYPE(by10_a[j].y)) + (FLOAT_TYPE(by10_a[j].z) + FLOAT_TYPE(by10_a[j].w)); + sy132_a[j] = (FLOAT_TYPE(by132_a[j].x) + FLOAT_TYPE(by132_a[j].y)) + (FLOAT_TYPE(by132_a[j].z) + FLOAT_TYPE(by132_a[j].w)); + sy20_a[j] = (FLOAT_TYPE(by20_a[j].x) + FLOAT_TYPE(by20_a[j].y)) + (FLOAT_TYPE(by20_a[j].z) + FLOAT_TYPE(by20_a[j].w)); + sy232_a[j] = (FLOAT_TYPE(by232_a[j].x) + FLOAT_TYPE(by232_a[j].y)) + (FLOAT_TYPE(by232_a[j].z) + FLOAT_TYPE(by232_a[j].w)); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q5_K_16_VEC4(a2, data_a2, data_a2_packed16, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_16_VEC4_BY(a2, temp, by10_a[j], by132_a[j], by20_a[j], by232_a[j], sy10_a[j], sy132_a[j], sy20_a[j], sy232_a[j]); + } + } + return; + } + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q5_K_16_VEC4(a2, data_a2, data_a2_packed16, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_16_VEC4(a2, temp); + } + } +} + +#define LOAD_Q5_K_8(PFX, ARR_P32) \ + const FLOAT_TYPEV2 PFX##_dm = FLOAT_TYPEV2(ARR_P32[ib].dm); \ + const uint32_t PFX##_s0 = ARR_P32[ib].scales[0]; \ + const uint32_t PFX##_s1 = ARR_P32[ib].scales[1]; \ + const uint32_t PFX##_s2 = ARR_P32[ib].scales[2]; \ + const vec4 PFX##_sc03 = vec4(unpack8(PFX##_s0 & 0x3F3F3F3Fu)); \ + const vec4 PFX##_m03 = vec4(unpack8(PFX##_s1 & 0x3F3F3F3Fu)); \ + const vec4 PFX##_sc47 = vec4(unpack8((PFX##_s2 & 0x0F0F0F0Fu) | ((PFX##_s0 >> 2) & 0x30303030u))); \ + const vec4 PFX##_m47 = vec4(unpack8(((PFX##_s2 >> 4) & 0x0F0F0F0Fu) | ((PFX##_s1 >> 2) & 0x30303030u))); \ + const uint32_t PFX##_qh_u32 = ARR_P32[ib].qh[itid8]; \ + const uint32_t PFX##_q0 = ARR_P32[ib].qs[itid8 ]; \ + const uint32_t PFX##_q1 = ARR_P32[ib].qs[itid8 + 8]; \ + const uint32_t PFX##_q2 = ARR_P32[ib].qs[itid8 + 16]; \ + const uint32_t PFX##_q3 = ARR_P32[ib].qs[itid8 + 24]; \ + const vec4 PFX##_q0_lo = vec4(unpack8((PFX##_q0 & 0x0F0F0F0Fu) | ((PFX##_qh_u32 << 4) & 0x10101010u))); \ + const vec4 PFX##_q0_hi = vec4(unpack8(((PFX##_q0 >> 4) & 0x0F0F0F0Fu) | ((PFX##_qh_u32 << 3) & 0x10101010u))); \ + const vec4 PFX##_q1_lo = vec4(unpack8((PFX##_q1 & 0x0F0F0F0Fu) | ((PFX##_qh_u32 << 2) & 0x10101010u))); \ + const vec4 PFX##_q1_hi = vec4(unpack8(((PFX##_q1 >> 4) & 0x0F0F0F0Fu) | ((PFX##_qh_u32 << 1) & 0x10101010u))); \ + const vec4 PFX##_q2_lo = vec4(unpack8((PFX##_q2 & 0x0F0F0F0Fu) | (PFX##_qh_u32 & 0x10101010u))); \ + const vec4 PFX##_q2_hi = vec4(unpack8(((PFX##_q2 >> 4) & 0x0F0F0F0Fu) | ((PFX##_qh_u32 >> 1) & 0x10101010u))); \ + const vec4 PFX##_q3_lo = vec4(unpack8((PFX##_q3 & 0x0F0F0F0Fu) | ((PFX##_qh_u32 >> 2) & 0x10101010u))); \ + const vec4 PFX##_q3_hi = vec4(unpack8(((PFX##_q3 >> 4) & 0x0F0F0F0Fu) | ((PFX##_qh_u32 >> 3) & 0x10101010u))) + +#define DOT_Q5_K_8_BY(PFX, DST_TEMP, BY0, BY1, BY2, BY3, BY4, BY5, BY6, BY7, SY0, SY1, SY2, SY3, SY4, SY5, SY6, SY7) do { \ + const FLOAT_TYPE d0 = dot(BY0, PFX##_q0_lo) * PFX##_sc03.x + dot(BY1, PFX##_q0_hi) * PFX##_sc03.y; \ + const FLOAT_TYPE d1 = dot(BY2, PFX##_q1_lo) * PFX##_sc03.z + dot(BY3, PFX##_q1_hi) * PFX##_sc03.w; \ + const FLOAT_TYPE d2 = dot(BY4, PFX##_q2_lo) * PFX##_sc47.x + dot(BY5, PFX##_q2_hi) * PFX##_sc47.y; \ + const FLOAT_TYPE d3 = dot(BY6, PFX##_q3_lo) * PFX##_sc47.z + dot(BY7, PFX##_q3_hi) * PFX##_sc47.w; \ + const FLOAT_TYPE sm = (SY0 * PFX##_m03.x + SY1 * PFX##_m03.y) + (SY2 * PFX##_m03.z + SY3 * PFX##_m03.w) + \ + (SY4 * PFX##_m47.x + SY5 * PFX##_m47.y) + (SY6 * PFX##_m47.z + SY7 * PFX##_m47.w); \ + DST_TEMP[j][n] = fma(PFX##_dm.x, (d0 + d1) + (d2 + d3), fma(-PFX##_dm.y, sm, DST_TEMP[j][n])); \ +} while (false) + +#define DOT_Q5_K_8(PFX, DST_TEMP) do { \ + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; \ + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8]); \ + const vec4 by2 = vec4(data_b_v4[b4 + 16]), by3 = vec4(data_b_v4[b4 + 24]); \ + const vec4 by4 = vec4(data_b_v4[b4 + 32]), by5 = vec4(data_b_v4[b4 + 40]); \ + const vec4 by6 = vec4(data_b_v4[b4 + 48]), by7 = vec4(data_b_v4[b4 + 56]); \ + const FLOAT_TYPE sy0 = (FLOAT_TYPE(by0.x) + FLOAT_TYPE(by0.y)) + (FLOAT_TYPE(by0.z) + FLOAT_TYPE(by0.w)); \ + const FLOAT_TYPE sy1 = (FLOAT_TYPE(by1.x) + FLOAT_TYPE(by1.y)) + (FLOAT_TYPE(by1.z) + FLOAT_TYPE(by1.w)); \ + const FLOAT_TYPE sy2 = (FLOAT_TYPE(by2.x) + FLOAT_TYPE(by2.y)) + (FLOAT_TYPE(by2.z) + FLOAT_TYPE(by2.w)); \ + const FLOAT_TYPE sy3 = (FLOAT_TYPE(by3.x) + FLOAT_TYPE(by3.y)) + (FLOAT_TYPE(by3.z) + FLOAT_TYPE(by3.w)); \ + const FLOAT_TYPE sy4 = (FLOAT_TYPE(by4.x) + FLOAT_TYPE(by4.y)) + (FLOAT_TYPE(by4.z) + FLOAT_TYPE(by4.w)); \ + const FLOAT_TYPE sy5 = (FLOAT_TYPE(by5.x) + FLOAT_TYPE(by5.y)) + (FLOAT_TYPE(by5.z) + FLOAT_TYPE(by5.w)); \ + const FLOAT_TYPE sy6 = (FLOAT_TYPE(by6.x) + FLOAT_TYPE(by6.y)) + (FLOAT_TYPE(by6.z) + FLOAT_TYPE(by6.w)); \ + const FLOAT_TYPE sy7 = (FLOAT_TYPE(by7.x) + FLOAT_TYPE(by7.y)) + (FLOAT_TYPE(by7.z) + FLOAT_TYPE(by7.w)); \ + DOT_Q5_K_8_BY(PFX, DST_TEMP, by0, by1, by2, by3, by4, by5, by6, by7, sy0, sy1, sy2, sy3, sy4, sy5, sy6, sy7); \ +} while (false) +void calc_superblock_8_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint itid8, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y_idx = i * QUANT_K + 4 * itid8; + if (NUM_COLS <= 4 && NUM_ROWS > 1) { + vec4 by0_a[NUM_COLS], by1_a[NUM_COLS], by2_a[NUM_COLS], by3_a[NUM_COLS]; + vec4 by4_a[NUM_COLS], by5_a[NUM_COLS], by6_a[NUM_COLS], by7_a[NUM_COLS]; + FLOAT_TYPE sy0_a[NUM_COLS], sy1_a[NUM_COLS], sy2_a[NUM_COLS], sy3_a[NUM_COLS]; + FLOAT_TYPE sy4_a[NUM_COLS], sy5_a[NUM_COLS], sy6_a[NUM_COLS], sy7_a[NUM_COLS]; [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - vec2 by10 = vec2(data_b_v2[(j*p.batch_stride_b + b_offset + y1_idx) / 2 ]); - vec2 by116 = vec2(data_b_v2[(j*p.batch_stride_b + b_offset + y1_idx) / 2 + 8]); - vec2 by132 = vec2(data_b_v2[(j*p.batch_stride_b + b_offset + y1_idx) / 2 + 16]); - vec2 by148 = vec2(data_b_v2[(j*p.batch_stride_b + b_offset + y1_idx) / 2 + 24]); - vec2 by20 = vec2(data_b_v2[(j*p.batch_stride_b + b_offset + y2_idx) / 2 ]); - vec2 by216 = vec2(data_b_v2[(j*p.batch_stride_b + b_offset + y2_idx) / 2 + 8]); - vec2 by232 = vec2(data_b_v2[(j*p.batch_stride_b + b_offset + y2_idx) / 2 + 16]); - vec2 by248 = vec2(data_b_v2[(j*p.batch_stride_b + b_offset + y2_idx) / 2 + 24]); - - const FLOAT_TYPE sx = - fma(FLOAT_TYPE(by10.x), q4_0, - fma(FLOAT_TYPE(by10.y), q4_1, - fma(FLOAT_TYPE(by116.x), q4_2, - FLOAT_TYPE(by116.y) * q4_3))); - const FLOAT_TYPE sy = - fma(FLOAT_TYPE(by132.x), q4_4, - fma(FLOAT_TYPE(by132.y), q4_5, - fma(FLOAT_TYPE(by148.x), q4_6, - FLOAT_TYPE(by148.y) * q4_7))); - const FLOAT_TYPE sz = - fma(FLOAT_TYPE(by20.x), q4_8, - fma(FLOAT_TYPE(by20.y), q4_9, - fma(FLOAT_TYPE(by216.x), q4_10, - FLOAT_TYPE(by216.y) * q4_11))); - const FLOAT_TYPE sw = - fma(FLOAT_TYPE(by232.x), q4_12, - fma(FLOAT_TYPE(by232.y), q4_13, - fma(FLOAT_TYPE(by248.x), q4_14, - FLOAT_TYPE(by248.y) * q4_15))); - const FLOAT_TYPE smin = - fma(FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y) + FLOAT_TYPE(by116.x) + FLOAT_TYPE(by116.y), sc2, - fma(FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y) + FLOAT_TYPE(by148.x) + FLOAT_TYPE(by148.y), sc3, - fma(FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y) + FLOAT_TYPE(by216.x) + FLOAT_TYPE(by216.y), sc6, - (FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y) + FLOAT_TYPE(by248.x) + FLOAT_TYPE(by248.y)) * sc7))); - temp[j][n] = fma(dm.x, fma(sx, sc0, fma(sy, sc1, fma(sz, sc4, sw * sc5))), fma(-dm.y, smin, temp[j][n])); + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; + by0_a[j] = vec4(data_b_v4[b4 ]); by1_a[j] = vec4(data_b_v4[b4 + 8]); + by2_a[j] = vec4(data_b_v4[b4 + 16]); by3_a[j] = vec4(data_b_v4[b4 + 24]); + by4_a[j] = vec4(data_b_v4[b4 + 32]); by5_a[j] = vec4(data_b_v4[b4 + 40]); + by6_a[j] = vec4(data_b_v4[b4 + 48]); by7_a[j] = vec4(data_b_v4[b4 + 56]); + sy0_a[j] = (FLOAT_TYPE(by0_a[j].x) + FLOAT_TYPE(by0_a[j].y)) + (FLOAT_TYPE(by0_a[j].z) + FLOAT_TYPE(by0_a[j].w)); + sy1_a[j] = (FLOAT_TYPE(by1_a[j].x) + FLOAT_TYPE(by1_a[j].y)) + (FLOAT_TYPE(by1_a[j].z) + FLOAT_TYPE(by1_a[j].w)); + sy2_a[j] = (FLOAT_TYPE(by2_a[j].x) + FLOAT_TYPE(by2_a[j].y)) + (FLOAT_TYPE(by2_a[j].z) + FLOAT_TYPE(by2_a[j].w)); + sy3_a[j] = (FLOAT_TYPE(by3_a[j].x) + FLOAT_TYPE(by3_a[j].y)) + (FLOAT_TYPE(by3_a[j].z) + FLOAT_TYPE(by3_a[j].w)); + sy4_a[j] = (FLOAT_TYPE(by4_a[j].x) + FLOAT_TYPE(by4_a[j].y)) + (FLOAT_TYPE(by4_a[j].z) + FLOAT_TYPE(by4_a[j].w)); + sy5_a[j] = (FLOAT_TYPE(by5_a[j].x) + FLOAT_TYPE(by5_a[j].y)) + (FLOAT_TYPE(by5_a[j].z) + FLOAT_TYPE(by5_a[j].w)); + sy6_a[j] = (FLOAT_TYPE(by6_a[j].x) + FLOAT_TYPE(by6_a[j].y)) + (FLOAT_TYPE(by6_a[j].z) + FLOAT_TYPE(by6_a[j].w)); + sy7_a[j] = (FLOAT_TYPE(by7_a[j].x) + FLOAT_TYPE(by7_a[j].y)) + (FLOAT_TYPE(by7_a[j].z) + FLOAT_TYPE(by7_a[j].w)); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + LOAD_Q5_K_8(a1, data_a_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_8_BY(a1, temp, by0_a[j], by1_a[j], by2_a[j], by3_a[j], by4_a[j], by5_a[j], by6_a[j], by7_a[j], sy0_a[j], sy1_a[j], sy2_a[j], sy3_a[j], sy4_a[j], sy5_a[j], sy6_a[j], sy7_a[j]); + } + if (GEN_GLU == 3) { + LOAD_Q5_K_8(a2, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_8_BY(a2, temp2, by0_a[j], by1_a[j], by2_a[j], by3_a[j], by4_a[j], by5_a[j], by6_a[j], by7_a[j], sy0_a[j], sy1_a[j], sy2_a[j], sy3_a[j], sy4_a[j], sy5_a[j], sy6_a[j], sy7_a[j]); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + LOAD_Q5_K_8(a1, data_a_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_8(a1, temp); + } + if (GEN_GLU == 3) { + LOAD_Q5_K_8(a2, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_8(a2, temp2); + } + } + } + } +} + +void calc_superblock_8_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint itid8, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y_idx = i * QUANT_K + 4 * itid8; + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + LOAD_Q5_K_8(a2, data_a2_packed32); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q5_K_8(a2, temp); } } } @@ -119,47 +423,459 @@ void calc_superblock(const uint a_offset, const uint b_offset, const uint v_im, void compute_outputs(const uint32_t first_row, const uint32_t num_rows) { uint a_offset, b_offset, d_offset; get_offsets(a_offset, b_offset, d_offset); +#ifndef MUL_MAT_ID + const bool use_a2 = (GEN_GLU == 2) && (first_row >= p.pair_m0); + const uint row_base = use_a2 ? (first_row - p.pair_m0) : first_row; + const uint eff_rows = (!use_a2 && GEN_GLU == 2) ? min(num_rows, p.pair_m0 - first_row) : num_rows; +#else + const bool use_a2 = false; + const uint row_base = first_row; + const uint eff_rows = num_rows; +#endif const uint num_blocks_per_row = p.ncols / QUANT_K; - // 16 threads are used to process each block - const uint it_size = gl_WorkGroupSize.x/16; +#ifdef USE_SUBGROUP_ADD_NO_SHMEM + const uint tid = gl_SubgroupInvocationID; +#else const uint tid = gl_LocalInvocationID.x; - const uint itid = tid%16; // 0...15 - const uint ix = tid/16; - - const uint il = itid/4; // 0...3 - const uint ir = itid - 4*il; // 0...3 - - const uint v_im = il / 2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224 - const uint v_in = il % 2; +#endif - const uint l0 = 4*ir + 2*v_in; // 0...15 - const uint q_offset = 32*v_im + l0; - const uint y_offset = 64*v_im + l0; + FLOAT_TYPE temp[NUM_COLS][NUM_ROWS]; + FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS]; [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { [[unroll]] for (uint i = 0; i < NUM_ROWS; ++i) { temp[j][i] = FLOAT_TYPE(0); + if (GEN_GLU == 3) { + temp2[j][i] = FLOAT_TYPE(0); + } } } - [[unroll]] for (uint i = ix; i < num_blocks_per_row; i += it_size) - calc_superblock(a_offset, b_offset, v_im, l0, q_offset, y_offset, i, num_blocks_per_row, first_row, num_rows); +#ifdef REPACK_PLANAR +#ifndef REPACK_FAST_KQ +#define REPACK_FAST_KQ GEN_FAST_KQ +#endif + if (REPACK_FAST_KQ >= 2) { + const uint it_size8 = gl_WorkGroupSize.x >> 3u; + const uint itid8 = tid & 7u; + const uint ix8 = tid >> 3u; + for (uint i = ix8; i < num_blocks_per_row; i += it_size8) { + const uint y_idx = i * QUANT_K + 4u * itid8; + if (NUM_COLS <= 2) { + vec4 by0_a[NUM_COLS], by1_a[NUM_COLS], by2_a[NUM_COLS], by3_a[NUM_COLS]; + vec4 by4_a[NUM_COLS], by5_a[NUM_COLS], by6_a[NUM_COLS], by7_a[NUM_COLS]; + FLOAT_TYPE sy0_a[NUM_COLS], sy1_a[NUM_COLS], sy2_a[NUM_COLS], sy3_a[NUM_COLS]; + FLOAT_TYPE sy4_a[NUM_COLS], sy5_a[NUM_COLS], sy6_a[NUM_COLS], sy7_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) >> 2u; + by0_a[j] = vec4(data_b_v4[b4 ]); by1_a[j] = vec4(data_b_v4[b4 + 8u]); + by2_a[j] = vec4(data_b_v4[b4 + 16u]); by3_a[j] = vec4(data_b_v4[b4 + 24u]); + by4_a[j] = vec4(data_b_v4[b4 + 32u]); by5_a[j] = vec4(data_b_v4[b4 + 40u]); + by6_a[j] = vec4(data_b_v4[b4 + 48u]); by7_a[j] = vec4(data_b_v4[b4 + 56u]); + sy0_a[j] = (FLOAT_TYPE(by0_a[j].x) + FLOAT_TYPE(by0_a[j].y)) + (FLOAT_TYPE(by0_a[j].z) + FLOAT_TYPE(by0_a[j].w)); + sy1_a[j] = (FLOAT_TYPE(by1_a[j].x) + FLOAT_TYPE(by1_a[j].y)) + (FLOAT_TYPE(by1_a[j].z) + FLOAT_TYPE(by1_a[j].w)); + sy2_a[j] = (FLOAT_TYPE(by2_a[j].x) + FLOAT_TYPE(by2_a[j].y)) + (FLOAT_TYPE(by2_a[j].z) + FLOAT_TYPE(by2_a[j].w)); + sy3_a[j] = (FLOAT_TYPE(by3_a[j].x) + FLOAT_TYPE(by3_a[j].y)) + (FLOAT_TYPE(by3_a[j].z) + FLOAT_TYPE(by3_a[j].w)); + sy4_a[j] = (FLOAT_TYPE(by4_a[j].x) + FLOAT_TYPE(by4_a[j].y)) + (FLOAT_TYPE(by4_a[j].z) + FLOAT_TYPE(by4_a[j].w)); + sy5_a[j] = (FLOAT_TYPE(by5_a[j].x) + FLOAT_TYPE(by5_a[j].y)) + (FLOAT_TYPE(by5_a[j].z) + FLOAT_TYPE(by5_a[j].w)); + sy6_a[j] = (FLOAT_TYPE(by6_a[j].x) + FLOAT_TYPE(by6_a[j].y)) + (FLOAT_TYPE(by6_a[j].z) + FLOAT_TYPE(by6_a[j].w)); + sy7_a[j] = (FLOAT_TYPE(by7_a[j].x) + FLOAT_TYPE(by7_a[j].y)) + (FLOAT_TYPE(by7_a[j].z) + FLOAT_TYPE(by7_a[j].w)); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q5_K_SB_U4; + const uint sb_u32 = sb_u4 << 2u; + { + const uvec4 hdr = use_a2 ? data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4] : data_a_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const vec4 sc03 = vec4(unpack8(hdr.y & 0x3F3F3F3Fu)); + const vec4 m03 = vec4(unpack8(hdr.z & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((hdr.w & 0x0F0F0F0Fu) | ((hdr.y >> 2u) & 0x30303030u))); + const vec4 m47 = vec4(unpack8(((hdr.w >> 4u) & 0x0F0F0F0Fu) | ((hdr.z >> 2u) & 0x30303030u))); + const uvec4 q = use_a2 ? data_a2_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8] : data_a_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8]; + const uint qh = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + itid8] : data_a_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + itid8]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE d0 = + dot(by0_a[j], repack_magic_u5((q.x & 0x000F000Fu) | ((qh << 4u) & 0x00100010u), ((q.x >> 8u) & 0x000F000Fu) | ((qh >> 4u) & 0x00100010u))) * sc03.x + + dot(by1_a[j], repack_magic_u5(((q.x >> 4u) & 0x000F000Fu) | ((qh << 3u) & 0x00100010u), ((q.x >> 12u) & 0x000F000Fu) | ((qh >> 5u) & 0x00100010u))) * sc03.y; + const FLOAT_TYPE d1 = + dot(by2_a[j], repack_magic_u5((q.y & 0x000F000Fu) | ((qh << 2u) & 0x00100010u), ((q.y >> 8u) & 0x000F000Fu) | ((qh >> 6u) & 0x00100010u))) * sc03.z + + dot(by3_a[j], repack_magic_u5(((q.y >> 4u) & 0x000F000Fu) | ((qh << 1u) & 0x00100010u), ((q.y >> 12u) & 0x000F000Fu) | ((qh >> 7u) & 0x00100010u))) * sc03.w; + const FLOAT_TYPE d2 = + dot(by4_a[j], repack_magic_u5((q.z & 0x000F000Fu) | ((qh ) & 0x00100010u), ((q.z >> 8u) & 0x000F000Fu) | ((qh >> 8u) & 0x00100010u))) * sc47.x + + dot(by5_a[j], repack_magic_u5(((q.z >> 4u) & 0x000F000Fu) | ((qh >> 1u) & 0x00100010u), ((q.z >> 12u) & 0x000F000Fu) | ((qh >> 9u) & 0x00100010u))) * sc47.y; + const FLOAT_TYPE d3 = + dot(by6_a[j], repack_magic_u5((q.w & 0x000F000Fu) | ((qh >> 2u) & 0x00100010u), ((q.w >> 8u) & 0x000F000Fu) | ((qh >> 10u) & 0x00100010u))) * sc47.z + + dot(by7_a[j], repack_magic_u5(((q.w >> 4u) & 0x000F000Fu) | ((qh >> 3u) & 0x00100010u), ((q.w >> 12u) & 0x000F000Fu) | ((qh >> 11u) & 0x00100010u))) * sc47.w; + const FLOAT_TYPE sm = (sy0_a[j] * m03.x + sy1_a[j] * m03.y) + (sy2_a[j] * m03.z + sy3_a[j] * m03.w) + + (sy4_a[j] * m47.x + sy5_a[j] * m47.y) + (sy6_a[j] * m47.z + sy7_a[j] * m47.w); + temp[j][n] = fma(dm.x, (d0 + d1) + (d2 + d3), fma(-dm.y, sm, temp[j][n])); + } + } + if (GEN_GLU == 3) { + const uvec4 hdr = data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const vec4 sc03 = vec4(unpack8(hdr.y & 0x3F3F3F3Fu)); + const vec4 m03 = vec4(unpack8(hdr.z & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((hdr.w & 0x0F0F0F0Fu) | ((hdr.y >> 2u) & 0x30303030u))); + const vec4 m47 = vec4(unpack8(((hdr.w >> 4u) & 0x0F0F0F0Fu) | ((hdr.z >> 2u) & 0x30303030u))); + const uvec4 q = data_a2_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8]; + const uint qh = data_a2_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + itid8]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE d0 = + dot(by0_a[j], repack_magic_u5((q.x & 0x000F000Fu) | ((qh << 4u) & 0x00100010u), ((q.x >> 8u) & 0x000F000Fu) | ((qh >> 4u) & 0x00100010u))) * sc03.x + + dot(by1_a[j], repack_magic_u5(((q.x >> 4u) & 0x000F000Fu) | ((qh << 3u) & 0x00100010u), ((q.x >> 12u) & 0x000F000Fu) | ((qh >> 5u) & 0x00100010u))) * sc03.y; + const FLOAT_TYPE d1 = + dot(by2_a[j], repack_magic_u5((q.y & 0x000F000Fu) | ((qh << 2u) & 0x00100010u), ((q.y >> 8u) & 0x000F000Fu) | ((qh >> 6u) & 0x00100010u))) * sc03.z + + dot(by3_a[j], repack_magic_u5(((q.y >> 4u) & 0x000F000Fu) | ((qh << 1u) & 0x00100010u), ((q.y >> 12u) & 0x000F000Fu) | ((qh >> 7u) & 0x00100010u))) * sc03.w; + const FLOAT_TYPE d2 = + dot(by4_a[j], repack_magic_u5((q.z & 0x000F000Fu) | ((qh ) & 0x00100010u), ((q.z >> 8u) & 0x000F000Fu) | ((qh >> 8u) & 0x00100010u))) * sc47.x + + dot(by5_a[j], repack_magic_u5(((q.z >> 4u) & 0x000F000Fu) | ((qh >> 1u) & 0x00100010u), ((q.z >> 12u) & 0x000F000Fu) | ((qh >> 9u) & 0x00100010u))) * sc47.y; + const FLOAT_TYPE d3 = + dot(by6_a[j], repack_magic_u5((q.w & 0x000F000Fu) | ((qh >> 2u) & 0x00100010u), ((q.w >> 8u) & 0x000F000Fu) | ((qh >> 10u) & 0x00100010u))) * sc47.z + + dot(by7_a[j], repack_magic_u5(((q.w >> 4u) & 0x000F000Fu) | ((qh >> 3u) & 0x00100010u), ((q.w >> 12u) & 0x000F000Fu) | ((qh >> 11u) & 0x00100010u))) * sc47.w; + const FLOAT_TYPE sm = (sy0_a[j] * m03.x + sy1_a[j] * m03.y) + (sy2_a[j] * m03.z + sy3_a[j] * m03.w) + + (sy4_a[j] * m47.x + sy5_a[j] * m47.y) + (sy6_a[j] * m47.z + sy7_a[j] * m47.w); + temp2[j][n] = fma(dm.x, (d0 + d1) + (d2 + d3), fma(-dm.y, sm, temp2[j][n])); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q5_K_SB_U4; + const uint sb_u32 = sb_u4 << 2u; + { + const uvec4 hdr = use_a2 ? data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4] : data_a_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const vec4 sc03 = vec4(unpack8(hdr.y & 0x3F3F3F3Fu)); + const vec4 m03 = vec4(unpack8(hdr.z & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((hdr.w & 0x0F0F0F0Fu) | ((hdr.y >> 2u) & 0x30303030u))); + const vec4 m47 = vec4(unpack8(((hdr.w >> 4u) & 0x0F0F0F0Fu) | ((hdr.z >> 2u) & 0x30303030u))); + const uvec4 q = use_a2 ? data_a2_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8] : data_a_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8]; + const uint qh = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + itid8] : data_a_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + itid8]; + const vec4 q0_lo = repack_magic_u5((q.x & 0x000F000Fu) | ((qh << 4u) & 0x00100010u), ((q.x >> 8u) & 0x000F000Fu) | ((qh >> 4u) & 0x00100010u)); + const vec4 q0_hi = repack_magic_u5(((q.x >> 4u) & 0x000F000Fu) | ((qh << 3u) & 0x00100010u), ((q.x >> 12u) & 0x000F000Fu) | ((qh >> 5u) & 0x00100010u)); + const vec4 q1_lo = repack_magic_u5((q.y & 0x000F000Fu) | ((qh << 2u) & 0x00100010u), ((q.y >> 8u) & 0x000F000Fu) | ((qh >> 6u) & 0x00100010u)); + const vec4 q1_hi = repack_magic_u5(((q.y >> 4u) & 0x000F000Fu) | ((qh << 1u) & 0x00100010u), ((q.y >> 12u) & 0x000F000Fu) | ((qh >> 7u) & 0x00100010u)); + const vec4 q2_lo = repack_magic_u5((q.z & 0x000F000Fu) | ((qh ) & 0x00100010u), ((q.z >> 8u) & 0x000F000Fu) | ((qh >> 8u) & 0x00100010u)); + const vec4 q2_hi = repack_magic_u5(((q.z >> 4u) & 0x000F000Fu) | ((qh >> 1u) & 0x00100010u), ((q.z >> 12u) & 0x000F000Fu) | ((qh >> 9u) & 0x00100010u)); + const vec4 q3_lo = repack_magic_u5((q.w & 0x000F000Fu) | ((qh >> 2u) & 0x00100010u), ((q.w >> 8u) & 0x000F000Fu) | ((qh >> 10u) & 0x00100010u)); + const vec4 q3_hi = repack_magic_u5(((q.w >> 4u) & 0x000F000Fu) | ((qh >> 3u) & 0x00100010u), ((q.w >> 12u) & 0x000F000Fu) | ((qh >> 11u) & 0x00100010u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) >> 2u; + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8u]); + const vec4 by2 = vec4(data_b_v4[b4 + 16u]), by3 = vec4(data_b_v4[b4 + 24u]); + const vec4 by4 = vec4(data_b_v4[b4 + 32u]), by5 = vec4(data_b_v4[b4 + 40u]); + const vec4 by6 = vec4(data_b_v4[b4 + 48u]), by7 = vec4(data_b_v4[b4 + 56u]); + const FLOAT_TYPE sy0 = (FLOAT_TYPE(by0.x) + FLOAT_TYPE(by0.y)) + (FLOAT_TYPE(by0.z) + FLOAT_TYPE(by0.w)); + const FLOAT_TYPE sy1 = (FLOAT_TYPE(by1.x) + FLOAT_TYPE(by1.y)) + (FLOAT_TYPE(by1.z) + FLOAT_TYPE(by1.w)); + const FLOAT_TYPE sy2 = (FLOAT_TYPE(by2.x) + FLOAT_TYPE(by2.y)) + (FLOAT_TYPE(by2.z) + FLOAT_TYPE(by2.w)); + const FLOAT_TYPE sy3 = (FLOAT_TYPE(by3.x) + FLOAT_TYPE(by3.y)) + (FLOAT_TYPE(by3.z) + FLOAT_TYPE(by3.w)); + const FLOAT_TYPE sy4 = (FLOAT_TYPE(by4.x) + FLOAT_TYPE(by4.y)) + (FLOAT_TYPE(by4.z) + FLOAT_TYPE(by4.w)); + const FLOAT_TYPE sy5 = (FLOAT_TYPE(by5.x) + FLOAT_TYPE(by5.y)) + (FLOAT_TYPE(by5.z) + FLOAT_TYPE(by5.w)); + const FLOAT_TYPE sy6 = (FLOAT_TYPE(by6.x) + FLOAT_TYPE(by6.y)) + (FLOAT_TYPE(by6.z) + FLOAT_TYPE(by6.w)); + const FLOAT_TYPE sy7 = (FLOAT_TYPE(by7.x) + FLOAT_TYPE(by7.y)) + (FLOAT_TYPE(by7.z) + FLOAT_TYPE(by7.w)); + const FLOAT_TYPE d0 = dot(by0, q0_lo) * sc03.x + dot(by1, q0_hi) * sc03.y; + const FLOAT_TYPE d1 = dot(by2, q1_lo) * sc03.z + dot(by3, q1_hi) * sc03.w; + const FLOAT_TYPE d2 = dot(by4, q2_lo) * sc47.x + dot(by5, q2_hi) * sc47.y; + const FLOAT_TYPE d3 = dot(by6, q3_lo) * sc47.z + dot(by7, q3_hi) * sc47.w; + const FLOAT_TYPE sm = (sy0 * m03.x + sy1 * m03.y) + (sy2 * m03.z + sy3 * m03.w) + + (sy4 * m47.x + sy5 * m47.y) + (sy6 * m47.z + sy7 * m47.w); + temp[j][n] = fma(dm.x, (d0 + d1) + (d2 + d3), fma(-dm.y, sm, temp[j][n])); + } + } + if (GEN_GLU == 3) { + const uvec4 hdr = data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const vec4 sc03 = vec4(unpack8(hdr.y & 0x3F3F3F3Fu)); + const vec4 m03 = vec4(unpack8(hdr.z & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((hdr.w & 0x0F0F0F0Fu) | ((hdr.y >> 2u) & 0x30303030u))); + const vec4 m47 = vec4(unpack8(((hdr.w >> 4u) & 0x0F0F0F0Fu) | ((hdr.z >> 2u) & 0x30303030u))); + const uvec4 q = data_a2_u4[sb_u4 + REPACK_QS_OFF_U4 + itid8]; + const uint qh = data_a2_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + itid8]; + const vec4 q0_lo = repack_magic_u5((q.x & 0x000F000Fu) | ((qh << 4u) & 0x00100010u), ((q.x >> 8u) & 0x000F000Fu) | ((qh >> 4u) & 0x00100010u)); + const vec4 q0_hi = repack_magic_u5(((q.x >> 4u) & 0x000F000Fu) | ((qh << 3u) & 0x00100010u), ((q.x >> 12u) & 0x000F000Fu) | ((qh >> 5u) & 0x00100010u)); + const vec4 q1_lo = repack_magic_u5((q.y & 0x000F000Fu) | ((qh << 2u) & 0x00100010u), ((q.y >> 8u) & 0x000F000Fu) | ((qh >> 6u) & 0x00100010u)); + const vec4 q1_hi = repack_magic_u5(((q.y >> 4u) & 0x000F000Fu) | ((qh << 1u) & 0x00100010u), ((q.y >> 12u) & 0x000F000Fu) | ((qh >> 7u) & 0x00100010u)); + const vec4 q2_lo = repack_magic_u5((q.z & 0x000F000Fu) | ((qh ) & 0x00100010u), ((q.z >> 8u) & 0x000F000Fu) | ((qh >> 8u) & 0x00100010u)); + const vec4 q2_hi = repack_magic_u5(((q.z >> 4u) & 0x000F000Fu) | ((qh >> 1u) & 0x00100010u), ((q.z >> 12u) & 0x000F000Fu) | ((qh >> 9u) & 0x00100010u)); + const vec4 q3_lo = repack_magic_u5((q.w & 0x000F000Fu) | ((qh >> 2u) & 0x00100010u), ((q.w >> 8u) & 0x000F000Fu) | ((qh >> 10u) & 0x00100010u)); + const vec4 q3_hi = repack_magic_u5(((q.w >> 4u) & 0x000F000Fu) | ((qh >> 3u) & 0x00100010u), ((q.w >> 12u) & 0x000F000Fu) | ((qh >> 11u) & 0x00100010u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) >> 2u; + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8u]); + const vec4 by2 = vec4(data_b_v4[b4 + 16u]), by3 = vec4(data_b_v4[b4 + 24u]); + const vec4 by4 = vec4(data_b_v4[b4 + 32u]), by5 = vec4(data_b_v4[b4 + 40u]); + const vec4 by6 = vec4(data_b_v4[b4 + 48u]), by7 = vec4(data_b_v4[b4 + 56u]); + const FLOAT_TYPE sy0 = (FLOAT_TYPE(by0.x) + FLOAT_TYPE(by0.y)) + (FLOAT_TYPE(by0.z) + FLOAT_TYPE(by0.w)); + const FLOAT_TYPE sy1 = (FLOAT_TYPE(by1.x) + FLOAT_TYPE(by1.y)) + (FLOAT_TYPE(by1.z) + FLOAT_TYPE(by1.w)); + const FLOAT_TYPE sy2 = (FLOAT_TYPE(by2.x) + FLOAT_TYPE(by2.y)) + (FLOAT_TYPE(by2.z) + FLOAT_TYPE(by2.w)); + const FLOAT_TYPE sy3 = (FLOAT_TYPE(by3.x) + FLOAT_TYPE(by3.y)) + (FLOAT_TYPE(by3.z) + FLOAT_TYPE(by3.w)); + const FLOAT_TYPE sy4 = (FLOAT_TYPE(by4.x) + FLOAT_TYPE(by4.y)) + (FLOAT_TYPE(by4.z) + FLOAT_TYPE(by4.w)); + const FLOAT_TYPE sy5 = (FLOAT_TYPE(by5.x) + FLOAT_TYPE(by5.y)) + (FLOAT_TYPE(by5.z) + FLOAT_TYPE(by5.w)); + const FLOAT_TYPE sy6 = (FLOAT_TYPE(by6.x) + FLOAT_TYPE(by6.y)) + (FLOAT_TYPE(by6.z) + FLOAT_TYPE(by6.w)); + const FLOAT_TYPE sy7 = (FLOAT_TYPE(by7.x) + FLOAT_TYPE(by7.y)) + (FLOAT_TYPE(by7.z) + FLOAT_TYPE(by7.w)); + const FLOAT_TYPE d0 = dot(by0, q0_lo) * sc03.x + dot(by1, q0_hi) * sc03.y; + const FLOAT_TYPE d1 = dot(by2, q1_lo) * sc03.z + dot(by3, q1_hi) * sc03.w; + const FLOAT_TYPE d2 = dot(by4, q2_lo) * sc47.x + dot(by5, q2_hi) * sc47.y; + const FLOAT_TYPE d3 = dot(by6, q3_lo) * sc47.z + dot(by7, q3_hi) * sc47.w; + const FLOAT_TYPE sm = (sy0 * m03.x + sy1 * m03.y) + (sy2 * m03.z + sy3 * m03.w) + + (sy4 * m47.x + sy5 * m47.y) + (sy6 * m47.z + sy7 * m47.w); + temp2[j][n] = fma(dm.x, (d0 + d1) + (d2 + d3), fma(-dm.y, sm, temp2[j][n])); + } + } + } + } + } + } else { + const uint it_size16 = gl_WorkGroupSize.x >> 4u; + const uint itid16 = tid & 15u; + const uint ix16 = tid >> 4u; + const uint il = itid16 >> 2u; + const uint ir = itid16 & 3u; + const uint v_im = il >> 1u; + const uint v_in = il & 1u; + const uint q_lane = 2u * ir + v_in; + const uint y_offset = 64u * v_im + 4u * q_lane; + for (uint i = ix16; i < num_blocks_per_row; i += it_size16) { + const uint y1_idx = i * QUANT_K + y_offset; + const uint y2_idx = y1_idx + 128u; + if (NUM_COLS <= 4) { + vec4 by10_a[NUM_COLS], by132_a[NUM_COLS], by20_a[NUM_COLS], by232_a[NUM_COLS]; + FLOAT_TYPE sy10_a[NUM_COLS], sy132_a[NUM_COLS], sy20_a[NUM_COLS], sy232_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) >> 2u; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) >> 2u; + by10_a[j] = vec4(data_b_v4[b4_1 ]); by132_a[j] = vec4(data_b_v4[b4_1 + 8u]); + by20_a[j] = vec4(data_b_v4[b4_2 ]); by232_a[j] = vec4(data_b_v4[b4_2 + 8u]); + sy10_a[j] = (FLOAT_TYPE(by10_a[j].x) + FLOAT_TYPE(by10_a[j].y)) + (FLOAT_TYPE(by10_a[j].z) + FLOAT_TYPE(by10_a[j].w)); + sy132_a[j] = (FLOAT_TYPE(by132_a[j].x) + FLOAT_TYPE(by132_a[j].y)) + (FLOAT_TYPE(by132_a[j].z) + FLOAT_TYPE(by132_a[j].w)); + sy20_a[j] = (FLOAT_TYPE(by20_a[j].x) + FLOAT_TYPE(by20_a[j].y)) + (FLOAT_TYPE(by20_a[j].z) + FLOAT_TYPE(by20_a[j].w)); + sy232_a[j] = (FLOAT_TYPE(by232_a[j].x) + FLOAT_TYPE(by232_a[j].y)) + (FLOAT_TYPE(by232_a[j].z) + FLOAT_TYPE(by232_a[j].w)); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q5_K_SB_U4; + const uint sb_u32 = sb_u4 << 2u; + const uint q_u32_base = ((sb_u4 + REPACK_QS_OFF_U4 + q_lane) << 2u) + v_im; + { + const uvec4 hdr = use_a2 ? data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4] : data_a_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const uint s01_u16 = (hdr.y >> (v_im * 16u)) & 0xFFFFu; + const uint s45_u16 = (hdr.z >> (v_im * 16u)) & 0xFFFFu; + const uint s89_u16 = (hdr.w >> (v_im * 16u)) & 0xFFFFu; + const uint scale_0_4_l = (s45_u16 << 16u) | s01_u16; + const uint scale_0_4_h = (scale_0_4_l & 0xC0C0C0C0u) >> 2u; + const vec4 sc03 = vec4(unpack8(scale_0_4_l & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((((s89_u16 << 12u) | s89_u16) & 0x0F0F0F0Fu) | scale_0_4_h)); + const uint qs0_u32 = use_a2 ? data_a2_u32[q_u32_base + 0u] : data_a_u32[q_u32_base + 0u]; + const uint qs64_u32 = use_a2 ? data_a2_u32[q_u32_base + 2u] : data_a_u32[q_u32_base + 2u]; + const uint qh_s = (use_a2 ? data_a2_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + q_lane] : data_a_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + q_lane]) >> (2u * v_im); + const vec4 q0_lo = repack_magic_u5((qs0_u32 & 0x000F000Fu) | ((qh_s << 4u) & 0x00100010u), ((qs0_u32 >> 8u) & 0x000F000Fu) | ((qh_s >> 4u) & 0x00100010u)); + const vec4 q0_hi = repack_magic_u5(((qs0_u32 >> 4u) & 0x000F000Fu) | ((qh_s << 3u) & 0x00100010u), ((qs0_u32 >> 12u) & 0x000F000Fu) | ((qh_s >> 5u) & 0x00100010u)); + const vec4 q2_lo = repack_magic_u5((qs64_u32 & 0x000F000Fu) | ((qh_s ) & 0x00100010u), ((qs64_u32 >> 8u) & 0x000F000Fu) | ((qh_s >> 8u) & 0x00100010u)); + const vec4 q2_hi = repack_magic_u5(((qs64_u32 >> 4u) & 0x000F000Fu) | ((qh_s >> 1u) & 0x00100010u), ((qs64_u32 >> 12u) & 0x000F000Fu) | ((qh_s >> 9u) & 0x00100010u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE sx = dot(by10_a[j], q0_lo); + const FLOAT_TYPE sy = dot(by132_a[j], q0_hi); + const FLOAT_TYPE sz = dot(by20_a[j], q2_lo); + const FLOAT_TYPE sw = dot(by232_a[j], q2_hi); + const FLOAT_TYPE smin = fma(sy10_a[j], sc03.z, fma(sy132_a[j], sc03.w, fma(sy20_a[j], sc47.z, sy232_a[j] * sc47.w))); + temp[j][n] = fma(dm.x, fma(sx, sc03.x, fma(sy, sc03.y, fma(sz, sc47.x, sw * sc47.y))), fma(-dm.y, smin, temp[j][n])); + } + } + if (GEN_GLU == 3) { + const uvec4 hdr = data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const uint s01_u16 = (hdr.y >> (v_im * 16u)) & 0xFFFFu; + const uint s45_u16 = (hdr.z >> (v_im * 16u)) & 0xFFFFu; + const uint s89_u16 = (hdr.w >> (v_im * 16u)) & 0xFFFFu; + const uint scale_0_4_l = (s45_u16 << 16u) | s01_u16; + const uint scale_0_4_h = (scale_0_4_l & 0xC0C0C0C0u) >> 2u; + const vec4 sc03 = vec4(unpack8(scale_0_4_l & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((((s89_u16 << 12u) | s89_u16) & 0x0F0F0F0Fu) | scale_0_4_h)); + const uint qs0_u32 = data_a2_u32[q_u32_base + 0u]; + const uint qs64_u32 = data_a2_u32[q_u32_base + 2u]; + const uint qh_s = data_a2_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + q_lane] >> (2u * v_im); + const vec4 q0_lo = repack_magic_u5((qs0_u32 & 0x000F000Fu) | ((qh_s << 4u) & 0x00100010u), ((qs0_u32 >> 8u) & 0x000F000Fu) | ((qh_s >> 4u) & 0x00100010u)); + const vec4 q0_hi = repack_magic_u5(((qs0_u32 >> 4u) & 0x000F000Fu) | ((qh_s << 3u) & 0x00100010u), ((qs0_u32 >> 12u) & 0x000F000Fu) | ((qh_s >> 5u) & 0x00100010u)); + const vec4 q2_lo = repack_magic_u5((qs64_u32 & 0x000F000Fu) | ((qh_s ) & 0x00100010u), ((qs64_u32 >> 8u) & 0x000F000Fu) | ((qh_s >> 8u) & 0x00100010u)); + const vec4 q2_hi = repack_magic_u5(((qs64_u32 >> 4u) & 0x000F000Fu) | ((qh_s >> 1u) & 0x00100010u), ((qs64_u32 >> 12u) & 0x000F000Fu) | ((qh_s >> 9u) & 0x00100010u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const FLOAT_TYPE sx = dot(by10_a[j], q0_lo); + const FLOAT_TYPE sy = dot(by132_a[j], q0_hi); + const FLOAT_TYPE sz = dot(by20_a[j], q2_lo); + const FLOAT_TYPE sw = dot(by232_a[j], q2_hi); + const FLOAT_TYPE smin = fma(sy10_a[j], sc03.z, fma(sy132_a[j], sc03.w, fma(sy20_a[j], sc47.z, sy232_a[j] * sc47.w))); + temp2[j][n] = fma(dm.x, fma(sx, sc03.x, fma(sy, sc03.y, fma(sz, sc47.x, sw * sc47.y))), fma(-dm.y, smin, temp2[j][n])); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q5_K_SB_U4; + const uint sb_u32 = sb_u4 << 2u; + const uint q_u32_base = ((sb_u4 + REPACK_QS_OFF_U4 + q_lane) << 2u) + v_im; + { + const uvec4 hdr = use_a2 ? data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4] : data_a_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const uint s01_u16 = (hdr.y >> (v_im * 16u)) & 0xFFFFu; + const uint s45_u16 = (hdr.z >> (v_im * 16u)) & 0xFFFFu; + const uint s89_u16 = (hdr.w >> (v_im * 16u)) & 0xFFFFu; + const uint scale_0_4_l = (s45_u16 << 16u) | s01_u16; + const uint scale_0_4_h = (scale_0_4_l & 0xC0C0C0C0u) >> 2u; + const vec4 sc03 = vec4(unpack8(scale_0_4_l & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((((s89_u16 << 12u) | s89_u16) & 0x0F0F0F0Fu) | scale_0_4_h)); + const uint qs0_u32 = use_a2 ? data_a2_u32[q_u32_base + 0u] : data_a_u32[q_u32_base + 0u]; + const uint qs64_u32 = use_a2 ? data_a2_u32[q_u32_base + 2u] : data_a_u32[q_u32_base + 2u]; + const uint qh_s = (use_a2 ? data_a2_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + q_lane] : data_a_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + q_lane]) >> (2u * v_im); + const vec4 q0_lo = repack_magic_u5((qs0_u32 & 0x000F000Fu) | ((qh_s << 4u) & 0x00100010u), ((qs0_u32 >> 8u) & 0x000F000Fu) | ((qh_s >> 4u) & 0x00100010u)); + const vec4 q0_hi = repack_magic_u5(((qs0_u32 >> 4u) & 0x000F000Fu) | ((qh_s << 3u) & 0x00100010u), ((qs0_u32 >> 12u) & 0x000F000Fu) | ((qh_s >> 5u) & 0x00100010u)); + const vec4 q2_lo = repack_magic_u5((qs64_u32 & 0x000F000Fu) | ((qh_s ) & 0x00100010u), ((qs64_u32 >> 8u) & 0x000F000Fu) | ((qh_s >> 8u) & 0x00100010u)); + const vec4 q2_hi = repack_magic_u5(((qs64_u32 >> 4u) & 0x000F000Fu) | ((qh_s >> 1u) & 0x00100010u), ((qs64_u32 >> 12u) & 0x000F000Fu) | ((qh_s >> 9u) & 0x00100010u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) >> 2u; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) >> 2u; + const vec4 by10 = vec4(data_b_v4[b4_1 ]), by132 = vec4(data_b_v4[b4_1 + 8u]); + const vec4 by20 = vec4(data_b_v4[b4_2 ]), by232 = vec4(data_b_v4[b4_2 + 8u]); + const FLOAT_TYPE sumy10 = (FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y)) + (FLOAT_TYPE(by10.z) + FLOAT_TYPE(by10.w)); + const FLOAT_TYPE sumy132 = (FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y)) + (FLOAT_TYPE(by132.z) + FLOAT_TYPE(by132.w)); + const FLOAT_TYPE sumy20 = (FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y)) + (FLOAT_TYPE(by20.z) + FLOAT_TYPE(by20.w)); + const FLOAT_TYPE sumy232 = (FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y)) + (FLOAT_TYPE(by232.z) + FLOAT_TYPE(by232.w)); + const FLOAT_TYPE sx = dot(by10, q0_lo); + const FLOAT_TYPE sy = dot(by132, q0_hi); + const FLOAT_TYPE sz = dot(by20, q2_lo); + const FLOAT_TYPE sw = dot(by232, q2_hi); + const FLOAT_TYPE smin = fma(sumy10, sc03.z, fma(sumy132, sc03.w, fma(sumy20, sc47.z, sumy232 * sc47.w))); + temp[j][n] = fma(dm.x, fma(sx, sc03.x, fma(sy, sc03.y, fma(sz, sc47.x, sw * sc47.y))), fma(-dm.y, smin, temp[j][n])); + } + } + if (GEN_GLU == 3) { + const uvec4 hdr = data_a2_u4[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 dm = unpackHalf2x16(hdr.x); + const uint s01_u16 = (hdr.y >> (v_im * 16u)) & 0xFFFFu; + const uint s45_u16 = (hdr.z >> (v_im * 16u)) & 0xFFFFu; + const uint s89_u16 = (hdr.w >> (v_im * 16u)) & 0xFFFFu; + const uint scale_0_4_l = (s45_u16 << 16u) | s01_u16; + const uint scale_0_4_h = (scale_0_4_l & 0xC0C0C0C0u) >> 2u; + const vec4 sc03 = vec4(unpack8(scale_0_4_l & 0x3F3F3F3Fu)); + const vec4 sc47 = vec4(unpack8((((s89_u16 << 12u) | s89_u16) & 0x0F0F0F0Fu) | scale_0_4_h)); + const uint qs0_u32 = data_a2_u32[q_u32_base + 0u]; + const uint qs64_u32 = data_a2_u32[q_u32_base + 2u]; + const uint qh_s = data_a2_u32[sb_u32 + REPACK_Q5_K_QH_OFF_U32 + q_lane] >> (2u * v_im); + const vec4 q0_lo = repack_magic_u5((qs0_u32 & 0x000F000Fu) | ((qh_s << 4u) & 0x00100010u), ((qs0_u32 >> 8u) & 0x000F000Fu) | ((qh_s >> 4u) & 0x00100010u)); + const vec4 q0_hi = repack_magic_u5(((qs0_u32 >> 4u) & 0x000F000Fu) | ((qh_s << 3u) & 0x00100010u), ((qs0_u32 >> 12u) & 0x000F000Fu) | ((qh_s >> 5u) & 0x00100010u)); + const vec4 q2_lo = repack_magic_u5((qs64_u32 & 0x000F000Fu) | ((qh_s ) & 0x00100010u), ((qs64_u32 >> 8u) & 0x000F000Fu) | ((qh_s >> 8u) & 0x00100010u)); + const vec4 q2_hi = repack_magic_u5(((qs64_u32 >> 4u) & 0x000F000Fu) | ((qh_s >> 1u) & 0x00100010u), ((qs64_u32 >> 12u) & 0x000F000Fu) | ((qh_s >> 9u) & 0x00100010u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4_1 = (j * p.batch_stride_b + b_offset + y1_idx) >> 2u; + const uint b4_2 = (j * p.batch_stride_b + b_offset + y2_idx) >> 2u; + const vec4 by10 = vec4(data_b_v4[b4_1 ]), by132 = vec4(data_b_v4[b4_1 + 8u]); + const vec4 by20 = vec4(data_b_v4[b4_2 ]), by232 = vec4(data_b_v4[b4_2 + 8u]); + const FLOAT_TYPE sumy10 = (FLOAT_TYPE(by10.x) + FLOAT_TYPE(by10.y)) + (FLOAT_TYPE(by10.z) + FLOAT_TYPE(by10.w)); + const FLOAT_TYPE sumy132 = (FLOAT_TYPE(by132.x) + FLOAT_TYPE(by132.y)) + (FLOAT_TYPE(by132.z) + FLOAT_TYPE(by132.w)); + const FLOAT_TYPE sumy20 = (FLOAT_TYPE(by20.x) + FLOAT_TYPE(by20.y)) + (FLOAT_TYPE(by20.z) + FLOAT_TYPE(by20.w)); + const FLOAT_TYPE sumy232 = (FLOAT_TYPE(by232.x) + FLOAT_TYPE(by232.y)) + (FLOAT_TYPE(by232.z) + FLOAT_TYPE(by232.w)); + const FLOAT_TYPE sx = dot(by10, q0_lo); + const FLOAT_TYPE sy = dot(by132, q0_hi); + const FLOAT_TYPE sz = dot(by20, q2_lo); + const FLOAT_TYPE sw = dot(by232, q2_hi); + const FLOAT_TYPE smin = fma(sumy10, sc03.z, fma(sumy132, sc03.w, fma(sumy20, sc47.z, sumy232 * sc47.w))); + temp2[j][n] = fma(dm.x, fma(sx, sc03.x, fma(sy, sc03.y, fma(sz, sc47.x, sw * sc47.y))), fma(-dm.y, smin, temp2[j][n])); + } + } + } + } + } + } +#else + if (GEN_FAST_KQ >= 2) { + const uint it_size8 = gl_WorkGroupSize.x / 8; + const uint itid8 = tid & 7; + const uint ix8 = tid >> 3; + if (GEN_GLU == 2 && use_a2) { + for (uint i = ix8; i < num_blocks_per_row; i += it_size8) { + calc_superblock_8_a2(temp, a_offset, b_offset, itid8, i, num_blocks_per_row, row_base, eff_rows); + } + } else { + for (uint i = ix8; i < num_blocks_per_row; i += it_size8) { + calc_superblock_8_a(temp, temp2, a_offset, b_offset, itid8, i, num_blocks_per_row, row_base, eff_rows); + } + } + } else if (GEN_FAST_KQ >= 1) { + const uint it_size = gl_WorkGroupSize.x / 16; + const uint itid = tid % 16; + const uint ix = tid / 16; + const uint il = itid / 4; + const uint ir = itid - 4 * il; + const uint v_im = il / 2; + const uint v_in = il % 2; + const uint l0 = 4 * (2 * ir + v_in); + const uint q_offset = 32 * v_im + l0; + const uint y_offset = 64 * v_im + l0; + if (GEN_GLU == 2 && use_a2) { + for (uint i = ix; i < num_blocks_per_row; i += it_size) { + calc_superblock_vec4_a2(temp, a_offset, b_offset, v_im, l0, q_offset, y_offset, i, num_blocks_per_row, row_base, eff_rows); + } + } else { + for (uint i = ix; i < num_blocks_per_row; i += it_size) { + calc_superblock_vec4_a(temp, temp2, a_offset, b_offset, v_im, l0, q_offset, y_offset, i, num_blocks_per_row, row_base, eff_rows); + } + } + } else { + // 16 threads are used to process each block + const uint it_size = gl_WorkGroupSize.x/16; + const uint itid = tid%16; // 0...15 + const uint ix = tid/16; + + const uint il = itid/4; // 0...3 + const uint ir = itid - 4*il; // 0...3 + + const uint v_im = il / 2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224 + const uint v_in = il % 2; + + const uint l0 = 4*ir + 2*v_in; // 0...15 + const uint q_offset = 32*v_im + l0; + const uint y_offset = 64*v_im + l0; - reduce_result(temp, d_offset, first_row, num_rows, tid); + if (GEN_GLU == 2 && use_a2) { + for (uint i = ix; i < num_blocks_per_row; i += it_size) { + calc_superblock_a2(temp, a_offset, b_offset, v_im, l0, q_offset, y_offset, i, num_blocks_per_row, row_base, eff_rows); + } + } else { + for (uint i = ix; i < num_blocks_per_row; i += it_size) { + calc_superblock_a(temp, temp2, a_offset, b_offset, v_im, l0, q_offset, y_offset, i, num_blocks_per_row, row_base, eff_rows); + } + } + } +#endif + + if (GEN_GLU == 3) { + reduce_pair_glu(temp, temp2, d_offset, first_row, eff_rows, tid); + } +#ifndef MUL_MAT_ID + else if (GEN_GLU == 2 && use_a2) { + reduce_result_d2(temp, row_base, eff_rows, tid); + } +#endif + else { + reduce_result(temp, d_offset, first_row, eff_rows, tid); + } } void main() { +#ifdef USE_SUBGROUP_ADD_NO_SHMEM + const uint first_row = NUM_ROWS * (NUM_SUBGROUPS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z) + gl_SubgroupID); +#else const uint first_row = NUM_ROWS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z); +#endif - // do NUM_ROWS at a time, unless there aren't enough remaining rows - if (first_row + NUM_ROWS <= p.stride_d) { - compute_outputs(first_row, NUM_ROWS); - } else { - if (first_row >= p.stride_d) { - return; - } - compute_outputs(first_row, p.stride_d - first_row); + if (first_row >= p.stride_d) { + return; } + compute_outputs(first_row, min(NUM_ROWS, p.stride_d - first_row)); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q6_k.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q6_k.comp index 3e89d91cbb04..ec17bbaf4aec 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q6_k.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q6_k.comp @@ -1,130 +1,608 @@ #version 450 #extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#ifdef REPACK_PLANAR +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable +#endif #include "mul_mat_vec_base.glsl" +#ifdef REPACK_PLANAR +#include "repack_planar.glsl" +layout (binding = 0) readonly buffer A_U32 { uint data_a_u32[]; }; +layout (binding = 0) readonly buffer A_U4 { uvec4 data_a_u4[]; }; +layout (binding = 3) readonly buffer A2_U32 { uint data_a2_u32[]; }; +layout (binding = 3) readonly buffer A2_U4 { uvec4 data_a2_u4[]; }; +#endif + +#ifdef USE_SUBGROUP_ADD_NO_SHMEM +layout(local_size_x_id = 0, local_size_y_id = 4, local_size_z = 1) in; +#else layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; +#endif -shared FLOAT_TYPE sccache[2][BLOCK_SIZE/16][16]; +#define LOAD_Q6_K_16(PFX, ARR_A, ARR_P16) \ + const uint32_t PFX##_ql0_u32 = uint32_t(ARR_P16[ib0 + i].ql[ql_offset / 2]) | (uint32_t(ARR_P16[ib0 + i].ql[ql_offset / 2 + 1]) << 16); \ + const uint32_t PFX##_ql32_u32 = uint32_t(ARR_P16[ib0 + i].ql[ql_offset / 2 + 16]) | (uint32_t(ARR_P16[ib0 + i].ql[ql_offset / 2 + 17]) << 16); \ + const uint32_t PFX##_qh_u32 = uint32_t(ARR_P16[ib0 + i].qh[qh_offset / 2]) | (uint32_t(ARR_P16[ib0 + i].qh[qh_offset / 2 + 1]) << 16); \ + const vec4 PFX##_q0 = vec4(unpack8((PFX##_ql0_u32 & 0x0F0F0F0Fu) | ((PFX##_qh_u32 & 0x03030303u) << 4))) - 32.0f; \ + const vec4 PFX##_q1 = vec4(unpack8((PFX##_ql32_u32 & 0x0F0F0F0Fu) | ((PFX##_qh_u32 & 0x0C0C0C0Cu) << 2))) - 32.0f; \ + const vec4 PFX##_q2 = vec4(unpack8(((PFX##_ql0_u32 >> 4) & 0x0F0F0F0Fu) | (PFX##_qh_u32 & 0x30303030u))) - 32.0f; \ + const vec4 PFX##_q3 = vec4(unpack8(((PFX##_ql32_u32 >> 4) & 0x0F0F0F0Fu) | ((PFX##_qh_u32 & 0xC0C0C0C0u) >> 2))) - 32.0f; \ + const FLOAT_TYPE PFX##_sc0 = FLOAT_TYPE(ARR_A[ib0 + i].scales[s_offset]); \ + const FLOAT_TYPE PFX##_sc1 = FLOAT_TYPE(ARR_A[ib0 + i].scales[s_offset + 2]); \ + const FLOAT_TYPE PFX##_sc2 = FLOAT_TYPE(ARR_A[ib0 + i].scales[s_offset + 4]); \ + const FLOAT_TYPE PFX##_sc3 = FLOAT_TYPE(ARR_A[ib0 + i].scales[s_offset + 6]); \ + const FLOAT_TYPE PFX##_d = FLOAT_TYPE(ARR_A[ib0 + i].d) -FLOAT_TYPE temp[NUM_COLS][NUM_ROWS]; -uint csel = 0; +#define DOT_Q6_K_16_WITH_BY(PFX, DST_TEMP, BY0, BY32, BY64, BY96) do { \ + FLOAT_TYPE sum[4] = {0, 0, 0, 0}; \ + [[unroll]] for (uint l = 0; l < 4; ++l) { \ + sum[0] = fma(FLOAT_TYPE((BY0)[l]), PFX##_q0[l], sum[0]); \ + sum[1] = fma(FLOAT_TYPE((BY32)[l]), PFX##_q1[l], sum[1]); \ + sum[2] = fma(FLOAT_TYPE((BY64)[l]), PFX##_q2[l], sum[2]); \ + sum[3] = fma(FLOAT_TYPE((BY96)[l]), PFX##_q3[l], sum[3]); \ + } \ + DST_TEMP[j][n] = fma(fma(sum[0], PFX##_sc0, fma(sum[1], PFX##_sc1, fma(sum[2], PFX##_sc2, sum[3] * PFX##_sc3))), PFX##_d, DST_TEMP[j][n]); \ +} while (false) -void calc_superblock(const uint a_offset, const uint b_offset, const uint itid, const uint ix, const uint ql_offset, const uint qh_offset, const uint s_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows, const bool all_threads) { +void calc_superblock_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint ql_offset, const uint qh_offset, const uint s_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { const uint y_idx = i * QUANT_K + y_offset; - [[unroll]] for (uint n = 0; n < num_rows; ++n) { - const uint ib0 = a_offset + (first_row+n)*num_blocks_per_row; - csel ^= 1; + if (NUM_COLS <= 4) { + vec4 by0_a[NUM_COLS], by32_a[NUM_COLS], by64_a[NUM_COLS], by96_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; + by0_a[j] = vec4(data_b_v4[b4 ]); + by32_a[j] = vec4(data_b_v4[b4 + 8]); + by64_a[j] = vec4(data_b_v4[b4 + 16]); + by96_a[j] = vec4(data_b_v4[b4 + 24]); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q6_K_16(a1, data_a, data_a_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q6_K_16_WITH_BY(a1, temp, by0_a[j], by32_a[j], by64_a[j], by96_a[j]); + } + if (GEN_GLU == 3) { + LOAD_Q6_K_16(a2, data_a2, data_a2_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q6_K_16_WITH_BY(a2, temp2, by0_a[j], by32_a[j], by64_a[j], by96_a[j]); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q6_K_16(a1, data_a, data_a_packed16); + if (GEN_GLU == 3) { + LOAD_Q6_K_16(a2, data_a2, data_a2_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; + const vec4 by0 = vec4(data_b_v4[b4]), by32 = vec4(data_b_v4[b4 + 8]), by64 = vec4(data_b_v4[b4 + 16]), by96 = vec4(data_b_v4[b4 + 24]); + DOT_Q6_K_16_WITH_BY(a1, temp, by0, by32, by64, by96); + DOT_Q6_K_16_WITH_BY(a2, temp2, by0, by32, by64, by96); + } + } else { + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; + const vec4 by0 = vec4(data_b_v4[b4]), by32 = vec4(data_b_v4[b4 + 8]), by64 = vec4(data_b_v4[b4 + 16]), by96 = vec4(data_b_v4[b4 + 24]); + DOT_Q6_K_16_WITH_BY(a1, temp, by0, by32, by64, by96); + } + } + } + } +} - if (!all_threads) { // when we don't have enough blocks to use all threads - if (i < num_blocks_per_row) - sccache[csel][ix][itid] = FLOAT_TYPE(data_a[ib0 + i].scales[itid]); - barrier(); +void calc_superblock_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint ql_offset, const uint qh_offset, const uint s_offset, const uint y_offset, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y_idx = i * QUANT_K + y_offset; - if (i >= num_blocks_per_row) - continue; + if (NUM_COLS <= 4) { + vec4 by0_a[NUM_COLS], by32_a[NUM_COLS], by64_a[NUM_COLS], by96_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; + by0_a[j] = vec4(data_b_v4[b4 ]); + by32_a[j] = vec4(data_b_v4[b4 + 8]); + by64_a[j] = vec4(data_b_v4[b4 + 16]); + by96_a[j] = vec4(data_b_v4[b4 + 24]); } - - const uint32_t ql0_u32 = uint32_t(data_a_packed16[ib0 + i].ql[ql_offset / 2]) | (uint32_t(data_a_packed16[ib0 + i].ql[ql_offset / 2 + 1]) << 16); - const uint32_t ql32_u32 = uint32_t(data_a_packed16[ib0 + i].ql[ql_offset / 2 + 16]) | (uint32_t(data_a_packed16[ib0 + i].ql[ql_offset / 2 + 17]) << 16); - - const uint32_t ql0_u32_lo4 = ql0_u32 & 0x0F0F0F0F; - const uint32_t ql0_u32_hi4 = (ql0_u32 >> 4) & 0x0F0F0F0F; - const uint32_t ql32_u32_lo4 = ql32_u32 & 0x0F0F0F0F; - const uint32_t ql32_u32_hi4 = (ql32_u32 >> 4) & 0x0F0F0F0F; - - const uint32_t qh_u32 = uint32_t(data_a_packed16[ib0 + i].qh[qh_offset / 2]) | (uint32_t(data_a_packed16[ib0 + i].qh[qh_offset / 2 + 1]) << 16); - const uint32_t qh0_u32 = (qh_u32 & 0x03030303) << 4; - const uint32_t qh2_u32 = (qh_u32 & 0x0C0C0C0C) << 2; - const uint32_t qh4_u32 = (qh_u32 & 0x30303030); - const uint32_t qh6_u32 = (qh_u32 & 0xC0C0C0C0) >> 2; - - const uint32_t q0_u32 = ql0_u32_lo4 | qh0_u32; - const uint32_t q1_u32 = ql32_u32_lo4 | qh2_u32; - const uint32_t q2_u32 = ql0_u32_hi4 | qh4_u32; - const uint32_t q3_u32 = ql32_u32_hi4 | qh6_u32; - - const vec4 q0 = vec4(unpack8(q0_u32)) - 32; - const vec4 q1 = vec4(unpack8(q1_u32)) - 32; - const vec4 q2 = vec4(unpack8(q2_u32)) - 32; - const vec4 q3 = vec4(unpack8(q3_u32)) - 32; - - if (all_threads) { - sccache[csel][ix][itid] = FLOAT_TYPE(data_a[ib0 + i].scales[itid]); - barrier(); + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q6_K_16(a2, data_a2, data_a2_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + DOT_Q6_K_16_WITH_BY(a2, temp, by0_a[j], by32_a[j], by64_a[j], by96_a[j]); + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib0 = a_offset + (first_row + rn) * num_blocks_per_row; + LOAD_Q6_K_16(a2, data_a2, data_a2_packed16); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4; + const vec4 by0 = vec4(data_b_v4[b4]), by32 = vec4(data_b_v4[b4 + 8]), by64 = vec4(data_b_v4[b4 + 16]), by96 = vec4(data_b_v4[b4 + 24]); + DOT_Q6_K_16_WITH_BY(a2, temp, by0, by32, by64, by96); + } } + } +} - const FLOAT_TYPE d = FLOAT_TYPE(data_a[ib0 + i].d); +#define RUN_Q6_K_8(ARR_A, ARR_P16, DST_TEMP) do { \ + const FLOAT_TYPE d = FLOAT_TYPE(ARR_A[ib].d); \ + [[unroll]] for (uint h = 0; h < 2; ++h) { \ + const uint ql_h = 32 * h + 2 * itid8; \ + const uint qh_h = 16 * h + 2 * itid8; \ + const uint s_h = 8 * h + (itid8 >> 2); \ + const uint32_t ql0_u32 = uint32_t(ARR_P16[ib].ql[ql_h]) | (uint32_t(ARR_P16[ib].ql[ql_h + 1]) << 16); \ + const uint32_t ql32_u32 = uint32_t(ARR_P16[ib].ql[ql_h + 16]) | (uint32_t(ARR_P16[ib].ql[ql_h + 17]) << 16); \ + const uint32_t qh_u32 = uint32_t(ARR_P16[ib].qh[qh_h]) | (uint32_t(ARR_P16[ib].qh[qh_h + 1]) << 16); \ + const vec4 q0 = vec4(unpack8((ql0_u32 & 0x0F0F0F0Fu) | ((qh_u32 & 0x03030303u) << 4))) - 32.0f; \ + const vec4 q1 = vec4(unpack8((ql32_u32 & 0x0F0F0F0Fu) | ((qh_u32 & 0x0C0C0C0Cu) << 2))) - 32.0f; \ + const vec4 q2 = vec4(unpack8(((ql0_u32 >> 4) & 0x0F0F0F0Fu) | (qh_u32 & 0x30303030u))) - 32.0f; \ + const vec4 q3 = vec4(unpack8(((ql32_u32 >> 4) & 0x0F0F0F0Fu) | ((qh_u32 & 0xC0C0C0C0u) >> 2))) - 32.0f; \ + const FLOAT_TYPE sc0 = FLOAT_TYPE(ARR_A[ib].scales[s_h ]) * d; \ + const FLOAT_TYPE sc1 = FLOAT_TYPE(ARR_A[ib].scales[s_h + 2]) * d; \ + const FLOAT_TYPE sc2 = FLOAT_TYPE(ARR_A[ib].scales[s_h + 4]) * d; \ + const FLOAT_TYPE sc3 = FLOAT_TYPE(ARR_A[ib].scales[s_h + 6]) * d; \ + const uint bk = 32 * h; \ + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { \ + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4 + bk; \ + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8]); \ + const vec4 by2 = vec4(data_b_v4[b4 + 16]), by3 = vec4(data_b_v4[b4 + 24]); \ + DST_TEMP[j][n] += (dot(by0, q0) * sc0 + dot(by1, q1) * sc1) + (dot(by2, q2) * sc2 + dot(by3, q3) * sc3); \ + } \ + } \ +} while (false) - [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { - vec4 by0 = vec4(data_b_v4[(j*p.batch_stride_b + b_offset + y_idx) / 4 ]); - vec4 by32 = vec4(data_b_v4[(j*p.batch_stride_b + b_offset + y_idx) / 4 + 8]); - vec4 by64 = vec4(data_b_v4[(j*p.batch_stride_b + b_offset + y_idx) / 4 + 16]); - vec4 by96 = vec4(data_b_v4[(j*p.batch_stride_b + b_offset + y_idx) / 4 + 24]); - - FLOAT_TYPE sum[4] = {0, 0, 0, 0}; - [[unroll]] for (uint l = 0; l < 4; ++l) { - sum[0] = fma(FLOAT_TYPE(by0[l]), q0[l], sum[0]); - sum[1] = fma(FLOAT_TYPE(by32[l]), q1[l], sum[1]); - sum[2] = fma(FLOAT_TYPE(by64[l]), q2[l], sum[2]); - sum[3] = fma(FLOAT_TYPE(by96[l]), q3[l], sum[3]); +#define RUN_Q6_K_8_BY(ARR_A, ARR_P16, DST_TEMP) do { \ + const FLOAT_TYPE d = FLOAT_TYPE(ARR_A[ib].d); \ + [[unroll]] for (uint h = 0; h < 2; ++h) { \ + const uint ql_h = 32 * h + 2 * itid8; \ + const uint qh_h = 16 * h + 2 * itid8; \ + const uint s_h = 8 * h + (itid8 >> 2); \ + const uint32_t ql0_u32 = uint32_t(ARR_P16[ib].ql[ql_h]) | (uint32_t(ARR_P16[ib].ql[ql_h + 1]) << 16); \ + const uint32_t ql32_u32 = uint32_t(ARR_P16[ib].ql[ql_h + 16]) | (uint32_t(ARR_P16[ib].ql[ql_h + 17]) << 16); \ + const uint32_t qh_u32 = uint32_t(ARR_P16[ib].qh[qh_h]) | (uint32_t(ARR_P16[ib].qh[qh_h + 1]) << 16); \ + const vec4 q0 = vec4(unpack8((ql0_u32 & 0x0F0F0F0Fu) | ((qh_u32 & 0x03030303u) << 4))) - 32.0f; \ + const vec4 q1 = vec4(unpack8((ql32_u32 & 0x0F0F0F0Fu) | ((qh_u32 & 0x0C0C0C0Cu) << 2))) - 32.0f; \ + const vec4 q2 = vec4(unpack8(((ql0_u32 >> 4) & 0x0F0F0F0Fu) | (qh_u32 & 0x30303030u))) - 32.0f; \ + const vec4 q3 = vec4(unpack8(((ql32_u32 >> 4) & 0x0F0F0F0Fu) | ((qh_u32 & 0xC0C0C0C0u) >> 2))) - 32.0f; \ + const FLOAT_TYPE sc0 = FLOAT_TYPE(ARR_A[ib].scales[s_h ]) * d; \ + const FLOAT_TYPE sc1 = FLOAT_TYPE(ARR_A[ib].scales[s_h + 2]) * d; \ + const FLOAT_TYPE sc2 = FLOAT_TYPE(ARR_A[ib].scales[s_h + 4]) * d; \ + const FLOAT_TYPE sc3 = FLOAT_TYPE(ARR_A[ib].scales[s_h + 6]) * d; \ + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { \ + DST_TEMP[j][n] += (dot(by_h[h][j][0], q0) * sc0 + dot(by_h[h][j][1], q1) * sc1) + (dot(by_h[h][j][2], q2) * sc2 + dot(by_h[h][j][3], q3) * sc3); \ + } \ + } \ +} while (false) + +void calc_superblock_8_a(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], inout FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint itid8, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y_idx = i * QUANT_K + 4 * itid8; + if (NUM_COLS <= 4 && NUM_ROWS > 1) { + vec4 by_h[2][NUM_COLS][4]; + [[unroll]] for (uint h = 0; h < 2; ++h) { + const uint bk = 32 * h; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) / 4 + bk; + by_h[h][j][0] = vec4(data_b_v4[b4 ]); by_h[h][j][1] = vec4(data_b_v4[b4 + 8]); + by_h[h][j][2] = vec4(data_b_v4[b4 + 16]); by_h[h][j][3] = vec4(data_b_v4[b4 + 24]); + } + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + RUN_Q6_K_8_BY(data_a, data_a_packed16, temp); + if (GEN_GLU == 3) { + RUN_Q6_K_8_BY(data_a2, data_a2_packed16, temp2); } - temp[j][n] = fma(fma(sum[0], sccache[csel][ix][s_offset], fma(sum[1], sccache[csel][ix][s_offset + 2], fma(sum[2], sccache[csel][ix][s_offset + 4], sum[3] * sccache[csel][ix][s_offset + 6]))), d, temp[j][n]); } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + RUN_Q6_K_8(data_a, data_a_packed16, temp); + if (GEN_GLU == 3) { + RUN_Q6_K_8(data_a2, data_a2_packed16, temp2); + } + } + } +} + +void calc_superblock_8_a2(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint a_offset, const uint b_offset, const uint itid8, const uint i, const uint num_blocks_per_row, const uint first_row, const uint num_rows) { + const uint y_idx = i * QUANT_K + 4 * itid8; + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < num_rows) ? n : 0; + const uint ib = a_offset + (first_row + rn) * num_blocks_per_row + i; + RUN_Q6_K_8(data_a2, data_a2_packed16, temp); } } void compute_outputs(const uint first_row, const uint num_rows) { uint a_offset, b_offset, d_offset; get_offsets(a_offset, b_offset, d_offset); +#ifndef MUL_MAT_ID + const bool use_a2 = (GEN_GLU == 2) && (first_row >= p.pair_m0); + const uint row_base = use_a2 ? (first_row - p.pair_m0) : first_row; + const uint eff_rows = (!use_a2 && GEN_GLU == 2) ? min(num_rows, p.pair_m0 - first_row) : num_rows; +#else + const bool use_a2 = false; + const uint row_base = first_row; + const uint eff_rows = num_rows; +#endif const uint num_blocks_per_row = p.ncols / QUANT_K; - // 16 threads are used to process each block - const uint it_size = gl_WorkGroupSize.x/16; +#ifdef USE_SUBGROUP_ADD_NO_SHMEM + const uint tid = gl_SubgroupInvocationID; +#else const uint tid = gl_LocalInvocationID.x; - const uint itid = tid%16; // 0...15 - const uint ix = tid/16; - - const uint v_im = itid/8; // 0 or 1. 0 computes 0..., 1 computes 128... - const uint v_in = itid - 8*v_im; // 0...7 - - const uint l0 = 4 * v_in; // 0, 4, 8, ..., 28 - const uint is = v_in / 4; +#endif - const uint ql_offset = 64*v_im + l0; - const uint qh_offset = 32*v_im + l0; - const uint s_offset = 8*v_im + is; - const uint y_offset = 128*v_im + l0; + FLOAT_TYPE temp[NUM_COLS][NUM_ROWS]; + FLOAT_TYPE temp2[NUM_COLS][NUM_ROWS]; [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { [[unroll]] for (uint i = 0; i < NUM_ROWS; ++i) { temp[j][i] = FLOAT_TYPE(0); + if (GEN_GLU == 3) { + temp2[j][i] = FLOAT_TYPE(0); + } + } + } + +#ifdef REPACK_PLANAR +#ifndef REPACK_FAST_KQ +#define REPACK_FAST_KQ GEN_FAST_KQ +#endif + if (REPACK_FAST_KQ >= 2) { + const uint it_size8 = gl_WorkGroupSize.x >> 3u; + const uint itid8 = tid & 7u; + const uint ix8 = tid >> 3u; + const uint sel = itid8 >> 2u; + for (uint i = ix8; i < num_blocks_per_row; i += it_size8) { + const uint y_idx = i * QUANT_K + 4u * itid8; + if (NUM_COLS <= 2) { + vec4 by_h[2][NUM_COLS][4]; + [[unroll]] for (uint h = 0u; h < 2u; ++h) { + const uint bk = 32u * h; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = ((j * p.batch_stride_b + b_offset + y_idx) >> 2u) + bk; + by_h[h][j][0] = vec4(data_b_v4[b4 ]); by_h[h][j][1] = vec4(data_b_v4[b4 + 8u]); + by_h[h][j][2] = vec4(data_b_v4[b4 + 16u]); by_h[h][j][3] = vec4(data_b_v4[b4 + 24u]); + } + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q6_K_SB_U4; + const uint sb_u32 = sb_u4 << 2u; + { + const uvec4 sc_hdr = use_a2 ? data_a2_u4[sb_u4 + REPACK_Q6_K_SC_OFF_U4] : data_a_u4[sb_u4 + REPACK_Q6_K_SC_OFF_U4]; + const float d = unpackHalf2x16(use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32] : data_a_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uvec4 q = use_a2 ? data_a2_u4[sb_u4 + REPACK_Q6_K_QL_OFF_U4 + itid8] : data_a_u4[sb_u4 + REPACK_Q6_K_QL_OFF_U4 + itid8]; + const uint qh0 = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 0u] : data_a_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 0u]; + const uint qh1 = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 1u] : data_a_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 1u]; + [[unroll]] for (uint h = 0u; h < 2u; ++h) { + const uint ql0 = (h == 0u) ? q.x : q.z; + const uint ql32 = (h == 0u) ? q.y : q.w; + const uint qh = (h == 0u) ? qh0 : qh1; + const uint sw_a = (h == 0u) ? sc_hdr.x : sc_hdr.z; + const uint sw_b = (h == 0u) ? sc_hdr.y : sc_hdr.w; + const vec4 q0 = repack_magic_q6((ql0 & 0x000F000Fu) | ((qh & 0x00030003u) << 4u), ((ql0 >> 8u) & 0x000F000Fu) | ((qh & 0x03000300u) >> 4u)); + const vec4 q1 = repack_magic_q6((ql32 & 0x000F000Fu) | ((qh & 0x000C000Cu) << 2u), ((ql32 >> 8u) & 0x000F000Fu) | ((qh & 0x0C000C00u) >> 6u)); + const vec4 q2 = repack_magic_q6(((ql0 >> 4u) & 0x000F000Fu) | (qh & 0x00300030u), ((ql0 >> 12u) & 0x000F000Fu) | ((qh & 0x30003000u) >> 8u)); + const vec4 q3 = repack_magic_q6(((ql32>> 4u) & 0x000F000Fu) | ((qh & 0x00C000C0u) >> 2u), ((ql32 >> 12u) & 0x000F000Fu) | ((qh & 0xC000C000u) >> 10u)); + const FLOAT_TYPE sc0 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int(sel * 8u), 8)) * d; + const FLOAT_TYPE sc1 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int((sel + 2u) * 8u), 8)) * d; + const FLOAT_TYPE sc2 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int(sel * 8u), 8)) * d; + const FLOAT_TYPE sc3 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int((sel + 2u) * 8u), 8)) * d; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + temp[j][n] += (dot(by_h[h][j][0], q0) * sc0 + dot(by_h[h][j][1], q1) * sc1) + + (dot(by_h[h][j][2], q2) * sc2 + dot(by_h[h][j][3], q3) * sc3); + } + } + } + if (GEN_GLU == 3) { + const uvec4 sc_hdr = data_a2_u4[sb_u4 + REPACK_Q6_K_SC_OFF_U4]; + const float d = unpackHalf2x16(data_a2_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uvec4 q = data_a2_u4[sb_u4 + REPACK_Q6_K_QL_OFF_U4 + itid8]; + const uint qh0 = data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 0u]; + const uint qh1 = data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 1u]; + [[unroll]] for (uint h = 0u; h < 2u; ++h) { + const uint ql0 = (h == 0u) ? q.x : q.z; + const uint ql32 = (h == 0u) ? q.y : q.w; + const uint qh = (h == 0u) ? qh0 : qh1; + const uint sw_a = (h == 0u) ? sc_hdr.x : sc_hdr.z; + const uint sw_b = (h == 0u) ? sc_hdr.y : sc_hdr.w; + const vec4 q0 = repack_magic_q6((ql0 & 0x000F000Fu) | ((qh & 0x00030003u) << 4u), ((ql0 >> 8u) & 0x000F000Fu) | ((qh & 0x03000300u) >> 4u)); + const vec4 q1 = repack_magic_q6((ql32 & 0x000F000Fu) | ((qh & 0x000C000Cu) << 2u), ((ql32 >> 8u) & 0x000F000Fu) | ((qh & 0x0C000C00u) >> 6u)); + const vec4 q2 = repack_magic_q6(((ql0 >> 4u) & 0x000F000Fu) | (qh & 0x00300030u), ((ql0 >> 12u) & 0x000F000Fu) | ((qh & 0x30003000u) >> 8u)); + const vec4 q3 = repack_magic_q6(((ql32>> 4u) & 0x000F000Fu) | ((qh & 0x00C000C0u) >> 2u), ((ql32 >> 12u) & 0x000F000Fu) | ((qh & 0xC000C000u) >> 10u)); + const FLOAT_TYPE sc0 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int(sel * 8u), 8)) * d; + const FLOAT_TYPE sc1 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int((sel + 2u) * 8u), 8)) * d; + const FLOAT_TYPE sc2 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int(sel * 8u), 8)) * d; + const FLOAT_TYPE sc3 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int((sel + 2u) * 8u), 8)) * d; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + temp2[j][n] += (dot(by_h[h][j][0], q0) * sc0 + dot(by_h[h][j][1], q1) * sc1) + + (dot(by_h[h][j][2], q2) * sc2 + dot(by_h[h][j][3], q3) * sc3); + } + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q6_K_SB_U4; + const uint sb_u32 = sb_u4 << 2u; + { + const uvec4 sc_hdr = use_a2 ? data_a2_u4[sb_u4 + REPACK_Q6_K_SC_OFF_U4] : data_a_u4[sb_u4 + REPACK_Q6_K_SC_OFF_U4]; + const float d = unpackHalf2x16(use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32] : data_a_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uvec4 q = use_a2 ? data_a2_u4[sb_u4 + REPACK_Q6_K_QL_OFF_U4 + itid8] : data_a_u4[sb_u4 + REPACK_Q6_K_QL_OFF_U4 + itid8]; + const uint qh0 = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 0u] : data_a_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 0u]; + const uint qh1 = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 1u] : data_a_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 1u]; + [[unroll]] for (uint h = 0u; h < 2u; ++h) { + const uint ql0 = (h == 0u) ? q.x : q.z; + const uint ql32 = (h == 0u) ? q.y : q.w; + const uint qh = (h == 0u) ? qh0 : qh1; + const uint sw_a = (h == 0u) ? sc_hdr.x : sc_hdr.z; + const uint sw_b = (h == 0u) ? sc_hdr.y : sc_hdr.w; + const vec4 q0 = repack_magic_q6((ql0 & 0x000F000Fu) | ((qh & 0x00030003u) << 4u), ((ql0 >> 8u) & 0x000F000Fu) | ((qh & 0x03000300u) >> 4u)); + const vec4 q1 = repack_magic_q6((ql32 & 0x000F000Fu) | ((qh & 0x000C000Cu) << 2u), ((ql32 >> 8u) & 0x000F000Fu) | ((qh & 0x0C000C00u) >> 6u)); + const vec4 q2 = repack_magic_q6(((ql0 >> 4u) & 0x000F000Fu) | (qh & 0x00300030u), ((ql0 >> 12u) & 0x000F000Fu) | ((qh & 0x30003000u) >> 8u)); + const vec4 q3 = repack_magic_q6(((ql32>> 4u) & 0x000F000Fu) | ((qh & 0x00C000C0u) >> 2u), ((ql32 >> 12u) & 0x000F000Fu) | ((qh & 0xC000C000u) >> 10u)); + const FLOAT_TYPE sc0 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int(sel * 8u), 8)) * d; + const FLOAT_TYPE sc1 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int((sel + 2u) * 8u), 8)) * d; + const FLOAT_TYPE sc2 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int(sel * 8u), 8)) * d; + const FLOAT_TYPE sc3 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int((sel + 2u) * 8u), 8)) * d; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = ((j * p.batch_stride_b + b_offset + y_idx) >> 2u) + 32u * h; + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8u]); + const vec4 by2 = vec4(data_b_v4[b4 + 16u]), by3 = vec4(data_b_v4[b4 + 24u]); + temp[j][n] += (dot(by0, q0) * sc0 + dot(by1, q1) * sc1) + (dot(by2, q2) * sc2 + dot(by3, q3) * sc3); + } + } + } + if (GEN_GLU == 3) { + const uvec4 sc_hdr = data_a2_u4[sb_u4 + REPACK_Q6_K_SC_OFF_U4]; + const float d = unpackHalf2x16(data_a2_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uvec4 q = data_a2_u4[sb_u4 + REPACK_Q6_K_QL_OFF_U4 + itid8]; + const uint qh0 = data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 0u]; + const uint qh1 = data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + 1u]; + [[unroll]] for (uint h = 0u; h < 2u; ++h) { + const uint ql0 = (h == 0u) ? q.x : q.z; + const uint ql32 = (h == 0u) ? q.y : q.w; + const uint qh = (h == 0u) ? qh0 : qh1; + const uint sw_a = (h == 0u) ? sc_hdr.x : sc_hdr.z; + const uint sw_b = (h == 0u) ? sc_hdr.y : sc_hdr.w; + const vec4 q0 = repack_magic_q6((ql0 & 0x000F000Fu) | ((qh & 0x00030003u) << 4u), ((ql0 >> 8u) & 0x000F000Fu) | ((qh & 0x03000300u) >> 4u)); + const vec4 q1 = repack_magic_q6((ql32 & 0x000F000Fu) | ((qh & 0x000C000Cu) << 2u), ((ql32 >> 8u) & 0x000F000Fu) | ((qh & 0x0C000C00u) >> 6u)); + const vec4 q2 = repack_magic_q6(((ql0 >> 4u) & 0x000F000Fu) | (qh & 0x00300030u), ((ql0 >> 12u) & 0x000F000Fu) | ((qh & 0x30003000u) >> 8u)); + const vec4 q3 = repack_magic_q6(((ql32>> 4u) & 0x000F000Fu) | ((qh & 0x00C000C0u) >> 2u), ((ql32 >> 12u) & 0x000F000Fu) | ((qh & 0xC000C000u) >> 10u)); + const FLOAT_TYPE sc0 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int(sel * 8u), 8)) * d; + const FLOAT_TYPE sc1 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int((sel + 2u) * 8u), 8)) * d; + const FLOAT_TYPE sc2 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int(sel * 8u), 8)) * d; + const FLOAT_TYPE sc3 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int((sel + 2u) * 8u), 8)) * d; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = ((j * p.batch_stride_b + b_offset + y_idx) >> 2u) + 32u * h; + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8u]); + const vec4 by2 = vec4(data_b_v4[b4 + 16u]), by3 = vec4(data_b_v4[b4 + 24u]); + temp2[j][n] += (dot(by0, q0) * sc0 + dot(by1, q1) * sc1) + (dot(by2, q2) * sc2 + dot(by3, q3) * sc3); + } + } + } + } + } + } + } else { + const uint it_size16 = gl_WorkGroupSize.x >> 4u; + const uint itid16 = tid & 15u; + const uint ix16 = tid >> 4u; + const uint itid8 = itid16 & 7u; + const uint h = itid16 >> 3u; + const uint sel = itid8 >> 2u; + for (uint i = ix16; i < num_blocks_per_row; i += it_size16) { + const uint y_idx = i * QUANT_K + 128u * h + 4u * itid8; + if (NUM_COLS <= 2) { + vec4 by0_a[NUM_COLS], by1_a[NUM_COLS], by2_a[NUM_COLS], by3_a[NUM_COLS]; + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) >> 2u; + by0_a[j] = vec4(data_b_v4[b4 ]); by1_a[j] = vec4(data_b_v4[b4 + 8u]); + by2_a[j] = vec4(data_b_v4[b4 + 16u]); by3_a[j] = vec4(data_b_v4[b4 + 24u]); + } + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q6_K_SB_U4; + const uint sb_u32 = sb_u4 << 2u; + const uint ql_base = ((sb_u4 + REPACK_Q6_K_QL_OFF_U4 + itid8) << 2u) + h * 2u; + { + const float d = unpackHalf2x16(use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32] : data_a_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uint sw_a = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 0u] : data_a_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 0u]; + const uint sw_b = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 1u] : data_a_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 1u]; + const FLOAT_TYPE sc0 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int(sel * 8u), 8)); + const FLOAT_TYPE sc1 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int((sel + 2u) * 8u), 8)); + const FLOAT_TYPE sc2 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int(sel * 8u), 8)); + const FLOAT_TYPE sc3 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int((sel + 2u) * 8u), 8)); + const uint ql0 = use_a2 ? data_a2_u32[ql_base + 0u] : data_a_u32[ql_base + 0u]; + const uint ql32 = use_a2 ? data_a2_u32[ql_base + 1u] : data_a_u32[ql_base + 1u]; + const uint qh = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + h] : data_a_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + h]; + const vec4 q0 = repack_magic_q6((ql0 & 0x000F000Fu) | ((qh & 0x00030003u) << 4u), ((ql0 >> 8u) & 0x000F000Fu) | ((qh & 0x03000300u) >> 4u)); + const vec4 q1 = repack_magic_q6((ql32 & 0x000F000Fu) | ((qh & 0x000C000Cu) << 2u), ((ql32 >> 8u) & 0x000F000Fu) | ((qh & 0x0C000C00u) >> 6u)); + const vec4 q2 = repack_magic_q6(((ql0 >> 4u) & 0x000F000Fu) | (qh & 0x00300030u), ((ql0 >> 12u) & 0x000F000Fu) | ((qh & 0x30003000u) >> 8u)); + const vec4 q3 = repack_magic_q6(((ql32>> 4u) & 0x000F000Fu) | ((qh & 0x00C000C0u) >> 2u), ((ql32 >> 12u) & 0x000F000Fu) | ((qh & 0xC000C000u) >> 10u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + FLOAT_TYPE sum[4] = {0, 0, 0, 0}; + [[unroll]] for (uint l = 0; l < 4; ++l) { + sum[0] = fma(FLOAT_TYPE(by0_a[j][l]), q0[l], sum[0]); + sum[1] = fma(FLOAT_TYPE(by1_a[j][l]), q1[l], sum[1]); + sum[2] = fma(FLOAT_TYPE(by2_a[j][l]), q2[l], sum[2]); + sum[3] = fma(FLOAT_TYPE(by3_a[j][l]), q3[l], sum[3]); + } + temp[j][n] = fma(fma(sum[0], sc0, fma(sum[1], sc1, fma(sum[2], sc2, sum[3] * sc3))), d, temp[j][n]); + } + } + if (GEN_GLU == 3) { + const float d = unpackHalf2x16(data_a2_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uint sw_a = data_a2_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 0u]; + const uint sw_b = data_a2_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 1u]; + const FLOAT_TYPE sc0 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int(sel * 8u), 8)); + const FLOAT_TYPE sc1 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int((sel + 2u) * 8u), 8)); + const FLOAT_TYPE sc2 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int(sel * 8u), 8)); + const FLOAT_TYPE sc3 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int((sel + 2u) * 8u), 8)); + const uint ql0 = data_a2_u32[ql_base + 0u]; + const uint ql32 = data_a2_u32[ql_base + 1u]; + const uint qh = data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + h]; + const vec4 q0 = repack_magic_q6((ql0 & 0x000F000Fu) | ((qh & 0x00030003u) << 4u), ((ql0 >> 8u) & 0x000F000Fu) | ((qh & 0x03000300u) >> 4u)); + const vec4 q1 = repack_magic_q6((ql32 & 0x000F000Fu) | ((qh & 0x000C000Cu) << 2u), ((ql32 >> 8u) & 0x000F000Fu) | ((qh & 0x0C000C00u) >> 6u)); + const vec4 q2 = repack_magic_q6(((ql0 >> 4u) & 0x000F000Fu) | (qh & 0x00300030u), ((ql0 >> 12u) & 0x000F000Fu) | ((qh & 0x30003000u) >> 8u)); + const vec4 q3 = repack_magic_q6(((ql32>> 4u) & 0x000F000Fu) | ((qh & 0x00C000C0u) >> 2u), ((ql32 >> 12u) & 0x000F000Fu) | ((qh & 0xC000C000u) >> 10u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + FLOAT_TYPE sum[4] = {0, 0, 0, 0}; + [[unroll]] for (uint l = 0; l < 4; ++l) { + sum[0] = fma(FLOAT_TYPE(by0_a[j][l]), q0[l], sum[0]); + sum[1] = fma(FLOAT_TYPE(by1_a[j][l]), q1[l], sum[1]); + sum[2] = fma(FLOAT_TYPE(by2_a[j][l]), q2[l], sum[2]); + sum[3] = fma(FLOAT_TYPE(by3_a[j][l]), q3[l], sum[3]); + } + temp2[j][n] = fma(fma(sum[0], sc0, fma(sum[1], sc1, fma(sum[2], sc2, sum[3] * sc3))), d, temp2[j][n]); + } + } + } + } else { + [[unroll]] for (uint n = 0; n < NUM_ROWS; ++n) { + const uint rn = (n == 0 || n < eff_rows) ? n : 0; + const uint sb_u4 = (a_offset + (row_base + rn) * num_blocks_per_row + i) * REPACK_Q6_K_SB_U4; + const uint sb_u32 = sb_u4 << 2u; + const uint ql_base = ((sb_u4 + REPACK_Q6_K_QL_OFF_U4 + itid8) << 2u) + h * 2u; + { + const float d = unpackHalf2x16(use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32] : data_a_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uint sw_a = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 0u] : data_a_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 0u]; + const uint sw_b = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 1u] : data_a_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 1u]; + const FLOAT_TYPE sc0 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int(sel * 8u), 8)); + const FLOAT_TYPE sc1 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int((sel + 2u) * 8u), 8)); + const FLOAT_TYPE sc2 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int(sel * 8u), 8)); + const FLOAT_TYPE sc3 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int((sel + 2u) * 8u), 8)); + const uint ql0 = use_a2 ? data_a2_u32[ql_base + 0u] : data_a_u32[ql_base + 0u]; + const uint ql32 = use_a2 ? data_a2_u32[ql_base + 1u] : data_a_u32[ql_base + 1u]; + const uint qh = use_a2 ? data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + h] : data_a_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + h]; + const vec4 q0 = repack_magic_q6((ql0 & 0x000F000Fu) | ((qh & 0x00030003u) << 4u), ((ql0 >> 8u) & 0x000F000Fu) | ((qh & 0x03000300u) >> 4u)); + const vec4 q1 = repack_magic_q6((ql32 & 0x000F000Fu) | ((qh & 0x000C000Cu) << 2u), ((ql32 >> 8u) & 0x000F000Fu) | ((qh & 0x0C000C00u) >> 6u)); + const vec4 q2 = repack_magic_q6(((ql0 >> 4u) & 0x000F000Fu) | (qh & 0x00300030u), ((ql0 >> 12u) & 0x000F000Fu) | ((qh & 0x30003000u) >> 8u)); + const vec4 q3 = repack_magic_q6(((ql32>> 4u) & 0x000F000Fu) | ((qh & 0x00C000C0u) >> 2u), ((ql32 >> 12u) & 0x000F000Fu) | ((qh & 0xC000C000u) >> 10u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) >> 2u; + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8u]); + const vec4 by2 = vec4(data_b_v4[b4 + 16u]), by3 = vec4(data_b_v4[b4 + 24u]); + FLOAT_TYPE sum[4] = {0, 0, 0, 0}; + [[unroll]] for (uint l = 0; l < 4; ++l) { + sum[0] = fma(FLOAT_TYPE(by0[l]), q0[l], sum[0]); + sum[1] = fma(FLOAT_TYPE(by1[l]), q1[l], sum[1]); + sum[2] = fma(FLOAT_TYPE(by2[l]), q2[l], sum[2]); + sum[3] = fma(FLOAT_TYPE(by3[l]), q3[l], sum[3]); + } + temp[j][n] = fma(fma(sum[0], sc0, fma(sum[1], sc1, fma(sum[2], sc2, sum[3] * sc3))), d, temp[j][n]); + } + } + if (GEN_GLU == 3) { + const float d = unpackHalf2x16(data_a2_u32[sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uint sw_a = data_a2_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 0u]; + const uint sw_b = data_a2_u32[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + h * 2u + 1u]; + const FLOAT_TYPE sc0 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int(sel * 8u), 8)); + const FLOAT_TYPE sc1 = FLOAT_TYPE(bitfieldExtract(int(sw_a), int((sel + 2u) * 8u), 8)); + const FLOAT_TYPE sc2 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int(sel * 8u), 8)); + const FLOAT_TYPE sc3 = FLOAT_TYPE(bitfieldExtract(int(sw_b), int((sel + 2u) * 8u), 8)); + const uint ql0 = data_a2_u32[ql_base + 0u]; + const uint ql32 = data_a2_u32[ql_base + 1u]; + const uint qh = data_a2_u32[sb_u32 + REPACK_Q6_K_QH_OFF_U32 + itid8 * 2u + h]; + const vec4 q0 = repack_magic_q6((ql0 & 0x000F000Fu) | ((qh & 0x00030003u) << 4u), ((ql0 >> 8u) & 0x000F000Fu) | ((qh & 0x03000300u) >> 4u)); + const vec4 q1 = repack_magic_q6((ql32 & 0x000F000Fu) | ((qh & 0x000C000Cu) << 2u), ((ql32 >> 8u) & 0x000F000Fu) | ((qh & 0x0C000C00u) >> 6u)); + const vec4 q2 = repack_magic_q6(((ql0 >> 4u) & 0x000F000Fu) | (qh & 0x00300030u), ((ql0 >> 12u) & 0x000F000Fu) | ((qh & 0x30003000u) >> 8u)); + const vec4 q3 = repack_magic_q6(((ql32>> 4u) & 0x000F000Fu) | ((qh & 0x00C000C0u) >> 2u), ((ql32 >> 12u) & 0x000F000Fu) | ((qh & 0xC000C000u) >> 10u)); + [[unroll]] for (uint j = 0; j < NUM_COLS; ++j) { + const uint b4 = (j * p.batch_stride_b + b_offset + y_idx) >> 2u; + const vec4 by0 = vec4(data_b_v4[b4 ]), by1 = vec4(data_b_v4[b4 + 8u]); + const vec4 by2 = vec4(data_b_v4[b4 + 16u]), by3 = vec4(data_b_v4[b4 + 24u]); + FLOAT_TYPE sum[4] = {0, 0, 0, 0}; + [[unroll]] for (uint l = 0; l < 4; ++l) { + sum[0] = fma(FLOAT_TYPE(by0[l]), q0[l], sum[0]); + sum[1] = fma(FLOAT_TYPE(by1[l]), q1[l], sum[1]); + sum[2] = fma(FLOAT_TYPE(by2[l]), q2[l], sum[2]); + sum[3] = fma(FLOAT_TYPE(by3[l]), q3[l], sum[3]); + } + temp2[j][n] = fma(fma(sum[0], sc0, fma(sum[1], sc1, fma(sum[2], sc2, sum[3] * sc3))), d, temp2[j][n]); + } + } + } + } } } +#else + if (GEN_FAST_KQ >= 2) { + const uint it_size8 = gl_WorkGroupSize.x / 8; + const uint itid8 = tid & 7; + const uint ix8 = tid >> 3; + if (GEN_GLU == 2 && use_a2) { + for (uint i = ix8; i < num_blocks_per_row; i += it_size8) { + calc_superblock_8_a2(temp, a_offset, b_offset, itid8, i, num_blocks_per_row, row_base, eff_rows); + } + } else { + for (uint i = ix8; i < num_blocks_per_row; i += it_size8) { + calc_superblock_8_a(temp, temp2, a_offset, b_offset, itid8, i, num_blocks_per_row, row_base, eff_rows); + } + } + } else { + // 16 threads are used to process each block + const uint it_size = gl_WorkGroupSize.x/16; + const uint itid = tid%16; // 0...15 + const uint ix = tid/16; + + const uint v_im = itid/8; // 0 or 1. 0 computes 0..., 1 computes 128... + const uint v_in = itid - 8*v_im; // 0...7 + + const uint l0 = 4 * v_in; // 0, 4, 8, ..., 28 + const uint is = v_in / 4; - const uint nbr_par_th = num_blocks_per_row%it_size; - const uint nbr_all_th = num_blocks_per_row - nbr_par_th; - uint i0 = 0; - [[unroll]] for (; i0 < nbr_all_th; i0 += it_size) - calc_superblock(a_offset, b_offset, itid, ix, ql_offset, qh_offset, s_offset, y_offset, i0 + ix, num_blocks_per_row, first_row, num_rows, true); - calc_superblock(a_offset, b_offset, itid, ix, ql_offset, qh_offset, s_offset, y_offset, i0 + ix, num_blocks_per_row, first_row, num_rows, false); + const uint ql_offset = 64*v_im + l0; + const uint qh_offset = 32*v_im + l0; + const uint s_offset = 8*v_im + is; + const uint y_offset = 128*v_im + l0; + + if (GEN_GLU == 2 && use_a2) { + for (uint i = ix; i < num_blocks_per_row; i += it_size) { + calc_superblock_a2(temp, a_offset, b_offset, ql_offset, qh_offset, s_offset, y_offset, i, num_blocks_per_row, row_base, eff_rows); + } + } else { + for (uint i = ix; i < num_blocks_per_row; i += it_size) { + calc_superblock_a(temp, temp2, a_offset, b_offset, ql_offset, qh_offset, s_offset, y_offset, i, num_blocks_per_row, row_base, eff_rows); + } + } + } +#endif - reduce_result(temp, d_offset, first_row, num_rows, tid); + if (GEN_GLU == 3) { + reduce_pair_glu(temp, temp2, d_offset, first_row, eff_rows, tid); + } +#ifndef MUL_MAT_ID + else if (GEN_GLU == 2 && use_a2) { + reduce_result_d2(temp, row_base, eff_rows, tid); + } +#endif + else { + reduce_result(temp, d_offset, first_row, eff_rows, tid); + } } void main() { +#ifdef USE_SUBGROUP_ADD_NO_SHMEM + const uint first_row = NUM_ROWS * (NUM_SUBGROUPS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z) + gl_SubgroupID); +#else const uint first_row = NUM_ROWS * (gl_WorkGroupID.x + gl_NumWorkGroups.x * gl_WorkGroupID.z); +#endif - // do NUM_ROWS at a time, unless there aren't enough remaining rows - if (first_row + NUM_ROWS <= p.stride_d) { - compute_outputs(first_row, NUM_ROWS); - } else { - if (first_row >= p.stride_d) { - return; - } - compute_outputs(first_row, p.stride_d - first_row); + if (first_row >= p.stride_d) { + return; } + compute_outputs(first_row, min(NUM_ROWS, p.stride_d - first_row)); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vecq_funcs.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vecq_funcs.glsl index 03c348bf9e3c..6cfe1e784df5 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vecq_funcs.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vecq_funcs.glsl @@ -148,8 +148,8 @@ i32vec2 repack(uint ib, uint iqs) { const u8vec4 i_a0 = unpack8( qs & 0x0F0F0F0F); const u8vec4 i_a1 = unpack8((qs >> 4) & 0x0F0F0F0F); - return i32vec2(pack32(i8vec4(kvalues_mxfp4[i_a0.x], kvalues_mxfp4[i_a0.y], kvalues_mxfp4[i_a0.z], kvalues_mxfp4[i_a0.w])), - pack32(i8vec4(kvalues_mxfp4[i_a1.x], kvalues_mxfp4[i_a1.y], kvalues_mxfp4[i_a1.z], kvalues_mxfp4[i_a1.w]))); + return i32vec2(pack32(i8vec4(int8_t(mxfp4_kval(uint(i_a0.x))), int8_t(mxfp4_kval(uint(i_a0.y))), int8_t(mxfp4_kval(uint(i_a0.z))), int8_t(mxfp4_kval(uint(i_a0.w))))), + pack32(i8vec4(int8_t(mxfp4_kval(uint(i_a1.x))), int8_t(mxfp4_kval(uint(i_a1.y))), int8_t(mxfp4_kval(uint(i_a1.z))), int8_t(mxfp4_kval(uint(i_a1.w)))))); } FLOAT_TYPE mul_q8_1(const int32_t q_sum, const float da, const vec2 dsb, const int32_t sum_divisor) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm.comp index 68de7637347e..fab322245a7c 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm.comp @@ -25,6 +25,7 @@ #if defined(COOPMAT) || defined(MUL_MAT_ID_USE_SUBGROUPS) #extension GL_KHR_shader_subgroup_basic : enable #extension GL_KHR_shader_subgroup_ballot : enable +#extension GL_KHR_shader_subgroup_shuffle : enable #endif #ifdef MUL_MAT_ID @@ -51,28 +52,6 @@ layout (constant_id = 12) const uint MmTypeA = 0; layout (constant_id = 11) const uint ALIGNED = 0; -#ifdef MULMAT_QUANT - -uint mm_load_vec_a() { - switch (MmTypeA) { - case GGML_TYPE_Q1_0: - case GGML_TYPE_Q4_0: - case GGML_TYPE_Q4_1: - case GGML_TYPE_Q5_1: - return 8u; - case GGML_TYPE_Q2_0: - case GGML_TYPE_Q5_0: - case GGML_TYPE_Q8_0: - case GGML_TYPE_Q2_K: - case GGML_TYPE_Q4_K: - case GGML_TYPE_Q5_K: - return 4u; - default: - return 2u; - } -} -#endif - #if !defined(TO_FLOAT_TYPE) #define TO_FLOAT_TYPE FLOAT_TYPE #endif @@ -122,13 +101,79 @@ layout (binding = 0) readonly buffer BUF_Q5_K_P32 { block_q5_K_packed32 data[] layout (binding = 1) readonly buffer B {B_TYPE data_b[];}; layout (binding = 1) readonly buffer B_SCALAR {B_TYPE_SCALAR data_b_scalar[];}; layout (binding = 2) writeonly buffer D {D_TYPE data_d[];}; -#ifndef MUL_MAT_ID +#if !defined(MUL_MAT_ID) && !defined(MM_FUSED) layout (binding = 3) writeonly buffer S {D_TYPE data_s[];}; #endif #ifdef MUL_MAT_ID layout (binding = 3) readonly buffer IDS {int data_ids[];}; layout (binding = 4) readonly buffer RowMap {uint data_row_map[];}; +#define MM_BIND_U 5 +#define MM_BIND_AUX0 6 +#define MM_BIND_AUX1 7 +#else +#define MM_BIND_U 3 +#define MM_BIND_AUX0 4 +#define MM_BIND_AUX1 5 +#endif + +#ifdef MM_FUSED +#ifndef MULMAT_QUANT +layout (binding = MM_BIND_U) readonly buffer U {A_TYPE data_u[];}; +#if defined(DATA_A_F32) +layout (binding = MM_BIND_U) readonly buffer U_SCALAR {float data_u_scalar[];}; +#elif defined(DATA_A_F16) +layout (binding = MM_BIND_U) readonly buffer U_SCALAR {float16_t data_u_scalar[];}; +#elif defined(DATA_A_BF16) +layout (binding = MM_BIND_U) readonly buffer U_SCALAR {uint16_t data_u_scalar[];}; +#endif +#if defined(A_TYPE_PACKED16) +layout (binding = MM_BIND_U) readonly buffer U_PACKED16 {A_TYPE_PACKED16 data_u_packed16[];}; +#endif +#if defined(A_TYPE_PACKED32) +layout (binding = MM_BIND_U) readonly buffer U_PACKED32 {A_TYPE_PACKED32 data_u_packed32[];}; +#endif +#else +layout (binding = MM_BIND_U) readonly buffer UBUF_Q1_0 { block_q1_0 data[]; } u_q1_0; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q2_0 { block_q2_0 data[]; } u_q2_0; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q2_K { block_q2_K data[]; } u_q2_k; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q3_K { block_q3_K data[]; } u_q3_k; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q4_K { block_q4_K data[]; } u_q4_k; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q5_K { block_q5_K data[]; } u_q5_k; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q6_K { block_q6_K data[]; } u_q6_k; +layout (binding = MM_BIND_U) readonly buffer UBUF_TQ1_0 { block_tq1_0 data[]; } u_tq1_0; +layout (binding = MM_BIND_U) readonly buffer UBUF_TQ2_0 { block_tq2_0 data[]; } u_tq2_0; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q4_0_P16 { block_q4_0_packed16 data[]; } u_q4_0_p16; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q5_0_P16 { block_q5_0_packed16 data[]; } u_q5_0_p16; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q8_0_P16 { block_q8_0_packed16 data[]; } u_q8_0_p16; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q3_K_P16 { block_q3_K_packed16 data[]; } u_q3_k_p16; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q6_K_P16 { block_q6_K_packed16 data[]; } u_q6_k_p16; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q4_1_P32 { block_q4_1_packed32 data[]; } u_q4_1_p32; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q5_1_P32 { block_q5_1_packed32 data[]; } u_q5_1_p32; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q2_K_P32 { block_q2_K_packed32 data[]; } u_q2_k_p32; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q4_K_P32 { block_q4_K_packed32 data[]; } u_q4_k_p32; +layout (binding = MM_BIND_U) readonly buffer UBUF_Q5_K_P32 { block_q5_K_packed32 data[]; } u_q5_k_p32; +#endif +layout (binding = MM_BIND_AUX0) readonly buffer AUX0 { float data_aux0[]; }; +layout (binding = MM_BIND_AUX1) readonly buffer AUX1 { float data_aux1[]; }; +#ifndef MUL_MAT_ID +layout (binding = MM_BIND_AUX1) writeonly buffer D2 { D_TYPE data_d2[]; }; +#endif + +#define MAT_VEC_FUSION_FLAGS_BIAS0 0x1u +#define MAT_VEC_FUSION_FLAGS_BIAS1 0x2u +#define MAT_VEC_FUSION_FLAGS_SCALE0 0x4u +#define MAT_VEC_FUSION_FLAGS_SCALE1 0x8u +#define MAT_VEC_FUSION_FLAGS_GLU_A 0x10u +#define MAT_VEC_FUSION_FLAGS_GLU_B 0x20u +#define MAT_VEC_FUSION_FLAGS_SIGMOID 0x80u +#define MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE 0x100u +#define MAT_VEC_FUSION_FLAGS_ROW_SCALE0 0x200u +#define MAT_VEC_FUSION_FLAGS_PAIR_GLU 0x400u +#define MAT_VEC_FUSION_FLAGS_PAIR_MM 0x800u +#define MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1 0x1000u +#define MAT_VEC_FUSION_FLAGS_SCALE0_TOK 0x2000u +#define MAT_VEC_FUSION_FLAGS_SCALE1_TOK 0x4000u #endif layout (push_constant) uniform parameter @@ -151,6 +196,11 @@ layout (push_constant) uniform parameter uint ne11; uint n_experts; uint row_ids_offset; +#ifdef MM_FUSED + uint fusion_flags; + float glu_alpha; + float glu_limit; +#endif #else uint base_work_group_z; uint num_batches; @@ -160,6 +210,12 @@ layout (push_constant) uniform parameter uint broadcast2; uint broadcast3; uint padded_N; +#ifdef MM_FUSED + uint fusion_flags; + uint pair_m0; + uint stride_d2; + uint batch_stride_d2; +#else uint k_units_per_tile; uint work_units_per_group; uint groups_with_extra_unit; @@ -172,6 +228,7 @@ layout (push_constant) uniform parameter uint div_Ls0; uint div_Ls1; #endif +#endif } p; layout (constant_id = 0) const uint BLOCK_SIZE = 64; @@ -197,26 +254,85 @@ layout (constant_id = 3) const uint BK = 16; // Assumed to be 32 if working wit #ifdef MULMAT_QUANT layout(constant_id = 13) const uint SHMEM_STRIDE_PAD = 4; layout(constant_id = 14) const bool APPLY_SLM_A_RESHAPE = false; +layout(constant_id = 15) const uint AGX_DIRECT_STORE = 0; +#ifdef MM_FUSED +layout(constant_id = 16) const uint MM_FUSE_MODE = 1; +#else +const uint MM_FUSE_MODE = 0; +#endif #else layout(constant_id = 12) const uint SHMEM_STRIDE_PAD = 4; layout(constant_id = 13) const bool APPLY_SLM_A_RESHAPE = false; +layout(constant_id = 14) const uint AGX_DIRECT_STORE = 0; +#ifdef MM_FUSED +layout(constant_id = 15) const uint MM_FUSE_MODE = 1; +#else +const uint MM_FUSE_MODE = 0; +#endif #endif #else const uint SHMEM_STRIDE_PAD = 1; const bool APPLY_SLM_A_RESHAPE = false; +const uint AGX_DIRECT_STORE = 0; +const uint MM_FUSE_MODE = 0; #endif -#ifndef MUL_MAT_ID +#if !defined(MUL_MAT_ID) && !defined(MM_FUSED) && !(defined(COOPMAT) && defined(MULMAT_QUANT)) layout(constant_id = 15) const bool stream_k = false; +#elif !defined(MUL_MAT_ID) +const bool stream_k = false; #endif #define SHMEM_STRIDE (BK / 2 + SHMEM_STRIDE_PAD) +#define SHMEM_A_STRIDE (APPLY_SLM_A_RESHAPE ? (BK / 2) : SHMEM_STRIDE) +#define SHMEM_B_STRIDE SHMEM_STRIDE -shared FLOAT_TYPEV2 buf_a[BM * SHMEM_STRIDE]; -shared FLOAT_TYPEV2 buf_b[BN * SHMEM_STRIDE]; +shared FLOAT_TYPEV2 buf_a[BM * SHMEM_A_STRIDE]; +shared FLOAT_TYPEV2 buf_b[BN * SHMEM_B_STRIDE]; #define NUM_WARPS (BLOCK_SIZE / WARP) #ifdef COOPMAT -shared ACC_TYPE coopmat_stage[TM * TN * NUM_WARPS]; +shared ACC_TYPE coopmat_stage[(AGX_DIRECT_STORE != 0) ? 1 : (TM * TN * NUM_WARPS)]; +#endif + +#ifdef MULMAT_QUANT +uint mm_load_vec_a() { + if (AGX_DIRECT_STORE == 1u) { + switch (MmTypeA) { + case GGML_TYPE_Q1_0: + case GGML_TYPE_Q4_0: + case GGML_TYPE_Q4_1: + case GGML_TYPE_Q5_1: + return 8u; + case GGML_TYPE_Q2_0: + case GGML_TYPE_Q5_0: + case GGML_TYPE_Q8_0: + case GGML_TYPE_Q2_K: + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + return 4u; + default: + return 2u; + } + } + switch (MmTypeA) { + case GGML_TYPE_Q8_0: + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + case GGML_TYPE_Q6_K: + return 16u; + case GGML_TYPE_Q1_0: + case GGML_TYPE_Q4_0: + case GGML_TYPE_Q4_1: + case GGML_TYPE_Q5_1: + return 8u; + case GGML_TYPE_Q2_0: + case GGML_TYPE_Q5_0: + case GGML_TYPE_Q2_K: + return 4u; + default: + return 2u; + } +} #endif #include "mul_mm_id_funcs.glsl" @@ -226,6 +342,58 @@ shared ACC_TYPE coopmat_stage[TM * TN * NUM_WARPS]; #include "iq_shmem_init.glsl" #endif +#ifdef MM_FUSED +#ifdef MUL_MAT_ID +float mm_apply_id_epilogue(float val, uint expert_idx, u16vec2 row_idx, uint d_row, uint d_idx) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0u) { + val += data_aux0[expert_idx * p.stride_d + d_row]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0) != 0u) { + const uint s0_idx = uint(row_idx.x) + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0_TOK) != 0u ? uint(row_idx.y) * p.nei0 : 0u); + val *= data_aux0[s0_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1) != 0u) { + const uint s1_idx = uint(row_idx.x) + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1_TOK) != 0u ? uint(row_idx.y) * p.nei0 : 0u); + val *= data_aux1[s1_idx]; + } + if ((p.fusion_flags & (MAT_VEC_FUSION_FLAGS_GLU_A | MAT_VEC_FUSION_FLAGS_GLU_B)) != 0u) { + const float o = data_aux0[d_idx]; + val = ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_GLU_A) != 0u) + ? (val / (1.0f + exp(-val)) * o) + : (o / (1.0f + exp(-o)) * val); + } + return val; +} +#else +float mm_apply_dense_epilogue(float val, uint d_row, uint d_col, uint d_idx) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0u) { + val += data_aux0[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS1) != 0u) { + val += data_aux1[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SIGMOID) != 0u) { + val = 1.0f / (1.0f + exp(-val)); + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE) != 0u) { + const float x = val + data_aux0[d_row]; + const float sp = (x > 20.0f) ? x : log(1.0f + exp(x)); + val = sp * data_aux1[d_row]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_ROW_SCALE0) != 0u) { + val *= data_aux0[d_col]; + } + if ((p.fusion_flags & (MAT_VEC_FUSION_FLAGS_GLU_A | MAT_VEC_FUSION_FLAGS_GLU_B)) != 0u) { + const float o = data_aux0[d_idx]; + val = ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_GLU_A) != 0u) + ? (val / (1.0f + exp(-val)) * o) + : (o / (1.0f + exp(-o)) * val); + } + return val; +} +#endif +#endif + void main() { #ifdef MUL_MAT_ID const uint tile_idx = gl_WorkGroupID.y + gl_WorkGroupID.z * gl_NumWorkGroups.y; @@ -238,6 +406,7 @@ void main() { const uint ic = 0; #else const uint group_idx = gl_WorkGroupID.x; +#ifndef MM_FUSED uint stream_k_work_unit; uint stream_k_work_unit_end; @@ -246,20 +415,23 @@ void main() { stream_k_work_unit_end = stream_k_work_unit + p.work_units_per_group + uint(group_idx < p.groups_with_extra_unit); } #endif +#endif #if defined(NEEDS_INIT_IQ_SHMEM) || defined(MULMAT_QUANT) init_iq_shmem(gl_WorkGroupSize); #endif + const uint BM_EFF = (MM_FUSE_MODE == 2u) ? (BM / 2u) : BM; + const uint WM_EFF = (MM_FUSE_MODE == 2u) ? (WM / 2u) : WM; + #ifdef MUL_MAT_ID - const uint blocks_m = (p.M + BM - 1) / BM; + const uint blocks_m = (p.M + BM_EFF - 1) / BM_EFF; const uint ir = gl_WorkGroupID.x % blocks_m; const uint ik = gl_WorkGroupID.x / blocks_m; + const bool pair_use_u = false; + const uint ir_mem = ir; + const uint m_lim = p.M; #endif - const uint WNITER = (WM * WN) / (WARP * TM * TN * WMITER); - const uint WSUBM = WM / WMITER; - const uint WSUBN = WN / WNITER; - #ifdef COOPMAT const uint warp_i = gl_SubgroupID; @@ -272,6 +444,10 @@ void main() { const uint store_r = tiw % TM; const uint store_c = tiw / TM; #else + const uint WNITER = (WM * WN) / (WARP * TM * TN * WMITER); + const uint WSUBM = WM / WMITER; + const uint WSUBN = WN / WNITER; + const uint warp_i = gl_LocalInvocationID.x / WARP; const uint tiw = gl_LocalInvocationID.x % WARP; @@ -301,10 +477,27 @@ void main() { const uint loadr_b = gl_LocalInvocationID.x % (BK / LOAD_VEC_B_EFF / LOAD_VEC_BATCH_B); const uint loadc_b = gl_LocalInvocationID.x / (BK / LOAD_VEC_B_EFF / LOAD_VEC_BATCH_B); - const uint loadstride_a = gl_WorkGroupSize.x * LOAD_VEC_A_EFF * LOAD_VEC_BATCH_A / BK; - const uint loadstride_b = gl_WorkGroupSize.x * LOAD_VEC_B_EFF * LOAD_VEC_BATCH_B / BK; + const uint loadstride_a = BLOCK_SIZE * LOAD_VEC_A_EFF * LOAD_VEC_BATCH_A / BK; + const uint loadstride_b = BLOCK_SIZE * LOAD_VEC_B_EFF * LOAD_VEC_BATCH_B / BK; #ifndef MUL_MAT_ID +#ifdef MM_FUSED + const uint blocks_m = (p.M + BM_EFF - 1) / BM_EFF; + const uint ic = gl_WorkGroupID.y; + const uint batch_idx = gl_WorkGroupID.z + p.base_work_group_z; + const uint ir = group_idx % blocks_m; + const uint ik = group_idx / blocks_m; + + const uint i13 = batch_idx / p.ne12; + const uint i12 = batch_idx % p.ne12; + const uint i03 = i13 / p.broadcast3; + const uint i02 = i12 / p.broadcast2; + const uint batch_idx_a = i03 * p.ne02 + i02; + + const bool pair_use_u = (MM_FUSE_MODE == 3u) && (ir * BM_EFF >= p.pair_m0); + const uint ir_mem = pair_use_u ? (ir - (p.pair_m0 / BM_EFF)) : ir; + const uint m_lim = (MM_FUSE_MODE == 3u) ? (pair_use_u ? (p.M - p.pair_m0) : p.pair_m0) : p.M; +#else do { uint stream_k_tile_k_unit; uint stream_k_tile_k_units; @@ -337,17 +530,24 @@ void main() { const uint i03 = fastdiv(i13, p.broadcast3_mp, fastdiv_L(p.div_Ls1, 2)); const uint i02 = fastdiv(i12, p.broadcast2_mp, fastdiv_L(p.div_Ls1, 1)); const uint batch_idx_a = i03 * p.ne02 + i02; + + const bool pair_use_u = false; + const uint ir_mem = ir; + const uint m_lim = p.M; +#endif #endif #ifdef MUL_MAT_ID load_row_ids(row_begin); - uint required_work_items = _ne1 * BK / LOAD_VEC_B_EFF / LOAD_VEC_BATCH_B; uint required_warp_c = (_ne1 + WN - 1) / WN; #endif #ifdef MUL_MAT_ID const uint start_k = 0; const uint end_k = p.K; +#elif defined(MM_FUSED) + const uint start_k = ik * p.k_split; + const uint end_k = min(p.K, (ik + 1) * p.k_split); #else uint start_k; uint end_k; @@ -366,7 +566,7 @@ void main() { #else batch_idx_a * (p.batch_stride_a / LOAD_VEC_A_EFF) + #endif - (ir * BM * p.stride_a + start_k) / LOAD_VEC_A_EFF; + (ir_mem * BM_EFF * p.stride_a + start_k) / LOAD_VEC_A_EFF; #ifdef MUL_MAT_ID uint pos_b = 0; #else @@ -375,7 +575,7 @@ void main() { #ifdef COOPMAT coopmat cache_a; - coopmat cache_b; + coopmat cache_b_arr[cms_per_col]; coopmat sums[cms_per_row * cms_per_col]; [[unroll]] for (uint i = 0; i < cms_per_row * cms_per_col; i++) { @@ -396,21 +596,325 @@ void main() { } #endif - for (uint block = start_k; block < end_k; block += BK) { - [[unroll]] for (uint l = 0; l < BM; l += loadstride_a) { - load_a_to_shmem(pos_a, loadr_a, loadc_a + l, ir * BM + loadc_a + l, block, end_k); +#ifdef COOPMAT + bool use_sw_pipe = false; +#if (defined(DATA_A_F32) || defined(DATA_A_F16)) && LOAD_VEC_A == 4 + const uint MAX_STAGE_A = 4u; +#else + const uint MAX_STAGE_A = 2u; +#endif + if (AGX_DIRECT_STORE != 1u) { + if (ALIGNED != 0) { + if (mm_can_stage_a()) { + if (LOAD_VEC_B == 8 || LOAD_VEC_B == 4) { + if (BM <= MAX_STAGE_A * loadstride_a && BN <= 2u * loadstride_b) { + use_sw_pipe = true; + } + } + } } - #ifdef MUL_MAT_ID - if (gl_LocalInvocationID.x < required_work_items) { - #endif - [[unroll]] for (uint l = 0; l < BN; l += loadstride_b) { + } + if (use_sw_pipe) { +#ifdef MUL_MAT_ID + const uint active_cols_b = min(BN, ((required_warp_c * WN) + 7u) & ~7u); +#endif + for (uint block = start_k; block < end_k; block += BK) { + FLOAT_TYPEV2 reg_a0[8]; + FLOAT_TYPEV2 reg_a1[8]; +#if (defined(DATA_A_F32) || defined(DATA_A_F16)) && LOAD_VEC_A == 4 + FLOAT_TYPEV2 reg_a2[8]; + FLOAT_TYPEV2 reg_a3[8]; +#endif + FLOAT_TYPEV2 reg_b0[4]; + FLOAT_TYPEV2 reg_b1[4]; +#ifdef MUL_MAT_ID + [[unroll]] for (uint bi = 0u; bi < 4u; ++bi) { + reg_b0[bi] = FLOAT_TYPEV2(0.0f); + reg_b1[bi] = FLOAT_TYPEV2(0.0f); + } +#endif + + if (loadstride_a <= BM || loadc_a < BM) { + const uint c_sh0 = loadc_a; +#ifdef MM_FUSED + if (MM_FUSE_MODE == 2u && c_sh0 >= BM_EFF) { + const uint c_mem0 = c_sh0 - BM_EFF; + stage_u_to_reg(pos_a, loadr_a, c_sh0, c_mem0, ir * BM_EFF + c_mem0, block, end_k, reg_a0); + } else if (pair_use_u) { + stage_u_to_reg(pos_a, loadr_a, c_sh0, c_sh0, ir * BM_EFF + c_sh0, block, end_k, reg_a0); + } else +#endif + { + stage_a_to_reg(pos_a, loadr_a, c_sh0, c_sh0, ir * BM_EFF + c_sh0, block, end_k, reg_a0); + } + } + if (loadstride_a < BM && loadc_a + loadstride_a < BM) { + const uint c_sh1 = loadc_a + loadstride_a; +#ifdef MM_FUSED + if (MM_FUSE_MODE == 2u && c_sh1 >= BM_EFF) { + const uint c_mem1 = c_sh1 - BM_EFF; + stage_u_to_reg(pos_a, loadr_a, c_sh1, c_mem1, ir * BM_EFF + c_mem1, block, end_k, reg_a1); + } else if (pair_use_u) { + stage_u_to_reg(pos_a, loadr_a, c_sh1, c_sh1, ir * BM_EFF + c_sh1, block, end_k, reg_a1); + } else +#endif + { + stage_a_to_reg(pos_a, loadr_a, c_sh1, c_sh1, ir * BM_EFF + c_sh1, block, end_k, reg_a1); + } + } +#if (defined(DATA_A_F32) || defined(DATA_A_F16)) && LOAD_VEC_A == 4 + if (2u * loadstride_a < BM && loadc_a + 2u * loadstride_a < BM) { + const uint c_sh2 = loadc_a + 2u * loadstride_a; +#ifdef MM_FUSED + if (MM_FUSE_MODE == 2u && c_sh2 >= BM_EFF) { + const uint c_mem2 = c_sh2 - BM_EFF; + stage_u_to_reg(pos_a, loadr_a, c_sh2, c_mem2, ir * BM_EFF + c_mem2, block, end_k, reg_a2); + } else if (pair_use_u) { + stage_u_to_reg(pos_a, loadr_a, c_sh2, c_sh2, ir * BM_EFF + c_sh2, block, end_k, reg_a2); + } else +#endif + { + stage_a_to_reg(pos_a, loadr_a, c_sh2, c_sh2, ir * BM_EFF + c_sh2, block, end_k, reg_a2); + } + } + if (3u * loadstride_a < BM && loadc_a + 3u * loadstride_a < BM) { + const uint c_sh3 = loadc_a + 3u * loadstride_a; +#ifdef MM_FUSED + if (MM_FUSE_MODE == 2u && c_sh3 >= BM_EFF) { + const uint c_mem3 = c_sh3 - BM_EFF; + stage_u_to_reg(pos_a, loadr_a, c_sh3, c_mem3, ir * BM_EFF + c_mem3, block, end_k, reg_a3); + } else if (pair_use_u) { + stage_u_to_reg(pos_a, loadr_a, c_sh3, c_sh3, ir * BM_EFF + c_sh3, block, end_k, reg_a3); + } else +#endif + { + stage_a_to_reg(pos_a, loadr_a, c_sh3, c_sh3, ir * BM_EFF + c_sh3, block, end_k, reg_a3); + } + } +#endif + +#ifdef MUL_MAT_ID + if (loadc_b < active_cols_b) { + stage_b_to_reg(pos_b, loadr_b, loadc_b, 0u, reg_b0); + } + if (loadstride_b < BN && loadc_b + loadstride_b < active_cols_b) { + stage_b_to_reg(pos_b, loadr_b, loadc_b + loadstride_b, 0u, reg_b1); + } +#else + if (loadstride_b <= BN || loadc_b < BN) { + stage_b_to_reg(pos_b, loadr_b, loadc_b, ic * BN + loadc_b, reg_b0); + } + if (loadstride_b < BN && loadc_b + loadstride_b < BN) { + const uint c_b1 = loadc_b + loadstride_b; + stage_b_to_reg(pos_b, loadr_b, c_b1, ic * BN + c_b1, reg_b1); + } +#endif + + if (block > start_k) { + barrier(); + } + + if (loadstride_a <= BM || loadc_a < BM) { + commit_stage_a(loadc_a, loadr_a, reg_a0); + } + if (loadstride_a < BM && loadc_a + loadstride_a < BM) { + commit_stage_a(loadc_a + loadstride_a, loadr_a, reg_a1); + } +#if (defined(DATA_A_F32) || defined(DATA_A_F16)) && LOAD_VEC_A == 4 + if (2u * loadstride_a < BM && loadc_a + 2u * loadstride_a < BM) { + commit_stage_a(loadc_a + 2u * loadstride_a, loadr_a, reg_a2); + } + if (3u * loadstride_a < BM && loadc_a + 3u * loadstride_a < BM) { + commit_stage_a(loadc_a + 3u * loadstride_a, loadr_a, reg_a3); + } +#endif +#ifdef MUL_MAT_ID + if (loadc_b < active_cols_b) { + commit_stage_b(loadc_b, loadr_b, reg_b0); + } + if (loadstride_b < BN && loadc_b + loadstride_b < active_cols_b) { + commit_stage_b(loadc_b + loadstride_b, loadr_b, reg_b1); + } +#else + if (loadstride_b <= BN || loadc_b < BN) { + commit_stage_b(loadc_b, loadr_b, reg_b0); + } + if (loadstride_b < BN && loadc_b + loadstride_b < BN) { + commit_stage_b(loadc_b + loadstride_b, loadr_b, reg_b1); + } +#endif + + barrier(); + + pos_a += BK / LOAD_VEC_A_EFF; + pos_b += BK / LOAD_VEC_B_EFF; + +#ifdef MUL_MAT_ID + if (warp_c < required_warp_c) +#endif + { +#define MM_COMPUTE_KTILE(K_OFF) \ + do { \ + const uint _i = (K_OFF); \ + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { \ + MM_LOAD_CACHE_B(_i, cm_col); \ + } \ + [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { \ + const uint sh_row_a = (MM_FUSE_MODE == 2u) \ + ? ((cm_row < cms_per_row / 2u) \ + ? (warp_r * WM_EFF + cm_row * TM) \ + : (BM_EFF + warp_r * WM_EFF + (cm_row - cms_per_row / 2u) * TM)) \ + : (warp_r * WM + cm_row * TM); \ + coopMatLoad(cache_a, buf_a, a_shmem_index(sh_row_a, _i / 2), a_shmem_stride(), gl_CooperativeMatrixLayoutRowMajor); \ + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { \ + sums[cm_col * cms_per_row + cm_row] = coopMatMulAdd(cache_a, cache_b_arr[cm_col], sums[cm_col * cms_per_row + cm_row]); \ + } \ + } \ + } while (false) + #if !defined(MUL_MAT_ID) - load_b_to_shmem(pos_b, loadr_b, loadc_b + l, ic * BN + loadc_b + l, block, end_k); +#define MM_LOAD_CACHE_B_COLMAJ(K_I, CM_COL) \ + coopMatLoad(cache_b_arr[CM_COL], buf_b, b_shmem_index(warp_c * WN + (CM_COL) * TN, (K_I) / 2), b_shmem_stride(), gl_CooperativeMatrixLayoutColumnMajor) +#else +#define MM_LOAD_CACHE_B_COLMAJ(K_I, CM_COL) \ + coopMatLoad(cache_b_arr[CM_COL], buf_b, (warp_c * WN + (CM_COL) * TN) * SHMEM_STRIDE + (K_I) / 2, SHMEM_STRIDE, gl_CooperativeMatrixLayoutColumnMajor) +#endif + +#if defined(FLOAT16) && !defined(DATA_A_BF16) && LOAD_VEC_B == 8 +#define MM_LOAD_CACHE_B(K_I, CM_COL) \ + do { \ + if (AGX_DIRECT_STORE != 0) { \ + if (APPLY_SLM_A_RESHAPE) { \ + if (BK == 32) { \ + const uint b_off = ((K_I) >> 3u) * ((BN << 2u) + 8u) + (((warp_c * WN + (CM_COL) * 8u) >> 3u) << 5u); \ + coopMatLoad(cache_b_arr[CM_COL], buf_b, b_off, 4u, gl_CooperativeMatrixLayoutRowMajor); \ + } else { \ + MM_LOAD_CACHE_B_COLMAJ(K_I, CM_COL); \ + } \ + } else { \ + MM_LOAD_CACHE_B_COLMAJ(K_I, CM_COL); \ + } \ + } else { \ + MM_LOAD_CACHE_B_COLMAJ(K_I, CM_COL); \ + } \ + } while (false) #else - load_b_to_shmem(pos_b, loadr_b, loadc_b + l, ic, _ne1, block, end_k); +#define MM_LOAD_CACHE_B(K_I, CM_COL) MM_LOAD_CACHE_B_COLMAJ(K_I, CM_COL) #endif + + if (AGX_DIRECT_STORE == 2u) { + [[dont_unroll]] for (uint i = 0; i < BK; i += 2u * TK) { + MM_COMPUTE_KTILE(i); + MM_COMPUTE_KTILE(i + TK); + } + } else if (AGX_DIRECT_STORE == 3u) { + [[dont_unroll]] for (uint i = 0; i < BK; i += TK) { + MM_COMPUTE_KTILE(i); + } + } else if (AGX_DIRECT_STORE == 4u) { + [[unroll]] for (uint i = 0; i < BK; i += TK) { + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + MM_COMPUTE_KTILE(i); + } + } else if (AGX_DIRECT_STORE == 5u) { + [[unroll]] for (uint i = 0; i < BK; i += TK) { + coopmat cache_a_arr[cms_per_row]; + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { + const uint sh_row_a = (MM_FUSE_MODE == 2u) + ? ((cm_row < cms_per_row / 2u) + ? (warp_r * WM_EFF + cm_row * TM) + : (BM_EFF + warp_r * WM_EFF + (cm_row - cms_per_row / 2u) * TM)) + : (warp_r * WM + cm_row * TM); + coopMatLoad(cache_a_arr[cm_row], buf_a, a_shmem_index(sh_row_a, i / 2), a_shmem_stride(), gl_CooperativeMatrixLayoutRowMajor); + } + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { + MM_LOAD_CACHE_B(i, cm_col); + } + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { + sums[cm_col * cms_per_row + cm_row] = coopMatMulAdd(cache_a_arr[cm_row], cache_b_arr[cm_col], sums[cm_col * cms_per_row + cm_row]); + } + } + } + } else { + [[unroll]] for (uint i = 0; i < BK; i += TK) { + MM_COMPUTE_KTILE(i); + } + } + +#undef MM_LOAD_CACHE_B +#undef MM_LOAD_CACHE_B_COLMAJ +#undef MM_COMPUTE_KTILE + } + } + } else +#endif + for (uint block = start_k; block < end_k; block += BK) { + [[unroll]] for (uint l = 0; l < BM; l += loadstride_a) { + if (loadstride_a <= BM || loadc_a + l < BM) { + const uint c_sh = loadc_a + l; +#ifdef MM_FUSED + if (MM_FUSE_MODE == 2u && c_sh >= BM_EFF) { + const uint c_mem = c_sh - BM_EFF; + const uint idx_m = ir * BM_EFF + c_mem; + if (idx_m < p.M) { + load_u_to_shmem(pos_a, loadr_a, c_sh, c_mem, idx_m, block, end_k); + } else { + const uint kp_cnt = (LOAD_VEC_A_EFF * LOAD_VEC_BATCH_A) / 2u; + const uint kp_base = loadr_a * kp_cnt; + [[unroll]] for (uint kp = 0; kp < kp_cnt; ++kp) { + store_a(c_sh, kp_base + kp, FLOAT_TYPEV2(0.0f)); + } + } + } else if (pair_use_u) { + const uint idx_m = ir * BM_EFF + c_sh; + if (idx_m < p.M) { + load_u_to_shmem(pos_a, loadr_a, c_sh, c_sh, idx_m, block, end_k); + } else { + const uint kp_cnt = (LOAD_VEC_A_EFF * LOAD_VEC_BATCH_A) / 2u; + const uint kp_base = loadr_a * kp_cnt; + [[unroll]] for (uint kp = 0; kp < kp_cnt; ++kp) { + store_a(c_sh, kp_base + kp, FLOAT_TYPEV2(0.0f)); + } + } + } else +#endif + { + const uint idx_m = ir * BM_EFF + c_sh; + if (idx_m < m_lim) { + load_a_to_shmem(pos_a, loadr_a, c_sh, c_sh, idx_m, block, end_k); + } else { + const uint kp_cnt = (LOAD_VEC_A_EFF * LOAD_VEC_BATCH_A) / 2u; + const uint kp_base = loadr_a * kp_cnt; + [[unroll]] for (uint kp = 0; kp < kp_cnt; ++kp) { + store_a(c_sh, kp_base + kp, FLOAT_TYPEV2(0.0f)); + } + } + } + } } #ifdef MUL_MAT_ID + const uint active_cols_b = min(BN, required_warp_c * WN); + [[unroll]] for (uint l = 0; l < BN; l += loadstride_b) { + const uint col_b = loadc_b + l; + if (col_b < _ne1) { + load_b_to_shmem(pos_b, loadr_b, col_b, ic, _ne1, block, end_k); + } else if (col_b < active_cols_b) { + const uint kp_cnt = (LOAD_VEC_B_EFF * LOAD_VEC_BATCH_B) / 2u; + const uint buf_idx = col_b * SHMEM_STRIDE + loadr_b * kp_cnt; + [[unroll]] for (uint kp = 0; kp < kp_cnt; ++kp) { + buf_b[buf_idx + kp] = FLOAT_TYPEV2(0.0f); + } + } + } + #else + [[unroll]] for (uint l = 0; l < BN; l += loadstride_b) { + if (loadstride_b <= BN || loadc_b + l < BN) { + load_b_to_shmem(pos_b, loadr_b, loadc_b + l, ic * BN + loadc_b + l, block, end_k); + } } #endif @@ -424,14 +928,24 @@ void main() { if (warp_c < required_warp_c) { #endif [[unroll]] for (uint i = 0; i < BK; i += TK) { + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { +#if !defined(MUL_MAT_ID) + coopMatLoad(cache_b_arr[cm_col], buf_b, b_shmem_index(warp_c * WN + cm_col * TN, i / 2), b_shmem_stride(), gl_CooperativeMatrixLayoutColumnMajor); +#else + coopMatLoad(cache_b_arr[cm_col], buf_b, (warp_c * WN + cm_col * TN) * SHMEM_STRIDE + i / 2, SHMEM_STRIDE, gl_CooperativeMatrixLayoutColumnMajor); +#endif + } [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { + const uint sh_row_a = (MM_FUSE_MODE == 2u) + ? ((cm_row < cms_per_row / 2u) + ? (warp_r * WM_EFF + cm_row * TM) + : (BM_EFF + warp_r * WM_EFF + (cm_row - cms_per_row / 2u) * TM)) + : (warp_r * WM + cm_row * TM); // Load from shared into cache - coopMatLoad(cache_a, buf_a, a_shmem_index(warp_r * WM + cm_row * TM, i / 2), a_shmem_stride(), gl_CooperativeMatrixLayoutRowMajor); + coopMatLoad(cache_a, buf_a, a_shmem_index(sh_row_a, i / 2), a_shmem_stride(), gl_CooperativeMatrixLayoutRowMajor); [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { - coopMatLoad(cache_b, buf_b, (warp_c * WN + cm_col * TN) * SHMEM_STRIDE + i / 2, SHMEM_STRIDE, gl_CooperativeMatrixLayoutColumnMajor); - - sums[cm_col * cms_per_row + cm_row] = coopMatMulAdd(cache_a, cache_b, sums[cm_col * cms_per_row + cm_row]); + sums[cm_col * cms_per_row + cm_row] = coopMatMulAdd(cache_a, cache_b_arr[cm_col], sums[cm_col * cms_per_row + cm_row]); } } } @@ -492,7 +1006,7 @@ void main() { #endif #endif - const uint dr = ir * BM + warp_r * WM; + const uint dr = ir_mem * BM_EFF + warp_r * WM_EFF; const uint dc = ic * BN + warp_c * WN; #ifndef MUL_MAT_ID @@ -502,7 +1016,7 @@ void main() { } #endif -#ifndef MUL_MAT_ID +#if !defined(MUL_MAT_ID) && !defined(MM_FUSED) bool stream_k_store_scratch; if (stream_k) { stream_k_store_scratch = stream_k_tile_k_unit + stream_k_tile_k_units != p.k_units_per_tile; @@ -510,66 +1024,236 @@ void main() { #endif #ifdef COOPMAT + const uint cms_out_rows = (MM_FUSE_MODE == 2u) ? (cms_per_row / 2u) : cms_per_row; + const uint cms_up_off = cms_per_row / 2u; #ifdef MUL_MAT_ID - [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { + if (AGX_DIRECT_STORE != 0 && TM == 8 && TN == 8 && WARP == 32) { + const uint agx_m_local = ((tiw >> 1u) & 3u) | ((tiw >> 2u) & 4u); + const uint agx_n_base = ((tiw & 1u) << 1u) | ((tiw >> 1u) & 4u); [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { - coopMatStore(sums[cm_col * cms_per_row + cm_row], coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); - - barrier(); - [[unroll]] for (uint col = 0; col < TN; col += storestride) { - const uint row_i = dc + cm_col * TN + col + store_c; - if (row_i >= _ne1) break; - - const u16vec2 row_idx = row_ids[row_i - ic * BN]; - - if (dr + cm_row * TM + store_r < p.M) { - data_d[row_idx.y * p.batch_stride_d + row_idx.x * p.stride_d + dr + cm_row * TM + store_r] = D_TYPE(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); + [[unroll]] for (uint elem = 0; elem < 2; elem++) { + const uint row_i = dc + cm_col * TN + (agx_n_base | elem); + if (row_i < _ne1) { + const u16vec2 row_idx = row_ids[row_i - ic * BN]; + const uint d_col_base = row_idx.y * p.batch_stride_d + row_idx.x * p.stride_d; + float row_scale = 1.0f; +#ifdef MM_FUSED + if (MM_FUSE_MODE == 4u) { + const uint s0_idx = uint(row_idx.x) + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0_TOK) != 0u ? uint(row_idx.y) * p.nei0 : 0u); + row_scale = data_aux0[s0_idx]; + } +#endif + [[unroll]] for (uint cm_row = 0; cm_row < cms_out_rows; cm_row++) { + const uint d_row = dr + cm_row * TM + agx_m_local; + if (d_row < p.M) { + const uint d_idx = d_col_base + d_row; + float val = float(sums[cm_col * cms_per_row + cm_row][elem]); +#ifdef MM_FUSED + if (MM_FUSE_MODE == 2u) { + const float u = float(sums[cm_col * cms_per_row + cms_up_off + cm_row][elem]); + val = (val / (1.0f + exp(-val))) * u; + } else if (MM_FUSE_MODE == 4u) { + val *= row_scale; + } else if (p.fusion_flags != 0u) { + val = mm_apply_id_epilogue(val, expert_idx, row_idx, d_row, d_idx); + } +#endif + data_d[d_idx] = D_TYPE(val); + } + } } } - barrier(); + } + } else { + [[unroll]] for (uint cm_row = 0; cm_row < cms_out_rows; cm_row++) { + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { + coopmat out_cm = sums[cm_col * cms_per_row + cm_row]; +#ifdef MM_FUSED + if (MM_FUSE_MODE == 2u) { + [[unroll]] for (uint e = 0; e < out_cm.length(); ++e) { + const float g = float(out_cm[e]); + const float u = float(sums[cm_col * cms_per_row + cms_up_off + cm_row][e]); + out_cm[e] = ACC_TYPE((g / (1.0f + exp(-g))) * u); + } + } +#endif + coopMatStore(out_cm, coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); + + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + [[unroll]] for (uint col = 0; col < TN; col += storestride) { + const uint row_i = dc + cm_col * TN + col + store_c; + if (row_i >= _ne1) break; + + const u16vec2 row_idx = row_ids[row_i - ic * BN]; + const uint d_row = dr + cm_col * 0u + cm_row * TM + store_r; + + if (d_row < p.M) { + const uint d_idx = row_idx.y * p.batch_stride_d + row_idx.x * p.stride_d + d_row; + float val = float(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); +#ifdef MM_FUSED + if (MM_FUSE_MODE != 2u && p.fusion_flags != 0u) { + val = mm_apply_id_epilogue(val, expert_idx, row_idx, d_row, d_idx); + } +#endif + data_d[d_idx] = D_TYPE(val); + } + } + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + } } } #else - [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { - [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { - coopmat cm_dtype = coopmat(sums[cm_col * cms_per_row + cm_row]); - if (stream_k) { - if (stream_k_store_scratch) { - const uint scratch_offset = group_idx * BM * BN + (warp_c * WN + cm_col * TN) * BM + warp_r * WM + cm_row * TM; - coopMatStore(cm_dtype, data_s, scratch_offset, BM, gl_CooperativeMatrixLayoutColumnMajor); + if (!stream_k && AGX_DIRECT_STORE != 0 && TM == 8 && TN == 8 && WARP == 32) { + const uint agx_m_local = ((tiw >> 1u) & 3u) | ((tiw >> 2u) & 4u); + const uint agx_n_base = ((tiw & 1u) << 1u) | ((tiw >> 1u) & 4u); +#ifdef MM_FUSED + float fast_row_scale[cms_per_col][2]; + if (MM_FUSE_MODE == 4u && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_ROW_SCALE0) != 0u) { + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { + [[unroll]] for (uint elem = 0; elem < 2; elem++) { + const uint d_col = dc + cm_col * TN + (agx_n_base | elem); + fast_row_scale[cm_col][elem] = (d_col < p.N) ? data_aux0[d_col] : 1.0f; + } + } + } +#endif + [[unroll]] for (uint cm_row = 0; cm_row < cms_out_rows; cm_row++) { + const uint d_row = dr + cm_row * TM + agx_m_local; + if (d_row < m_lim) { + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { + [[unroll]] for (uint elem = 0; elem < 2; elem++) { + const uint d_col = dc + cm_col * TN + (agx_n_base | elem); + if (d_col < p.N) { + float val = float(sums[cm_col * cms_per_row + cm_row][elem]); +#ifdef MM_FUSED + if (MM_FUSE_MODE == 3u && pair_use_u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1) != 0u) { + val = 1.0f / (1.0f + exp(-val)); + } + data_d2[batch_idx * p.batch_stride_d2 + d_col * p.stride_d2 + d_row] = D_TYPE(val); + } else +#endif + { + const uint d_idx = offsets + d_col * p.stride_d + d_row; +#ifdef MM_FUSED + if (MM_FUSE_MODE == 2u) { + const float u = float(sums[cm_col * cms_per_row + cms_up_off + cm_row][elem]); + val = (val / (1.0f + exp(-val))) * u; + } else if (MM_FUSE_MODE == 4u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0u) { + val += data_aux0[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS1) != 0u) { + val += data_aux1[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_ROW_SCALE0) != 0u) { + val *= fast_row_scale[cm_col][elem]; + } + } else if (MM_FUSE_MODE == 1u) { + val = mm_apply_dense_epilogue(val, d_row, d_col, d_idx); + } +#endif + data_d[d_idx] = D_TYPE(val); + } + } + } + } + } + } + } else { +#ifndef MM_FUSED + [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { + coopmat cm_dtype = coopmat(sums[cm_col * cms_per_row + cm_row]); + if (stream_k) { + if (stream_k_store_scratch) { + const uint scratch_offset = group_idx * BM * BN + (warp_c * WN + cm_col * TN) * BM + warp_r * WM + cm_row * TM; + coopMatStore(cm_dtype, data_s, scratch_offset, BM, gl_CooperativeMatrixLayoutColumnMajor); + } else { + coopMatStore(cm_dtype, data_d, offsets + (dc + cm_col * TN) * p.stride_d + dr + cm_row * TM, p.stride_d, gl_CooperativeMatrixLayoutColumnMajor); + } } else { - coopMatStore(cm_dtype, data_d, offsets + (dc + cm_col * TN) * p.stride_d + dr + cm_row * TM, p.stride_d, gl_CooperativeMatrixLayoutColumnMajor); + const bool is_aligned = p.stride_d % 4 == 0; // Assumption: D_TYPE == float + const bool is_in_bounds = dr + (cm_row + 1) * TM <= p.M && dc + (cm_col + 1) * TN <= p.N; + + if (is_aligned && is_in_bounds) { + // Full coopMat is within bounds and stride_d is aligned with 16B + coopMatStore(cm_dtype, data_d, offsets + (dc + cm_col * TN) * p.stride_d + dr + cm_row * TM, p.stride_d, gl_CooperativeMatrixLayoutColumnMajor); + } else if (is_in_bounds) { + // Full coopMat is within bounds, but stride_d is not aligned + coopMatStore(sums[cm_col * cms_per_row + cm_row], coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); + + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + [[unroll]] for (uint col = 0; col < TN; col += storestride) { + data_d[offsets + (dc + cm_col * TN + col + store_c) * p.stride_d + dr + cm_row * TM + store_r] = D_TYPE(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); + } + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + } else if (dr + cm_row * TM < p.M && dc + cm_col * TN < p.N) { + // Partial coopMat is within bounds + coopMatStore(sums[cm_col * cms_per_row + cm_row], coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); + + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + [[unroll]] for (uint col = 0; col < TN; col += storestride) { + if (dr + cm_row * TM + store_r < p.M && dc + cm_col * TN + col + store_c < p.N) { + data_d[offsets + (dc + cm_col * TN + col + store_c) * p.stride_d + dr + cm_row * TM + store_r] = D_TYPE(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); + } + } + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + } } - } else { - const bool is_aligned = p.stride_d % 4 == 0; // Assumption: D_TYPE == float - const bool is_in_bounds = dr + (cm_row + 1) * TM <= p.M && dc + (cm_col + 1) * TN <= p.N; - - if (is_aligned && is_in_bounds) { - // Full coopMat is within bounds and stride_d is aligned with 16B - coopMatStore(cm_dtype, data_d, offsets + (dc + cm_col * TN) * p.stride_d + dr + cm_row * TM, p.stride_d, gl_CooperativeMatrixLayoutColumnMajor); - } else if (is_in_bounds) { - // Full coopMat is within bounds, but stride_d is not aligned - coopMatStore(sums[cm_col * cms_per_row + cm_row], coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); - - controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); - [[unroll]] for (uint col = 0; col < TN; col += storestride) { - data_d[offsets + (dc + cm_col * TN + col + store_c) * p.stride_d + dr + cm_row * TM + store_r] = D_TYPE(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); + } + } +#else + [[unroll]] for (uint cm_row = 0; cm_row < cms_out_rows; cm_row++) { + [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { + const bool is_in_bounds = dr + (cm_row + 1) * TM <= m_lim && dc + (cm_col + 1) * TN <= p.N; + + if (dr + cm_row * TM < m_lim && dc + cm_col * TN < p.N) { + coopmat out_cm = sums[cm_col * cms_per_row + cm_row]; + if (MM_FUSE_MODE == 2u) { + [[unroll]] for (uint e = 0; e < out_cm.length(); ++e) { + const float g = float(out_cm[e]); + const float u = float(sums[cm_col * cms_per_row + cms_up_off + cm_row][e]); + out_cm[e] = ACC_TYPE((g / (1.0f + exp(-g))) * u); + } } - controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); - } else if (dr + cm_row * TM < p.M && dc + cm_col * TN < p.N) { - // Partial coopMat is within bounds - coopMatStore(sums[cm_col * cms_per_row + cm_row], coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); + coopMatStore(out_cm, coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); [[unroll]] for (uint col = 0; col < TN; col += storestride) { - if (dr + cm_row * TM + store_r < p.M && dc + cm_col * TN + col + store_c < p.N) { - data_d[offsets + (dc + cm_col * TN + col + store_c) * p.stride_d + dr + cm_row * TM + store_r] = D_TYPE(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); + const uint d_row = dr + cm_row * TM + store_r; + const uint d_col = dc + cm_col * TN + col + store_c; + if (is_in_bounds || (d_row < m_lim && d_col < p.N)) { + float val = float(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); + if (pair_use_u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1) != 0u) { + val = 1.0f / (1.0f + exp(-val)); + } + data_d2[batch_idx * p.batch_stride_d2 + d_col * p.stride_d2 + d_row] = D_TYPE(val); + } else { + const uint d_idx = offsets + d_col * p.stride_d + d_row; + if (MM_FUSE_MODE == 4u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0u) { + val += data_aux0[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS1) != 0u) { + val += data_aux1[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_ROW_SCALE0) != 0u) { + val *= data_aux0[d_col]; + } + } else if (MM_FUSE_MODE == 1u) { + val = mm_apply_dense_epilogue(val, d_row, d_col, d_idx); + } + data_d[d_idx] = D_TYPE(val); + } } } controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); } } } +#endif } #endif // MUL_MAT_ID #else @@ -595,6 +1279,7 @@ void main() { data_d[row_idx.y * p.batch_stride_d + row_idx.x * p.stride_d + dr_warp + 2 * cr + 1] = D_TYPE(sums[sums_idx].y); } #else +#ifndef MM_FUSED if (stream_k) { const uint scratch_offset = group_idx * BM * BN + (dc_warp + cc - ic * BN) * BM + dr_warp + 2 * cr - ir * BM; if (stream_k_store_scratch) { @@ -604,7 +1289,9 @@ void main() { data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + 2 * cr] = D_TYPE(sums[sums_idx].x); data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + 2 * cr + 1] = D_TYPE(sums[sums_idx].y); } - } else { + } else +#endif + { if (dr_warp + 2 * cr < p.M && dc_warp + cc < p.N) { data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + 2 * cr] = D_TYPE(sums[sums_idx].x); } @@ -618,7 +1305,7 @@ void main() { } } #endif // COOPMAT -#ifndef MUL_MAT_ID +#if !defined(MUL_MAT_ID) && !defined(MM_FUSED) if (stream_k) { stream_k_work_unit += stream_k_tile_k_units; } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_funcs.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_funcs.glsl index 588fb73546a3..00a3d8ef0a93 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_funcs.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_funcs.glsl @@ -17,662 +17,328 @@ void store_a(uint m, uint k_pair, FLOAT_TYPEV2 value) { buf_a[a_shmem_index(m, k_pair)] = value; } -void load_a_to_shmem(const uint pos_a, const uint row, const uint col, const uint idx_m, const uint block, const uint end_k) { -#if defined(DATA_A_F32) || defined(DATA_A_F16) -#if LOAD_VEC_A == 8 - if (ALIGNED != 0) { - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - FLOAT_TYPEV8 aa = FLOAT_TYPEV8(data_a[idx]); - store_a(col, k_pair, aa[0].xy); - store_a(col, k_pair + 1, aa[0].zw); - store_a(col, k_pair + 2, aa[1].xy); - store_a(col, k_pair + 3, aa[1].zw); - return; - } -#elif LOAD_VEC_A == 4 - if (ALIGNED != 0) { - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - FLOAT_TYPEV4 aa = FLOAT_TYPEV4(data_a[idx]); - store_a(col, k_pair, aa.xy); - store_a(col, k_pair + 1, aa.zw); - return; - } -#endif - const uint idx = pos_a + col * p.stride_a + row * 2; - if (idx_m < p.M && block + row * 2 + 1 < end_k) { - store_a(col, row, FLOAT_TYPEV2(data_a_scalar[idx], - data_a_scalar[idx + 1])); - } else if (idx_m < p.M && block + row * 2 < end_k) { - store_a(col, row, FLOAT_TYPEV2(data_a_scalar[idx], 0.0f)); - } else { - store_a(col, row, FLOAT_TYPEV2(0.0f)); - } -#elif defined(DATA_A_BF16) -#if LOAD_VEC_A == 4 - if (ALIGNED != 0) { - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - FLOAT_TYPEV4 aa = FLOAT_TYPEV4(TO_FLOAT_TYPE(data_a[idx])); - store_a(col, k_pair, aa.xy); - store_a(col, k_pair + 1, aa.zw); - return; - } -#endif - const uint idx = pos_a + col * p.stride_a + row * 2; - if (idx_m < p.M && block + row * 2 + 1 < end_k) { - store_a(col, row, FLOAT_TYPEV2(TO_FLOAT_TYPE(data_a_scalar[idx]), - TO_FLOAT_TYPE(data_a_scalar[idx + 1]))); - } else if (idx_m < p.M && block + row * 2 < end_k) { - store_a(col, row, FLOAT_TYPEV2(TO_FLOAT_TYPE(data_a_scalar[idx]), 0.0f)); - } else { - store_a(col, row, FLOAT_TYPEV2(0.0f)); - } -#elif defined(DATA_A_IQ1_S) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - - const uint ib = idx / 32; - const uint ib32 = (idx % 32) / 4; - const uint ib8 = idx % 32; - - const float d = float(data_a[ib].d); - const uint qh = data_a[ib].qh[ib32]; - const uint qs = data_a[ib].qs[ib8]; - const float dl = d * (2 * bitfieldExtract(qh, 12, 3) + 1); - const float delta = ((qh & 0x8000) != 0) ? -IQ1S_DELTA : IQ1S_DELTA; - const int16_t grid = int16_t(iq1s_grid[qs | (bitfieldExtract(qh, 3 * int(ib8 & 3), 3) << 8)]); - - [[unroll]] for (int k = 0; k < 4; ++k) { - store_a(col, k_pair + k, FLOAT_TYPEV2(dl * (bitfieldExtract(grid, 4 * k , 2) + delta), - dl * (bitfieldExtract(grid, 4 * k + 2, 2) + delta))); - - } -#elif defined(DATA_A_IQ1_M) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - - const uint ib = idx / 32; - const uint ib8 = idx % 32; - const uint ib16 = ib8 / 2; - - const uint16_t[4] scales = data_a[ib].scales; - const u16vec4 s = u16vec4(scales[0], scales[1], scales[2], scales[3]) >> 12; - const float d = float(unpackHalf2x16(s.x | (s.y << 4) | (s.z << 8) | (s.w << 12)).x); - const uint sc = scales[ib8 / 8]; - const uint qs = data_a[ib].qs[ib8]; - const uint qh = data_a[ib].qh[ib16] >> (4 * (ib8 & 1)); - const float dl = d * (2 * bitfieldExtract(sc, 3 * int(ib16 & 3), 3) + 1); - const float delta = ((qh & 8) != 0) ? -IQ1M_DELTA : IQ1M_DELTA; - const int16_t grid = int16_t(iq1s_grid[qs | ((qh & 7) << 8)]); - - [[unroll]] for (int k = 0; k < 4; ++k) { - store_a(col, k_pair + k, FLOAT_TYPEV2(dl * (bitfieldExtract(grid, 4 * k , 2) + delta), - dl * (bitfieldExtract(grid, 4 * k + 2, 2) + delta))); - - } -#elif defined(DATA_A_IQ2_XXS) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - - const uint ib = idx / 32; - const uint ib32 = (idx % 32) / 4; - const uint ib8 = idx % 4; - - const float d = float(data_a[ib].d); - const uint qs = data_a[ib].qs[8 * ib32 + ib8]; - const uint signs = pack32(u8vec4( - data_a[ib].qs[8*ib32 + 4], - data_a[ib].qs[8*ib32 + 5], - data_a[ib].qs[8*ib32 + 6], - data_a[ib].qs[8*ib32 + 7] - )); - const FLOAT_TYPE db = FLOAT_TYPE(d * 0.25 * (0.5 + (signs >> 28))); - const uint32_t sign7 = bitfieldExtract(signs, 7 * int(ib8), 7); - const uint sign = sign7 | (bitCount(sign7) << 7); - const uvec2 grid = iq2xxs_grid[qs]; - const vec4 grid0 = vec4(unpack8(grid.x)); - const vec4 grid1 = vec4(unpack8(grid.y)); - - store_a(col, k_pair, db * FLOAT_TYPEV2((sign & 1) != 0 ? -grid0.x : grid0.x, - (sign & 2) != 0 ? -grid0.y : grid0.y)); - - store_a(col, k_pair + 1, db * FLOAT_TYPEV2((sign & 4) != 0 ? -grid0.z : grid0.z, - (sign & 8) != 0 ? -grid0.w : grid0.w)); - - store_a(col, k_pair + 2, db * FLOAT_TYPEV2((sign & 16) != 0 ? -grid1.x : grid1.x, - (sign & 32) != 0 ? -grid1.y : grid1.y)); - - store_a(col, k_pair + 3, db * FLOAT_TYPEV2((sign & 64) != 0 ? -grid1.z : grid1.z, - (sign & 128) != 0 ? -grid1.w : grid1.w)); - -#elif defined(DATA_A_IQ2_XS) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - - const uint ib = idx / 32; - const uint ib32 = (idx % 32) / 4; - const uint ib8 = idx % 4; - - const float d = float(data_a[ib].d); - const uint scale = (data_a[ib].scales[ib32] >> (2 * (ib8 & 2))) & 0xf; - const FLOAT_TYPE db = FLOAT_TYPE(d * 0.25 * (0.5 + scale)); - const uint qs = data_a[ib].qs[4 * ib32 + ib8]; - const uint sign7 = qs >> 9; - const uint sign = sign7 | (bitCount(sign7) << 7); - const uvec2 grid = iq2xs_grid[qs & 511]; - const vec4 grid0 = vec4(unpack8(grid.x)); - const vec4 grid1 = vec4(unpack8(grid.y)); - - store_a(col, k_pair, db * FLOAT_TYPEV2((sign & 1) != 0 ? -grid0.x : grid0.x, - (sign & 2) != 0 ? -grid0.y : grid0.y)); - - store_a(col, k_pair + 1, db * FLOAT_TYPEV2((sign & 4) != 0 ? -grid0.z : grid0.z, - (sign & 8) != 0 ? -grid0.w : grid0.w)); - - store_a(col, k_pair + 2, db * FLOAT_TYPEV2((sign & 16) != 0 ? -grid1.x : grid1.x, - (sign & 32) != 0 ? -grid1.y : grid1.y)); - - store_a(col, k_pair + 3, db * FLOAT_TYPEV2((sign & 64) != 0 ? -grid1.z : grid1.z, - (sign & 128) != 0 ? -grid1.w : grid1.w)); - -#elif defined(DATA_A_IQ2_S) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - - const uint ib = idx / 32; - const uint ib8 = idx % 32; - const uint ib32 = ib8 / 4; - - const uint scale = (data_a[ib].scales[ib32] >> (2 * (ib8 & 2))) & 0xf; - const uint qs = data_a[ib].qs[ib8]; - const uint qh = data_a[ib].qh[ib32]; - const uint qhshift = 2 * (ib8 % 4); - const uint sign = data_a[ib].qs[QUANT_K_IQ2_S / 8 + ib8]; - - const float d = float(data_a[ib].d); - const FLOAT_TYPE db = FLOAT_TYPE(d * 0.25 * (0.5 + scale)); - const uvec2 grid = iq2s_grid[qs | ((qh << (8 - qhshift)) & 0x300)]; - const vec4 grid0 = vec4(unpack8(grid.x)); - const vec4 grid1 = vec4(unpack8(grid.y)); - - store_a(col, k_pair, db * FLOAT_TYPEV2((sign & 1) != 0 ? -grid0.x : grid0.x, - (sign & 2) != 0 ? -grid0.y : grid0.y)); - - store_a(col, k_pair + 1, db * FLOAT_TYPEV2((sign & 4) != 0 ? -grid0.z : grid0.z, - (sign & 8) != 0 ? -grid0.w : grid0.w)); - - store_a(col, k_pair + 2, db * FLOAT_TYPEV2((sign & 16) != 0 ? -grid1.x : grid1.x, - (sign & 32) != 0 ? -grid1.y : grid1.y)); - - store_a(col, k_pair + 3, db * FLOAT_TYPEV2((sign & 64) != 0 ? -grid1.z : grid1.z, - (sign & 128) != 0 ? -grid1.w : grid1.w)); - -#elif defined(DATA_A_IQ3_XXS) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - - const uint ib = idx / 64; - const uint iqs = idx % 64; - const uint is = QUANT_K_IQ3_XXS / 4 + 4 * (iqs / 8); - - const float d = float(data_a[ib].d); - const uint qs = data_a[ib].qs[iqs]; - const uint signs = pack32(u16vec2( - data_a_packed16[ib].qs[is/2], - data_a_packed16[ib].qs[is/2+1] - )); - const float db = d * 0.5 * (0.5 + (signs >> 28)); - const uint32_t sign7 = bitfieldExtract(signs, 7 * (int(iqs / 2) % 4), 7); - const uint sign = (sign7 | (bitCount(sign7) << 7)) >> (4 * (idx % 2)); - const uint grid = iq3xxs_grid[qs]; - const vec4 v = db * vec4(unpack8(grid)); - - store_a(col, k_pair, FLOAT_TYPEV2((sign & 1) != 0 ? -v.x : v.x, - (sign & 2) != 0 ? -v.y : v.y)); - - store_a(col, k_pair + 1, FLOAT_TYPEV2((sign & 4) != 0 ? -v.z : v.z, - (sign & 8) != 0 ? -v.w : v.w)); - -#elif defined(DATA_A_IQ3_S) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 2; - - const uint ib = idx / 64; - const uint iqs = idx % 64; - const uint iqh = iqs / 8; - - const float d = float(data_a[ib].d); - const uint qs = data_a[ib].qs[iqs]; - const uint qh = data_a[ib].qh[iqh]; - const int8_t sign = int8_t(data_a[ib].signs[iqs / 2] >> (4 * (idx % 2))); - const uint scale = data_a[ib].scales[iqs / 16]; - const i8vec2 sign01 = i8vec2(1 - (2 & i8vec2(sign << 1, sign))); - const float db = d * (1 + 2 * ((scale >> (4 * (iqh & 1))) & 0xf)); - const uint32_t grid = iq3s_grid[qs | ((qh << (8 - (iqs % 8))) & 256)]; - const vec4 v = db * vec4(unpack8(grid)); +#if !defined(MUL_MAT_ID) +uint b_shmem_index(uint n, uint k_pair) { + return n * SHMEM_STRIDE + k_pair; +} - store_a(col, k_pair, FLOAT_TYPEV2((sign & 1) != 0 ? -v.x : v.x, - (sign & 2) != 0 ? -v.y : v.y)); +uint b_shmem_stride() { + return SHMEM_STRIDE; +} - store_a(col, k_pair + 1, FLOAT_TYPEV2((sign & 4) != 0 ? -v.z : v.z, - (sign & 8) != 0 ? -v.w : v.w)); +void store_b(uint n, uint k_pair, FLOAT_TYPEV2 value) { + buf_b[b_shmem_index(n, k_pair)] = value; +} +#endif +bool mm_can_stage_a() { +#if (defined(DATA_A_F32) || defined(DATA_A_F16)) && (LOAD_VEC_A == 8 || LOAD_VEC_A == 4) + return ALIGNED != 0; #elif defined(DATA_A_IQ4_XS) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 4; - - const uint ib = idx / 32; - const uint ib32 = (idx % 32) / 4; - const uint iq = 4 * ib32 + (idx % 4); - - const uint sl = (data_a[ib].scales_l[ib32/2] >> (4 * (ib32 & 1))) & 0xF; - const uint sh = ((data_a[ib].scales_h) >> (2 * ib32)) & 3; - const float d = float(data_a[ib].d); - const float dl = d * float(int(sl | (sh << 4)) - 32); - const uint vui = uint(data_a_packed32[ib].qs[iq]); - - const u8vec4 qs0 = unpack8( vui & 0x0F0F0F0F); - const u8vec4 qs1 = unpack8((vui >> 4) & 0x0F0F0F0F); - const vec4 v0 = dl * vec4(kvalues_iq4nl[qs0.x], kvalues_iq4nl[qs0.y], kvalues_iq4nl[qs0.z], kvalues_iq4nl[qs0.w]); - const vec4 v1 = dl * vec4(kvalues_iq4nl[qs1.x], kvalues_iq4nl[qs1.y], kvalues_iq4nl[qs1.z], kvalues_iq4nl[qs1.w]); - - store_a(col, k_pair, FLOAT_TYPEV2(v0.xy)); - store_a(col, k_pair + 1, FLOAT_TYPEV2(v0.zw)); - store_a(col, k_pair + 8, FLOAT_TYPEV2(v1.xy)); - store_a(col, k_pair + 9, FLOAT_TYPEV2(v1.zw)); - -#elif defined(DATA_A_IQ4_NL) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 4; - - const uint ib = idx / 8; - const uint iqs = idx & 0x07; - - const FLOAT_TYPE d = FLOAT_TYPE(data_a_packed16[ib].d); - const uint vui = uint(data_a_packed16[ib].qs[iqs]); - - store_a(col, k_pair, d * FLOAT_TYPEV2(kvalues_iq4nl[vui & 0xF], - kvalues_iq4nl[bitfieldExtract(vui, 8, 4)])); - - store_a(col, k_pair + 8, d * FLOAT_TYPEV2(kvalues_iq4nl[bitfieldExtract(vui, 4, 4)], - kvalues_iq4nl[vui >> 12])); - -#elif defined(DATA_A_MXFP4) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint k_pair = row * LOAD_VEC_A / 4; - - const uint ib = idx / 8; - const uint iqs = (idx & 0x07) * 2; - - const uint vui = uint(data_a[ib].qs[iqs]); - const uint vui2 = uint(data_a[ib].qs[iqs+1]); - -#ifdef USE_OCP_FP4 - const float d = e8m0_to_fp32(data_a[ib].e); - const u8vec2 packed = u8vec2(vui, vui2); - store_a(col, k_pair, FLOAT_TYPEV2(bitcastExtractfe2m1EXT(packed, 0u)) * FLOAT_TYPE(d)); - store_a(col, k_pair + 8, FLOAT_TYPEV2(bitcastExtractfe2m1EXT(packed, 4u)) * FLOAT_TYPE(d)); + return true; +#elif defined(MULMAT_QUANT) + return MmTypeA == GGML_TYPE_Q8_0 || MmTypeA == GGML_TYPE_Q4_K || MmTypeA == GGML_TYPE_Q5_K || MmTypeA == GGML_TYPE_Q6_K; #else - const float d = e8m0_to_fp32(data_a[ib].e) * 0.5; - store_a(col, k_pair, FLOAT_TYPEV2(kvalues_mxfp4[vui & 0xF] * d, - kvalues_mxfp4[vui2 & 0xF] * d)); - - store_a(col, k_pair + 8, FLOAT_TYPEV2(kvalues_mxfp4[vui >> 4] * d, - kvalues_mxfp4[vui2 >> 4] * d)); - + return false; #endif -#elif defined(DATA_A_NVFP4) - const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row; - const uint eff_row = (row & 3) + (row & ~3) * 2; - - const uint ib = idx / 16u; - const uint sub = (idx & 0xC) >> 2; - const uint iqs = (idx & 0xF) * 2; - const uint vui = uint(data_a[ib].qs[iqs]); - const uint vui2 = uint(data_a[ib].qs[iqs+1]); +} -#ifdef USE_OCP_FP4 - const FLOAT_TYPE d = FLOAT_TYPE(ue4m3_from_bits(data_a[ib].d[sub])); - const u8vec2 packed = u8vec2(vui, vui2); - store_a(col, eff_row, FLOAT_TYPEV2(bitcastExtractfe2m1EXT(packed, 0u)) * d); - store_a(col, eff_row + 4, FLOAT_TYPEV2(bitcastExtractfe2m1EXT(packed, 4u)) * d); -#else - const float d = ue4m3_to_fp32(data_a[ib].d[sub]) * 0.5; - store_a(col, eff_row, FLOAT_TYPEV2(kvalues_mxfp4[vui & 0xF] * d, - kvalues_mxfp4[vui2 & 0xF] * d)); - store_a(col, eff_row + 4, FLOAT_TYPEV2(kvalues_mxfp4[vui >> 4] * d, - kvalues_mxfp4[vui2 >> 4] * d)); +void commit_stage_a(const uint col_sh, const uint row, const FLOAT_TYPEV2 stage_v[8]) { +#if (defined(DATA_A_F32) || defined(DATA_A_F16)) && LOAD_VEC_A == 8 + const uint kp = row * 4u; + store_a(col_sh, kp + 0u, stage_v[0]); + store_a(col_sh, kp + 1u, stage_v[1]); + store_a(col_sh, kp + 2u, stage_v[2]); + store_a(col_sh, kp + 3u, stage_v[3]); +#elif (defined(DATA_A_F32) || defined(DATA_A_F16)) && LOAD_VEC_A == 4 + const uint kp = row * 2u; + store_a(col_sh, kp + 0u, stage_v[0]); + store_a(col_sh, kp + 1u, stage_v[1]); +#elif defined(DATA_A_IQ4_XS) + const uint kp = row * 2u; + store_a(col_sh, kp + 0u, stage_v[0]); + store_a(col_sh, kp + 1u, stage_v[1]); + store_a(col_sh, kp + 8u, stage_v[2]); + store_a(col_sh, kp + 9u, stage_v[3]); +#elif defined(MULMAT_QUANT) + const uint kp = row * 8u; + store_a(col_sh, kp + 0u, stage_v[0]); + store_a(col_sh, kp + 1u, stage_v[1]); + store_a(col_sh, kp + 2u, stage_v[2]); + store_a(col_sh, kp + 3u, stage_v[3]); + store_a(col_sh, kp + 4u, stage_v[4]); + store_a(col_sh, kp + 5u, stage_v[5]); + store_a(col_sh, kp + 6u, stage_v[6]); + store_a(col_sh, kp + 7u, stage_v[7]); #endif -#else - if (MmTypeA == GGML_TYPE_Q4_0) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 4; - - const uint ib = idx / 4; - const uint iqs = idx & 0x03; - - const float d = float(a_q4_0_p16.data[ib].d); - const uint vui = uint(a_q4_0_p16.data[ib].qs[2*iqs]) | (uint(a_q4_0_p16.data[ib].qs[2*iqs + 1]) << 16); - const vec4 v0 = (vec4(unpack8(vui & 0x0F0F0F0F)) - 8.0f) * d; - const vec4 v1 = (vec4(unpack8((vui >> 4) & 0x0F0F0F0F)) - 8.0f) * d; - - store_a(col, k_pair, FLOAT_TYPEV2(v0.xy)); - store_a(col, k_pair + 1, FLOAT_TYPEV2(v0.zw)); - store_a(col, k_pair + 8, FLOAT_TYPEV2(v1.xy)); - store_a(col, k_pair + 9, FLOAT_TYPEV2(v1.zw)); - } else if (MmTypeA == GGML_TYPE_Q4_1) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 4; - - const uint ib = idx / 4; - const uint iqs = idx & 0x03; - - const vec2 dm = vec2(a_q4_1_p32.data[ib].dm); - const uint vui = a_q4_1_p32.data[ib].qs[iqs]; - const vec4 v0 = vec4(unpack8(vui & 0x0F0F0F0F)) * dm.x + dm.y; - const vec4 v1 = vec4(unpack8((vui >> 4) & 0x0F0F0F0F)) * dm.x + dm.y; - - store_a(col, k_pair, FLOAT_TYPEV2(v0.xy)); - store_a(col, k_pair + 1, FLOAT_TYPEV2(v0.zw)); - store_a(col, k_pair + 8, FLOAT_TYPEV2(v1.xy)); - store_a(col, k_pair + 9, FLOAT_TYPEV2(v1.zw)); - } else if (MmTypeA == GGML_TYPE_Q5_0) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 4; - - const uint ib = idx / 8; - const uint iqs = idx & 0x07; - - const float d = float(a_q5_0_p16.data[ib].d); - const uint uint_qh = uint(a_q5_0_p16.data[ib].qh[1]) << 16 | uint(a_q5_0_p16.data[ib].qh[0]); - const ivec2 qh0 = ivec2(((uint_qh >> 2*iqs) << 4) & 0x10, (uint_qh >> (2*iqs + 12)) & 0x10); - const ivec2 qh1 = ivec2(((uint_qh >> (2*iqs + 1)) << 4) & 0x10, (uint_qh >> (2*iqs + 13)) & 0x10); - - const uint vui = uint(a_q5_0_p16.data[ib].qs[iqs]); - const vec4 v = (vec4((vui & 0xF) | qh0.x, ((vui >> 4) & 0xF) | qh0.y, ((vui >> 8) & 0xF) | qh1.x, (vui >> 12) | qh1.y) - 16.0f) * d; - - store_a(col, k_pair, FLOAT_TYPEV2(v.xz)); - store_a(col, k_pair + 8, FLOAT_TYPEV2(v.yw)); - } else if (MmTypeA == GGML_TYPE_Q5_1) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 4; - - const uint ib = idx / 4; - const uint iqs = idx & 0x03; - - const vec2 dm = vec2(a_q5_1_p32.data[ib].dm); - const uint uint_qh = a_q5_1_p32.data[ib].qh; - const uvec2 qh0 = uvec2(((uint_qh >> 4*iqs) << 4) & 0x10, (uint_qh >> (4*iqs + 12)) & 0x10); - const uvec2 qh1 = uvec2(((uint_qh >> (4*iqs + 1)) << 4) & 0x10, (uint_qh >> (4*iqs + 13)) & 0x10); - const uvec2 qh2 = uvec2(((uint_qh >> (4*iqs + 2)) << 4) & 0x10, (uint_qh >> (4*iqs + 14)) & 0x10); - const uvec2 qh3 = uvec2(((uint_qh >> (4*iqs + 3)) << 4) & 0x10, (uint_qh >> (4*iqs + 15)) & 0x10); - - const uint vui = a_q5_1_p32.data[ib].qs[iqs]; - const vec4 v0 = vec4((vui & 0xF) | qh0.x, ((vui >> 4) & 0xF) | qh0.y, ((vui >> 8) & 0xF) | qh1.x, ((vui >> 12) & 0xF) | qh1.y) * dm.x + dm.y; - const vec4 v1 = vec4(((vui >> 16) & 0xF) | qh2.x, ((vui >> 20) & 0xF) | qh2.y, ((vui >> 24) & 0xF) | qh3.x, ((vui >> 28) & 0xF) | qh3.y) * dm.x + dm.y; - - store_a(col, k_pair, FLOAT_TYPEV2(v0.xz)); - store_a(col, k_pair + 1, FLOAT_TYPEV2(v1.xz)); - store_a(col, k_pair + 8, FLOAT_TYPEV2(v0.yw)); - store_a(col, k_pair + 9, FLOAT_TYPEV2(v1.yw)); - } else if (MmTypeA == GGML_TYPE_Q8_0) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 2; - - const uint ib = idx / 8; - const uint iqs = idx & 0x07; - - const float d = float(a_q8_0_p16.data[ib].d); - const i8vec2 v0 = unpack8(int32_t(a_q8_0_p16.data[ib].qs[2*iqs])).xy; // vec4 used due to #12147 - const i8vec2 v1 = unpack8(int32_t(a_q8_0_p16.data[ib].qs[2*iqs + 1])).xy; - const vec4 v = vec4(v0.x, v0.y, v1.x, v1.y) * d; - - store_a(col, k_pair, FLOAT_TYPEV2(v.xy)); - store_a(col, k_pair + 1, FLOAT_TYPEV2(v.zw)); - } else if (MmTypeA == GGML_TYPE_Q1_0) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 2; - - const uint ib = idx / 16; - const uint iqs = idx & 0xfu; - - const float d = float(a_q1_0.data[ib].d); - const uint bits = uint(a_q1_0.data[ib].qs[iqs]); - - store_a(col, k_pair, FLOAT_TYPEV2((bits & 0x01u) != 0u ? d : -d, (bits & 0x02u) != 0u ? d : -d)); - store_a(col, k_pair + 1, FLOAT_TYPEV2((bits & 0x04u) != 0u ? d : -d, (bits & 0x08u) != 0u ? d : -d)); - store_a(col, k_pair + 2, FLOAT_TYPEV2((bits & 0x10u) != 0u ? d : -d, (bits & 0x20u) != 0u ? d : -d)); - store_a(col, k_pair + 3, FLOAT_TYPEV2((bits & 0x40u) != 0u ? d : -d, (bits & 0x80u) != 0u ? d : -d)); - } else if (MmTypeA == GGML_TYPE_Q2_0) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 2; - - const uint ib = idx / 16; - const uint iqs = idx & 0xfu; - - const FLOAT_TYPE d = FLOAT_TYPE(a_q2_0.data[ib].d); - const uint bits = uint(a_q2_0.data[ib].qs[iqs]); - - store_a(col, k_pair, d * (FLOAT_TYPEV2(bits & 3u, (bits >> 2u) & 3u) - FLOAT_TYPEV2(1.0f))); - store_a(col, k_pair + 1, d * (FLOAT_TYPEV2((bits >> 4u) & 3u, bits >> 6u) - FLOAT_TYPEV2(1.0f))); - } else if (MmTypeA == GGML_TYPE_Q2_K) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 2; - - const uint ib = idx / 64; // 4 values per idx - const uint iqs = (idx % 64) * 2; // 0,2,4..126 - - const uint qsi = (iqs / 64) * 16 + (iqs % 16); // 0..15 - const uint scalesi = iqs / 8; // 0..15 - const uint qsshift = ((iqs % 64) / 16) * 2; // 0,2,4,6 - - const vec4 qs = vec4(unpack8((a_q2_k_p32.data[ib].qs[qsi / 2] >> qsshift) & 0x03030303)); - const uint scales = a_q2_k.data[ib].scales[scalesi]; - const vec2 dm = vec2(a_q2_k.data[ib].dm); - - const vec4 v = dm.x * float(scales & 0xF) * qs - dm.y * float(scales >> 4); - - store_a(col, k_pair, FLOAT_TYPEV2(v.xy)); - store_a(col, k_pair + 1, FLOAT_TYPEV2(v.zw)); - } else if (MmTypeA == GGML_TYPE_Q3_K) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 2; - - const uint ib = idx / 128; // 2 values per idx - const uint iqs = idx % 128; // 0..127 - - const uint n = iqs / 64; // 0,1 - const uint qsi = n * 32 + (iqs % 16) * 2; // 0,2,4..62 - const uint hmi = (iqs % 16) * 2; // 0,2,4..30 - const uint j = (iqs % 64) / 4; // 0..3 - const uint is = iqs / 8; // 0..15 - const uint halfsplit = ((iqs % 64) / 16); // 0,1,2,3 - const uint qsshift = halfsplit * 2; // 0,2,4,6 - - const int8_t us = int8_t(((a_q3_k.data[ib].scales[is % 8] >> (4 * int(is / 8))) & 0xF) - | (((a_q3_k.data[ib].scales[8 + (is % 4)] >> (2 * int(is / 4))) & 3) << 4)); - const float dl = float(a_q3_k.data[ib].d) * float(us - 32); - - const vec2 qs = vec2(unpack8((uint(a_q3_k_p16.data[ib].qs[qsi / 2]) >> qsshift) & 0x0303).xy); - const vec2 hm = vec2(unpack8(((uint(a_q3_k_p16.data[ib].hmask[hmi / 2]) >> (4 * n + halfsplit)) & 0x0101 ^ 0x0101) << 2).xy); - - store_a(col, k_pair, FLOAT_TYPEV2(dl * (qs.x - hm.x), - dl * (qs.y - hm.y))); - - } else if (MmTypeA == GGML_TYPE_Q4_K) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 2; - - const uint ib = idx / 64; // 4 values per idx - const uint iqs = (idx % 64) * 2; // 0,2,4..126 - - const uint n = iqs / 32; // 0,1,2,3 - const uint b = (iqs % 32) / 16; // 0,1 - const uint is = 2 * n + b; // 0..7 - const uint qsi = n * 32 + (iqs % 16) * 2; // 0,2,4..126 - - const vec2 loadd = vec2(a_q4_k.data[ib].dm); - - const uvec3 scales = uvec3(a_q4_k_p32.data[ib].scales[0], - a_q4_k_p32.data[ib].scales[1], - a_q4_k_p32.data[ib].scales[2]); - const uint scalesoffs = (is & 3) * 8; - - const uint scidx0 = (is < 4) ? 0 : 2; - const uint scidxshift0 = scalesoffs; - const uint scidxshift1 = (is < 4) ? scalesoffs : scalesoffs + 2; - const uint mbidx0 = (is < 4) ? 1 : 2; - const uint mbidxshift0 = (is < 4) ? scalesoffs : scalesoffs + 4; - const uint mbidxshift1 = (is < 4) ? scalesoffs : scalesoffs + 2; - - const uint8_t sc = uint8_t(((scales[scidx0] >> scidxshift0) & 0xF) | ((scales[0] >> scidxshift1) & 0x30)); - const uint8_t mbyte = uint8_t(((scales[mbidx0] >> mbidxshift0) & 0xF) | ((scales[1] >> mbidxshift1) & 0x30)); - - const float d = loadd.x * sc; - const float m = -loadd.y * mbyte; - - const vec4 q = vec4(unpack8((a_q4_k_p32.data[ib].qs[qsi / 4] >> (b * 4)) & 0x0F0F0F0F)); - - store_a(col, k_pair, FLOAT_TYPEV2(fma(d, q.x, m), fma(d, q.y, m))); - store_a(col, k_pair + 1, FLOAT_TYPEV2(fma(d, q.z, m), fma(d, q.w, m))); - } else if (MmTypeA == GGML_TYPE_Q5_K) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 2; - - const uint ib = idx / 64; // 4 values per idx - const uint iqs = (idx % 64) * 2; // 0,2,4..126 - - const uint n = iqs / 32; // 0,1,2,3 - const uint b = (iqs % 32) / 16; // 0,1 - const uint is = 2 * n + b; // 0..7 - const uint qsi = n * 32 + (iqs % 16) * 2; // 0,2,4..126 - const uint qhi = (iqs % 16) * 2; // 0,2,4..30 - - const vec2 loadd = vec2(a_q5_k.data[ib].dm); - - const uvec3 scales = uvec3(a_q5_k_p32.data[ib].scales[0], - a_q5_k_p32.data[ib].scales[1], - a_q5_k_p32.data[ib].scales[2]); - const uint scalesoffs = (is & 3) * 8; - - const uint scidx0 = (is < 4) ? 0 : 2; - const uint scidxshift0 = scalesoffs; - const uint scidxshift1 = (is < 4) ? scalesoffs : scalesoffs + 2; - const uint mbidx0 = (is < 4) ? 1 : 2; - const uint mbidxshift0 = (is < 4) ? scalesoffs : scalesoffs + 4; - const uint mbidxshift1 = (is < 4) ? scalesoffs : scalesoffs + 2; - - const uint8_t sc = uint8_t(((scales[scidx0] >> scidxshift0) & 0xF) | ((scales[0] >> scidxshift1) & 0x30)); - const uint8_t mbyte = uint8_t(((scales[mbidx0] >> mbidxshift0) & 0xF) | ((scales[1] >> mbidxshift1) & 0x30)); - - const float d = loadd.x * sc; - const float m = -loadd.y * mbyte; - - const uint qs = (a_q5_k_p32.data[ib].qs[qsi / 4] >> (b * 4)) & 0x0F0F0F0F; - const uint qh = ((a_q5_k_p32.data[ib].qh[qhi / 4] >> (iqs / 16)) & 0x01010101) << 4; - const vec4 q = vec4(unpack8(qs | qh)); - - store_a(col, k_pair, FLOAT_TYPEV2(fma(d, q.x, m), fma(d, q.y, m))); - store_a(col, k_pair + 1, FLOAT_TYPEV2(fma(d, q.z, m), fma(d, q.w, m))); - } else if (MmTypeA == GGML_TYPE_Q6_K) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - const uint k_pair = row * mm_load_vec_a() / 2; - - const uint ib = idx / 128; // 2 values per idx - const uint iqs = idx % 128; // 0..127 - - const uint n = iqs / 64; // 0,1 - const uint b = ((iqs % 64) / 32) * 4; // 0,4 - const uint is_b = (iqs % 16) / 8; // 0,1 - const uint qhshift = ((iqs % 64) / 16) * 2; // 0,2,4,6 - const uint is = 8 * n + qhshift + is_b; // 0..15 - const uint qsi = n * 32 + (iqs % 32); // 0..63 - const uint qhi = n * 16 + (iqs % 16); // 0..31 - - const float dscale = float(a_q6_k.data[ib].d) * float(a_q6_k.data[ib].scales[is]); - - const uint ql = (uint(a_q6_k_p16.data[ib].ql[qsi]) >> b) & 0x0F0F; - const uint qh = (uint(a_q6_k_p16.data[ib].qh[qhi]) >> qhshift) & 0x0303; - const vec2 q = (vec2(unpack8(ql | (qh << 4)).xy) - 32) * dscale; - - store_a(col, k_pair, FLOAT_TYPEV2(q.x, q.y)); - } else if (MmTypeA == GGML_TYPE_TQ1_0) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; - - const uint ib = idx / 128; // 2 values per idx - const uint iqs = (idx % 128) * 2; // elem 0,2,4..254 - - const float d = float(a_tq1_0.data[ib].d); - vec2 v; - for (uint kk = 0u; kk < 2u; ++kk) { - const uint e = iqs + kk; - const uint bidx = tq1_0_byte_of(e); - const uint qbyte = uint(bidx < 48u ? a_tq1_0.data[ib].qs[bidx] - : a_tq1_0.data[ib].qh[bidx - 48u]); - v[kk] = d * (float(tq1_0_trit(qbyte, tq1_0_digit_of(e))) - 1.0); - } - - const uint k_pair = row * mm_load_vec_a() / 2; - store_a(col, k_pair, FLOAT_TYPEV2(v.xy)); - } else if (MmTypeA == GGML_TYPE_TQ2_0) { - const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row; +} - const uint ib = idx / 128; // 2 values per idx - const uint iqs = (idx % 128) * 2; // elem 0,2,4..254 +#define MM_STORE_A(slot, m, kp, val) store_a(m, kp, val) + +void load_a_to_shmem(const uint pos_a, const uint row, const uint col_sh, const uint col_mem, const uint idx_m, const uint block, const uint end_k) { +#define MM_DATA_A data_a +#define MM_DATA_A_SCALAR data_a_scalar +#define MM_DATA_A_P16 data_a_packed16 +#define MM_DATA_A_P32 data_a_packed32 +#define MM_Q1_0 a_q1_0 +#define MM_Q2_0 a_q2_0 +#define MM_Q2_K a_q2_k +#define MM_Q3_K a_q3_k +#define MM_Q4_K a_q4_k +#define MM_Q5_K a_q5_k +#define MM_Q6_K a_q6_k +#define MM_TQ1_0 a_tq1_0 +#define MM_TQ2_0 a_tq2_0 +#define MM_Q4_0_P16 a_q4_0_p16 +#define MM_Q5_0_P16 a_q5_0_p16 +#define MM_Q8_0_P16 a_q8_0_p16 +#define MM_Q3_K_P16 a_q3_k_p16 +#define MM_Q6_K_P16 a_q6_k_p16 +#define MM_Q4_1_P32 a_q4_1_p32 +#define MM_Q5_1_P32 a_q5_1_p32 +#define MM_Q2_K_P32 a_q2_k_p32 +#define MM_Q4_K_P32 a_q4_k_p32 +#define MM_Q5_K_P32 a_q5_k_p32 +#include "mul_mm_load_a_body.glsl" +#undef MM_DATA_A +#undef MM_DATA_A_SCALAR +#undef MM_DATA_A_P16 +#undef MM_DATA_A_P32 +#undef MM_Q1_0 +#undef MM_Q2_0 +#undef MM_Q2_K +#undef MM_Q3_K +#undef MM_Q4_K +#undef MM_Q5_K +#undef MM_Q6_K +#undef MM_TQ1_0 +#undef MM_TQ2_0 +#undef MM_Q4_0_P16 +#undef MM_Q5_0_P16 +#undef MM_Q8_0_P16 +#undef MM_Q3_K_P16 +#undef MM_Q6_K_P16 +#undef MM_Q4_1_P32 +#undef MM_Q5_1_P32 +#undef MM_Q2_K_P32 +#undef MM_Q4_K_P32 +#undef MM_Q5_K_P32 +} - const uint qsi = (iqs / 128) * 32 + (iqs % 32); // byte pair start - const uint shift = 2 * ((iqs % 128) / 32); // 0,2,4,6 +#ifdef MM_FUSED +void load_u_to_shmem(const uint pos_a, const uint row, const uint col_sh, const uint col_mem, const uint idx_m, const uint block, const uint end_k) { +#define MM_DATA_A data_u +#define MM_DATA_A_SCALAR data_u_scalar +#define MM_DATA_A_P16 data_u_packed16 +#define MM_DATA_A_P32 data_u_packed32 +#define MM_Q1_0 u_q1_0 +#define MM_Q2_0 u_q2_0 +#define MM_Q2_K u_q2_k +#define MM_Q3_K u_q3_k +#define MM_Q4_K u_q4_k +#define MM_Q5_K u_q5_k +#define MM_Q6_K u_q6_k +#define MM_TQ1_0 u_tq1_0 +#define MM_TQ2_0 u_tq2_0 +#define MM_Q4_0_P16 u_q4_0_p16 +#define MM_Q5_0_P16 u_q5_0_p16 +#define MM_Q8_0_P16 u_q8_0_p16 +#define MM_Q3_K_P16 u_q3_k_p16 +#define MM_Q6_K_P16 u_q6_k_p16 +#define MM_Q4_1_P32 u_q4_1_p32 +#define MM_Q5_1_P32 u_q5_1_p32 +#define MM_Q2_K_P32 u_q2_k_p32 +#define MM_Q4_K_P32 u_q4_k_p32 +#define MM_Q5_K_P32 u_q5_k_p32 +#include "mul_mm_load_a_body.glsl" +#undef MM_DATA_A +#undef MM_DATA_A_SCALAR +#undef MM_DATA_A_P16 +#undef MM_DATA_A_P32 +#undef MM_Q1_0 +#undef MM_Q2_0 +#undef MM_Q2_K +#undef MM_Q3_K +#undef MM_Q4_K +#undef MM_Q5_K +#undef MM_Q6_K +#undef MM_TQ1_0 +#undef MM_TQ2_0 +#undef MM_Q4_0_P16 +#undef MM_Q5_0_P16 +#undef MM_Q8_0_P16 +#undef MM_Q3_K_P16 +#undef MM_Q6_K_P16 +#undef MM_Q4_1_P32 +#undef MM_Q5_1_P32 +#undef MM_Q2_K_P32 +#undef MM_Q4_K_P32 +#undef MM_Q5_K_P32 +} +#endif - const uvec2 qs = uvec2(a_tq2_0.data[ib].qs[qsi], a_tq2_0.data[ib].qs[qsi + 1]); - const float d = float(a_tq2_0.data[ib].d); +#undef MM_STORE_A + +#ifdef COOPMAT +#define MM_STORE_A(slot, m, kp, val) stage_v[slot] = (val) + +void stage_a_to_reg(const uint pos_a, const uint row, const uint col_sh, const uint col_mem, const uint idx_m, const uint block, const uint end_k, out FLOAT_TYPEV2 stage_v[8]) { + [[unroll]] for (uint s = 0u; s < 8u; ++s) { stage_v[s] = FLOAT_TYPEV2(0.0f); } + if (idx_m >= p.M) { return; } +#define MM_DATA_A data_a +#define MM_DATA_A_SCALAR data_a_scalar +#define MM_DATA_A_P16 data_a_packed16 +#define MM_DATA_A_P32 data_a_packed32 +#define MM_Q1_0 a_q1_0 +#define MM_Q2_0 a_q2_0 +#define MM_Q2_K a_q2_k +#define MM_Q3_K a_q3_k +#define MM_Q4_K a_q4_k +#define MM_Q5_K a_q5_k +#define MM_Q6_K a_q6_k +#define MM_TQ1_0 a_tq1_0 +#define MM_TQ2_0 a_tq2_0 +#define MM_Q4_0_P16 a_q4_0_p16 +#define MM_Q5_0_P16 a_q5_0_p16 +#define MM_Q8_0_P16 a_q8_0_p16 +#define MM_Q3_K_P16 a_q3_k_p16 +#define MM_Q6_K_P16 a_q6_k_p16 +#define MM_Q4_1_P32 a_q4_1_p32 +#define MM_Q5_1_P32 a_q5_1_p32 +#define MM_Q2_K_P32 a_q2_k_p32 +#define MM_Q4_K_P32 a_q4_k_p32 +#define MM_Q5_K_P32 a_q5_k_p32 +#include "mul_mm_load_a_body.glsl" +#undef MM_DATA_A +#undef MM_DATA_A_SCALAR +#undef MM_DATA_A_P16 +#undef MM_DATA_A_P32 +#undef MM_Q1_0 +#undef MM_Q2_0 +#undef MM_Q2_K +#undef MM_Q3_K +#undef MM_Q4_K +#undef MM_Q5_K +#undef MM_Q6_K +#undef MM_TQ1_0 +#undef MM_TQ2_0 +#undef MM_Q4_0_P16 +#undef MM_Q5_0_P16 +#undef MM_Q8_0_P16 +#undef MM_Q3_K_P16 +#undef MM_Q6_K_P16 +#undef MM_Q4_1_P32 +#undef MM_Q5_1_P32 +#undef MM_Q2_K_P32 +#undef MM_Q4_K_P32 +#undef MM_Q5_K_P32 +} - const vec2 v = d * (vec2((qs >> shift) & 3) - 1.0); +#ifdef MM_FUSED +void stage_u_to_reg(const uint pos_a, const uint row, const uint col_sh, const uint col_mem, const uint idx_m, const uint block, const uint end_k, out FLOAT_TYPEV2 stage_v[8]) { + [[unroll]] for (uint s = 0u; s < 8u; ++s) { stage_v[s] = FLOAT_TYPEV2(0.0f); } + if (idx_m >= p.M) { return; } +#define MM_DATA_A data_u +#define MM_DATA_A_SCALAR data_u_scalar +#define MM_DATA_A_P16 data_u_packed16 +#define MM_DATA_A_P32 data_u_packed32 +#define MM_Q1_0 u_q1_0 +#define MM_Q2_0 u_q2_0 +#define MM_Q2_K u_q2_k +#define MM_Q3_K u_q3_k +#define MM_Q4_K u_q4_k +#define MM_Q5_K u_q5_k +#define MM_Q6_K u_q6_k +#define MM_TQ1_0 u_tq1_0 +#define MM_TQ2_0 u_tq2_0 +#define MM_Q4_0_P16 u_q4_0_p16 +#define MM_Q5_0_P16 u_q5_0_p16 +#define MM_Q8_0_P16 u_q8_0_p16 +#define MM_Q3_K_P16 u_q3_k_p16 +#define MM_Q6_K_P16 u_q6_k_p16 +#define MM_Q4_1_P32 u_q4_1_p32 +#define MM_Q5_1_P32 u_q5_1_p32 +#define MM_Q2_K_P32 u_q2_k_p32 +#define MM_Q4_K_P32 u_q4_k_p32 +#define MM_Q5_K_P32 u_q5_k_p32 +#include "mul_mm_load_a_body.glsl" +#undef MM_DATA_A +#undef MM_DATA_A_SCALAR +#undef MM_DATA_A_P16 +#undef MM_DATA_A_P32 +#undef MM_Q1_0 +#undef MM_Q2_0 +#undef MM_Q2_K +#undef MM_Q3_K +#undef MM_Q4_K +#undef MM_Q5_K +#undef MM_Q6_K +#undef MM_TQ1_0 +#undef MM_TQ2_0 +#undef MM_Q4_0_P16 +#undef MM_Q5_0_P16 +#undef MM_Q8_0_P16 +#undef MM_Q3_K_P16 +#undef MM_Q6_K_P16 +#undef MM_Q4_1_P32 +#undef MM_Q5_1_P32 +#undef MM_Q2_K_P32 +#undef MM_Q4_K_P32 +#undef MM_Q5_K_P32 +} +#endif - const uint k_pair = row * mm_load_vec_a() / 2; - store_a(col, k_pair, FLOAT_TYPEV2(v.xy)); - } +#undef MM_STORE_A #endif -} #if !defined(MUL_MAT_ID) void load_b_to_shmem(const uint pos_b, const uint row, const uint col, const uint idx_n, const uint block, const uint end_k) { #if LOAD_VEC_B == 8 if (ALIGNED != 0) { - // Not supported for b_type bf16 because bf16mat2x4 does not exist - const uint idx = pos_b + col * p.stride_b / LOAD_VEC_B + row; - const uint buf_idx = col * SHMEM_STRIDE + row * LOAD_VEC_B / 2; - FLOAT_TYPEV8 bb = FLOAT_TYPEV8(data_b[idx]); - buf_b[buf_idx + 0] = bb[0].xy; - buf_b[buf_idx + 1] = bb[0].zw; - buf_b[buf_idx + 2] = bb[1].xy; - buf_b[buf_idx + 3] = bb[1].zw; + const uint kp = row * (LOAD_VEC_B / 2); + if (idx_n < p.N) { + // Not supported for b_type bf16 because bf16mat2x4 does not exist + const uint idx = pos_b + col * p.stride_b / LOAD_VEC_B + row; + FLOAT_TYPEV8 bb = FLOAT_TYPEV8(data_b[idx]); + store_b(col, kp + 0, bb[0].xy); + store_b(col, kp + 1, bb[0].zw); + store_b(col, kp + 2, bb[1].xy); + store_b(col, kp + 3, bb[1].zw); + } else { + store_b(col, kp + 0, FLOAT_TYPEV2(0.0f)); + store_b(col, kp + 1, FLOAT_TYPEV2(0.0f)); + store_b(col, kp + 2, FLOAT_TYPEV2(0.0f)); + store_b(col, kp + 3, FLOAT_TYPEV2(0.0f)); + } return; } #elif LOAD_VEC_B == 4 if (ALIGNED != 0) { - const uint idx = pos_b + col * p.stride_b / LOAD_VEC_B + row; - const uint buf_idx = col * SHMEM_STRIDE + row * LOAD_VEC_B / 2; + const uint kp = row * (LOAD_VEC_B / 2); + if (idx_n < p.N) { + const uint idx = pos_b + col * p.stride_b / LOAD_VEC_B + row; #if defined(DATA_B_BF16) - FLOAT_TYPEV4 bb = FLOAT_TYPEV4(TO_FLOAT_TYPE(data_b[idx])); + FLOAT_TYPEV4 bb = FLOAT_TYPEV4(TO_FLOAT_TYPE(data_b[idx])); #else - FLOAT_TYPEV4 bb = FLOAT_TYPEV4(data_b[idx]); + FLOAT_TYPEV4 bb = FLOAT_TYPEV4(data_b[idx]); #endif - buf_b[buf_idx + 0] = bb.xy; - buf_b[buf_idx + 1] = bb.zw; + store_b(col, kp + 0, bb.xy); + store_b(col, kp + 1, bb.zw); + } else { + store_b(col, kp + 0, FLOAT_TYPEV2(0.0f)); + store_b(col, kp + 1, FLOAT_TYPEV2(0.0f)); + } return; } #endif const uint idx = pos_b + col * p.stride_b + row * 2; - const uint buf_idx = col * SHMEM_STRIDE + row; if (idx_n < p.N && block + row * 2 + 1 < end_k) { - buf_b[buf_idx] = FLOAT_TYPEV2(TO_FLOAT_TYPE(data_b_scalar[idx]), - TO_FLOAT_TYPE(data_b_scalar[idx + 1])); + store_b(col, row, FLOAT_TYPEV2(TO_FLOAT_TYPE(data_b_scalar[idx]), + TO_FLOAT_TYPE(data_b_scalar[idx + 1]))); } else if (idx_n < p.N && block + row * 2 < end_k) { - buf_b[buf_idx] = FLOAT_TYPEV2(TO_FLOAT_TYPE(data_b_scalar[idx]), 0.0f); + store_b(col, row, FLOAT_TYPEV2(TO_FLOAT_TYPE(data_b_scalar[idx]), 0.0f)); } else { - buf_b[buf_idx] = FLOAT_TYPEV2(0.0f); + store_b(col, row, FLOAT_TYPEV2(0.0f)); } } #else @@ -721,3 +387,94 @@ void load_b_to_shmem(const uint pos_b, const uint row, const uint col, const uin } } #endif + +#ifdef COOPMAT +void stage_b_to_reg(const uint pos_b, const uint row, const uint col, const uint idx_n, out FLOAT_TYPEV2 stage_bv[4]) { +#if !defined(MUL_MAT_ID) + if (idx_n >= p.N) { + stage_bv[0] = FLOAT_TYPEV2(0.0f); + stage_bv[1] = FLOAT_TYPEV2(0.0f); + stage_bv[2] = FLOAT_TYPEV2(0.0f); + stage_bv[3] = FLOAT_TYPEV2(0.0f); + return; + } + const uint idx = pos_b + col * p.stride_b / LOAD_VEC_B + row; +#else + if (col >= _ne1) { + stage_bv[0] = FLOAT_TYPEV2(0.0f); + stage_bv[1] = FLOAT_TYPEV2(0.0f); + stage_bv[2] = FLOAT_TYPEV2(0.0f); + stage_bv[3] = FLOAT_TYPEV2(0.0f); + return; + } + const u16vec2 row_idx = row_ids[col]; + const uint idx = pos_b + row_idx.y * p.batch_stride_b / LOAD_VEC_B + (row_idx.x % p.ne11) * p.stride_b / LOAD_VEC_B + row; +#endif +#if LOAD_VEC_B == 8 + FLOAT_TYPEV8 bb = FLOAT_TYPEV8(data_b[idx]); + stage_bv[0] = bb[0].xy; + stage_bv[1] = bb[0].zw; + stage_bv[2] = bb[1].xy; + stage_bv[3] = bb[1].zw; +#elif LOAD_VEC_B == 4 +#if defined(DATA_B_BF16) + FLOAT_TYPEV4 bb = FLOAT_TYPEV4(TO_FLOAT_TYPE(data_b[idx])); +#else + FLOAT_TYPEV4 bb = FLOAT_TYPEV4(data_b[idx]); +#endif + stage_bv[0] = bb.xy; + stage_bv[1] = bb.zw; + stage_bv[2] = FLOAT_TYPEV2(0.0f); + stage_bv[3] = FLOAT_TYPEV2(0.0f); +#endif +} + +void commit_stage_b(const uint col, const uint row, const FLOAT_TYPEV2 stage_bv[4]) { +#if LOAD_VEC_B == 8 && defined(FLOAT16) && !defined(DATA_A_BF16) + if (AGX_DIRECT_STORE != 0) { + if (APPLY_SLM_A_RESHAPE) { + if (BK == 32) { + const uint odd_c = col & 1u; + const bool is_odd = odd_c != 0u; + const uint base_sh = row * ((BN << 2u) + 8u) + ((col >> 3u) << 5u) + ((col & 7u) >> 1u); + [[unroll]] for (uint q = 0u; q < 2u; ++q) { + const f16vec2 v0 = stage_bv[2u * q + 0u]; + const f16vec2 v1 = stage_bv[2u * q + 1u]; + const f16vec2 my_keep = is_odd ? f16vec2(v0.y, v1.y) : f16vec2(v0.x, v1.x); + const f16vec2 my_send = is_odd ? f16vec2(v0.x, v1.x) : f16vec2(v0.y, v1.y); + const f16vec2 partner = unpackFloat2x16(subgroupShuffleXor(packFloat2x16(my_send), 4u)); + buf_b[base_sh + (((4u * q + 0u) + odd_c) << 2u)] = is_odd ? f16vec2(partner.x, my_keep.x) : f16vec2(my_keep.x, partner.x); + buf_b[base_sh + (((4u * q + 2u) + odd_c) << 2u)] = is_odd ? f16vec2(partner.y, my_keep.y) : f16vec2(my_keep.y, partner.y); + } + return; + } + } + } +#endif +#if !defined(MUL_MAT_ID) +#if LOAD_VEC_B == 8 + const uint kp = row * 4u; + store_b(col, kp + 0u, stage_bv[0]); + store_b(col, kp + 1u, stage_bv[1]); + store_b(col, kp + 2u, stage_bv[2]); + store_b(col, kp + 3u, stage_bv[3]); +#elif LOAD_VEC_B == 4 + const uint kp = row * 2u; + store_b(col, kp + 0u, stage_bv[0]); + store_b(col, kp + 1u, stage_bv[1]); +#endif +#else +#if LOAD_VEC_B == 8 + const uint buf_idx = col * SHMEM_STRIDE + row * 4u; + buf_b[buf_idx + 0u] = stage_bv[0]; + buf_b[buf_idx + 1u] = stage_bv[1]; + buf_b[buf_idx + 2u] = stage_bv[2]; + buf_b[buf_idx + 3u] = stage_bv[3]; +#elif LOAD_VEC_B == 4 + const uint buf_idx = col * SHMEM_STRIDE + row * 2u; + buf_b[buf_idx + 0u] = stage_bv[0]; + buf_b[buf_idx + 1u] = stage_bv[1]; +#endif +#endif +} +#endif diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_load_a_body.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_load_a_body.glsl new file mode 100644 index 000000000000..b61914ebda7c --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_load_a_body.glsl @@ -0,0 +1,742 @@ +#if defined(DATA_A_F32) || defined(DATA_A_F16) +#if LOAD_VEC_A == 8 + if (ALIGNED != 0) { + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + FLOAT_TYPEV8 aa = FLOAT_TYPEV8(MM_DATA_A[idx]); + MM_STORE_A(0, col_sh, k_pair, aa[0].xy); + MM_STORE_A(1, col_sh, k_pair + 1, aa[0].zw); + MM_STORE_A(2, col_sh, k_pair + 2, aa[1].xy); + MM_STORE_A(3, col_sh, k_pair + 3, aa[1].zw); + return; + } +#elif LOAD_VEC_A == 4 + if (ALIGNED != 0) { + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + FLOAT_TYPEV4 aa = FLOAT_TYPEV4(MM_DATA_A[idx]); + MM_STORE_A(0, col_sh, k_pair, aa.xy); + MM_STORE_A(1, col_sh, k_pair + 1, aa.zw); + return; + } +#endif + const uint idx = pos_a + col_mem * p.stride_a + row * 2; + if (idx_m < p.M && block + row * 2 + 1 < end_k) { + store_a(col_sh, row, FLOAT_TYPEV2(MM_DATA_A_SCALAR[idx], + MM_DATA_A_SCALAR[idx + 1])); + } else if (idx_m < p.M && block + row * 2 < end_k) { + store_a(col_sh, row, FLOAT_TYPEV2(MM_DATA_A_SCALAR[idx], 0.0f)); + } else { + store_a(col_sh, row, FLOAT_TYPEV2(0.0f)); + } +#elif defined(DATA_A_BF16) +#if LOAD_VEC_A == 4 + if (ALIGNED != 0) { + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + FLOAT_TYPEV4 aa = FLOAT_TYPEV4(TO_FLOAT_TYPE(MM_DATA_A[idx])); + store_a(col_sh, k_pair, aa.xy); + store_a(col_sh, k_pair + 1, aa.zw); + return; + } +#endif + const uint idx = pos_a + col_mem * p.stride_a + row * 2; + if (idx_m < p.M && block + row * 2 + 1 < end_k) { + store_a(col_sh, row, FLOAT_TYPEV2(TO_FLOAT_TYPE(MM_DATA_A_SCALAR[idx]), + TO_FLOAT_TYPE(MM_DATA_A_SCALAR[idx + 1]))); + } else if (idx_m < p.M && block + row * 2 < end_k) { + store_a(col_sh, row, FLOAT_TYPEV2(TO_FLOAT_TYPE(MM_DATA_A_SCALAR[idx]), 0.0f)); + } else { + store_a(col_sh, row, FLOAT_TYPEV2(0.0f)); + } +#elif defined(DATA_A_IQ1_S) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + + const uint ib = idx / 32; + const uint ib32 = (idx % 32) / 4; + const uint ib8 = idx % 32; + + const float d = float(MM_DATA_A[ib].d); + const uint qh = MM_DATA_A[ib].qh[ib32]; + const uint qs = MM_DATA_A[ib].qs[ib8]; + const float dl = d * (2 * bitfieldExtract(qh, 12, 3) + 1); + const float delta = ((qh & 0x8000) != 0) ? -IQ1S_DELTA : IQ1S_DELTA; + const int16_t grid = int16_t(iq1s_grid[qs | (bitfieldExtract(qh, 3 * int(ib8 & 3), 3) << 8)]); + + [[unroll]] for (int k = 0; k < 4; ++k) { + store_a(col_sh, k_pair + k, FLOAT_TYPEV2(dl * (bitfieldExtract(grid, 4 * k , 2) + delta), + dl * (bitfieldExtract(grid, 4 * k + 2, 2) + delta))); + } +#elif defined(DATA_A_IQ1_M) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + + const uint ib = idx / 32; + const uint ib8 = idx % 32; + const uint ib16 = ib8 / 2; + + const uint16_t[4] scales = MM_DATA_A[ib].scales; + const u16vec4 s = u16vec4(scales[0], scales[1], scales[2], scales[3]) >> 12; + const float d = float(unpackHalf2x16(s.x | (s.y << 4) | (s.z << 8) | (s.w << 12)).x); + const uint sc = scales[ib8 / 8]; + const uint qs = MM_DATA_A[ib].qs[ib8]; + const uint qh = MM_DATA_A[ib].qh[ib16] >> (4 * (ib8 & 1)); + const float dl = d * (2 * bitfieldExtract(sc, 3 * int(ib16 & 3), 3) + 1); + const float delta = ((qh & 8) != 0) ? -IQ1M_DELTA : IQ1M_DELTA; + const int16_t grid = int16_t(iq1s_grid[qs | ((qh & 7) << 8)]); + + [[unroll]] for (int k = 0; k < 4; ++k) { + store_a(col_sh, k_pair + k, FLOAT_TYPEV2(dl * (bitfieldExtract(grid, 4 * k , 2) + delta), + dl * (bitfieldExtract(grid, 4 * k + 2, 2) + delta))); + } +#elif defined(DATA_A_IQ2_XXS) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + + const uint ib = idx / 32; + const uint ib32 = (idx % 32) / 4; + const uint ib8 = idx % 4; + + const float d = float(MM_DATA_A[ib].d); + const uint qs = MM_DATA_A[ib].qs[8 * ib32 + ib8]; + const uint signs = pack32(u8vec4( + MM_DATA_A[ib].qs[8*ib32 + 4], + MM_DATA_A[ib].qs[8*ib32 + 5], + MM_DATA_A[ib].qs[8*ib32 + 6], + MM_DATA_A[ib].qs[8*ib32 + 7] + )); + const FLOAT_TYPE db = FLOAT_TYPE(d * 0.25 * (0.5 + (signs >> 28))); + const uint32_t sign7 = bitfieldExtract(signs, 7 * int(ib8), 7); + const uint sign = sign7 | (bitCount(sign7) << 7); + const uvec2 grid = iq2xxs_grid[qs]; + const vec4 grid0 = vec4(unpack8(grid.x)); + const vec4 grid1 = vec4(unpack8(grid.y)); + + store_a(col_sh, k_pair, db * FLOAT_TYPEV2((sign & 1) != 0 ? -grid0.x : grid0.x, + (sign & 2) != 0 ? -grid0.y : grid0.y)); + store_a(col_sh, k_pair + 1, db * FLOAT_TYPEV2((sign & 4) != 0 ? -grid0.z : grid0.z, + (sign & 8) != 0 ? -grid0.w : grid0.w)); + store_a(col_sh, k_pair + 2, db * FLOAT_TYPEV2((sign & 16) != 0 ? -grid1.x : grid1.x, + (sign & 32) != 0 ? -grid1.y : grid1.y)); + store_a(col_sh, k_pair + 3, db * FLOAT_TYPEV2((sign & 64) != 0 ? -grid1.z : grid1.z, + (sign & 128) != 0 ? -grid1.w : grid1.w)); +#elif defined(DATA_A_IQ2_XS) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + + const uint ib = idx / 32; + const uint ib32 = (idx % 32) / 4; + const uint ib8 = idx % 4; + + const float d = float(MM_DATA_A[ib].d); + const uint scale = (MM_DATA_A[ib].scales[ib32] >> (2 * (ib8 & 2))) & 0xf; + const FLOAT_TYPE db = FLOAT_TYPE(d * 0.25 * (0.5 + scale)); + const uint qs = MM_DATA_A[ib].qs[4 * ib32 + ib8]; + const uint sign7 = qs >> 9; + const uint sign = sign7 | (bitCount(sign7) << 7); + const uvec2 grid = iq2xs_grid[qs & 511]; + const vec4 grid0 = vec4(unpack8(grid.x)); + const vec4 grid1 = vec4(unpack8(grid.y)); + + store_a(col_sh, k_pair, db * FLOAT_TYPEV2((sign & 1) != 0 ? -grid0.x : grid0.x, + (sign & 2) != 0 ? -grid0.y : grid0.y)); + store_a(col_sh, k_pair + 1, db * FLOAT_TYPEV2((sign & 4) != 0 ? -grid0.z : grid0.z, + (sign & 8) != 0 ? -grid0.w : grid0.w)); + store_a(col_sh, k_pair + 2, db * FLOAT_TYPEV2((sign & 16) != 0 ? -grid1.x : grid1.x, + (sign & 32) != 0 ? -grid1.y : grid1.y)); + store_a(col_sh, k_pair + 3, db * FLOAT_TYPEV2((sign & 64) != 0 ? -grid1.z : grid1.z, + (sign & 128) != 0 ? -grid1.w : grid1.w)); +#elif defined(DATA_A_IQ2_S) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + + const uint ib = idx / 32; + const uint ib8 = idx % 32; + const uint ib32 = ib8 / 4; + + const uint scale = (MM_DATA_A[ib].scales[ib32] >> (2 * (ib8 & 2))) & 0xf; + const uint qs = MM_DATA_A[ib].qs[ib8]; + const uint qh = MM_DATA_A[ib].qh[ib32]; + const uint qhshift = 2 * (ib8 % 4); + const uint sign = MM_DATA_A[ib].qs[QUANT_K_IQ2_S / 8 + ib8]; + + const float d = float(MM_DATA_A[ib].d); + const FLOAT_TYPE db = FLOAT_TYPE(d * 0.25 * (0.5 + scale)); + const uvec2 grid = iq2s_grid[qs | ((qh << (8 - qhshift)) & 0x300)]; + const vec4 grid0 = vec4(unpack8(grid.x)); + const vec4 grid1 = vec4(unpack8(grid.y)); + + store_a(col_sh, k_pair, db * FLOAT_TYPEV2((sign & 1) != 0 ? -grid0.x : grid0.x, + (sign & 2) != 0 ? -grid0.y : grid0.y)); + store_a(col_sh, k_pair + 1, db * FLOAT_TYPEV2((sign & 4) != 0 ? -grid0.z : grid0.z, + (sign & 8) != 0 ? -grid0.w : grid0.w)); + store_a(col_sh, k_pair + 2, db * FLOAT_TYPEV2((sign & 16) != 0 ? -grid1.x : grid1.x, + (sign & 32) != 0 ? -grid1.y : grid1.y)); + store_a(col_sh, k_pair + 3, db * FLOAT_TYPEV2((sign & 64) != 0 ? -grid1.z : grid1.z, + (sign & 128) != 0 ? -grid1.w : grid1.w)); +#elif defined(DATA_A_IQ3_XXS) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + + const uint ib = idx / 64; + const uint iqs = idx % 64; + const uint is = QUANT_K_IQ3_XXS / 4 + 4 * (iqs / 8); + + const float d = float(MM_DATA_A[ib].d); + const uint qs = MM_DATA_A[ib].qs[iqs]; + const uint signs = pack32(u16vec2( + MM_DATA_A_P16[ib].qs[is/2], + MM_DATA_A_P16[ib].qs[is/2+1] + )); + const float db = d * 0.5 * (0.5 + (signs >> 28)); + const uint32_t sign7 = bitfieldExtract(signs, 7 * (int(iqs / 2) % 4), 7); + const uint sign = (sign7 | (bitCount(sign7) << 7)) >> (4 * (idx % 2)); + const uint grid = iq3xxs_grid[qs]; + const vec4 v = db * vec4(unpack8(grid)); + + store_a(col_sh, k_pair, FLOAT_TYPEV2((sign & 1) != 0 ? -v.x : v.x, + (sign & 2) != 0 ? -v.y : v.y)); + store_a(col_sh, k_pair + 1, FLOAT_TYPEV2((sign & 4) != 0 ? -v.z : v.z, + (sign & 8) != 0 ? -v.w : v.w)); +#elif defined(DATA_A_IQ3_S) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 2; + + const uint ib = idx / 64; + const uint iqs = idx % 64; + const uint iqh = iqs / 8; + + const float d = float(MM_DATA_A[ib].d); + const uint qs = MM_DATA_A[ib].qs[iqs]; + const uint qh = MM_DATA_A[ib].qh[iqh]; + const int8_t sign = int8_t(MM_DATA_A[ib].signs[iqs / 2] >> (4 * (idx % 2))); + const uint scale = MM_DATA_A[ib].scales[iqs / 16]; + const float db = d * (1 + 2 * ((scale >> (4 * (iqh & 1))) & 0xf)); + const uint32_t grid = iq3s_grid[qs | ((qh << (8 - (iqs % 8))) & 256)]; + const vec4 v = db * vec4(unpack8(grid)); + + store_a(col_sh, k_pair, FLOAT_TYPEV2((sign & 1) != 0 ? -v.x : v.x, + (sign & 2) != 0 ? -v.y : v.y)); + store_a(col_sh, k_pair + 1, FLOAT_TYPEV2((sign & 4) != 0 ? -v.z : v.z, + (sign & 8) != 0 ? -v.w : v.w)); +#elif defined(DATA_A_IQ4_XS) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 4; + + const uint ib = idx / 32; + const uint ib32 = (idx % 32) / 4; + const uint iq = 4 * ib32 + (idx % 4); + + const uint sl = (MM_DATA_A[ib].scales_l[ib32/2] >> (4 * (ib32 & 1))) & 0xF; + const uint sh = ((MM_DATA_A[ib].scales_h) >> (2 * ib32)) & 3; + const float d = float(MM_DATA_A[ib].d); + const float dl = d * float(int(sl | (sh << 4)) - 32); + const uint vui = uint(MM_DATA_A_P32[ib].qs[iq]); + + const u8vec4 qs0 = unpack8( vui & 0x0F0F0F0F); + const u8vec4 qs1 = unpack8((vui >> 4) & 0x0F0F0F0F); + const vec4 v0 = dl * vec4(kvalues_iq4nl[qs0.x], kvalues_iq4nl[qs0.y], kvalues_iq4nl[qs0.z], kvalues_iq4nl[qs0.w]); + const vec4 v1 = dl * vec4(kvalues_iq4nl[qs1.x], kvalues_iq4nl[qs1.y], kvalues_iq4nl[qs1.z], kvalues_iq4nl[qs1.w]); + + MM_STORE_A(0, col_sh, k_pair, FLOAT_TYPEV2(v0.xy)); + MM_STORE_A(1, col_sh, k_pair + 1, FLOAT_TYPEV2(v0.zw)); + MM_STORE_A(2, col_sh, k_pair + 8, FLOAT_TYPEV2(v1.xy)); + MM_STORE_A(3, col_sh, k_pair + 9, FLOAT_TYPEV2(v1.zw)); +#elif defined(DATA_A_IQ4_NL) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 4; + + const uint ib = idx / 8; + const uint iqs = idx & 0x07; + + const FLOAT_TYPE d = FLOAT_TYPE(MM_DATA_A_P16[ib].d); + const uint vui = uint(MM_DATA_A_P16[ib].qs[iqs]); + + store_a(col_sh, k_pair, d * FLOAT_TYPEV2(kvalues_iq4nl[vui & 0xF], + kvalues_iq4nl[bitfieldExtract(vui, 8, 4)])); + store_a(col_sh, k_pair + 8, d * FLOAT_TYPEV2(kvalues_iq4nl[bitfieldExtract(vui, 4, 4)], + kvalues_iq4nl[vui >> 12])); +#elif defined(DATA_A_MXFP4) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint k_pair = row * LOAD_VEC_A / 4; + + const uint ib = idx / 8; + const uint iqs = (idx & 0x07) * 2; + + const uint vui = uint(MM_DATA_A[ib].qs[iqs]); + const uint vui2 = uint(MM_DATA_A[ib].qs[iqs+1]); + +#ifdef USE_OCP_FP4 + const float d = e8m0_to_fp32(MM_DATA_A[ib].e); + const u8vec2 packed = u8vec2(vui, vui2); + store_a(col_sh, k_pair, FLOAT_TYPEV2(bitcastExtractfe2m1EXT(packed, 0u)) * FLOAT_TYPE(d)); + store_a(col_sh, k_pair + 8, FLOAT_TYPEV2(bitcastExtractfe2m1EXT(packed, 4u)) * FLOAT_TYPE(d)); +#else + const float d = e8m0_to_fp32(MM_DATA_A[ib].e) * 0.5; + store_a(col_sh, k_pair, FLOAT_TYPEV2(float(mxfp4_kval(uint(vui) & 0xFu)) * d, + float(mxfp4_kval(uint(vui2) & 0xFu)) * d)); + store_a(col_sh, k_pair + 8, FLOAT_TYPEV2(float(mxfp4_kval(uint(vui) >> 4u)) * d, + float(mxfp4_kval(uint(vui2) >> 4u)) * d)); +#endif +#elif defined(DATA_A_NVFP4) + const uint idx = pos_a + col_mem * p.stride_a / LOAD_VEC_A + row; + const uint eff_row = (row & 3) + (row & ~3) * 2; + + const uint ib = idx / 16u; + const uint sub = (idx & 0xC) >> 2; + const uint iqs = (idx & 0xF) * 2; + const uint vui = uint(MM_DATA_A[ib].qs[iqs]); + const uint vui2 = uint(MM_DATA_A[ib].qs[iqs+1]); + +#ifdef USE_OCP_FP4 + const FLOAT_TYPE d = FLOAT_TYPE(ue4m3_from_bits(MM_DATA_A[ib].d[sub])); + const u8vec2 packed = u8vec2(vui, vui2); + store_a(col_sh, eff_row, FLOAT_TYPEV2(bitcastExtractfe2m1EXT(packed, 0u)) * d); + store_a(col_sh, eff_row + 4, FLOAT_TYPEV2(bitcastExtractfe2m1EXT(packed, 4u)) * d); +#else + const float d = ue4m3_to_fp32(MM_DATA_A[ib].d[sub]) * 0.5; + store_a(col_sh, eff_row, FLOAT_TYPEV2(float(mxfp4_kval(uint(vui) & 0xFu)) * d, + float(mxfp4_kval(uint(vui2) & 0xFu)) * d)); + store_a(col_sh, eff_row + 4, FLOAT_TYPEV2(float(mxfp4_kval(uint(vui) >> 4u)) * d, + float(mxfp4_kval(uint(vui2) >> 4u)) * d)); +#endif +#else + if (MmTypeA == GGML_TYPE_Q4_0) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 4; + + const uint ib = idx / 4; + const uint iqs = idx & 0x03; + + const float d = float(MM_Q4_0_P16.data[ib].d); + const uint vui = uint(MM_Q4_0_P16.data[ib].qs[2*iqs]) | (uint(MM_Q4_0_P16.data[ib].qs[2*iqs + 1]) << 16); + const vec4 v0 = (vec4(unpack8(vui & 0x0F0F0F0F)) - 8.0f) * d; + const vec4 v1 = (vec4(unpack8((vui >> 4) & 0x0F0F0F0F)) - 8.0f) * d; + + store_a(col_sh, k_pair, FLOAT_TYPEV2(v0.xy)); + store_a(col_sh, k_pair + 1, FLOAT_TYPEV2(v0.zw)); + store_a(col_sh, k_pair + 8, FLOAT_TYPEV2(v1.xy)); + store_a(col_sh, k_pair + 9, FLOAT_TYPEV2(v1.zw)); + } else if (MmTypeA == GGML_TYPE_Q4_1) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 4; + + const uint ib = idx / 4; + const uint iqs = idx & 0x03; + + const vec2 dm = vec2(MM_Q4_1_P32.data[ib].dm); + const uint vui = MM_Q4_1_P32.data[ib].qs[iqs]; + const vec4 v0 = vec4(unpack8(vui & 0x0F0F0F0F)) * dm.x + dm.y; + const vec4 v1 = vec4(unpack8((vui >> 4) & 0x0F0F0F0F)) * dm.x + dm.y; + + store_a(col_sh, k_pair, FLOAT_TYPEV2(v0.xy)); + store_a(col_sh, k_pair + 1, FLOAT_TYPEV2(v0.zw)); + store_a(col_sh, k_pair + 8, FLOAT_TYPEV2(v1.xy)); + store_a(col_sh, k_pair + 9, FLOAT_TYPEV2(v1.zw)); + } else if (MmTypeA == GGML_TYPE_Q5_0) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 4; + + const uint ib = idx / 8; + const uint iqs = idx & 0x07; + + const float d = float(MM_Q5_0_P16.data[ib].d); + const uint uint_qh = uint(MM_Q5_0_P16.data[ib].qh[1]) << 16 | uint(MM_Q5_0_P16.data[ib].qh[0]); + const ivec2 qh0 = ivec2(((uint_qh >> 2*iqs) << 4) & 0x10, (uint_qh >> (2*iqs + 12)) & 0x10); + const ivec2 qh1 = ivec2(((uint_qh >> (2*iqs + 1)) << 4) & 0x10, (uint_qh >> (2*iqs + 13)) & 0x10); + + const uint vui = uint(MM_Q5_0_P16.data[ib].qs[iqs]); + const vec4 v = (vec4((vui & 0xF) | qh0.x, ((vui >> 4) & 0xF) | qh0.y, ((vui >> 8) & 0xF) | qh1.x, (vui >> 12) | qh1.y) - 16.0f) * d; + + store_a(col_sh, k_pair, FLOAT_TYPEV2(v.xz)); + store_a(col_sh, k_pair + 8, FLOAT_TYPEV2(v.yw)); + } else if (MmTypeA == GGML_TYPE_Q5_1) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 4; + + const uint ib = idx / 4; + const uint iqs = idx & 0x03; + + const vec2 dm = vec2(MM_Q5_1_P32.data[ib].dm); + const uint uint_qh = MM_Q5_1_P32.data[ib].qh; + const uvec2 qh0 = uvec2(((uint_qh >> 4*iqs) << 4) & 0x10, (uint_qh >> (4*iqs + 12)) & 0x10); + const uvec2 qh1 = uvec2(((uint_qh >> (4*iqs + 1)) << 4) & 0x10, (uint_qh >> (4*iqs + 13)) & 0x10); + const uvec2 qh2 = uvec2(((uint_qh >> (4*iqs + 2)) << 4) & 0x10, (uint_qh >> (4*iqs + 14)) & 0x10); + const uvec2 qh3 = uvec2(((uint_qh >> (4*iqs + 3)) << 4) & 0x10, (uint_qh >> (4*iqs + 15)) & 0x10); + + const uint vui = MM_Q5_1_P32.data[ib].qs[iqs]; + const vec4 v0 = vec4((vui & 0xF) | qh0.x, ((vui >> 4) & 0xF) | qh0.y, ((vui >> 8) & 0xF) | qh1.x, ((vui >> 12) & 0xF) | qh1.y) * dm.x + dm.y; + const vec4 v1 = vec4(((vui >> 16) & 0xF) | qh2.x, ((vui >> 20) & 0xF) | qh2.y, ((vui >> 24) & 0xF) | qh3.x, ((vui >> 28) & 0xF) | qh3.y) * dm.x + dm.y; + + store_a(col_sh, k_pair, FLOAT_TYPEV2(v0.xz)); + store_a(col_sh, k_pair + 1, FLOAT_TYPEV2(v1.xz)); + store_a(col_sh, k_pair + 8, FLOAT_TYPEV2(v0.yw)); + store_a(col_sh, k_pair + 9, FLOAT_TYPEV2(v1.yw)); + } else if (MmTypeA == GGML_TYPE_Q8_0) { + if (AGX_DIRECT_STORE == 1u) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 2; + + const uint ib = idx / 8; + const uint iqs = idx & 0x07; + + const float d = float(MM_Q8_0_P16.data[ib].d); + const i8vec2 v0 = unpack8(int32_t(MM_Q8_0_P16.data[ib].qs[2*iqs])).xy; + const i8vec2 v1 = unpack8(int32_t(MM_Q8_0_P16.data[ib].qs[2*iqs + 1])).xy; + const vec4 v = vec4(v0.x, v0.y, v1.x, v1.y) * d; + + MM_STORE_A(0, col_sh, k_pair, FLOAT_TYPEV2(v.xy)); + MM_STORE_A(1, col_sh, k_pair + 1, FLOAT_TYPEV2(v.zw)); + } else { + const uint idx = pos_a + col_mem * (p.stride_a >> 4u) + row; + const uint k_pair = row * 8u; + + const uint ib = idx >> 1u; + const uint iqs = (idx & 1u) << 3u; + + const FLOAT_TYPE d = FLOAT_TYPE(MM_Q8_0_P16.data[ib].d); + MM_STORE_A(0, col_sh, k_pair + 0u, FLOAT_TYPEV2(unpack8(MM_Q8_0_P16.data[ib].qs[iqs + 0u])) * d); + MM_STORE_A(1, col_sh, k_pair + 1u, FLOAT_TYPEV2(unpack8(MM_Q8_0_P16.data[ib].qs[iqs + 1u])) * d); + MM_STORE_A(2, col_sh, k_pair + 2u, FLOAT_TYPEV2(unpack8(MM_Q8_0_P16.data[ib].qs[iqs + 2u])) * d); + MM_STORE_A(3, col_sh, k_pair + 3u, FLOAT_TYPEV2(unpack8(MM_Q8_0_P16.data[ib].qs[iqs + 3u])) * d); + MM_STORE_A(4, col_sh, k_pair + 4u, FLOAT_TYPEV2(unpack8(MM_Q8_0_P16.data[ib].qs[iqs + 4u])) * d); + MM_STORE_A(5, col_sh, k_pair + 5u, FLOAT_TYPEV2(unpack8(MM_Q8_0_P16.data[ib].qs[iqs + 5u])) * d); + MM_STORE_A(6, col_sh, k_pair + 6u, FLOAT_TYPEV2(unpack8(MM_Q8_0_P16.data[ib].qs[iqs + 6u])) * d); + MM_STORE_A(7, col_sh, k_pair + 7u, FLOAT_TYPEV2(unpack8(MM_Q8_0_P16.data[ib].qs[iqs + 7u])) * d); + } + } else if (MmTypeA == GGML_TYPE_Q1_0) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 2; + + const uint ib = idx / 16; + const uint iqs = idx & 0xfu; + + const float d = float(MM_Q1_0.data[ib].d); + const uint bits = uint(MM_Q1_0.data[ib].qs[iqs]); + + store_a(col_sh, k_pair, FLOAT_TYPEV2((bits & 0x01u) != 0u ? d : -d, (bits & 0x02u) != 0u ? d : -d)); + store_a(col_sh, k_pair + 1, FLOAT_TYPEV2((bits & 0x04u) != 0u ? d : -d, (bits & 0x08u) != 0u ? d : -d)); + store_a(col_sh, k_pair + 2, FLOAT_TYPEV2((bits & 0x10u) != 0u ? d : -d, (bits & 0x20u) != 0u ? d : -d)); + store_a(col_sh, k_pair + 3, FLOAT_TYPEV2((bits & 0x40u) != 0u ? d : -d, (bits & 0x80u) != 0u ? d : -d)); + } else if (MmTypeA == GGML_TYPE_Q2_0) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 2; + + const uint ib = idx / 16; + const uint iqs = idx & 0xfu; + + const FLOAT_TYPE d = FLOAT_TYPE(MM_Q2_0.data[ib].d); + const uint bits = uint(MM_Q2_0.data[ib].qs[iqs]); + + store_a(col_sh, k_pair, d * (FLOAT_TYPEV2(bits & 3u, (bits >> 2u) & 3u) - FLOAT_TYPEV2(1.0f))); + store_a(col_sh, k_pair + 1, d * (FLOAT_TYPEV2((bits >> 4u) & 3u, bits >> 6u) - FLOAT_TYPEV2(1.0f))); + } else if (MmTypeA == GGML_TYPE_Q2_K) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 2; + + const uint ib = idx / 64; + const uint iqs = (idx % 64) * 2; + + const uint qsi = (iqs / 64) * 16 + (iqs % 16); + const uint scalesi = iqs / 8; + const uint qsshift = ((iqs % 64) / 16) * 2; + + const vec4 qs = vec4(unpack8((MM_Q2_K_P32.data[ib].qs[qsi / 2] >> qsshift) & 0x03030303)); + const uint scales = MM_Q2_K.data[ib].scales[scalesi]; + const vec2 dm = vec2(MM_Q2_K.data[ib].dm); + + const vec4 v = dm.x * float(scales & 0xF) * qs - dm.y * float(scales >> 4); + + store_a(col_sh, k_pair, FLOAT_TYPEV2(v.xy)); + store_a(col_sh, k_pair + 1, FLOAT_TYPEV2(v.zw)); + } else if (MmTypeA == GGML_TYPE_Q3_K) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 2; + + const uint ib = idx / 128; + const uint iqs = idx % 128; + + const uint n = iqs / 64; + const uint qsi = n * 32 + (iqs % 16) * 2; + const uint hmi = (iqs % 16) * 2; + const uint is = iqs / 8; + const uint halfsplit = ((iqs % 64) / 16); + const uint qsshift = halfsplit * 2; + + const int8_t us = int8_t(((MM_Q3_K.data[ib].scales[is % 8] >> (4 * int(is / 8))) & 0xF) + | (((MM_Q3_K.data[ib].scales[8 + (is % 4)] >> (2 * int(is / 4))) & 3) << 4)); + const float dl = float(MM_Q3_K.data[ib].d) * float(us - 32); + + const vec2 qs = vec2(unpack8((uint(MM_Q3_K_P16.data[ib].qs[qsi / 2]) >> qsshift) & 0x0303).xy); + const vec2 hm = vec2(unpack8(((uint(MM_Q3_K_P16.data[ib].hmask[hmi / 2]) >> (4 * n + halfsplit)) & 0x0101 ^ 0x0101) << 2).xy); + + store_a(col_sh, k_pair, FLOAT_TYPEV2(dl * (qs.x - hm.x), + dl * (qs.y - hm.y))); + } else if (MmTypeA == GGML_TYPE_Q4_K) { + if (AGX_DIRECT_STORE == 1u) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 2; + + const uint ib = idx / 64; + const uint iqs = (idx % 64) * 2; + + const uint n = iqs / 32; + const uint b = (iqs % 32) / 16; + const uint is = 2 * n + b; + const uint qsi = n * 32 + (iqs % 16) * 2; + + const vec2 loadd = vec2(MM_Q4_K.data[ib].dm); + + const uvec3 scales = uvec3(MM_Q4_K_P32.data[ib].scales[0], + MM_Q4_K_P32.data[ib].scales[1], + MM_Q4_K_P32.data[ib].scales[2]); + const uint scalesoffs = (is & 3) * 8; + + const uint scidxshift0 = scalesoffs; + const uint scidxshift1 = (is < 4) ? scalesoffs : scalesoffs + 2; + const uint mbidxshift0 = (is < 4) ? scalesoffs : scalesoffs + 4; + const uint mbidxshift1 = (is < 4) ? scalesoffs : scalesoffs + 2; + + const uint sc_word = (is < 4) ? scales.x : scales.z; + const uint mb_word = (is < 4) ? scales.y : scales.z; + const uint8_t sc = uint8_t(((sc_word >> scidxshift0) & 0xF) | ((scales.x >> scidxshift1) & 0x30)); + const uint8_t mbyte = uint8_t(((mb_word >> mbidxshift0) & 0xF) | ((scales.y >> mbidxshift1) & 0x30)); + + const float d = loadd.x * sc; + const float m = -loadd.y * mbyte; + + const vec4 q = vec4(unpack8((MM_Q4_K_P32.data[ib].qs[qsi / 4] >> (b * 4)) & 0x0F0F0F0F)); + + MM_STORE_A(0, col_sh, k_pair, FLOAT_TYPEV2(fma(d, q.x, m), fma(d, q.y, m))); + MM_STORE_A(1, col_sh, k_pair + 1, FLOAT_TYPEV2(fma(d, q.z, m), fma(d, q.w, m))); + } else { + const uint idx = pos_a + col_mem * (p.stride_a >> 4u) + row; + const uint k_pair = row * 8u; + + const uint ib = idx >> 4u; + const uint il = idx & 15u; + const uint is = il >> 1u; + const uint b = is & 1u; + const uint n = il >> 2u; + const uint w_idx = (n << 3u) + ((il & 1u) << 2u); + + const vec2 loadd = vec2(MM_Q4_K.data[ib].dm); + + const uvec3 scales = uvec3(MM_Q4_K_P32.data[ib].scales[0], + MM_Q4_K_P32.data[ib].scales[1], + MM_Q4_K_P32.data[ib].scales[2]); + const uint scalesoffs = (is & 3u) * 8u; + const uint scidxshift1 = (is < 4u) ? scalesoffs : scalesoffs + 2u; + const uint mbidxshift0 = (is < 4u) ? scalesoffs : scalesoffs + 4u; + const uint sc_word = (is < 4u) ? scales.x : scales.z; + const uint mb_word = (is < 4u) ? scales.y : scales.z; + const uint sc = ((sc_word >> scalesoffs) & 0xFu) | ((scales.x >> scidxshift1) & 0x30u); + const uint mbyte = ((mb_word >> mbidxshift0) & 0xFu) | ((scales.y >> scidxshift1) & 0x30u); + + const float d_hi = (b == 0u) ? 1.0f : 0.0625f; + const uint q_mk = (b == 0u) ? 0x0F0F0F0Fu : 0xF0F0F0F0u; + const FLOAT_TYPEV4 d = FLOAT_TYPEV4(loadd.x * float(sc) * d_hi); + const FLOAT_TYPEV4 m = FLOAT_TYPEV4(-loadd.y * float(mbyte)); + + const FLOAT_TYPEV4 q0 = fma(d, FLOAT_TYPEV4(unpack8(MM_Q4_K_P32.data[ib].qs[w_idx + 0u] & q_mk)), m); + const FLOAT_TYPEV4 q1 = fma(d, FLOAT_TYPEV4(unpack8(MM_Q4_K_P32.data[ib].qs[w_idx + 1u] & q_mk)), m); + const FLOAT_TYPEV4 q2 = fma(d, FLOAT_TYPEV4(unpack8(MM_Q4_K_P32.data[ib].qs[w_idx + 2u] & q_mk)), m); + const FLOAT_TYPEV4 q3 = fma(d, FLOAT_TYPEV4(unpack8(MM_Q4_K_P32.data[ib].qs[w_idx + 3u] & q_mk)), m); + + MM_STORE_A(0, col_sh, k_pair + 0u, q0.xy); + MM_STORE_A(1, col_sh, k_pair + 1u, q0.zw); + MM_STORE_A(2, col_sh, k_pair + 2u, q1.xy); + MM_STORE_A(3, col_sh, k_pair + 3u, q1.zw); + MM_STORE_A(4, col_sh, k_pair + 4u, q2.xy); + MM_STORE_A(5, col_sh, k_pair + 5u, q2.zw); + MM_STORE_A(6, col_sh, k_pair + 6u, q3.xy); + MM_STORE_A(7, col_sh, k_pair + 7u, q3.zw); + } + } else if (MmTypeA == GGML_TYPE_Q5_K) { + if (AGX_DIRECT_STORE == 1u) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 2; + + const uint ib = idx / 64; + const uint iqs = (idx % 64) * 2; + + const uint n = iqs / 32; + const uint b = (iqs % 32) / 16; + const uint is = 2 * n + b; + const uint qsi = n * 32 + (iqs % 16) * 2; + const uint qhi = (iqs % 16) * 2; + + const vec2 loadd = vec2(MM_Q5_K.data[ib].dm); + + const uvec3 scales = uvec3(MM_Q5_K_P32.data[ib].scales[0], + MM_Q5_K_P32.data[ib].scales[1], + MM_Q5_K_P32.data[ib].scales[2]); + const uint scalesoffs = (is & 3) * 8; + + const uint scidxshift0 = scalesoffs; + const uint scidxshift1 = (is < 4) ? scalesoffs : scalesoffs + 2; + const uint mbidxshift0 = (is < 4) ? scalesoffs : scalesoffs + 4; + const uint mbidxshift1 = (is < 4) ? scalesoffs : scalesoffs + 2; + + const uint sc_word = (is < 4) ? scales.x : scales.z; + const uint mb_word = (is < 4) ? scales.y : scales.z; + const uint8_t sc = uint8_t(((sc_word >> scidxshift0) & 0xF) | ((scales.x >> scidxshift1) & 0x30)); + const uint8_t mbyte = uint8_t(((mb_word >> mbidxshift0) & 0xF) | ((scales.y >> mbidxshift1) & 0x30)); + + const float d = loadd.x * sc; + const float m = -loadd.y * mbyte; + + const uint qs = (MM_Q5_K_P32.data[ib].qs[qsi / 4] >> (b * 4)) & 0x0F0F0F0F; + const uint qh = ((MM_Q5_K_P32.data[ib].qh[qhi / 4] >> (iqs / 16)) & 0x01010101) << 4; + const vec4 q = vec4(unpack8(qs | qh)); + + MM_STORE_A(0, col_sh, k_pair, FLOAT_TYPEV2(fma(d, q.x, m), fma(d, q.y, m))); + MM_STORE_A(1, col_sh, k_pair + 1, FLOAT_TYPEV2(fma(d, q.z, m), fma(d, q.w, m))); + } else { + const uint idx = pos_a + col_mem * (p.stride_a >> 4u) + row; + const uint k_pair = row * 8u; + + const uint ib = idx >> 4u; + const uint il = idx & 15u; + const uint is = il >> 1u; + const uint b = is & 1u; + const uint n = il >> 2u; + const uint w_idx = (n << 3u) + ((il & 1u) << 2u); + const uint qh_idx = (il & 1u) << 2u; + + const vec2 loadd = vec2(MM_Q5_K.data[ib].dm); + + const uvec3 scales = uvec3(MM_Q5_K_P32.data[ib].scales[0], + MM_Q5_K_P32.data[ib].scales[1], + MM_Q5_K_P32.data[ib].scales[2]); + const uint scalesoffs = (is & 3u) * 8u; + const uint scidxshift1 = (is < 4u) ? scalesoffs : scalesoffs + 2u; + const uint mbidxshift0 = (is < 4u) ? scalesoffs : scalesoffs + 4u; + const uint sc_word = (is < 4u) ? scales.x : scales.z; + const uint mb_word = (is < 4u) ? scales.y : scales.z; + const uint sc = ((sc_word >> scalesoffs) & 0xFu) | ((scales.x >> scidxshift1) & 0x30u); + const uint mbyte = ((mb_word >> mbidxshift0) & 0xFu) | ((scales.y >> scidxshift1) & 0x30u); + + const FLOAT_TYPEV4 d = FLOAT_TYPEV4(loadd.x * float(sc)); + const FLOAT_TYPEV4 m = FLOAT_TYPEV4(-loadd.y * float(mbyte)); + + const uint shift = b * 4u; + const uint qs0 = (MM_Q5_K_P32.data[ib].qs[w_idx + 0u] >> shift) & 0x0F0F0F0Fu; + const uint qs1 = (MM_Q5_K_P32.data[ib].qs[w_idx + 1u] >> shift) & 0x0F0F0F0Fu; + const uint qs2 = (MM_Q5_K_P32.data[ib].qs[w_idx + 2u] >> shift) & 0x0F0F0F0Fu; + const uint qs3 = (MM_Q5_K_P32.data[ib].qs[w_idx + 3u] >> shift) & 0x0F0F0F0Fu; + const uint qh0 = ((MM_Q5_K_P32.data[ib].qh[qh_idx + 0u] >> is) & 0x01010101u) << 4u; + const uint qh1 = ((MM_Q5_K_P32.data[ib].qh[qh_idx + 1u] >> is) & 0x01010101u) << 4u; + const uint qh2 = ((MM_Q5_K_P32.data[ib].qh[qh_idx + 2u] >> is) & 0x01010101u) << 4u; + const uint qh3 = ((MM_Q5_K_P32.data[ib].qh[qh_idx + 3u] >> is) & 0x01010101u) << 4u; + const FLOAT_TYPEV4 q0 = fma(d, FLOAT_TYPEV4(unpack8(qs0 | qh0)), m); + const FLOAT_TYPEV4 q1 = fma(d, FLOAT_TYPEV4(unpack8(qs1 | qh1)), m); + const FLOAT_TYPEV4 q2 = fma(d, FLOAT_TYPEV4(unpack8(qs2 | qh2)), m); + const FLOAT_TYPEV4 q3 = fma(d, FLOAT_TYPEV4(unpack8(qs3 | qh3)), m); + + MM_STORE_A(0, col_sh, k_pair + 0u, q0.xy); + MM_STORE_A(1, col_sh, k_pair + 1u, q0.zw); + MM_STORE_A(2, col_sh, k_pair + 2u, q1.xy); + MM_STORE_A(3, col_sh, k_pair + 3u, q1.zw); + MM_STORE_A(4, col_sh, k_pair + 4u, q2.xy); + MM_STORE_A(5, col_sh, k_pair + 5u, q2.zw); + MM_STORE_A(6, col_sh, k_pair + 6u, q3.xy); + MM_STORE_A(7, col_sh, k_pair + 7u, q3.zw); + } + } else if (MmTypeA == GGML_TYPE_Q6_K) { + if (AGX_DIRECT_STORE == 1u) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + const uint k_pair = row * mm_load_vec_a() / 2; + + const uint ib = idx / 128; + const uint iqs = idx % 128; + + const uint n = iqs / 64; + const uint b = ((iqs % 64) / 32) * 4; + const uint is_b = (iqs % 16) / 8; + const uint qhshift = ((iqs % 64) / 16) * 2; + const uint is = 8 * n + qhshift + is_b; + const uint qsi = n * 32 + (iqs % 32); + const uint qhi = n * 16 + (iqs % 16); + + const float dscale = float(MM_Q6_K.data[ib].d) * float(MM_Q6_K.data[ib].scales[is]); + + const uint ql = (uint(MM_Q6_K_P16.data[ib].ql[qsi]) >> b) & 0x0F0F; + const uint qh = (uint(MM_Q6_K_P16.data[ib].qh[qhi]) >> qhshift) & 0x0303; + const vec2 q = (vec2(unpack8(ql | (qh << 4)).xy) - 32) * dscale; + + MM_STORE_A(0, col_sh, k_pair, FLOAT_TYPEV2(q.x, q.y)); + } else { + const uint idx = pos_a + col_mem * (p.stride_a >> 4u) + row; + const uint k_pair = row * 8u; + + const uint ib = idx >> 4u; + const uint il = idx & 15u; + const uint b = ((il >> 2u) & 1u) * 4u; + const uint qhshift = ((il >> 1u) & 3u) * 2u; + const uint qsi = ((il & 8u) << 2u) + ((il & 3u) << 3u); + const uint qhi = ((il & 8u) << 1u) + ((il & 1u) << 3u); + + const float dscale = float(MM_Q6_K.data[ib].d) * float(MM_Q6_K.data[ib].scales[il]); + + const uint ql01 = ((uint(MM_Q6_K_P16.data[ib].ql[qsi + 0u]) | (uint(MM_Q6_K_P16.data[ib].ql[qsi + 1u]) << 16u)) >> b) & 0x0F0F0F0Fu; + const uint ql23 = ((uint(MM_Q6_K_P16.data[ib].ql[qsi + 2u]) | (uint(MM_Q6_K_P16.data[ib].ql[qsi + 3u]) << 16u)) >> b) & 0x0F0F0F0Fu; + const uint ql45 = ((uint(MM_Q6_K_P16.data[ib].ql[qsi + 4u]) | (uint(MM_Q6_K_P16.data[ib].ql[qsi + 5u]) << 16u)) >> b) & 0x0F0F0F0Fu; + const uint ql67 = ((uint(MM_Q6_K_P16.data[ib].ql[qsi + 6u]) | (uint(MM_Q6_K_P16.data[ib].ql[qsi + 7u]) << 16u)) >> b) & 0x0F0F0F0Fu; + const uint qh01 = ((uint(MM_Q6_K_P16.data[ib].qh[qhi + 0u]) | (uint(MM_Q6_K_P16.data[ib].qh[qhi + 1u]) << 16u)) >> qhshift) & 0x03030303u; + const uint qh23 = ((uint(MM_Q6_K_P16.data[ib].qh[qhi + 2u]) | (uint(MM_Q6_K_P16.data[ib].qh[qhi + 3u]) << 16u)) >> qhshift) & 0x03030303u; + const uint qh45 = ((uint(MM_Q6_K_P16.data[ib].qh[qhi + 4u]) | (uint(MM_Q6_K_P16.data[ib].qh[qhi + 5u]) << 16u)) >> qhshift) & 0x03030303u; + const uint qh67 = ((uint(MM_Q6_K_P16.data[ib].qh[qhi + 6u]) | (uint(MM_Q6_K_P16.data[ib].qh[qhi + 7u]) << 16u)) >> qhshift) & 0x03030303u; + const FLOAT_TYPEV4 d = FLOAT_TYPEV4(dscale); + const FLOAT_TYPEV4 m = FLOAT_TYPEV4(-32.0f * dscale); + const FLOAT_TYPEV4 q0 = fma(FLOAT_TYPEV4(unpack8(ql01 | (qh01 << 4u))), d, m); + const FLOAT_TYPEV4 q1 = fma(FLOAT_TYPEV4(unpack8(ql23 | (qh23 << 4u))), d, m); + const FLOAT_TYPEV4 q2 = fma(FLOAT_TYPEV4(unpack8(ql45 | (qh45 << 4u))), d, m); + const FLOAT_TYPEV4 q3 = fma(FLOAT_TYPEV4(unpack8(ql67 | (qh67 << 4u))), d, m); + + MM_STORE_A(0, col_sh, k_pair + 0u, q0.xy); + MM_STORE_A(1, col_sh, k_pair + 1u, q0.zw); + MM_STORE_A(2, col_sh, k_pair + 2u, q1.xy); + MM_STORE_A(3, col_sh, k_pair + 3u, q1.zw); + MM_STORE_A(4, col_sh, k_pair + 4u, q2.xy); + MM_STORE_A(5, col_sh, k_pair + 5u, q2.zw); + MM_STORE_A(6, col_sh, k_pair + 6u, q3.xy); + MM_STORE_A(7, col_sh, k_pair + 7u, q3.zw); + } + } else if (MmTypeA == GGML_TYPE_TQ1_0) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + + const uint ib = idx / 128; + const uint iqs = (idx % 128) * 2; + + const float d = float(MM_TQ1_0.data[ib].d); + vec2 v; + for (uint kk = 0u; kk < 2u; ++kk) { + const uint e = iqs + kk; + const uint bidx = tq1_0_byte_of(e); + const uint qbyte = uint(bidx < 48u ? MM_TQ1_0.data[ib].qs[bidx] + : MM_TQ1_0.data[ib].qh[bidx - 48u]); + v[kk] = d * (float(tq1_0_trit(qbyte, tq1_0_digit_of(e))) - 1.0); + } + + const uint k_pair = row * mm_load_vec_a() / 2; + store_a(col_sh, k_pair, FLOAT_TYPEV2(v.xy)); + } else if (MmTypeA == GGML_TYPE_TQ2_0) { + const uint idx = pos_a + col_mem * p.stride_a / mm_load_vec_a() + row; + + const uint ib = idx / 128; + const uint iqs = (idx % 128) * 2; + + const uint qsi = (iqs / 128) * 32 + (iqs % 32); + const uint shift = 2 * ((iqs % 128) / 32); + + const uvec2 qs = uvec2(MM_TQ2_0.data[ib].qs[qsi], MM_TQ2_0.data[ib].qs[qsi + 1]); + const float d = float(MM_TQ2_0.data[ib].d); + + const vec2 v = d * (vec2((qs >> shift) & 3) - 1.0); + + const uint k_pair = row * mm_load_vec_a() / 2; + store_a(col_sh, k_pair, FLOAT_TYPEV2(v.xy)); + } +#endif diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_cm1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_cm1.comp index eaf7eb65d4e2..54ff16e03502 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_cm1.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_cm1.comp @@ -110,7 +110,7 @@ shared float buf_b_d[BN * BK_STEP]; shared float buf_b_s[BN * BK_STEP]; #endif -#if defined(DATA_A_IQ4_NL) || defined(DATA_A_IQ4_XS) || defined(DATA_A_MXFP4) || defined(DATA_A_NVFP4) +#if defined(DATA_A_IQ4_NL) || defined(DATA_A_IQ4_XS) shared int8_t cm1_kvalues[16]; #endif @@ -163,21 +163,6 @@ void main() { cm1_kvalues[gl_LocalInvocationIndex] = kvalues_iq4nl_const[gl_LocalInvocationIndex]; } barrier(); -#elif defined(DATA_A_MXFP4) - if (gl_LocalInvocationIndex < 16u) { - cm1_kvalues[gl_LocalInvocationIndex] = kvalues_mxfp4_const[gl_LocalInvocationIndex]; - } - barrier(); -#elif defined(DATA_A_NVFP4) - if (gl_LocalInvocationIndex < 16u) { - cm1_kvalues[gl_LocalInvocationIndex] = kvalues_mxfp4_const[gl_LocalInvocationIndex]; - } -#if !defined(USE_OCP_FP4) - for (uint i = gl_LocalInvocationIndex; i < 256u; i += BLOCK_SIZE) { - ue4m3_fp32_lut[i] = ue4m3_to_fp32_build(i); - } -#endif - barrier(); #endif const uint blocks_m = (p.M + BM - 1) / BM; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_cm1_funcs.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_cm1_funcs.glsl index 50c61f6cff3b..a6eb69b4afa4 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_cm1_funcs.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_cm1_funcs.glsl @@ -230,11 +230,11 @@ void block_a_to_shmem(block_a_prefetch blk, uint buf_ib, uint ks, uint loadr, bo const u8vec4 lo_idx = unpack8(blk.qs & 0x0F0F0F0F); const u8vec4 hi_idx = unpack8((blk.qs >> 4) & 0x0F0F0F0F); buf_a_qs[buf_ib * QPITCH + ks * (BK / 4) + loadr ] = - pack32(i8vec4(cm1_kvalues[lo_idx.x], cm1_kvalues[lo_idx.y], - cm1_kvalues[lo_idx.z], cm1_kvalues[lo_idx.w])); + pack32(i8vec4(int8_t(mxfp4_kval(uint(lo_idx.x))), int8_t(mxfp4_kval(uint(lo_idx.y))), + int8_t(mxfp4_kval(uint(lo_idx.z))), int8_t(mxfp4_kval(uint(lo_idx.w))))); buf_a_qs[buf_ib * QPITCH + ks * (BK / 4) + loadr + 4] = - pack32(i8vec4(cm1_kvalues[hi_idx.x], cm1_kvalues[hi_idx.y], - cm1_kvalues[hi_idx.z], cm1_kvalues[hi_idx.w])); + pack32(i8vec4(int8_t(mxfp4_kval(uint(hi_idx.x))), int8_t(mxfp4_kval(uint(hi_idx.y))), + int8_t(mxfp4_kval(uint(hi_idx.z))), int8_t(mxfp4_kval(uint(hi_idx.w))))); if (loadr == 0) { buf_a_d[ks * BM + buf_ib] = in_bounds ? e8m0_to_fp32(blk.e) * 0.5 : 0.0f; @@ -492,11 +492,11 @@ void block_a_to_shmem(block_a_prefetch blk, uint buf_ib, uint ks, uint loadr, bo const uint sub_base = (loadr >> 1) * 4; const uint byte_group = loadr & 1u; buf_a_qs[buf_ib * QPITCH + ks * (BK / 4) + sub_base + byte_group] = - pack32(i8vec4(cm1_kvalues[lo_idx.x], cm1_kvalues[lo_idx.y], - cm1_kvalues[lo_idx.z], cm1_kvalues[lo_idx.w])); + pack32(i8vec4(int8_t(mxfp4_kval(uint(lo_idx.x))), int8_t(mxfp4_kval(uint(lo_idx.y))), + int8_t(mxfp4_kval(uint(lo_idx.z))), int8_t(mxfp4_kval(uint(lo_idx.w))))); buf_a_qs[buf_ib * QPITCH + ks * (BK / 4) + sub_base + 2 + byte_group] = - pack32(i8vec4(cm1_kvalues[hi_idx.x], cm1_kvalues[hi_idx.y], - cm1_kvalues[hi_idx.z], cm1_kvalues[hi_idx.w])); + pack32(i8vec4(int8_t(mxfp4_kval(uint(hi_idx.x))), int8_t(mxfp4_kval(uint(hi_idx.y))), + int8_t(mxfp4_kval(uint(hi_idx.z))), int8_t(mxfp4_kval(uint(hi_idx.w))))); if (loadr == 0) { buf_a_d[(ks * KSCALES ) * BM + buf_ib] = in_bounds ? ue4m3_to_fp32(blk.d0) * 0.5 : 0.0f; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_funcs.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_funcs.glsl index 9d94fd2b7577..d14ed2f165a1 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_funcs.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_funcs.glsl @@ -256,8 +256,8 @@ void block_a_to_shmem(const uint buf_ib, const uint ib, const uint iqs, const bo const u8vec4 i_a0 = unpack8( qs & 0x0F0F0F0F); const u8vec4 i_a1 = unpack8((qs >> 4) & 0x0F0F0F0F); - buf_a[buf_ib].qs[iqs ] = mmq_a_store(pack32(i8vec4(kvalues_mxfp4[i_a0.x], kvalues_mxfp4[i_a0.y], kvalues_mxfp4[i_a0.z], kvalues_mxfp4[i_a0.w]))); - buf_a[buf_ib].qs[iqs + 4] = mmq_a_store(pack32(i8vec4(kvalues_mxfp4[i_a1.x], kvalues_mxfp4[i_a1.y], kvalues_mxfp4[i_a1.z], kvalues_mxfp4[i_a1.w]))); + buf_a[buf_ib].qs[iqs ] = mmq_a_store(pack32(i8vec4(int8_t(mxfp4_kval(uint(i_a0.x))), int8_t(mxfp4_kval(uint(i_a0.y))), int8_t(mxfp4_kval(uint(i_a0.z))), int8_t(mxfp4_kval(uint(i_a0.w)))))); + buf_a[buf_ib].qs[iqs + 4] = mmq_a_store(pack32(i8vec4(int8_t(mxfp4_kval(uint(i_a1.x))), int8_t(mxfp4_kval(uint(i_a1.y))), int8_t(mxfp4_kval(uint(i_a1.z))), int8_t(mxfp4_kval(uint(i_a1.w)))))); if (iqs == 0) { buf_a[buf_ib].d = FLOAT_TYPE(e8m0_to_fp32(data_a[ib].e) * 0.5); diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mv_mma.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mv_mma.comp new file mode 100644 index 000000000000..3877bcbb40d7 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mv_mma.comp @@ -0,0 +1,2300 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : enable +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_8bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int8 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_shuffle : enable +#extension GL_KHR_memory_scope_semantics : enable +#extension GL_KHR_cooperative_matrix : enable + +#ifndef FLOAT_TYPE +#define FLOAT_TYPE float16_t +#endif + +#include "types.glsl" + +// Zero-spill register-direct 8x8x8 cooperative-matrix few-column matmul / MoE matmul_id for Apple AGX (G17P). +// Subgroup layout (AGX3B 8x8 coopmat): +// lane l in [0..31] owns: +// fm = ((l >> 1) & 3) | ((l >> 2) & 4) in [0..7] +// fn = ((l & 1) << 1) | ((l >> 1) & 4) in {0, 2, 4, 6} (elements e=0,1 -> fn, fn+1) + +layout(local_size_x = 32, local_size_y_id = 0, local_size_z = 1) in; + +layout(constant_id = 0) const uint WG_SG = 1; // total subgroups per workgroup = NSG * MSG * CSG +layout(constant_id = 1) const uint NT = 2; // 8*NT M-rows per subgroup +layout(constant_id = 2) const uint RT = 1; // 8*RT N-cols per subgroup (1, 2, 4) +layout(constant_id = 3) const uint NSG = 1; // K-split subgroups +// 0 = plain, 1 = single-op epilogue, 2 = PAIR_MM (dense only), 3 = PAIR_GLU, 4 = fast epilogue +layout(constant_id = 4) const uint FUSE_MODE = 0; +layout(constant_id = 5) const uint USE_SH_B = 1; +layout(constant_id = 6) const uint K_PAIRS = 1; +layout(constant_id = 7) const uint CSG = 1; // column-split subgroups (MUL_MAT_ID cooperative dequant) +layout(constant_id = 8) const uint B_IS_F16 = 0; // compile-time FP16 B buffer specialization +layout(constant_id = 9) const uint FUSE_LORA = 0; // compile-time fused dynamic LoRA specialization + +const uint MSG = WG_SG / (NSG * CSG); +const uint WG_THREADS = 32u * WG_SG; +const uint BN_COLS = 8u * RT * CSG; + +#if defined(DATA_A_F32) +#define MMA_FTYPE float +#define MMA_FVEC4 vec4 +#define MMA_FVEC2 vec2 +#define MMA_ELEM_SHIFT 0u +#elif defined(DATA_A_F32_F16) +#define MMA_FTYPE float16_t +#define MMA_FVEC4 f16vec4 +#define MMA_FVEC2 f16vec2 +#define MMA_ELEM_SHIFT 0u +#elif defined(DATA_A_F16) +#define MMA_FTYPE float16_t +#define MMA_FVEC4 f16vec4 +#define MMA_FVEC2 f16vec2 +#define MMA_ELEM_SHIFT 0u +#elif defined(DATA_A_Q4_K) || defined(DATA_A_Q5_K) || defined(DATA_A_Q6_K) || defined(DATA_A_IQ4_XS) +#define MMA_FTYPE float16_t +#define MMA_FVEC4 f16vec4 +#define MMA_FVEC2 f16vec2 +#define MMA_ELEM_SHIFT 8u +#elif defined(DATA_A_NVFP4) +#define MMA_FTYPE float16_t +#define MMA_FVEC4 f16vec4 +#define MMA_FVEC2 f16vec2 +#define MMA_ELEM_SHIFT 6u +#else +#define MMA_FTYPE float16_t +#define MMA_FVEC4 f16vec4 +#define MMA_FVEC2 f16vec2 +#define MMA_ELEM_SHIFT 5u +#endif + +#ifdef MUL_MAT_ID +#define MMA_BIND_U 5 +#define MMA_BIND_AUX0 6 +#define MMA_BIND_AUX1 7 +#else +// Matches mul_mat_vec 7-binding layout: {A=0, B=1, D=2, F0/U=3, F1=4, D2=5, F2=6} +#define MMA_BIND_U 3 +#define MMA_BIND_AUX0 3 +#define MMA_BIND_AUX1 4 +#endif + +// Per-type SSBO bindings (only the active type's descriptors are declared) +#if defined(DATA_A_F32) || defined(DATA_A_F32_F16) +layout(binding = 0) readonly buffer BUF_A_F32 { float data[]; } a_f32; +layout(binding = 0) readonly buffer BUF_A_F32V4 { vec4 data[]; } a_f32v4; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_F32 { float data[]; } u_f32; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_F32V4 { vec4 data[]; } u_f32v4; +#elif defined(DATA_A_F16) +layout(binding = 0) readonly buffer BUF_A_F16 { float16_t data[]; } a_f16; +layout(binding = 0) readonly buffer BUF_A_F16V4 { f16vec4 data[]; } a_f16v4; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_F16 { float16_t data[]; } u_f16; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_F16V4 { f16vec4 data[]; } u_f16v4; +#elif defined(DATA_A_Q8_0) +layout(binding = 0) readonly buffer BUF_A_Q8_0 { block_q8_0_packed16 data[]; } a_q8_0; +layout(binding = 0) readonly buffer BUF_A_U32 { uint data[]; } a_u32; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q8_0 { block_q8_0_packed16 data[]; } u_q8_0; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_U32 { uint data[]; } u_u32; +#elif defined(DATA_A_Q4_0) +layout(binding = 0) readonly buffer BUF_A_Q4_0 { block_q4_0_packed16 data[]; } a_q4_0; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q4_0 { block_q4_0_packed16 data[]; } u_q4_0; +#elif defined(DATA_A_Q4_1) +layout(binding = 0) readonly buffer BUF_A_Q4_1 { block_q4_1_packed32 data[]; } a_q4_1; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q4_1 { block_q4_1_packed32 data[]; } u_q4_1; +#elif defined(DATA_A_Q5_0) +layout(binding = 0) readonly buffer BUF_A_Q5_0 { block_q5_0_packed16 data[]; } a_q5_0; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q5_0 { block_q5_0_packed16 data[]; } u_q5_0; +#elif defined(DATA_A_Q5_1) +layout(binding = 0) readonly buffer BUF_A_Q5_1 { block_q5_1_packed32 data[]; } a_q5_1; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q5_1 { block_q5_1_packed32 data[]; } u_q5_1; +#elif defined(DATA_A_Q4_K) +layout(binding = 0) readonly buffer BUF_A_Q4_K { block_q4_K data[]; } a_q4_k; +layout(binding = 0) readonly buffer BUF_A_Q4_KP32 { block_q4_K_packed32 data[]; } a_q4_k_p32; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q4_K { block_q4_K data[]; } u_q4_k; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q4_KP32 { block_q4_K_packed32 data[]; } u_q4_k_p32; +#elif defined(DATA_A_Q5_K) +layout(binding = 0) readonly buffer BUF_A_Q5_K { block_q5_K data[]; } a_q5_k; +layout(binding = 0) readonly buffer BUF_A_Q5_KP32 { block_q5_K_packed32 data[]; } a_q5_k_p32; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q5_K { block_q5_K data[]; } u_q5_k; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q5_KP32 { block_q5_K_packed32 data[]; } u_q5_k_p32; +#elif defined(DATA_A_Q6_K) +layout(binding = 0) readonly buffer BUF_A_Q6_K { block_q6_K data[]; } a_q6_k; +layout(binding = 0) readonly buffer BUF_A_Q6_KP16 { block_q6_K_packed16 data[]; } a_q6_k_p16; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q6_K { block_q6_K data[]; } u_q6_k; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_Q6_KP16 { block_q6_K_packed16 data[]; } u_q6_k_p16; +#elif defined(DATA_A_IQ4_XS) +layout(binding = 0) readonly buffer BUF_A_IQ4_XS { block_iq4_xs data[]; } a_iq4_xs; +layout(binding = 0) readonly buffer BUF_A_IQ4XSP32 { block_iq4_xs_packed32 data[]; } a_iq4_xs_p32; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_IQ4_XS { block_iq4_xs data[]; } u_iq4_xs; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_IQ4XSP32 { block_iq4_xs_packed32 data[]; } u_iq4_xs_p32; +#elif defined(DATA_A_IQ4_NL) +layout(binding = 0) readonly buffer BUF_A_IQ4_NL { block_iq4_nl_packed16 data[]; } a_iq4_nl; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_IQ4_NL { block_iq4_nl_packed16 data[]; } u_iq4_nl; +#elif defined(DATA_A_NVFP4) +layout(binding = 0) readonly buffer BUF_A_NVFP4 { block_nvfp4_packed32 data[]; } a_nvfp4; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_NVFP4 { block_nvfp4_packed32 data[]; } u_nvfp4; +#endif +#ifdef REPACK_PLANAR +#include "repack_planar.glsl" +layout(binding = 0) readonly buffer BUF_A_REPACK_U32 { uint data[]; } a_u32; +layout(binding = 0) readonly buffer BUF_A_REPACK_U2 { uvec2 data[]; } a_u2; +layout(binding = 0) readonly buffer BUF_A_REPACK_U4 { uvec4 data[]; } a_u4; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_REPACK_U32 { uint data[]; } u_u32; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_REPACK_U2 { uvec2 data[]; } u_u2; +layout(binding = MMA_BIND_U) readonly buffer BUF_U_REPACK_U4 { uvec4 data[]; } u_u4; +uint g_mma_slice_blk_base; +#endif + +// B bindings (binding = 1) +layout(binding = 1) readonly buffer BUF_B_F32 { float data_b[]; }; +layout(binding = 1) readonly buffer BUF_B_F32V2 { vec2 data_b_v2[]; }; +layout(binding = 1) readonly buffer BUF_B_F32V4 { vec4 data_b_v4[]; }; +layout(binding = 1) readonly buffer BUF_B_F16 { float16_t data_b_f16[]; }; +layout(binding = 1) readonly buffer BUF_B_F16V2 { f16vec2 data_b_f16v2[]; }; +layout(binding = 1) readonly buffer BUF_B_F16V4 { f16vec4 data_b_f16v4[]; }; + +// D binding (binding = 2) +layout(binding = 2) writeonly buffer BUF_D_F32 { float data_d[]; }; + +#ifdef MUL_MAT_ID +layout(binding = 3) readonly buffer BUF_IDS { int data_ids[]; }; +layout(binding = 4) readonly buffer BUF_ROW_MAP { uint data_row_map[]; }; +layout(binding = MMA_BIND_AUX1) writeonly buffer BUF_D_F16 { float16_t data_d_f16[]; }; +#else +layout(binding = 5) writeonly buffer BUF_D2_F32 { float data_d2[]; }; +layout(binding = 6) readonly buffer BUF_F2_F32 { float data_aux2[]; }; +layout(binding = 7) readonly buffer BUF_LORA_B0 { float data[]; } lora_b0; +layout(binding = 7) readonly buffer BUF_LORA_B0_V4 { vec4 data[]; } lora_b0_v4; +layout(binding = 8) readonly buffer BUF_LORA_H0 { float data[]; } lora_h0; +layout(binding = 8) readonly buffer BUF_LORA_H0_V4 { vec4 data[]; } lora_h0_v4; +layout(binding = 9) readonly buffer BUF_LORA_B1 { float data[]; } lora_b1; +layout(binding = 9) readonly buffer BUF_LORA_B1_V4 { vec4 data[]; } lora_b1_v4; +layout(binding = 10) readonly buffer BUF_LORA_H1 { float data[]; } lora_h1; +layout(binding = 10) readonly buffer BUF_LORA_H1_V4 { vec4 data[]; } lora_h1_v4; +#endif + +layout(binding = MMA_BIND_AUX0) readonly buffer BUF_AUX0 { float data_aux0[]; }; +layout(binding = MMA_BIND_AUX1) readonly buffer BUF_AUX1 { float data_aux1[]; }; + +#define MAT_VEC_FUSION_FLAGS_BIAS0 0x1u +#define MAT_VEC_FUSION_FLAGS_BIAS1 0x2u +#define MAT_VEC_FUSION_FLAGS_SCALE0 0x4u +#define MAT_VEC_FUSION_FLAGS_SCALE1 0x8u +#define MAT_VEC_FUSION_FLAGS_GLU_A 0x10u +#define MAT_VEC_FUSION_FLAGS_GLU_B 0x20u +#define MAT_VEC_FUSION_FLAGS_SIGMOID 0x80u +#define MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE 0x100u +#define MAT_VEC_FUSION_FLAGS_ROW_SCALE0 0x200u +#define MAT_VEC_FUSION_FLAGS_PAIR_GLU 0x400u +#define MAT_VEC_FUSION_FLAGS_PAIR_MM 0x800u +#define MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1 0x1000u +#define MAT_VEC_FUSION_FLAGS_SCALE0_TOK 0x2000u +#define MAT_VEC_FUSION_FLAGS_SCALE1_TOK 0x4000u +#define MAT_VEC_FUSION_FLAGS_B_F16 0x10000u +#define MAT_VEC_FUSION_FLAGS_D_F16_AUX1 0x20000u +#define MAT_VEC_FUSION_FLAGS_SKIP_F32_D 0x40000u +#define MAT_VEC_FUSION_FLAGS_LORA0 0x80000u +#define MAT_VEC_FUSION_FLAGS_LORA1 0x100000u +#define MAT_VEC_FUSION_FLAGS_EXP_SCALE0 0x200000u +#define MAT_VEC_FUSION_FLAGS_SITU_MERGED 0x400000u + +layout(push_constant) uniform parameter { +#ifdef MUL_MAT_ID + uint M; + uint N; + uint K; + uint stride_a; + uint stride_b; + uint stride_d; + uint batch_stride_a; + uint batch_stride_b; + uint batch_stride_d; + uint nei0; + uint nei1; + uint nbi1; + uint ne11; + uint n_experts; + uint row_ids_offset; + uint fusion_flags; + float glu_alpha; + float glu_limit; +#else + uint M; + uint N; + uint K; + uint stride_a; + uint stride_b; + uint stride_d; + uint batch_stride_a; + uint batch_stride_b; + uint batch_stride_d; + uint fusion_flags; + uint base_work_group_z; + uint ne02; + uint ne12; + uint broadcast2; + uint broadcast3; + uint pair_m0; + uint stride_d2; + uint batch_stride_d2; + uint lora_r; + float lora_scale0; + float lora_scale1; +#endif +} p; + +#ifndef MUL_MAT_ID +const uint RED_SLOTS = (NSG > 1u) ? (NSG * MSG * RT * NT * 64u * ((FUSE_MODE == 3u) ? 2u : 1u)) : 1u; +shared float red_shmem[RED_SLOTS]; +#endif + +// Cooperative B staging tile when MSG > 1 && USE_SH_B != 0 +const bool COOP_SH_B = (MSG > 1u) && (USE_SH_B != 0u); +const uint SH_B_COLS = COOP_SH_B ? BN_COLS : 1u; +const uint SH_B_K4 = COOP_SH_B ? (16u * K_PAIRS) : 1u; +shared MMA_FVEC4 sh_b[SH_B_COLS][SH_B_K4]; + +#ifdef MUL_MAT_ID +const bool USE_SH_IDS = (SH_B_COLS * SH_B_K4 * 8u) < 16384u; +shared uint sh_b_base[USE_SH_IDS ? BN_COLS : 1u]; +shared uint sh_r_ids[USE_SH_IDS ? BN_COLS : 1u]; +shared float sh_col_scale[(USE_SH_IDS && FUSE_MODE == 4u) ? BN_COLS : 1u]; + +uint mma_id_col_packed(uint row_begin, uint tile_ne1, uint col_i) { + if (USE_SH_IDS) { + return sh_r_ids[min(col_i, BN_COLS - 1u)]; + } + return data_row_map[p.row_ids_offset + row_begin + min(col_i, tile_ne1 - 1u)]; +} +uint mma_id_col_b_base(uint row_begin, uint tile_ne1, uint col_i) { + if (USE_SH_IDS) { + return sh_b_base[min(col_i, BN_COLS - 1u)]; + } + const uint packed = mma_id_col_packed(row_begin, tile_ne1, col_i); + return (packed >> 16u) * p.batch_stride_b + ((packed & 0xFFFFu) % p.ne11) * p.stride_b; +} +#endif + +uint mma_lane_fm(uint l) { return ((l >> 1u) & 3u) | ((l >> 2u) & 4u); } +uint mma_lane_fn(uint l) { return ((l & 1u) << 1u) | ((l >> 1u) & 4u); } + +#if defined(DATA_A_IQ4_XS) || defined(DATA_A_IQ4_NL) +float iq4nl_lut(uint idx) { + switch (idx) { + case 0u: return -127.0f; + case 1u: return -104.0f; + case 2u: return -83.0f; + case 3u: return -65.0f; + case 4u: return -49.0f; + case 5u: return -35.0f; + case 6u: return -22.0f; + case 7u: return -10.0f; + case 8u: return 1.0f; + case 9u: return 13.0f; + case 10u: return 25.0f; + case 11u: return 38.0f; + case 12u: return 53.0f; + case 13u: return 69.0f; + case 14u: return 89.0f; + default: return 113.0f; + } +} +#endif + +MMA_FVEC4 load_b_mvec4(uint elem_idx, bool v4_ok, bool b_is_f16) { + if (b_is_f16) { + if (v4_ok) { + return MMA_FVEC4(data_b_f16v4[elem_idx >> 2u]); + } + return MMA_FVEC4(data_b_f16[elem_idx + 0u], data_b_f16[elem_idx + 1u], data_b_f16[elem_idx + 2u], data_b_f16[elem_idx + 3u]); + } + if (v4_ok) { + return MMA_FVEC4(data_b_v4[elem_idx >> 2u]); + } + return MMA_FVEC4(data_b[elem_idx + 0u], data_b[elem_idx + 1u], data_b[elem_idx + 2u], data_b[elem_idx + 3u]); +} + +MMA_FVEC2 load_b_mvec2(uint elem_idx, bool v2_ok, bool b_is_f16) { + if (b_is_f16) { + if (v2_ok) { + return MMA_FVEC2(data_b_f16v2[elem_idx >> 1u]); + } + return MMA_FVEC2(data_b_f16[elem_idx + 0u], data_b_f16[elem_idx + 1u]); + } + if (v2_ok) { + return MMA_FVEC2(data_b_v2[elem_idx >> 1u]); + } + return MMA_FVEC2(data_b[elem_idx + 0u], data_b[elem_idx + 1u]); +} + +// Unified single-body dequant16 (prevents duplicate temporary live ranges in PAIR_GLU / PAIR_MM!) +void dequant16(bool use_u, uint row_unit_base, uint ci, out MMA_FVEC4 w0, out MMA_FVEC4 w1, out MMA_FVEC4 w2, out MMA_FVEC4 w3) { +#if defined(DATA_A_F32) || defined(DATA_A_F32_F16) + const uint base = row_unit_base + (ci << 4u); + if ((base & 3u) == 0u) { + const uint v4 = base >> 2u; + if (use_u) { + w0 = MMA_FVEC4(u_f32v4.data[v4 + 0u]); w1 = MMA_FVEC4(u_f32v4.data[v4 + 1u]); w2 = MMA_FVEC4(u_f32v4.data[v4 + 2u]); w3 = MMA_FVEC4(u_f32v4.data[v4 + 3u]); + } else { + w0 = MMA_FVEC4(a_f32v4.data[v4 + 0u]); w1 = MMA_FVEC4(a_f32v4.data[v4 + 1u]); w2 = MMA_FVEC4(a_f32v4.data[v4 + 2u]); w3 = MMA_FVEC4(a_f32v4.data[v4 + 3u]); + } + } else if (use_u) { + w0 = MMA_FVEC4(u_f32.data[base+0u], u_f32.data[base+1u], u_f32.data[base+2u], u_f32.data[base+3u]); + w1 = MMA_FVEC4(u_f32.data[base+4u], u_f32.data[base+5u], u_f32.data[base+6u], u_f32.data[base+7u]); + w2 = MMA_FVEC4(u_f32.data[base+8u], u_f32.data[base+9u], u_f32.data[base+10u], u_f32.data[base+11u]); + w3 = MMA_FVEC4(u_f32.data[base+12u], u_f32.data[base+13u], u_f32.data[base+14u], u_f32.data[base+15u]); + } else { + w0 = MMA_FVEC4(a_f32.data[base+0u], a_f32.data[base+1u], a_f32.data[base+2u], a_f32.data[base+3u]); + w1 = MMA_FVEC4(a_f32.data[base+4u], a_f32.data[base+5u], a_f32.data[base+6u], a_f32.data[base+7u]); + w2 = MMA_FVEC4(a_f32.data[base+8u], a_f32.data[base+9u], a_f32.data[base+10u], a_f32.data[base+11u]); + w3 = MMA_FVEC4(a_f32.data[base+12u], a_f32.data[base+13u], a_f32.data[base+14u], a_f32.data[base+15u]); + } +#elif defined(DATA_A_F16) + const uint base = row_unit_base + (ci << 4u); + if ((base & 3u) == 0u) { + const uint v4 = base >> 2u; + if (use_u) { + w0 = u_f16v4.data[v4 + 0u]; w1 = u_f16v4.data[v4 + 1u]; w2 = u_f16v4.data[v4 + 2u]; w3 = u_f16v4.data[v4 + 3u]; + } else { + w0 = a_f16v4.data[v4 + 0u]; w1 = a_f16v4.data[v4 + 1u]; w2 = a_f16v4.data[v4 + 2u]; w3 = a_f16v4.data[v4 + 3u]; + } + } else if (use_u) { + w0 = f16vec4(u_f16.data[base+0u], u_f16.data[base+1u], u_f16.data[base+2u], u_f16.data[base+3u]); + w1 = f16vec4(u_f16.data[base+4u], u_f16.data[base+5u], u_f16.data[base+6u], u_f16.data[base+7u]); + w2 = f16vec4(u_f16.data[base+8u], u_f16.data[base+9u], u_f16.data[base+10u], u_f16.data[base+11u]); + w3 = f16vec4(u_f16.data[base+12u], u_f16.data[base+13u], u_f16.data[base+14u], u_f16.data[base+15u]); + } else { + w0 = f16vec4(a_f16.data[base+0u], a_f16.data[base+1u], a_f16.data[base+2u], a_f16.data[base+3u]); + w1 = f16vec4(a_f16.data[base+4u], a_f16.data[base+5u], a_f16.data[base+6u], a_f16.data[base+7u]); + w2 = f16vec4(a_f16.data[base+8u], a_f16.data[base+9u], a_f16.data[base+10u], a_f16.data[base+11u]); + w3 = f16vec4(a_f16.data[base+12u], a_f16.data[base+13u], a_f16.data[base+14u], a_f16.data[base+15u]); + } +#elif defined(DATA_A_Q8_0) + const uint ib = row_unit_base + (ci >> 1u); + const uint iqs = (ci & 1u) << 3u; + float16_t d; + uint q01, q23, q45, q67; + if (use_u) { + d = u_q8_0.data[ib].d; + q01 = pack32(u16vec2(uint16_t(u_q8_0.data[ib].qs[iqs + 0u]), uint16_t(u_q8_0.data[ib].qs[iqs + 1u]))) ^ 0x80808080u; + q23 = pack32(u16vec2(uint16_t(u_q8_0.data[ib].qs[iqs + 2u]), uint16_t(u_q8_0.data[ib].qs[iqs + 3u]))) ^ 0x80808080u; + q45 = pack32(u16vec2(uint16_t(u_q8_0.data[ib].qs[iqs + 4u]), uint16_t(u_q8_0.data[ib].qs[iqs + 5u]))) ^ 0x80808080u; + q67 = pack32(u16vec2(uint16_t(u_q8_0.data[ib].qs[iqs + 6u]), uint16_t(u_q8_0.data[ib].qs[iqs + 7u]))) ^ 0x80808080u; + } else { + d = a_q8_0.data[ib].d; + q01 = pack32(u16vec2(uint16_t(a_q8_0.data[ib].qs[iqs + 0u]), uint16_t(a_q8_0.data[ib].qs[iqs + 1u]))) ^ 0x80808080u; + q23 = pack32(u16vec2(uint16_t(a_q8_0.data[ib].qs[iqs + 2u]), uint16_t(a_q8_0.data[ib].qs[iqs + 3u]))) ^ 0x80808080u; + q45 = pack32(u16vec2(uint16_t(a_q8_0.data[ib].qs[iqs + 4u]), uint16_t(a_q8_0.data[ib].qs[iqs + 5u]))) ^ 0x80808080u; + q67 = pack32(u16vec2(uint16_t(a_q8_0.data[ib].qs[iqs + 6u]), uint16_t(a_q8_0.data[ib].qs[iqs + 7u]))) ^ 0x80808080u; + } + const f16vec2 bias16 = f16vec2(float16_t(1152.0)); + const f16vec2 e0 = unpackFloat2x16((q01 & 0x00FF00FFu) | 0x64006400u) - bias16; + const f16vec2 o0 = unpackFloat2x16(((q01 >> 8u) & 0x00FF00FFu) | 0x64006400u) - bias16; + const f16vec2 e1 = unpackFloat2x16((q23 & 0x00FF00FFu) | 0x64006400u) - bias16; + const f16vec2 o1 = unpackFloat2x16(((q23 >> 8u) & 0x00FF00FFu) | 0x64006400u) - bias16; + const f16vec2 e2 = unpackFloat2x16((q45 & 0x00FF00FFu) | 0x64006400u) - bias16; + const f16vec2 o2 = unpackFloat2x16(((q45 >> 8u) & 0x00FF00FFu) | 0x64006400u) - bias16; + const f16vec2 e3 = unpackFloat2x16((q67 & 0x00FF00FFu) | 0x64006400u) - bias16; + const f16vec2 o3 = unpackFloat2x16(((q67 >> 8u) & 0x00FF00FFu) | 0x64006400u) - bias16; + w0 = d * f16vec4(e0.x, o0.x, e0.y, o0.y); + w1 = d * f16vec4(e1.x, o1.x, e1.y, o1.y); + w2 = d * f16vec4(e2.x, o2.x, e2.y, o2.y); + w3 = d * f16vec4(e3.x, o3.x, e3.y, o3.y); +#elif defined(DATA_A_Q4_0) + const uint ib = row_unit_base + (ci >> 1u); + const uint shift = (ci & 1u) * 4u; + float d; + uint u0, u1, u2, u3; + if (use_u) { + d = float(u_q4_0.data[ib].d); + u0 = ((uint(u_q4_0.data[ib].qs[0]) | (uint(u_q4_0.data[ib].qs[1]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u1 = ((uint(u_q4_0.data[ib].qs[2]) | (uint(u_q4_0.data[ib].qs[3]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u2 = ((uint(u_q4_0.data[ib].qs[4]) | (uint(u_q4_0.data[ib].qs[5]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u3 = ((uint(u_q4_0.data[ib].qs[6]) | (uint(u_q4_0.data[ib].qs[7]) << 16u)) >> shift) & 0x0F0F0F0Fu; + } else { + d = float(a_q4_0.data[ib].d); + u0 = ((uint(a_q4_0.data[ib].qs[0]) | (uint(a_q4_0.data[ib].qs[1]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u1 = ((uint(a_q4_0.data[ib].qs[2]) | (uint(a_q4_0.data[ib].qs[3]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u2 = ((uint(a_q4_0.data[ib].qs[4]) | (uint(a_q4_0.data[ib].qs[5]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u3 = ((uint(a_q4_0.data[ib].qs[6]) | (uint(a_q4_0.data[ib].qs[7]) << 16u)) >> shift) & 0x0F0F0F0Fu; + } + const f16vec4 dv = f16vec4(d); + const f16vec4 mv = f16vec4(-8.0f * d); + w0 = fma(dv, f16vec4(unpack8(u0)), mv); + w1 = fma(dv, f16vec4(unpack8(u1)), mv); + w2 = fma(dv, f16vec4(unpack8(u2)), mv); + w3 = fma(dv, f16vec4(unpack8(u3)), mv); +#elif defined(DATA_A_Q4_1) + const uint ib = row_unit_base + (ci >> 1u); + const uint shift = (ci & 1u) * 4u; + vec2 dm; + uint q0, q1, q2, q3; + if (use_u) { + dm = vec2(u_q4_1.data[ib].dm); + q0 = u_q4_1.data[ib].qs[0]; q1 = u_q4_1.data[ib].qs[1]; q2 = u_q4_1.data[ib].qs[2]; q3 = u_q4_1.data[ib].qs[3]; + } else { + dm = vec2(a_q4_1.data[ib].dm); + q0 = a_q4_1.data[ib].qs[0]; q1 = a_q4_1.data[ib].qs[1]; q2 = a_q4_1.data[ib].qs[2]; q3 = a_q4_1.data[ib].qs[3]; + } + const vec4 d = vec4(dm.x), m = vec4(dm.y); + w0 = f16vec4(fma(d, vec4(unpack8((q0 >> shift) & 0x0F0F0F0Fu)), m)); + w1 = f16vec4(fma(d, vec4(unpack8((q1 >> shift) & 0x0F0F0F0Fu)), m)); + w2 = f16vec4(fma(d, vec4(unpack8((q2 >> shift) & 0x0F0F0F0Fu)), m)); + w3 = f16vec4(fma(d, vec4(unpack8((q3 >> shift) & 0x0F0F0F0Fu)), m)); +#elif defined(DATA_A_Q5_0) + const uint ib = row_unit_base + (ci >> 1u); + const uint half_i = ci & 1u; + const uint shift = half_i * 4u; + float d; + uint qh, u0, u1, u2, u3; + if (use_u) { + d = float(u_q5_0.data[ib].d); + qh = (uint(u_q5_0.data[ib].qh[0]) | (uint(u_q5_0.data[ib].qh[1]) << 16u)) >> (half_i * 16u); + u0 = ((uint(u_q5_0.data[ib].qs[0]) | (uint(u_q5_0.data[ib].qs[1]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u1 = ((uint(u_q5_0.data[ib].qs[2]) | (uint(u_q5_0.data[ib].qs[3]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u2 = ((uint(u_q5_0.data[ib].qs[4]) | (uint(u_q5_0.data[ib].qs[5]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u3 = ((uint(u_q5_0.data[ib].qs[6]) | (uint(u_q5_0.data[ib].qs[7]) << 16u)) >> shift) & 0x0F0F0F0Fu; + } else { + d = float(a_q5_0.data[ib].d); + qh = (uint(a_q5_0.data[ib].qh[0]) | (uint(a_q5_0.data[ib].qh[1]) << 16u)) >> (half_i * 16u); + u0 = ((uint(a_q5_0.data[ib].qs[0]) | (uint(a_q5_0.data[ib].qs[1]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u1 = ((uint(a_q5_0.data[ib].qs[2]) | (uint(a_q5_0.data[ib].qs[3]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u2 = ((uint(a_q5_0.data[ib].qs[4]) | (uint(a_q5_0.data[ib].qs[5]) << 16u)) >> shift) & 0x0F0F0F0Fu; + u3 = ((uint(a_q5_0.data[ib].qs[6]) | (uint(a_q5_0.data[ib].qs[7]) << 16u)) >> shift) & 0x0F0F0F0Fu; + } + const float m = -16.0f * d; + const vec4 h0 = vec4(((qh >> 0u) & 1u) << 4u, ((qh >> 1u) & 1u) << 4u, ((qh >> 2u) & 1u) << 4u, ((qh >> 3u) & 1u) << 4u); + const vec4 h1 = vec4(((qh >> 4u) & 1u) << 4u, ((qh >> 5u) & 1u) << 4u, ((qh >> 6u) & 1u) << 4u, ((qh >> 7u) & 1u) << 4u); + const vec4 h2 = vec4(((qh >> 8u) & 1u) << 4u, ((qh >> 9u) & 1u) << 4u, ((qh >>10u) & 1u) << 4u, ((qh >>11u) & 1u) << 4u); + const vec4 h3 = vec4(((qh >>12u) & 1u) << 4u, ((qh >>13u) & 1u) << 4u, ((qh >>14u) & 1u) << 4u, ((qh >>15u) & 1u) << 4u); + w0 = f16vec4(fma(vec4(d), vec4(unpack8(u0)) + h0, vec4(m))); + w1 = f16vec4(fma(vec4(d), vec4(unpack8(u1)) + h1, vec4(m))); + w2 = f16vec4(fma(vec4(d), vec4(unpack8(u2)) + h2, vec4(m))); + w3 = f16vec4(fma(vec4(d), vec4(unpack8(u3)) + h3, vec4(m))); +#elif defined(DATA_A_Q5_1) + const uint ib = row_unit_base + (ci >> 1u); + const uint half_i = ci & 1u; + const uint shift = half_i * 4u; + vec2 dm; + uint qh, q0, q1, q2, q3; + if (use_u) { + dm = vec2(u_q5_1.data[ib].dm); qh = u_q5_1.data[ib].qh >> (half_i * 16u); + q0 = u_q5_1.data[ib].qs[0]; q1 = u_q5_1.data[ib].qs[1]; q2 = u_q5_1.data[ib].qs[2]; q3 = u_q5_1.data[ib].qs[3]; + } else { + dm = vec2(a_q5_1.data[ib].dm); qh = a_q5_1.data[ib].qh >> (half_i * 16u); + q0 = a_q5_1.data[ib].qs[0]; q1 = a_q5_1.data[ib].qs[1]; q2 = a_q5_1.data[ib].qs[2]; q3 = a_q5_1.data[ib].qs[3]; + } + const vec4 d = vec4(dm.x), m = vec4(dm.y); + const vec4 h0 = vec4(((qh >> 0u) & 1u) << 4u, ((qh >> 1u) & 1u) << 4u, ((qh >> 2u) & 1u) << 4u, ((qh >> 3u) & 1u) << 4u); + const vec4 h1 = vec4(((qh >> 4u) & 1u) << 4u, ((qh >> 5u) & 1u) << 4u, ((qh >> 6u) & 1u) << 4u, ((qh >> 7u) & 1u) << 4u); + const vec4 h2 = vec4(((qh >> 8u) & 1u) << 4u, ((qh >> 9u) & 1u) << 4u, ((qh >>10u) & 1u) << 4u, ((qh >>11u) & 1u) << 4u); + const vec4 h3 = vec4(((qh >>12u) & 1u) << 4u, ((qh >>13u) & 1u) << 4u, ((qh >>14u) & 1u) << 4u, ((qh >>15u) & 1u) << 4u); + w0 = f16vec4(fma(d, vec4(unpack8((q0 >> shift) & 0x0F0F0F0Fu)) + h0, m)); + w1 = f16vec4(fma(d, vec4(unpack8((q1 >> shift) & 0x0F0F0F0Fu)) + h1, m)); + w2 = f16vec4(fma(d, vec4(unpack8((q2 >> shift) & 0x0F0F0F0Fu)) + h2, m)); + w3 = f16vec4(fma(d, vec4(unpack8((q3 >> shift) & 0x0F0F0F0Fu)) + h3, m)); +#elif defined(DATA_A_Q4_K) +#ifdef REPACK_PLANAR + const uint sb_u4 = (row_unit_base + (ci >> 4u)) * REPACK_Q4_K_SB_U4; + const uint il = ci & 15u; + const uint is = il >> 1u; + const uint shift = (is & 1u) * 4u; + const uint sub = il >> 2u; + const uint w_lo = (il & 1u) << 2u; + const uvec4 hdr = use_u ? u_u4.data[sb_u4 + REPACK_HDR_OFF_U4] : a_u4.data[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 loadd = unpackHalf2x16(hdr.x); + const uint scalesoffs = (is & 3u) * 8u; + const uint scidxshift1 = (is < 4u) ? scalesoffs : (scalesoffs + 2u); + const uint mbidxshift0 = (is < 4u) ? scalesoffs : (scalesoffs + 4u); + const uint sc_word = (is < 4u) ? hdr.y : hdr.w; + const uint mb_word = (is < 4u) ? hdr.z : hdr.w; + const uint sc = ((sc_word >> scalesoffs) & 0xFu) | ((hdr.y >> scidxshift1) & 0x30u); + const uint mbyte = ((mb_word >> mbidxshift0) & 0xFu) | ((hdr.z >> scidxshift1) & 0x30u); + const uint q_base = ((sb_u4 + REPACK_QS_OFF_U4 + w_lo) << 2u) + sub; + const uint q0 = use_u ? u_u32.data[q_base + 0u] : a_u32.data[q_base + 0u]; + const uint q1 = use_u ? u_u32.data[q_base + 4u] : a_u32.data[q_base + 4u]; + const uint q2 = use_u ? u_u32.data[q_base + 8u] : a_u32.data[q_base + 8u]; + const uint q3 = use_u ? u_u32.data[q_base + 12u] : a_u32.data[q_base + 12u]; + const f16vec4 d = f16vec4(loadd.x * float(sc)); + const f16vec4 m = f16vec4(-loadd.y * float(mbyte)); + w0 = fma(d, repack_magic_u4_h(q0 >> shift), m); + w1 = fma(d, repack_magic_u4_h(q1 >> shift), m); + w2 = fma(d, repack_magic_u4_h(q2 >> shift), m); + w3 = fma(d, repack_magic_u4_h(q3 >> shift), m); +#else + const uint ib = row_unit_base + (ci >> 4u); + const uint il = ci & 15u; + const uint is = il >> 1u; + const uint b = is & 1u; + const uint n = il >> 2u; + const uint w_idx = (n << 3u) + ((il & 1u) << 2u); + vec2 loadd; + uvec3 scales; + uint q0, q1, q2, q3; + if (use_u) { + loadd = vec2(u_q4_k.data[ib].dm); + scales = uvec3(u_q4_k_p32.data[ib].scales[0], u_q4_k_p32.data[ib].scales[1], u_q4_k_p32.data[ib].scales[2]); + q0 = u_q4_k_p32.data[ib].qs[w_idx + 0u]; q1 = u_q4_k_p32.data[ib].qs[w_idx + 1u]; + q2 = u_q4_k_p32.data[ib].qs[w_idx + 2u]; q3 = u_q4_k_p32.data[ib].qs[w_idx + 3u]; + } else { + loadd = vec2(a_q4_k.data[ib].dm); + scales = uvec3(a_q4_k_p32.data[ib].scales[0], a_q4_k_p32.data[ib].scales[1], a_q4_k_p32.data[ib].scales[2]); + q0 = a_q4_k_p32.data[ib].qs[w_idx + 0u]; q1 = a_q4_k_p32.data[ib].qs[w_idx + 1u]; + q2 = a_q4_k_p32.data[ib].qs[w_idx + 2u]; q3 = a_q4_k_p32.data[ib].qs[w_idx + 3u]; + } + const uint scalesoffs = (is & 3u) * 8u; + const uint scidxshift1 = (is < 4u) ? scalesoffs : (scalesoffs + 2u); + const uint mbidxshift0 = (is < 4u) ? scalesoffs : (scalesoffs + 4u); + const uint sc_word = (is < 4u) ? scales.x : scales.z; + const uint mb_word = (is < 4u) ? scales.y : scales.z; + const uint sc = ((sc_word >> scalesoffs) & 0xFu) | ((scales.x >> scidxshift1) & 0x30u); + const uint mbyte = ((mb_word >> mbidxshift0) & 0xFu) | ((scales.y >> scidxshift1) & 0x30u); + const float d_hi = (b == 0u) ? loadd.x : (loadd.x * 0.0625f); + const uint q_mk = (b == 0u) ? 0x0F0F0F0Fu : 0xF0F0F0F0u; + const f16vec4 d = f16vec4(d_hi * float(sc)); + const f16vec4 m = f16vec4(-loadd.y * float(mbyte)); + w0 = fma(d, f16vec4(unpack8(q0 & q_mk)), m); + w1 = fma(d, f16vec4(unpack8(q1 & q_mk)), m); + w2 = fma(d, f16vec4(unpack8(q2 & q_mk)), m); + w3 = fma(d, f16vec4(unpack8(q3 & q_mk)), m); +#endif +#elif defined(DATA_A_Q5_K) +#ifdef REPACK_PLANAR + const uint sb_u4 = (row_unit_base + (ci >> 4u)) * REPACK_Q5_K_SB_U4; + const uint il = ci & 15u; + const uint is = il >> 1u; + const uint shift = (is & 1u) * 4u; + const uint sub = il >> 2u; + const uint w_lo = (il & 1u) << 2u; + const uvec4 hdr = use_u ? u_u4.data[sb_u4 + REPACK_HDR_OFF_U4] : a_u4.data[sb_u4 + REPACK_HDR_OFF_U4]; + const vec2 loadd = unpackHalf2x16(hdr.x); + const uint scalesoffs = (is & 3u) * 8u; + const uint scidxshift1 = (is < 4u) ? scalesoffs : (scalesoffs + 2u); + const uint mbidxshift0 = (is < 4u) ? scalesoffs : (scalesoffs + 4u); + const uint sc_word = (is < 4u) ? hdr.y : hdr.w; + const uint mb_word = (is < 4u) ? hdr.z : hdr.w; + const uint sc = ((sc_word >> scalesoffs) & 0xFu) | ((hdr.y >> scidxshift1) & 0x30u); + const uint mbyte = ((mb_word >> mbidxshift0) & 0xFu) | ((hdr.z >> scidxshift1) & 0x30u); + const uint q_base = ((sb_u4 + REPACK_QS_OFF_U4 + w_lo) << 2u) + sub; + const uint qh_base = (sb_u4 << 2u) + REPACK_Q5_K_QH_OFF_U32 + w_lo; + const uint ql0 = use_u ? u_u32.data[q_base + 0u] : a_u32.data[q_base + 0u]; + const uint ql1 = use_u ? u_u32.data[q_base + 4u] : a_u32.data[q_base + 4u]; + const uint ql2 = use_u ? u_u32.data[q_base + 8u] : a_u32.data[q_base + 8u]; + const uint ql3 = use_u ? u_u32.data[q_base + 12u] : a_u32.data[q_base + 12u]; + const uint qh0 = use_u ? u_u32.data[qh_base + 0u] : a_u32.data[qh_base + 0u]; + const uint qh1 = use_u ? u_u32.data[qh_base + 1u] : a_u32.data[qh_base + 1u]; + const uint qh2 = use_u ? u_u32.data[qh_base + 2u] : a_u32.data[qh_base + 2u]; + const uint qh3 = use_u ? u_u32.data[qh_base + 3u] : a_u32.data[qh_base + 3u]; + const bool qh_left = (is <= 4u); + const uint qh_sh = qh_left ? (4u - is) : (is - 4u); + const uint sh_13 = is + 4u; + const f16vec4 d = f16vec4(loadd.x * float(sc)); + const f16vec4 m = f16vec4(-loadd.y * float(mbyte)); + w0 = fma(d, repack_magic_u5_h(((ql0 >> shift) & 0x000F000Fu) | ((qh_left ? (qh0 << qh_sh) : (qh0 >> qh_sh)) & 0x00100010u), ((ql0 >> (shift + 8u)) & 0x000F000Fu) | ((qh0 >> sh_13) & 0x00100010u)), m); + w1 = fma(d, repack_magic_u5_h(((ql1 >> shift) & 0x000F000Fu) | ((qh_left ? (qh1 << qh_sh) : (qh1 >> qh_sh)) & 0x00100010u), ((ql1 >> (shift + 8u)) & 0x000F000Fu) | ((qh1 >> sh_13) & 0x00100010u)), m); + w2 = fma(d, repack_magic_u5_h(((ql2 >> shift) & 0x000F000Fu) | ((qh_left ? (qh2 << qh_sh) : (qh2 >> qh_sh)) & 0x00100010u), ((ql2 >> (shift + 8u)) & 0x000F000Fu) | ((qh2 >> sh_13) & 0x00100010u)), m); + w3 = fma(d, repack_magic_u5_h(((ql3 >> shift) & 0x000F000Fu) | ((qh_left ? (qh3 << qh_sh) : (qh3 >> qh_sh)) & 0x00100010u), ((ql3 >> (shift + 8u)) & 0x000F000Fu) | ((qh3 >> sh_13) & 0x00100010u)), m); +#else + const uint ib = row_unit_base + (ci >> 4u); + const uint il = ci & 15u; + const uint is = il >> 1u; + const uint b = is & 1u; + const uint n = il >> 2u; + const uint w_idx = (n << 3u) + ((il & 1u) << 2u); + const uint qh_idx = (il & 1u) << 2u; + vec2 loadd; + uvec3 scales; + uint ql0, ql1, ql2, ql3, qh0, qh1, qh2, qh3; + if (use_u) { + loadd = vec2(u_q5_k.data[ib].dm); + scales = uvec3(u_q5_k_p32.data[ib].scales[0], u_q5_k_p32.data[ib].scales[1], u_q5_k_p32.data[ib].scales[2]); + ql0 = u_q5_k_p32.data[ib].qs[w_idx + 0u]; ql1 = u_q5_k_p32.data[ib].qs[w_idx + 1u]; + ql2 = u_q5_k_p32.data[ib].qs[w_idx + 2u]; ql3 = u_q5_k_p32.data[ib].qs[w_idx + 3u]; + qh0 = u_q5_k_p32.data[ib].qh[qh_idx + 0u]; qh1 = u_q5_k_p32.data[ib].qh[qh_idx + 1u]; + qh2 = u_q5_k_p32.data[ib].qh[qh_idx + 2u]; qh3 = u_q5_k_p32.data[ib].qh[qh_idx + 3u]; + } else { + loadd = vec2(a_q5_k.data[ib].dm); + scales = uvec3(a_q5_k_p32.data[ib].scales[0], a_q5_k_p32.data[ib].scales[1], a_q5_k_p32.data[ib].scales[2]); + ql0 = a_q5_k_p32.data[ib].qs[w_idx + 0u]; ql1 = a_q5_k_p32.data[ib].qs[w_idx + 1u]; + ql2 = a_q5_k_p32.data[ib].qs[w_idx + 2u]; ql3 = a_q5_k_p32.data[ib].qs[w_idx + 3u]; + qh0 = a_q5_k_p32.data[ib].qh[qh_idx + 0u]; qh1 = a_q5_k_p32.data[ib].qh[qh_idx + 1u]; + qh2 = a_q5_k_p32.data[ib].qh[qh_idx + 2u]; qh3 = a_q5_k_p32.data[ib].qh[qh_idx + 3u]; + } + const uint scalesoffs = (is & 3u) * 8u; + const uint scidxshift1 = (is < 4u) ? scalesoffs : (scalesoffs + 2u); + const uint mbidxshift0 = (is < 4u) ? scalesoffs : (scalesoffs + 4u); + const uint sc_word = (is < 4u) ? scales.x : scales.z; + const uint mb_word = (is < 4u) ? scales.y : scales.z; + const uint sc = ((sc_word >> scalesoffs) & 0xFu) | ((scales.x >> scidxshift1) & 0x30u); + const uint mbyte = ((mb_word >> mbidxshift0) & 0xFu) | ((scales.y >> scidxshift1) & 0x30u); + const f16vec4 d = f16vec4(loadd.x * float(sc)); + const f16vec4 m = f16vec4(-loadd.y * float(mbyte)); + const uint shift = b * 4u; + const bool qh_left = (is <= 4u); + const uint qh_sh = qh_left ? (4u - is) : (is - 4u); + const uint qhb0 = (qh_left ? (qh0 << qh_sh) : (qh0 >> qh_sh)) & 0x10101010u; + const uint qhb1 = (qh_left ? (qh1 << qh_sh) : (qh1 >> qh_sh)) & 0x10101010u; + const uint qhb2 = (qh_left ? (qh2 << qh_sh) : (qh2 >> qh_sh)) & 0x10101010u; + const uint qhb3 = (qh_left ? (qh3 << qh_sh) : (qh3 >> qh_sh)) & 0x10101010u; + w0 = fma(d, f16vec4(unpack8(((ql0 >> shift) & 0x0F0F0F0Fu) | qhb0)), m); + w1 = fma(d, f16vec4(unpack8(((ql1 >> shift) & 0x0F0F0F0Fu) | qhb1)), m); + w2 = fma(d, f16vec4(unpack8(((ql2 >> shift) & 0x0F0F0F0Fu) | qhb2)), m); + w3 = fma(d, f16vec4(unpack8(((ql3 >> shift) & 0x0F0F0F0Fu) | qhb3)), m); +#endif +#elif defined(DATA_A_Q6_K) +#ifdef REPACK_PLANAR + const uint sb_u4 = (row_unit_base + (ci >> 4u)) * REPACK_Q6_K_SB_U4; + const uint sb_u32 = sb_u4 << 2u; + const uint il = ci & 15u; + const uint h = il >> 3u; + const uint sh_n = ((il >> 2u) & 1u) * 4u; + const uint qhshift = ((il >> 1u) & 3u) * 2u; + const uint q_comp = (h << 1u) | ((il >> 1u) & 1u); + const uint w_lo = (il & 1u) << 2u; + const float d_f = unpackHalf2x16(use_u ? u_u32.data[sb_u32 + REPACK_Q6_K_D_OFF_U32] : a_u32.data[sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; + const uint sc_word = use_u ? u_u32.data[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + (il >> 2u)] : a_u32.data[sb_u32 + REPACK_Q6_K_SC_OFF_U32 + (il >> 2u)]; + const float16_t sc = float16_t(d_f * float(bitfieldExtract(int(sc_word), int((il & 3u) * 8u), 8))); + const uint q_base = ((sb_u4 + REPACK_Q6_K_QL_OFF_U4 + w_lo) << 2u) + q_comp; + const uint qh_base = sb_u32 + REPACK_Q6_K_QH_OFF_U32 + w_lo * 2u + h; + const uint ql0 = use_u ? u_u32.data[q_base + 0u] : a_u32.data[q_base + 0u]; + const uint ql1 = use_u ? u_u32.data[q_base + 4u] : a_u32.data[q_base + 4u]; + const uint ql2 = use_u ? u_u32.data[q_base + 8u] : a_u32.data[q_base + 8u]; + const uint ql3 = use_u ? u_u32.data[q_base + 12u] : a_u32.data[q_base + 12u]; + const uint qh0 = (use_u ? u_u32.data[qh_base + 0u] : a_u32.data[qh_base + 0u]) >> qhshift; + const uint qh1 = (use_u ? u_u32.data[qh_base + 2u] : a_u32.data[qh_base + 2u]) >> qhshift; + const uint qh2 = (use_u ? u_u32.data[qh_base + 4u] : a_u32.data[qh_base + 4u]) >> qhshift; + const uint qh3 = (use_u ? u_u32.data[qh_base + 6u] : a_u32.data[qh_base + 6u]) >> qhshift; + const f16vec4 dv = f16vec4(sc); + w0 = repack_magic_q6_h(((ql0 >> sh_n) & 0x000F000Fu) | ((qh0 & 0x00030003u) << 4u), ((ql0 >> (sh_n + 8u)) & 0x000F000Fu) | ((qh0 >> 4u) & 0x00300030u)) * dv; + w1 = repack_magic_q6_h(((ql1 >> sh_n) & 0x000F000Fu) | ((qh1 & 0x00030003u) << 4u), ((ql1 >> (sh_n + 8u)) & 0x000F000Fu) | ((qh1 >> 4u) & 0x00300030u)) * dv; + w2 = repack_magic_q6_h(((ql2 >> sh_n) & 0x000F000Fu) | ((qh2 & 0x00030003u) << 4u), ((ql2 >> (sh_n + 8u)) & 0x000F000Fu) | ((qh2 >> 4u) & 0x00300030u)) * dv; + w3 = repack_magic_q6_h(((ql3 >> sh_n) & 0x000F000Fu) | ((qh3 & 0x00030003u) << 4u), ((ql3 >> (sh_n + 8u)) & 0x000F000Fu) | ((qh3 >> 4u) & 0x00300030u)) * dv; +#else + const uint ib = row_unit_base + (ci >> 4u); + const uint il = ci & 15u; + const uint b = ((il >> 2u) & 1u) * 4u; + const uint qhshift = ((il >> 1u) & 3u) * 2u; + const uint qsi = ((il & 8u) << 2u) + ((il & 3u) << 3u); + const uint qhi = ((il & 8u) << 1u) + ((il & 1u) << 3u); + float dscale; + uint ql01, ql23, ql45, ql67, qh01, qh23, qh45, qh67; + if (use_u) { + dscale = float(u_q6_k.data[ib].d) * float(u_q6_k.data[ib].scales[il]); + ql01 = ((uint(u_q6_k_p16.data[ib].ql[qsi + 0u]) | (uint(u_q6_k_p16.data[ib].ql[qsi + 1u]) << 16u)) >> b) & 0x0F0F0F0Fu; + ql23 = ((uint(u_q6_k_p16.data[ib].ql[qsi + 2u]) | (uint(u_q6_k_p16.data[ib].ql[qsi + 3u]) << 16u)) >> b) & 0x0F0F0F0Fu; + ql45 = ((uint(u_q6_k_p16.data[ib].ql[qsi + 4u]) | (uint(u_q6_k_p16.data[ib].ql[qsi + 5u]) << 16u)) >> b) & 0x0F0F0F0Fu; + ql67 = ((uint(u_q6_k_p16.data[ib].ql[qsi + 6u]) | (uint(u_q6_k_p16.data[ib].ql[qsi + 7u]) << 16u)) >> b) & 0x0F0F0F0Fu; + qh01 = ((uint(u_q6_k_p16.data[ib].qh[qhi + 0u]) | (uint(u_q6_k_p16.data[ib].qh[qhi + 1u]) << 16u)) >> qhshift) & 0x03030303u; + qh23 = ((uint(u_q6_k_p16.data[ib].qh[qhi + 2u]) | (uint(u_q6_k_p16.data[ib].qh[qhi + 3u]) << 16u)) >> qhshift) & 0x03030303u; + qh45 = ((uint(u_q6_k_p16.data[ib].qh[qhi + 4u]) | (uint(u_q6_k_p16.data[ib].qh[qhi + 5u]) << 16u)) >> qhshift) & 0x03030303u; + qh67 = ((uint(u_q6_k_p16.data[ib].qh[qhi + 6u]) | (uint(u_q6_k_p16.data[ib].qh[qhi + 7u]) << 16u)) >> qhshift) & 0x03030303u; + } else { + dscale = float(a_q6_k.data[ib].d) * float(a_q6_k.data[ib].scales[il]); + ql01 = ((uint(a_q6_k_p16.data[ib].ql[qsi + 0u]) | (uint(a_q6_k_p16.data[ib].ql[qsi + 1u]) << 16u)) >> b) & 0x0F0F0F0Fu; + ql23 = ((uint(a_q6_k_p16.data[ib].ql[qsi + 2u]) | (uint(a_q6_k_p16.data[ib].ql[qsi + 3u]) << 16u)) >> b) & 0x0F0F0F0Fu; + ql45 = ((uint(a_q6_k_p16.data[ib].ql[qsi + 4u]) | (uint(a_q6_k_p16.data[ib].ql[qsi + 5u]) << 16u)) >> b) & 0x0F0F0F0Fu; + ql67 = ((uint(a_q6_k_p16.data[ib].ql[qsi + 6u]) | (uint(a_q6_k_p16.data[ib].ql[qsi + 7u]) << 16u)) >> b) & 0x0F0F0F0Fu; + qh01 = ((uint(a_q6_k_p16.data[ib].qh[qhi + 0u]) | (uint(a_q6_k_p16.data[ib].qh[qhi + 1u]) << 16u)) >> qhshift) & 0x03030303u; + qh23 = ((uint(a_q6_k_p16.data[ib].qh[qhi + 2u]) | (uint(a_q6_k_p16.data[ib].qh[qhi + 3u]) << 16u)) >> qhshift) & 0x03030303u; + qh45 = ((uint(a_q6_k_p16.data[ib].qh[qhi + 4u]) | (uint(a_q6_k_p16.data[ib].qh[qhi + 5u]) << 16u)) >> qhshift) & 0x03030303u; + qh67 = ((uint(a_q6_k_p16.data[ib].qh[qhi + 6u]) | (uint(a_q6_k_p16.data[ib].qh[qhi + 7u]) << 16u)) >> qhshift) & 0x03030303u; + } + const f16vec4 dv = f16vec4(dscale); + const f16vec4 mv = f16vec4(-32.0f * dscale); + w0 = fma(f16vec4(unpack8(ql01 | (qh01 << 4u))), dv, mv); + w1 = fma(f16vec4(unpack8(ql23 | (qh23 << 4u))), dv, mv); + w2 = fma(f16vec4(unpack8(ql45 | (qh45 << 4u))), dv, mv); + w3 = fma(f16vec4(unpack8(ql67 | (qh67 << 4u))), dv, mv); +#endif +#elif defined(DATA_A_IQ4_XS) + const uint ib = row_unit_base + (ci >> 4u); + const uint il = ci & 15u; + const uint ib32 = il >> 1u; + const uint shift = (il & 1u) * 4u; + const uint qbase = ib32 << 2u; + float dl; + uint r0, r1, r2, r3; + if (use_u) { + const uint sl = (uint(u_iq4_xs.data[ib].scales_l[ib32 >> 1u]) >> (4u * (ib32 & 1u))) & 0xFu; + const uint sh = (uint(u_iq4_xs.data[ib].scales_h) >> (2u * ib32)) & 3u; + dl = float(u_iq4_xs.data[ib].d) * float(int(sl | (sh << 4u)) - 32); + r0 = u_iq4_xs_p32.data[ib].qs[qbase + 0u]; r1 = u_iq4_xs_p32.data[ib].qs[qbase + 1u]; + r2 = u_iq4_xs_p32.data[ib].qs[qbase + 2u]; r3 = u_iq4_xs_p32.data[ib].qs[qbase + 3u]; + } else { + const uint sl = (uint(a_iq4_xs.data[ib].scales_l[ib32 >> 1u]) >> (4u * (ib32 & 1u))) & 0xFu; + const uint sh = (uint(a_iq4_xs.data[ib].scales_h) >> (2u * ib32)) & 3u; + dl = float(a_iq4_xs.data[ib].d) * float(int(sl | (sh << 4u)) - 32); + r0 = a_iq4_xs_p32.data[ib].qs[qbase + 0u]; r1 = a_iq4_xs_p32.data[ib].qs[qbase + 1u]; + r2 = a_iq4_xs_p32.data[ib].qs[qbase + 2u]; r3 = a_iq4_xs_p32.data[ib].qs[qbase + 3u]; + } + const u8vec4 q0 = unpack8((r0 >> shift) & 0x0F0F0F0Fu); + const u8vec4 q1 = unpack8((r1 >> shift) & 0x0F0F0F0Fu); + const u8vec4 q2 = unpack8((r2 >> shift) & 0x0F0F0F0Fu); + const u8vec4 q3 = unpack8((r3 >> shift) & 0x0F0F0F0Fu); + w0 = f16vec4(dl * vec4(iq4nl_lut(q0.x), iq4nl_lut(q0.y), iq4nl_lut(q0.z), iq4nl_lut(q0.w))); + w1 = f16vec4(dl * vec4(iq4nl_lut(q1.x), iq4nl_lut(q1.y), iq4nl_lut(q1.z), iq4nl_lut(q1.w))); + w2 = f16vec4(dl * vec4(iq4nl_lut(q2.x), iq4nl_lut(q2.y), iq4nl_lut(q2.z), iq4nl_lut(q2.w))); + w3 = f16vec4(dl * vec4(iq4nl_lut(q3.x), iq4nl_lut(q3.y), iq4nl_lut(q3.z), iq4nl_lut(q3.w))); +#elif defined(DATA_A_IQ4_NL) + const uint ib = row_unit_base + (ci >> 1u); + const uint shift = (ci & 1u) * 4u; + float d; + uint r0, r1, r2, r3; + if (use_u) { + d = float(u_iq4_nl.data[ib].d); + r0 = (uint(u_iq4_nl.data[ib].qs[0]) | (uint(u_iq4_nl.data[ib].qs[1]) << 16u)); + r1 = (uint(u_iq4_nl.data[ib].qs[2]) | (uint(u_iq4_nl.data[ib].qs[3]) << 16u)); + r2 = (uint(u_iq4_nl.data[ib].qs[4]) | (uint(u_iq4_nl.data[ib].qs[5]) << 16u)); + r3 = (uint(u_iq4_nl.data[ib].qs[6]) | (uint(u_iq4_nl.data[ib].qs[7]) << 16u)); + } else { + d = float(a_iq4_nl.data[ib].d); + r0 = (uint(a_iq4_nl.data[ib].qs[0]) | (uint(a_iq4_nl.data[ib].qs[1]) << 16u)); + r1 = (uint(a_iq4_nl.data[ib].qs[2]) | (uint(a_iq4_nl.data[ib].qs[3]) << 16u)); + r2 = (uint(a_iq4_nl.data[ib].qs[4]) | (uint(a_iq4_nl.data[ib].qs[5]) << 16u)); + r3 = (uint(a_iq4_nl.data[ib].qs[6]) | (uint(a_iq4_nl.data[ib].qs[7]) << 16u)); + } + const u8vec4 q0 = unpack8((r0 >> shift) & 0x0F0F0F0Fu); + const u8vec4 q1 = unpack8((r1 >> shift) & 0x0F0F0F0Fu); + const u8vec4 q2 = unpack8((r2 >> shift) & 0x0F0F0F0Fu); + const u8vec4 q3 = unpack8((r3 >> shift) & 0x0F0F0F0Fu); + w0 = f16vec4(d * vec4(iq4nl_lut(q0.x), iq4nl_lut(q0.y), iq4nl_lut(q0.z), iq4nl_lut(q0.w))); + w1 = f16vec4(d * vec4(iq4nl_lut(q1.x), iq4nl_lut(q1.y), iq4nl_lut(q1.z), iq4nl_lut(q1.w))); + w2 = f16vec4(d * vec4(iq4nl_lut(q2.x), iq4nl_lut(q2.y), iq4nl_lut(q2.z), iq4nl_lut(q2.w))); + w3 = f16vec4(d * vec4(iq4nl_lut(q3.x), iq4nl_lut(q3.y), iq4nl_lut(q3.z), iq4nl_lut(q3.w))); +#elif defined(DATA_A_NVFP4) + const uint sub = ci & 3u; + uint d_u32, q0, q1; +#ifdef REPACK_PLANAR + const uint b_in_slice = (row_unit_base - g_mma_slice_blk_base) + (ci >> 2u); + uint s_blks = p.batch_stride_a >> 6u; +#ifndef MUL_MAT_ID + if (FUSE_MODE == 2u && use_u) { + s_blks = (p.K >> 6u) * (p.M - p.pair_m0); + } else if (FUSE_MODE == 2u) { + s_blks = (p.K >> 6u) * p.pair_m0; + } +#endif + const uint slice_u32 = g_mma_slice_blk_base * 9u; + const uint slice_u2 = slice_u32 >> 1u; + if (use_u) { + d_u32 = u_u32.data[slice_u32 + s_blks * 8u + b_in_slice]; + const uvec2 q01 = u_u2.data[slice_u2 + b_in_slice * 4u + sub]; + q0 = q01.x; q1 = q01.y; + } else { + d_u32 = a_u32.data[slice_u32 + s_blks * 8u + b_in_slice]; + const uvec2 q01 = a_u2.data[slice_u2 + b_in_slice * 4u + sub]; + q0 = q01.x; q1 = q01.y; + } +#else + const uint ib = row_unit_base + (ci >> 2u); + if (use_u) { + d_u32 = u_nvfp4.data[ib].d[0]; + q0 = u_nvfp4.data[ib].qs[2u * sub + 0u]; + q1 = u_nvfp4.data[ib].qs[2u * sub + 1u]; + } else { + d_u32 = a_nvfp4.data[ib].d[0]; + q0 = a_nvfp4.data[ib].qs[2u * sub + 0u]; + q1 = a_nvfp4.data[ib].qs[2u * sub + 1u]; + } +#endif + const uint du = (d_u32 >> (sub * 8u)) & 0xFFu; + const f16vec4 dv = f16vec4(float16_t(ue4m3_to_fp32_build(du))); + const f16vec2 e0_lo = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(q0)); + const f16vec2 o0_lo = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(q0 >> 8u)); + const f16vec2 e1_lo = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(q1)); + const f16vec2 o1_lo = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(q1 >> 8u)); + const f16vec2 e0_hi = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(q0 >> 4u)); + const f16vec2 o0_hi = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(q0 >> 12u)); + const f16vec2 e1_hi = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(q1 >> 4u)); + const f16vec2 o1_hi = unpackFloat2x16(nvfp4_e2m1_pair_fp16_bits(q1 >> 12u)); + w0 = dv * f16vec4(e0_lo.x, o0_lo.x, e0_lo.y, o0_lo.y); + w1 = dv * f16vec4(e1_lo.x, o1_lo.x, e1_lo.y, o1_lo.y); + w2 = dv * f16vec4(e0_hi.x, o0_hi.x, e0_hi.y, o0_hi.y); + w3 = dv * f16vec4(e1_hi.x, o1_hi.x, e1_hi.y, o1_hi.y); +#endif +} + +#ifdef MUL_MAT_ID +float mma_apply_id_epilogue(float val, uint expert_idx, u16vec2 row_idx, uint d_row, uint d_idx) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0u) { + val += data_aux0[expert_idx * p.stride_d + d_row]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0u) { + precise float v_exp = val * data_aux0[expert_idx]; + val = v_exp; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0) != 0u) { + const uint s0_idx = uint(row_idx.x) + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0_TOK) != 0u ? uint(row_idx.y) * p.nei0 : 0u); + val *= data_aux0[s0_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1) != 0u) { + const uint s1_idx = uint(row_idx.x) + ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1_TOK) != 0u ? uint(row_idx.y) * p.nei0 : 0u); + val *= data_aux1[s1_idx]; + } + if ((p.fusion_flags & (MAT_VEC_FUSION_FLAGS_GLU_A | MAT_VEC_FUSION_FLAGS_GLU_B)) != 0u) { + const float o = data_aux0[d_idx]; + val = ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_GLU_A) != 0u) + ? (val / (1.0f + exp(-val)) * o) + : (o / (1.0f + exp(-o)) * val); + } + return val; +} +#else +float mma_apply_dense_epilogue(float val, uint d_row, uint d_col, uint d_idx, bool is_pair_second) { + if (is_pair_second) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_PAIR_MM_SIGMOID1) != 0u) { + val = 1.0f / (1.0f + exp(-val)); + } + return val; + } + if (FUSE_MODE == 2u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE) != 0u) { + const float x = val + data_aux1[d_row]; + const float sp = (x > 20.0f) ? x : log(1.0f + exp(x)); + val = sp * data_aux2[d_row]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SIGMOID) != 0u) { + val = 1.0f / (1.0f + exp(-val)); + } + return val; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0u) { + val += data_aux0[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS1) != 0u) { + val += data_aux1[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SIGMOID) != 0u) { + val = 1.0f / (1.0f + exp(-val)); + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SOFTPLUS_GATE) != 0u) { + const float x = val + data_aux0[d_row]; + const float sp = (x > 20.0f) ? x : log(1.0f + exp(x)); + val = sp * data_aux1[d_row]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_ROW_SCALE0) != 0u) { + val *= data_aux0[d_col]; + } + if ((p.fusion_flags & (MAT_VEC_FUSION_FLAGS_GLU_A | MAT_VEC_FUSION_FLAGS_GLU_B)) != 0u) { + const float o = data_aux0[d_idx]; + val = ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_GLU_A) != 0u) + ? (val / (1.0f + exp(-val)) * o) + : (o / (1.0f + exp(-o)) * val); + } + return val; +} + +float mma_eval_lora0(uint row, uint col) { + if (FUSE_LORA == 0u) { return 0.0f; } + float acc = 0.0f; + if ((p.lora_r & 3u) == 0u) { + const uint r4 = p.lora_r >> 2u; + const uint b_off = row * r4; + const uint h_off = col * r4; + for (uint k4 = 0u; k4 < r4; ++k4) { + acc += dot(lora_b0_v4.data[b_off + k4], lora_h0_v4.data[h_off + k4]); + } + } else { + const uint b_off = row * p.lora_r; + const uint h_off = col * p.lora_r; + for (uint k = 0u; k < p.lora_r; ++k) { + acc = fma(lora_b0.data[b_off + k], lora_h0.data[h_off + k], acc); + } + } + return acc * p.lora_scale0; +} + +float mma_eval_lora1(uint row, uint col) { + if (FUSE_LORA == 0u) { return 0.0f; } + float acc = 0.0f; + if ((p.lora_r & 3u) == 0u) { + const uint r4 = p.lora_r >> 2u; + const uint b_off = row * r4; + const uint h_off = col * r4; + for (uint k4 = 0u; k4 < r4; ++k4) { + acc += dot(lora_b1_v4.data[b_off + k4], lora_h1_v4.data[h_off + k4]); + } + } else { + const uint b_off = row * p.lora_r; + const uint h_off = col * p.lora_r; + for (uint k = 0u; k < p.lora_r; ++k) { + acc = fma(lora_b1.data[b_off + k], lora_h1.data[h_off + k], acc); + } + } + return acc * p.lora_scale1; +} +#endif + +void main() { + const uint lane = gl_LocalInvocationID.x; + const uint sgitg = gl_LocalInvocationID.y; + const uint tid = sgitg * 32u + lane; + const uint sg_k = (CSG > 1u) ? 0u : (sgitg % NSG); + const uint sg_c = (CSG > 1u) ? (sgitg % CSG) : 0u; + const uint sg_m = (CSG > 1u) ? (sgitg / CSG) : (sgitg / NSG); + const uint sg_c_off = sg_c * (8u * RT); + const uint fm = mma_lane_fm(lane); + const uint fn = mma_lane_fn(lane); + + const uint wg_m0 = gl_WorkGroupID.x * (8u * NT * MSG); + const uint sg_m0 = wg_m0 + sg_m * (8u * NT); + + const uint stride_a_u = p.stride_a >> MMA_ELEM_SHIFT; + +#ifdef MUL_MAT_ID + const uint tile_idx = gl_WorkGroupID.y + gl_WorkGroupID.z * gl_NumWorkGroups.y; + if (tile_idx >= data_row_map[0]) { + return; + } + const uint expert_idx = data_row_map[1u + 2u * tile_idx]; + const uint row_begin = tile_idx * BN_COLS; + const uint tile_ne1 = data_row_map[2u + 2u * tile_idx]; + if (tile_ne1 == 0u || wg_m0 >= p.M) { + return; + } + const uint n_valid = tile_ne1; + const uint a_batch_base = expert_idx * (p.batch_stride_a >> MMA_ELEM_SHIFT); +#ifdef REPACK_PLANAR + g_mma_slice_blk_base = a_batch_base; +#endif + if (USE_SH_IDS) { + for (uint c_it = tid; c_it < BN_COLS; c_it += WG_THREADS) { + const uint c = min(c_it, tile_ne1 - 1u); + const uint packed = data_row_map[p.row_ids_offset + row_begin + c]; + const uint slot = packed & 0xFFFFu; + const uint tok = packed >> 16u; + sh_r_ids[c_it] = packed; + sh_b_base[c_it] = tok * p.batch_stride_b + (slot % p.ne11) * p.stride_b; + if (FUSE_MODE == 4u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0u) { + const uint s1_idx = slot + (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1_TOK) != 0u) ? (tok * p.nei0) : 0u); + sh_col_scale[c_it] = ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1) != 0u) ? data_aux1[s1_idx] : 1.0f; + } else { + const uint s0_idx = slot + (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0_TOK) != 0u) ? (tok * p.nei0) : 0u); + sh_col_scale[c_it] = data_aux0[s0_idx]; + } + } + } + barrier(); + } +#else + if (wg_m0 >= p.M) { + return; + } + const uint wg_n0 = gl_WorkGroupID.y * (8u * RT); + const uint n_valid = (wg_n0 < p.N) ? min(8u * RT, p.N - wg_n0) : 0u; + if (n_valid == 0u) { + return; + } + const uint batch_idx = gl_WorkGroupID.z + p.base_work_group_z; + const uint i13 = batch_idx / p.ne12; + const uint i12 = batch_idx % p.ne12; + const uint i03 = i13 / p.broadcast3; + const uint i02 = i12 / p.broadcast2; + const uint batch_idx_a = i03 * p.ne02 + i02; + const uint a_batch_base = batch_idx_a * (p.batch_stride_a >> MMA_ELEM_SHIFT); +#ifdef REPACK_PLANAR + g_mma_slice_blk_base = a_batch_base; +#endif + const uint b_batch_base = batch_idx * p.batch_stride_b; +#endif + + uint a_row_base[NT]; + uint u_row_base[NT]; + bool tile_second[NT]; +#ifdef MUL_MAT_ID + const uint u_row_off = (FUSE_MODE == 3u && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u) ? (p.M * stride_a_u) : 0u; +#else + const uint u_row_off = 0u; +#endif + [[unroll]] for (uint t = 0u; t < NT; ++t) { + const uint tile_r = sg_m0 + 8u * t; +#ifndef MUL_MAT_ID + if (FUSE_MODE == 2u && tile_r >= p.pair_m0) { + tile_second[t] = true; + const uint m1 = p.M - p.pair_m0; + const uint r1 = min(tile_r - p.pair_m0 + fm, m1 - 1u); + a_row_base[t] = a_batch_base + r1 * stride_a_u; + } else if (FUSE_MODE == 2u) { + tile_second[t] = false; + const uint r0 = min(tile_r + fm, p.pair_m0 - 1u); + a_row_base[t] = a_batch_base + r0 * stride_a_u; + } else +#endif + { + tile_second[t] = false; + const uint r0 = min(tile_r + fm, p.M - 1u); + a_row_base[t] = a_batch_base + r0 * stride_a_u; + } + u_row_base[t] = a_row_base[t] + u_row_off; + } + + coopmat mc[RT][NT]; + coopmat mc_u[RT][NT]; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + [[unroll]] for (uint t = 0u; t < NT; ++t) { + mc[rt][t] = coopmat(0.0f); + mc_u[rt][t] = coopmat(0.0f); + } + } + + const bool b_is_f16 = (B_IS_F16 != 0u); + + // Cooperative B-tile path when MSG > 1 && USE_SH_B != 0 (NSG == 1, CSG == 1, K % 64 == 0) + if (MSG > 1u && USE_SH_B != 0u) { + const bool v4_ok = ((p.stride_b & 3u) == 0u) && ((p.batch_stride_b & 3u) == 0u); + const uint k4_lane_base = 4u * (fm >> 1u) + 2u * (fm & 1u); + +#define MMA_SG_FENCE() controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease) +#define MMA_NO_FENCE() do {} while (false) + +#define MMA_ACCUM_SHB_1D(ACC_VEC, SUB_OFF, W0, W1, W2, W3) \ + do { \ + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { \ + if (rt == 0u || (8u * rt < n_valid)) { \ + const uint c0 = 8u * rt + fn + 0u; \ + const uint c1 = 8u * rt + fn + 1u; \ + const MMA_FVEC4 ba0 = sh_b[c0][(SUB_OFF) + k4_lane_base + 0u]; \ + const MMA_FVEC4 ba1 = sh_b[c0][(SUB_OFF) + k4_lane_base + 1u]; \ + const MMA_FVEC4 bb0 = sh_b[c1][(SUB_OFF) + k4_lane_base + 0u]; \ + const MMA_FVEC4 bb1 = sh_b[c1][(SUB_OFF) + k4_lane_base + 1u]; \ + [[unroll]] for (uint s = 0u; s < 4u; ++s) { \ + coopmat ma0, ma1; \ + coopmat mb0, mb1; \ + ma0[0] = (W0)[s]; ma0[1] = (W2)[s]; \ + ma1[0] = (W1)[s]; ma1[1] = (W3)[s]; \ + mb0[0] = ba0[s]; mb0[1] = bb0[s]; \ + mb1[0] = ba1[s]; mb1[1] = bb1[s]; \ + ACC_VEC[rt] = coopMatMulAdd(ma0, mb0, ACC_VEC[rt]); \ + ACC_VEC[rt] = coopMatMulAdd(ma1, mb1, ACC_VEC[rt]); \ + } \ + } \ + } \ + } while (false) + +#define MMA_ACCUM_SHB(MC_ARR, SUB_OFF, W0, W1, W2, W3) \ + do { \ + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { \ + if (use_sg_fence) { MMA_SG_FENCE(); } \ + if (rt == 0u || (8u * rt < n_valid)) { \ + const uint c0 = 8u * rt + fn + 0u; \ + const uint c1 = 8u * rt + fn + 1u; \ + const MMA_FVEC4 ba0 = sh_b[c0][(SUB_OFF) + k4_lane_base + 0u]; \ + const MMA_FVEC4 ba1 = sh_b[c0][(SUB_OFF) + k4_lane_base + 1u]; \ + const MMA_FVEC4 bb0 = sh_b[c1][(SUB_OFF) + k4_lane_base + 0u]; \ + const MMA_FVEC4 bb1 = sh_b[c1][(SUB_OFF) + k4_lane_base + 1u]; \ + [[unroll]] for (uint s = 0u; s < 4u; ++s) { \ + coopmat ma0, ma1; \ + coopmat mb0, mb1; \ + ma0[0] = (W0)[s]; ma0[1] = (W2)[s]; \ + ma1[0] = (W1)[s]; ma1[1] = (W3)[s]; \ + mb0[0] = ba0[s]; mb0[1] = bb0[s]; \ + mb1[0] = ba1[s]; mb1[1] = bb1[s]; \ + MC_ARR[rt][t] = coopMatMulAdd(ma0, mb0, MC_ARR[rt][t]); \ + MC_ARR[rt][t] = coopMatMulAdd(ma1, mb1, MC_ARR[rt][t]); \ + } \ + } \ + } \ + } while (false) + +#if defined(DATA_A_Q4_K) +#ifdef REPACK_PLANAR +#define MMA_ACCUM_KPAIRS_GEN(LOOP_ATTR, FENCE_MACRO, TARGET_MACRO, TARGET_ARR, USE_U, ROW_BASE) \ + do { \ + FENCE_MACRO(); \ + const bool _mma_use_u = (USE_U); \ + const uint _mma_rbase = (ROW_BASE); \ + if (K_PAIRS == 1u || K_PAIRS == 2u || K_PAIRS == 4u) { \ + const uint _mma_sb_u4 = (_mma_rbase + ((g * K_PAIRS) >> 2u)) * REPACK_Q4_K_SB_U4; \ + const uint _mma_sub_base = (g * K_PAIRS) & 3u; \ + const uint _mma_fn2 = fn >> 1u; \ + const uint _mma_b = _mma_fn2 >> 1u; \ + const uint _mma_shift = _mma_b * 4u; \ + const uint _mma_w_lo = (_mma_fn2 & 1u) << 2u; \ + const uvec4 _mma_hdr = _mma_use_u ? u_u4.data[_mma_sb_u4 + REPACK_HDR_OFF_U4] \ + : a_u4.data[_mma_sb_u4 + REPACK_HDR_OFF_U4]; \ + const vec2 _mma_loadd = unpackHalf2x16(_mma_hdr.x); \ + const uint _mma_q_base_row = (_mma_sb_u4 + REPACK_QS_OFF_U4 + _mma_w_lo) << 2u; \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + const uint _mma_sub = _mma_sub_base + s_kp; \ + const uint _mma_is = (_mma_sub << 1u) | _mma_b; \ + const uint _mma_scalesoffs = (_mma_is & 3u) * 8u; \ + const uint _mma_scidxshift1 = (_mma_is < 4u) ? _mma_scalesoffs : (_mma_scalesoffs + 2u); \ + const uint _mma_mbidxshift0 = (_mma_is < 4u) ? _mma_scalesoffs : (_mma_scalesoffs + 4u); \ + const uint _mma_sc_word = (_mma_is < 4u) ? _mma_hdr.y : _mma_hdr.w; \ + const uint _mma_mb_word = (_mma_is < 4u) ? _mma_hdr.z : _mma_hdr.w; \ + const uint _mma_sc = ((_mma_sc_word >> _mma_scalesoffs) & 0xFu) \ + | ((_mma_hdr.y >> _mma_scidxshift1) & 0x30u); \ + const uint _mma_mbyte = ((_mma_mb_word >> _mma_mbidxshift0) & 0xFu) \ + | ((_mma_hdr.z >> _mma_scidxshift1) & 0x30u); \ + const uint _mma_q_base = _mma_q_base_row + _mma_sub; \ + uint q0, q1, q2, q3; \ + if (_mma_use_u) { \ + q0 = u_u32.data[_mma_q_base + 0u]; q1 = u_u32.data[_mma_q_base + 4u]; \ + q2 = u_u32.data[_mma_q_base + 8u]; q3 = u_u32.data[_mma_q_base + 12u]; \ + } else { \ + q0 = a_u32.data[_mma_q_base + 0u]; q1 = a_u32.data[_mma_q_base + 4u]; \ + q2 = a_u32.data[_mma_q_base + 8u]; q3 = a_u32.data[_mma_q_base + 12u]; \ + } \ + const f16vec4 d = f16vec4(_mma_loadd.x * float(_mma_sc)); \ + const f16vec4 m = f16vec4(-_mma_loadd.y * float(_mma_mbyte)); \ + const f16vec4 w0 = fma(d, repack_magic_u4_h(q0 >> _mma_shift), m); \ + const f16vec4 w1 = fma(d, repack_magic_u4_h(q1 >> _mma_shift), m); \ + const f16vec4 w2 = fma(d, repack_magic_u4_h(q2 >> _mma_shift), m); \ + const f16vec4 w3 = fma(d, repack_magic_u4_h(q3 >> _mma_shift), m); \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } else { \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + MMA_FVEC4 w0, w1, w2, w3; \ + dequant16(_mma_use_u, _mma_rbase, ((g * K_PAIRS + s_kp) << 2u) + (fn >> 1u), w0, w1, w2, w3); \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } \ + } while (false) +#else +#define MMA_ACCUM_KPAIRS_GEN(LOOP_ATTR, FENCE_MACRO, TARGET_MACRO, TARGET_ARR, USE_U, ROW_BASE) \ + do { \ + FENCE_MACRO(); \ + const uint ib = (ROW_BASE) + ((g * K_PAIRS) >> 2u); \ + const uint sub_base = (g * K_PAIRS) & 3u; \ + const uint fn2 = fn >> 1u; \ + const uint b = fn2 >> 1u; \ + const float d_hi = (b == 0u) ? 1.0f : 0.0625f; \ + const uint q_mk = (b == 0u) ? 0x0F0F0F0Fu : 0xF0F0F0F0u; \ + const uint w_lo = (fn2 & 1u) << 2u; \ + vec2 loadd; \ + uvec3 scales; \ + if (USE_U) { \ + loadd = vec2(u_q4_k.data[ib].dm); \ + scales = uvec3(u_q4_k_p32.data[ib].scales[0], u_q4_k_p32.data[ib].scales[1], u_q4_k_p32.data[ib].scales[2]); \ + } else { \ + loadd = vec2(a_q4_k.data[ib].dm); \ + scales = uvec3(a_q4_k_p32.data[ib].scales[0], a_q4_k_p32.data[ib].scales[1], a_q4_k_p32.data[ib].scales[2]); \ + } \ + const float dx = loadd.x * d_hi; \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + const uint sub = sub_base + s_kp; \ + const uint is = (sub << 1u) | b; \ + const uint scalesoffs = (is & 3u) * 8u; \ + const uint scidxshift1 = (is < 4u) ? scalesoffs : (scalesoffs + 2u); \ + const uint mbidxshift0 = (is < 4u) ? scalesoffs : (scalesoffs + 4u); \ + const uint sc_word = (is < 4u) ? scales.x : scales.z; \ + const uint mb_word = (is < 4u) ? scales.y : scales.z; \ + const uint sc = ((sc_word >> scalesoffs) & 0xFu) | ((scales.x >> scidxshift1) & 0x30u); \ + const uint mbyte = ((mb_word >> mbidxshift0) & 0xFu) | ((scales.y >> scidxshift1) & 0x30u); \ + const f16vec4 d = f16vec4(dx * float(sc)); \ + const f16vec4 m = f16vec4(-loadd.y * float(mbyte)); \ + const uint w_idx = (sub << 3u) + w_lo; \ + uint q0, q1, q2, q3; \ + if (USE_U) { \ + q0 = u_q4_k_p32.data[ib].qs[w_idx + 0u]; q1 = u_q4_k_p32.data[ib].qs[w_idx + 1u]; \ + q2 = u_q4_k_p32.data[ib].qs[w_idx + 2u]; q3 = u_q4_k_p32.data[ib].qs[w_idx + 3u]; \ + } else { \ + q0 = a_q4_k_p32.data[ib].qs[w_idx + 0u]; q1 = a_q4_k_p32.data[ib].qs[w_idx + 1u]; \ + q2 = a_q4_k_p32.data[ib].qs[w_idx + 2u]; q3 = a_q4_k_p32.data[ib].qs[w_idx + 3u]; \ + } \ + const f16vec4 w0 = fma(d, f16vec4(unpack8(q0 & q_mk)), m); \ + const f16vec4 w1 = fma(d, f16vec4(unpack8(q1 & q_mk)), m); \ + const f16vec4 w2 = fma(d, f16vec4(unpack8(q2 & q_mk)), m); \ + const f16vec4 w3 = fma(d, f16vec4(unpack8(q3 & q_mk)), m); \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } while (false) +#endif +#elif defined(DATA_A_Q5_K) +#ifdef REPACK_PLANAR +#define MMA_ACCUM_KPAIRS_GEN(LOOP_ATTR, FENCE_MACRO, TARGET_MACRO, TARGET_ARR, USE_U, ROW_BASE) \ + do { \ + FENCE_MACRO(); \ + const bool _mma_use_u = (USE_U); \ + const uint _mma_rbase = (ROW_BASE); \ + if (K_PAIRS == 1u || K_PAIRS == 2u || K_PAIRS == 4u) { \ + const uint _mma_sb_u4 = (_mma_rbase + ((g * K_PAIRS) >> 2u)) * REPACK_Q5_K_SB_U4; \ + const uint _mma_sub_base = (g * K_PAIRS) & 3u; \ + const uint _mma_fn2 = fn >> 1u; \ + const uint _mma_b = _mma_fn2 >> 1u; \ + const uint _mma_shift = _mma_b * 4u; \ + const uint _mma_w_lo = (_mma_fn2 & 1u) << 2u; \ + const uvec4 _mma_hdr = _mma_use_u ? u_u4.data[_mma_sb_u4 + REPACK_HDR_OFF_U4] \ + : a_u4.data[_mma_sb_u4 + REPACK_HDR_OFF_U4]; \ + const vec2 _mma_loadd = unpackHalf2x16(_mma_hdr.x); \ + const uvec4 _mma_qh_v = _mma_use_u \ + ? u_u4.data[_mma_sb_u4 + REPACK_Q5_K_QH_OFF_U4 + (_mma_fn2 & 1u)] \ + : a_u4.data[_mma_sb_u4 + REPACK_Q5_K_QH_OFF_U4 + (_mma_fn2 & 1u)]; \ + const uint _mma_qh0 = _mma_qh_v.x; \ + const uint _mma_qh1 = _mma_qh_v.y; \ + const uint _mma_qh2 = _mma_qh_v.z; \ + const uint _mma_qh3 = _mma_qh_v.w; \ + const uint _mma_q_base_row = (_mma_sb_u4 + REPACK_QS_OFF_U4 + _mma_w_lo) << 2u; \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + const uint _mma_sub = _mma_sub_base + s_kp; \ + const uint _mma_is = (_mma_sub << 1u) | _mma_b; \ + const uint _mma_scalesoffs = (_mma_is & 3u) * 8u; \ + const uint _mma_scidxshift1 = (_mma_is < 4u) ? _mma_scalesoffs : (_mma_scalesoffs + 2u); \ + const uint _mma_mbidxshift0 = (_mma_is < 4u) ? _mma_scalesoffs : (_mma_scalesoffs + 4u); \ + const uint _mma_sc_word = (_mma_is < 4u) ? _mma_hdr.y : _mma_hdr.w; \ + const uint _mma_mb_word = (_mma_is < 4u) ? _mma_hdr.z : _mma_hdr.w; \ + const uint _mma_sc = ((_mma_sc_word >> _mma_scalesoffs) & 0xFu) \ + | ((_mma_hdr.y >> _mma_scidxshift1) & 0x30u); \ + const uint _mma_mbyte = ((_mma_mb_word >> _mma_mbidxshift0) & 0xFu) \ + | ((_mma_hdr.z >> _mma_scidxshift1) & 0x30u); \ + const uint _mma_q_base = _mma_q_base_row + _mma_sub; \ + uint ql0, ql1, ql2, ql3; \ + if (_mma_use_u) { \ + ql0 = u_u32.data[_mma_q_base + 0u]; ql1 = u_u32.data[_mma_q_base + 4u]; \ + ql2 = u_u32.data[_mma_q_base + 8u]; ql3 = u_u32.data[_mma_q_base + 12u]; \ + } else { \ + ql0 = a_u32.data[_mma_q_base + 0u]; ql1 = a_u32.data[_mma_q_base + 4u]; \ + ql2 = a_u32.data[_mma_q_base + 8u]; ql3 = a_u32.data[_mma_q_base + 12u]; \ + } \ + const bool _mma_qh_left = (_mma_is <= 4u); \ + const uint _mma_qh_sh = _mma_qh_left ? (4u - _mma_is) : (_mma_is - 4u); \ + const uint _mma_sh_13 = _mma_is + 4u; \ + const f16vec4 d = f16vec4(_mma_loadd.x * float(_mma_sc)); \ + const f16vec4 m = f16vec4(-_mma_loadd.y * float(_mma_mbyte)); \ + const f16vec4 w0 = fma(d, repack_magic_u5_h(((ql0 >> _mma_shift) & 0x000F000Fu) | ((_mma_qh_left ? (_mma_qh0 << _mma_qh_sh) : (_mma_qh0 >> _mma_qh_sh)) & 0x00100010u), ((ql0 >> (_mma_shift + 8u)) & 0x000F000Fu) | ((_mma_qh0 >> _mma_sh_13) & 0x00100010u)), m); \ + const f16vec4 w1 = fma(d, repack_magic_u5_h(((ql1 >> _mma_shift) & 0x000F000Fu) | ((_mma_qh_left ? (_mma_qh1 << _mma_qh_sh) : (_mma_qh1 >> _mma_qh_sh)) & 0x00100010u), ((ql1 >> (_mma_shift + 8u)) & 0x000F000Fu) | ((_mma_qh1 >> _mma_sh_13) & 0x00100010u)), m); \ + const f16vec4 w2 = fma(d, repack_magic_u5_h(((ql2 >> _mma_shift) & 0x000F000Fu) | ((_mma_qh_left ? (_mma_qh2 << _mma_qh_sh) : (_mma_qh2 >> _mma_qh_sh)) & 0x00100010u), ((ql2 >> (_mma_shift + 8u)) & 0x000F000Fu) | ((_mma_qh2 >> _mma_sh_13) & 0x00100010u)), m); \ + const f16vec4 w3 = fma(d, repack_magic_u5_h(((ql3 >> _mma_shift) & 0x000F000Fu) | ((_mma_qh_left ? (_mma_qh3 << _mma_qh_sh) : (_mma_qh3 >> _mma_qh_sh)) & 0x00100010u), ((ql3 >> (_mma_shift + 8u)) & 0x000F000Fu) | ((_mma_qh3 >> _mma_sh_13) & 0x00100010u)), m); \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } else { \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + MMA_FVEC4 w0, w1, w2, w3; \ + dequant16(_mma_use_u, _mma_rbase, ((g * K_PAIRS + s_kp) << 2u) + (fn >> 1u), w0, w1, w2, w3); \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } \ + } while (false) +#else +#define MMA_ACCUM_KPAIRS_GEN(LOOP_ATTR, FENCE_MACRO, TARGET_MACRO, TARGET_ARR, USE_U, ROW_BASE) \ + do { \ + FENCE_MACRO(); \ + const uint ib = (ROW_BASE) + ((g * K_PAIRS) >> 2u); \ + const uint sub_base = (g * K_PAIRS) & 3u; \ + const uint fn2 = fn >> 1u; \ + const uint shift = (fn2 >> 1u) * 4u; \ + const uint w_lo = (fn2 & 1u) << 2u; \ + vec2 loadd; \ + uvec3 scales; \ + uint qh0, qh1, qh2, qh3; \ + if (USE_U) { \ + loadd = vec2(u_q5_k.data[ib].dm); \ + scales = uvec3(u_q5_k_p32.data[ib].scales[0], u_q5_k_p32.data[ib].scales[1], u_q5_k_p32.data[ib].scales[2]); \ + qh0 = u_q5_k_p32.data[ib].qh[w_lo + 0u]; qh1 = u_q5_k_p32.data[ib].qh[w_lo + 1u]; \ + qh2 = u_q5_k_p32.data[ib].qh[w_lo + 2u]; qh3 = u_q5_k_p32.data[ib].qh[w_lo + 3u]; \ + } else { \ + loadd = vec2(a_q5_k.data[ib].dm); \ + scales = uvec3(a_q5_k_p32.data[ib].scales[0], a_q5_k_p32.data[ib].scales[1], a_q5_k_p32.data[ib].scales[2]); \ + qh0 = a_q5_k_p32.data[ib].qh[w_lo + 0u]; qh1 = a_q5_k_p32.data[ib].qh[w_lo + 1u]; \ + qh2 = a_q5_k_p32.data[ib].qh[w_lo + 2u]; qh3 = a_q5_k_p32.data[ib].qh[w_lo + 3u]; \ + } \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + const uint sub = sub_base + s_kp; \ + const uint is = (sub << 1u) | (fn2 >> 1u); \ + const uint scalesoffs = (is & 3u) * 8u; \ + const uint scidxshift1 = (is < 4u) ? scalesoffs : (scalesoffs + 2u); \ + const uint mbidxshift0 = (is < 4u) ? scalesoffs : (scalesoffs + 4u); \ + const uint sc_word = (is < 4u) ? scales.x : scales.z; \ + const uint mb_word = (is < 4u) ? scales.y : scales.z; \ + const uint sc = ((sc_word >> scalesoffs) & 0xFu) | ((scales.x >> scidxshift1) & 0x30u); \ + const uint mbyte = ((mb_word >> mbidxshift0) & 0xFu) | ((scales.y >> scidxshift1) & 0x30u); \ + const f16vec4 d = f16vec4(loadd.x * float(sc)); \ + const f16vec4 m = f16vec4(-loadd.y * float(mbyte)); \ + const uint w_idx = (sub << 3u) + w_lo; \ + uint ql0, ql1, ql2, ql3; \ + if (USE_U) { \ + ql0 = u_q5_k_p32.data[ib].qs[w_idx + 0u]; ql1 = u_q5_k_p32.data[ib].qs[w_idx + 1u]; \ + ql2 = u_q5_k_p32.data[ib].qs[w_idx + 2u]; ql3 = u_q5_k_p32.data[ib].qs[w_idx + 3u]; \ + } else { \ + ql0 = a_q5_k_p32.data[ib].qs[w_idx + 0u]; ql1 = a_q5_k_p32.data[ib].qs[w_idx + 1u]; \ + ql2 = a_q5_k_p32.data[ib].qs[w_idx + 2u]; ql3 = a_q5_k_p32.data[ib].qs[w_idx + 3u]; \ + } \ + const bool qh_left = (is <= 4u); \ + const uint qh_sh = qh_left ? (4u - is) : (is - 4u); \ + const uint qhb0 = (qh_left ? (qh0 << qh_sh) : (qh0 >> qh_sh)) & 0x10101010u; \ + const uint qhb1 = (qh_left ? (qh1 << qh_sh) : (qh1 >> qh_sh)) & 0x10101010u; \ + const uint qhb2 = (qh_left ? (qh2 << qh_sh) : (qh2 >> qh_sh)) & 0x10101010u; \ + const uint qhb3 = (qh_left ? (qh3 << qh_sh) : (qh3 >> qh_sh)) & 0x10101010u; \ + const f16vec4 w0 = fma(d, f16vec4(unpack8(((ql0 >> shift) & 0x0F0F0F0Fu) | qhb0)), m); \ + const f16vec4 w1 = fma(d, f16vec4(unpack8(((ql1 >> shift) & 0x0F0F0F0Fu) | qhb1)), m); \ + const f16vec4 w2 = fma(d, f16vec4(unpack8(((ql2 >> shift) & 0x0F0F0F0Fu) | qhb2)), m); \ + const f16vec4 w3 = fma(d, f16vec4(unpack8(((ql3 >> shift) & 0x0F0F0F0Fu) | qhb3)), m); \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } while (false) +#endif +#elif defined(DATA_A_Q6_K) +#ifdef REPACK_PLANAR +#define MMA_ACCUM_KPAIRS_GEN(LOOP_ATTR, FENCE_MACRO, TARGET_MACRO, TARGET_ARR, USE_U, ROW_BASE) \ + do { \ + FENCE_MACRO(); \ + const bool _mma_use_u = (USE_U); \ + const uint _mma_rbase = (ROW_BASE); \ + if (K_PAIRS <= 2u) { \ + const uint _mma_sb_u4 = (_mma_rbase + ((g * K_PAIRS) >> 2u)) * REPACK_Q6_K_SB_U4; \ + const uint _mma_sb_u32 = _mma_sb_u4 << 2u; \ + const uint _mma_sub_base = (g * K_PAIRS) & 3u; \ + const uint _mma_fn2 = fn >> 1u; \ + const uint _mma_h = _mma_sub_base >> 1u; \ + const uint _mma_w_lo = (_mma_fn2 & 1u) << 2u; \ + const uint _mma_q_comp = (_mma_h << 1u) | (_mma_fn2 >> 1u); \ + const float _mma_d_f = unpackHalf2x16(_mma_use_u \ + ? u_u32.data[_mma_sb_u32 + REPACK_Q6_K_D_OFF_U32] \ + : a_u32.data[_mma_sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; \ + const uint _mma_q_base = ((_mma_sb_u4 + REPACK_Q6_K_QL_OFF_U4 + _mma_w_lo) << 2u) + _mma_q_comp; \ + const uint _mma_qh_base = _mma_sb_u32 + REPACK_Q6_K_QH_OFF_U32 + _mma_w_lo * 2u + _mma_h; \ + uint _mma_ql0, _mma_ql1, _mma_ql2, _mma_ql3; \ + uint _mma_qh_raw0, _mma_qh_raw1, _mma_qh_raw2, _mma_qh_raw3; \ + if (_mma_use_u) { \ + _mma_ql0 = u_u32.data[_mma_q_base + 0u]; _mma_ql1 = u_u32.data[_mma_q_base + 4u]; \ + _mma_ql2 = u_u32.data[_mma_q_base + 8u]; _mma_ql3 = u_u32.data[_mma_q_base + 12u]; \ + _mma_qh_raw0 = u_u32.data[_mma_qh_base + 0u]; _mma_qh_raw1 = u_u32.data[_mma_qh_base + 2u]; \ + _mma_qh_raw2 = u_u32.data[_mma_qh_base + 4u]; _mma_qh_raw3 = u_u32.data[_mma_qh_base + 6u]; \ + } else { \ + _mma_ql0 = a_u32.data[_mma_q_base + 0u]; _mma_ql1 = a_u32.data[_mma_q_base + 4u]; \ + _mma_ql2 = a_u32.data[_mma_q_base + 8u]; _mma_ql3 = a_u32.data[_mma_q_base + 12u]; \ + _mma_qh_raw0 = a_u32.data[_mma_qh_base + 0u]; _mma_qh_raw1 = a_u32.data[_mma_qh_base + 2u]; \ + _mma_qh_raw2 = a_u32.data[_mma_qh_base + 4u]; _mma_qh_raw3 = a_u32.data[_mma_qh_base + 6u]; \ + } \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + const uint _mma_sub = _mma_sub_base + s_kp; \ + const uint _mma_sh_n = (_mma_sub & 1u) * 4u; \ + const uint _mma_qhshift = (((_mma_sub & 1u) << 1u) | (_mma_fn2 >> 1u)) * 2u; \ + const uint _mma_sc_word = _mma_use_u \ + ? u_u32.data[_mma_sb_u32 + REPACK_Q6_K_SC_OFF_U32 + _mma_sub] \ + : a_u32.data[_mma_sb_u32 + REPACK_Q6_K_SC_OFF_U32 + _mma_sub]; \ + const float16_t _mma_sc = float16_t(_mma_d_f * float(bitfieldExtract(int(_mma_sc_word), int(_mma_fn2 * 8u), 8))); \ + const uint qh0 = _mma_qh_raw0 >> _mma_qhshift; \ + const uint qh1 = _mma_qh_raw1 >> _mma_qhshift; \ + const uint qh2 = _mma_qh_raw2 >> _mma_qhshift; \ + const uint qh3 = _mma_qh_raw3 >> _mma_qhshift; \ + const f16vec4 dv = f16vec4(_mma_sc); \ + const f16vec4 w0 = repack_magic_q6_h(((_mma_ql0 >> _mma_sh_n) & 0x000F000Fu) | ((qh0 & 0x00030003u) << 4u), ((_mma_ql0 >> (_mma_sh_n + 8u)) & 0x000F000Fu) | ((qh0 >> 4u) & 0x00300030u)) * dv; \ + const f16vec4 w1 = repack_magic_q6_h(((_mma_ql1 >> _mma_sh_n) & 0x000F000Fu) | ((qh1 & 0x00030003u) << 4u), ((_mma_ql1 >> (_mma_sh_n + 8u)) & 0x000F000Fu) | ((qh1 >> 4u) & 0x00300030u)) * dv; \ + const f16vec4 w2 = repack_magic_q6_h(((_mma_ql2 >> _mma_sh_n) & 0x000F000Fu) | ((qh2 & 0x00030003u) << 4u), ((_mma_ql2 >> (_mma_sh_n + 8u)) & 0x000F000Fu) | ((qh2 >> 4u) & 0x00300030u)) * dv; \ + const f16vec4 w3 = repack_magic_q6_h(((_mma_ql3 >> _mma_sh_n) & 0x000F000Fu) | ((qh3 & 0x00030003u) << 4u), ((_mma_ql3 >> (_mma_sh_n + 8u)) & 0x000F000Fu) | ((qh3 >> 4u) & 0x00300030u)) * dv; \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } else if (K_PAIRS == 4u) { \ + const uint _mma_sb_u4 = (_mma_rbase + g) * REPACK_Q6_K_SB_U4; \ + const uint _mma_sb_u32 = _mma_sb_u4 << 2u; \ + const uint _mma_fn2 = fn >> 1u; \ + const uint _mma_w_lo = (_mma_fn2 & 1u) << 2u; \ + const float _mma_d_f = unpackHalf2x16(_mma_use_u \ + ? u_u32.data[_mma_sb_u32 + REPACK_Q6_K_D_OFF_U32] \ + : a_u32.data[_mma_sb_u32 + REPACK_Q6_K_D_OFF_U32]).x; \ + const uvec4 _mma_sc_all = _mma_use_u \ + ? u_u4.data[_mma_sb_u4 + REPACK_Q6_K_SC_OFF_U4] \ + : a_u4.data[_mma_sb_u4 + REPACK_Q6_K_SC_OFF_U4]; \ + const uint _mma_q_base_row = (_mma_sb_u4 + REPACK_Q6_K_QL_OFF_U4 + _mma_w_lo) << 2u; \ + const uint _mma_qh_base_r = _mma_sb_u32 + REPACK_Q6_K_QH_OFF_U32 + _mma_w_lo * 2u; \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + const uint _mma_h = s_kp >> 1u; \ + const uint _mma_sh_n = (s_kp & 1u) * 4u; \ + const uint _mma_qhshift = (((s_kp & 1u) << 1u) | (_mma_fn2 >> 1u)) * 2u; \ + const uint _mma_q_comp = (_mma_h << 1u) | (_mma_fn2 >> 1u); \ + const uint _mma_sc_word = _mma_sc_all[s_kp]; \ + const float16_t _mma_sc = float16_t(_mma_d_f * float(bitfieldExtract(int(_mma_sc_word), int(_mma_fn2 * 8u), 8))); \ + const uint _mma_q_base = _mma_q_base_row + _mma_q_comp; \ + const uint _mma_qh_base = _mma_qh_base_r + _mma_h; \ + uint ql0, ql1, ql2, ql3, qh0, qh1, qh2, qh3; \ + if (_mma_use_u) { \ + ql0 = u_u32.data[_mma_q_base + 0u]; ql1 = u_u32.data[_mma_q_base + 4u]; \ + ql2 = u_u32.data[_mma_q_base + 8u]; ql3 = u_u32.data[_mma_q_base + 12u]; \ + qh0 = u_u32.data[_mma_qh_base + 0u] >> _mma_qhshift; \ + qh1 = u_u32.data[_mma_qh_base + 2u] >> _mma_qhshift; \ + qh2 = u_u32.data[_mma_qh_base + 4u] >> _mma_qhshift; \ + qh3 = u_u32.data[_mma_qh_base + 6u] >> _mma_qhshift; \ + } else { \ + ql0 = a_u32.data[_mma_q_base + 0u]; ql1 = a_u32.data[_mma_q_base + 4u]; \ + ql2 = a_u32.data[_mma_q_base + 8u]; ql3 = a_u32.data[_mma_q_base + 12u]; \ + qh0 = a_u32.data[_mma_qh_base + 0u] >> _mma_qhshift; \ + qh1 = a_u32.data[_mma_qh_base + 2u] >> _mma_qhshift; \ + qh2 = a_u32.data[_mma_qh_base + 4u] >> _mma_qhshift; \ + qh3 = a_u32.data[_mma_qh_base + 6u] >> _mma_qhshift; \ + } \ + const f16vec4 dv = f16vec4(_mma_sc); \ + const f16vec4 w0 = repack_magic_q6_h(((ql0 >> _mma_sh_n) & 0x000F000Fu) | ((qh0 & 0x00030003u) << 4u), ((ql0 >> (_mma_sh_n + 8u)) & 0x000F000Fu) | ((qh0 >> 4u) & 0x00300030u)) * dv; \ + const f16vec4 w1 = repack_magic_q6_h(((ql1 >> _mma_sh_n) & 0x000F000Fu) | ((qh1 & 0x00030003u) << 4u), ((ql1 >> (_mma_sh_n + 8u)) & 0x000F000Fu) | ((qh1 >> 4u) & 0x00300030u)) * dv; \ + const f16vec4 w2 = repack_magic_q6_h(((ql2 >> _mma_sh_n) & 0x000F000Fu) | ((qh2 & 0x00030003u) << 4u), ((ql2 >> (_mma_sh_n + 8u)) & 0x000F000Fu) | ((qh2 >> 4u) & 0x00300030u)) * dv; \ + const f16vec4 w3 = repack_magic_q6_h(((ql3 >> _mma_sh_n) & 0x000F000Fu) | ((qh3 & 0x00030003u) << 4u), ((ql3 >> (_mma_sh_n + 8u)) & 0x000F000Fu) | ((qh3 >> 4u) & 0x00300030u)) * dv; \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } else { \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + MMA_FVEC4 w0, w1, w2, w3; \ + dequant16(_mma_use_u, _mma_rbase, ((g * K_PAIRS + s_kp) << 2u) + (fn >> 1u), w0, w1, w2, w3); \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } \ + } while (false) +#else +#define MMA_ACCUM_KPAIRS_GEN(LOOP_ATTR, FENCE_MACRO, TARGET_MACRO, TARGET_ARR, USE_U, ROW_BASE) \ + do { \ + FENCE_MACRO(); \ + const uint ib = (ROW_BASE) + ((g * K_PAIRS) >> 2u); \ + const uint sub_base = (g * K_PAIRS) & 3u; \ + const uint fn2 = fn >> 1u; \ + const float d_sb = float((USE_U) ? u_q6_k.data[ib].d : a_q6_k.data[ib].d); \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + const uint il = ((sub_base + s_kp) << 2u) | fn2; \ + const uint b = ((il >> 2u) & 1u) * 4u; \ + const uint qhshift = ((il >> 1u) & 3u) * 2u; \ + const uint qsi = ((il & 8u) << 2u) + ((il & 3u) << 3u); \ + const uint qhi = ((il & 8u) << 1u) + ((il & 1u) << 3u); \ + float dscale; \ + uint ql01, ql23, ql45, ql67, qh01, qh23, qh45, qh67; \ + if (USE_U) { \ + dscale = d_sb * float(u_q6_k.data[ib].scales[il]); \ + ql01 = ((uint(u_q6_k_p16.data[ib].ql[qsi + 0u]) | (uint(u_q6_k_p16.data[ib].ql[qsi + 1u]) << 16u)) >> b) & 0x0F0F0F0Fu; \ + ql23 = ((uint(u_q6_k_p16.data[ib].ql[qsi + 2u]) | (uint(u_q6_k_p16.data[ib].ql[qsi + 3u]) << 16u)) >> b) & 0x0F0F0F0Fu; \ + ql45 = ((uint(u_q6_k_p16.data[ib].ql[qsi + 4u]) | (uint(u_q6_k_p16.data[ib].ql[qsi + 5u]) << 16u)) >> b) & 0x0F0F0F0Fu; \ + ql67 = ((uint(u_q6_k_p16.data[ib].ql[qsi + 6u]) | (uint(u_q6_k_p16.data[ib].ql[qsi + 7u]) << 16u)) >> b) & 0x0F0F0F0Fu; \ + qh01 = ((uint(u_q6_k_p16.data[ib].qh[qhi + 0u]) | (uint(u_q6_k_p16.data[ib].qh[qhi + 1u]) << 16u)) >> qhshift) & 0x03030303u; \ + qh23 = ((uint(u_q6_k_p16.data[ib].qh[qhi + 2u]) | (uint(u_q6_k_p16.data[ib].qh[qhi + 3u]) << 16u)) >> qhshift) & 0x03030303u; \ + qh45 = ((uint(u_q6_k_p16.data[ib].qh[qhi + 4u]) | (uint(u_q6_k_p16.data[ib].qh[qhi + 5u]) << 16u)) >> qhshift) & 0x03030303u; \ + qh67 = ((uint(u_q6_k_p16.data[ib].qh[qhi + 6u]) | (uint(u_q6_k_p16.data[ib].qh[qhi + 7u]) << 16u)) >> qhshift) & 0x03030303u; \ + } else { \ + dscale = d_sb * float(a_q6_k.data[ib].scales[il]); \ + ql01 = ((uint(a_q6_k_p16.data[ib].ql[qsi + 0u]) | (uint(a_q6_k_p16.data[ib].ql[qsi + 1u]) << 16u)) >> b) & 0x0F0F0F0Fu; \ + ql23 = ((uint(a_q6_k_p16.data[ib].ql[qsi + 2u]) | (uint(a_q6_k_p16.data[ib].ql[qsi + 3u]) << 16u)) >> b) & 0x0F0F0F0Fu; \ + ql45 = ((uint(a_q6_k_p16.data[ib].ql[qsi + 4u]) | (uint(a_q6_k_p16.data[ib].ql[qsi + 5u]) << 16u)) >> b) & 0x0F0F0F0Fu; \ + ql67 = ((uint(a_q6_k_p16.data[ib].ql[qsi + 6u]) | (uint(a_q6_k_p16.data[ib].ql[qsi + 7u]) << 16u)) >> b) & 0x0F0F0F0Fu; \ + qh01 = ((uint(a_q6_k_p16.data[ib].qh[qhi + 0u]) | (uint(a_q6_k_p16.data[ib].qh[qhi + 1u]) << 16u)) >> qhshift) & 0x03030303u; \ + qh23 = ((uint(a_q6_k_p16.data[ib].qh[qhi + 2u]) | (uint(a_q6_k_p16.data[ib].qh[qhi + 3u]) << 16u)) >> qhshift) & 0x03030303u; \ + qh45 = ((uint(a_q6_k_p16.data[ib].qh[qhi + 4u]) | (uint(a_q6_k_p16.data[ib].qh[qhi + 5u]) << 16u)) >> qhshift) & 0x03030303u; \ + qh67 = ((uint(a_q6_k_p16.data[ib].qh[qhi + 6u]) | (uint(a_q6_k_p16.data[ib].qh[qhi + 7u]) << 16u)) >> qhshift) & 0x03030303u; \ + } \ + const f16vec4 dv = f16vec4(dscale); \ + const f16vec4 mv = f16vec4(-32.0f * dscale); \ + const f16vec4 w0 = fma(f16vec4(unpack8(ql01 | (qh01 << 4u))), dv, mv); \ + const f16vec4 w1 = fma(f16vec4(unpack8(ql23 | (qh23 << 4u))), dv, mv); \ + const f16vec4 w2 = fma(f16vec4(unpack8(ql45 | (qh45 << 4u))), dv, mv); \ + const f16vec4 w3 = fma(f16vec4(unpack8(ql67 | (qh67 << 4u))), dv, mv); \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } while (false) +#endif +#else +#define MMA_ACCUM_KPAIRS_GEN(LOOP_ATTR, FENCE_MACRO, TARGET_MACRO, TARGET_ARR, USE_U, ROW_BASE) \ + do { \ + FENCE_MACRO(); \ + LOOP_ATTR for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { \ + FENCE_MACRO(); \ + MMA_FVEC4 w0, w1, w2, w3; \ + dequant16((USE_U), (ROW_BASE), ((g * K_PAIRS + s_kp) << 2u) + (fn >> 1u), w0, w1, w2, w3); \ + FENCE_MACRO(); \ + TARGET_MACRO(TARGET_ARR, (s_kp << 4u), w0, w1, w2, w3); \ + } \ + } while (false) +#endif + +#define MMA_ACCUM_KPAIRS(MC_ARR, USE_U, ROW_BASE) \ + MMA_ACCUM_KPAIRS_GEN([[dont_unroll]], MMA_NO_FENCE, MMA_ACCUM_SHB, MC_ARR, USE_U, ROW_BASE) +#define MMA_ACCUM_KPAIRS_UNROLLED(ACC_VEC, USE_U, ROW_BASE) \ + MMA_ACCUM_KPAIRS_GEN([[unroll]], MMA_NO_FENCE, MMA_ACCUM_SHB_1D, ACC_VEC, USE_U, ROW_BASE) +#define MMA_ACCUM_KPAIRS_FENCED(MC_ARR, USE_U, ROW_BASE) \ + MMA_ACCUM_KPAIRS_GEN([[unroll]], MMA_SG_FENCE, MMA_ACCUM_SHB, MC_ARR, USE_U, ROW_BASE) +#define MMA_ACCUM_PRELOADED_MB(MC_ARR, SUB_OFF, W0, W1, W2, W3) \ + do { \ + const uint _kp_i = (SUB_OFF) >> 4u; \ + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { \ + if (rt == 0u || (8u * rt < n_valid)) { \ + [[unroll]] for (uint s = 0u; s < 4u; ++s) { \ + coopmat ma0, ma1; \ + ma0[0] = (W0)[s]; ma0[1] = (W2)[s]; \ + ma1[0] = (W1)[s]; ma1[1] = (W3)[s]; \ + MC_ARR[rt][t] = coopMatMulAdd(ma0, mb0_all[_kp_i][rt][s], MC_ARR[rt][t]); \ + MC_ARR[rt][t] = coopMatMulAdd(ma1, mb1_all[_kp_i][rt][s], MC_ARR[rt][t]); \ + } \ + } \ + } \ + } while (false) + + const uint K4_PER_COL = 16u * K_PAIRS; + const uint K_CHUNK = 64u * K_PAIRS; + const uint nch = p.K / K_CHUNK; + const uint B_ELEMS = K4_PER_COL * 8u * RT; + const uint B_LOADS = (B_ELEMS + WG_THREADS - 1u) / WG_THREADS; + + const bool stage_tmp_b = (USE_SH_B == 1u) ? true : ((USE_SH_B == 5u) ? true : (USE_SH_B == 8u)); + const bool use_sg_fence = (USE_SH_B == 5u) ? true : (USE_SH_B == 6u); + const bool load_mb_once = (USE_SH_B == 7u) ? true : ((USE_SH_B == 8u) ? true : (USE_SH_B == 9u)); + const bool fence_mb_once = (USE_SH_B != 9u); + const bool preload_mb_all = (USE_SH_B == 10u) ? true : (USE_SH_B == 11u); + + for (uint g = 0u; g < nch; ++g) { + if (stage_tmp_b) { + MMA_FVEC4 tmp_b[B_LOADS]; + [[unroll]] for (uint li = 0u; li < B_LOADS; ++li) { + tmp_b[li] = MMA_FVEC4(0.0f); + } + [[unroll]] for (uint li = 0u; li < B_LOADS; ++li) { + const uint col_min = (li * WG_THREADS) / K4_PER_COL; + if (li == 0u || col_min < n_valid) { + const uint idx = li * WG_THREADS + tid; + const uint col_in_tile = idx / K4_PER_COL; + const uint k4 = idx % K4_PER_COL; + if (idx < B_ELEMS && col_in_tile < n_valid) { +#ifdef MUL_MAT_ID + const uint b_base = mma_id_col_b_base(row_begin, tile_ne1, col_in_tile); +#else + const uint b_base = b_batch_base + (wg_n0 + col_in_tile) * p.stride_b; +#endif + tmp_b[li] = load_b_mvec4(b_base + g * K_CHUNK + (k4 << 2u), v4_ok, b_is_f16); + } + } + } + + if (g > 0u) { + barrier(); + } + + [[unroll]] for (uint li = 0u; li < B_LOADS; ++li) { +#ifdef MUL_MAT_ID + const uint col_min = (li * WG_THREADS) / K4_PER_COL; + if (li == 0u || col_min < n_valid) { + const uint idx = li * WG_THREADS + tid; + if (idx < B_ELEMS) { + sh_b[idx / K4_PER_COL][idx % K4_PER_COL] = tmp_b[li]; + } + } +#else + const uint idx = li * WG_THREADS + tid; + if (idx < B_ELEMS) { + sh_b[idx / K4_PER_COL][idx % K4_PER_COL] = tmp_b[li]; + } +#endif + } + barrier(); + } else { +#ifndef MUL_MAT_ID + if (B_LOADS * WG_THREADS == B_ELEMS && n_valid == 8u * RT && v4_ok) { + MMA_FVEC4 bv_arr[B_LOADS]; + [[unroll]] for (uint li = 0u; li < B_LOADS; ++li) { + const uint idx = li * WG_THREADS + tid; + const uint col_in_tile = idx / K4_PER_COL; + const uint k4 = idx % K4_PER_COL; + const uint b4 = (b_batch_base + (wg_n0 + col_in_tile) * p.stride_b + g * K_CHUNK) >> 2u; + bv_arr[li] = b_is_f16 ? MMA_FVEC4(data_b_f16v4[b4 + k4]) : MMA_FVEC4(data_b_v4[b4 + k4]); + } + if (g > 0u) { + barrier(); + } + [[unroll]] for (uint li = 0u; li < B_LOADS; ++li) { + const uint idx = li * WG_THREADS + tid; + sh_b[idx / K4_PER_COL][idx % K4_PER_COL] = bv_arr[li]; + } + barrier(); + } else +#endif + { + if (g > 0u) { + barrier(); + } + [[unroll]] for (uint li = 0u; li < B_LOADS; ++li) { + const uint idx = li * WG_THREADS + tid; + if (idx < B_ELEMS) { + const uint col_in_tile = idx / K4_PER_COL; + const uint k4 = idx % K4_PER_COL; + MMA_FVEC4 bv = MMA_FVEC4(0.0f); + if (col_in_tile < n_valid) { +#ifdef MUL_MAT_ID + const uint b_base = mma_id_col_b_base(row_begin, tile_ne1, col_in_tile); +#else + const uint b_base = b_batch_base + (wg_n0 + col_in_tile) * p.stride_b; +#endif + bv = load_b_mvec4(b_base + g * K_CHUNK + (k4 << 2u), v4_ok, b_is_f16); + } + sh_b[col_in_tile][k4] = bv; + } + } + barrier(); + } + } + + if (load_mb_once) { + [[unroll]] for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { + if (fence_mb_once) { MMA_SG_FENCE(); } + const uint sub_off = (s_kp << 4u) + k4_lane_base; + coopmat mb0[RT][4]; + coopmat mb1[RT][4]; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + const uint c0 = 8u * rt + fn + 0u; + const uint c1 = 8u * rt + fn + 1u; + const MMA_FVEC4 ba0 = sh_b[c0][sub_off + 0u]; + const MMA_FVEC4 ba1 = sh_b[c0][sub_off + 1u]; + const MMA_FVEC4 bb0 = sh_b[c1][sub_off + 0u]; + const MMA_FVEC4 bb1 = sh_b[c1][sub_off + 1u]; + [[unroll]] for (uint s = 0u; s < 4u; ++s) { + mb0[rt][s][0] = ba0[s]; mb0[rt][s][1] = bb0[s]; + mb1[rt][s][0] = ba1[s]; mb1[rt][s][1] = bb1[s]; + } + } + } + const uint ci_kp = ((g * K_PAIRS + s_kp) << 2u) + (fn >> 1u); + [[unroll]] for (uint t = 0u; t < NT; ++t) { + if (fence_mb_once) { MMA_SG_FENCE(); } + MMA_FVEC4 w0, w1, w2, w3; + dequant16(FUSE_MODE == 2u && tile_second[t], a_row_base[t], ci_kp, w0, w1, w2, w3); + if (fence_mb_once) { MMA_SG_FENCE(); } + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + [[unroll]] for (uint s = 0u; s < 4u; ++s) { + coopmat ma0, ma1; + ma0[0] = w0[s]; ma0[1] = w2[s]; + ma1[0] = w1[s]; ma1[1] = w3[s]; + mc[rt][t] = coopMatMulAdd(ma0, mb0[rt][s], mc[rt][t]); + mc[rt][t] = coopMatMulAdd(ma1, mb1[rt][s], mc[rt][t]); + } + } + } + if (FUSE_MODE == 3u) { + if (fence_mb_once) { MMA_SG_FENCE(); } + MMA_FVEC4 uw0, uw1, uw2, uw3; + dequant16(true, u_row_base[t], ci_kp, uw0, uw1, uw2, uw3); + if (fence_mb_once) { MMA_SG_FENCE(); } + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + [[unroll]] for (uint s = 0u; s < 4u; ++s) { + coopmat uma0, uma1; + uma0[0] = uw0[s]; uma0[1] = uw2[s]; + uma1[0] = uw1[s]; uma1[1] = uw3[s]; + mc_u[rt][t] = coopMatMulAdd(uma0, mb0[rt][s], mc_u[rt][t]); + mc_u[rt][t] = coopMatMulAdd(uma1, mb1[rt][s], mc_u[rt][t]); + } + } + } + } + } + } + } else if (preload_mb_all) { + coopmat mb0_all[K_PAIRS][RT][4]; + coopmat mb1_all[K_PAIRS][RT][4]; + [[unroll]] for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { + const uint sub_off = (s_kp << 4u) + k4_lane_base; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + const uint c0 = 8u * rt + fn + 0u; + const uint c1 = 8u * rt + fn + 1u; + const MMA_FVEC4 ba0 = sh_b[c0][sub_off + 0u]; + const MMA_FVEC4 ba1 = sh_b[c0][sub_off + 1u]; + const MMA_FVEC4 bb0 = sh_b[c1][sub_off + 0u]; + const MMA_FVEC4 bb1 = sh_b[c1][sub_off + 1u]; + [[unroll]] for (uint s = 0u; s < 4u; ++s) { + mb0_all[s_kp][rt][s][0] = ba0[s]; mb0_all[s_kp][rt][s][1] = bb0[s]; + mb1_all[s_kp][rt][s][0] = ba1[s]; mb1_all[s_kp][rt][s][1] = bb1[s]; + } + } + } + } + if (USE_SH_B == 11u) { + [[unroll]] for (uint t = 0u; t < NT; ++t) { + MMA_ACCUM_KPAIRS_GEN([[unroll]], MMA_SG_FENCE, MMA_ACCUM_PRELOADED_MB, mc, (FUSE_MODE == 2u && tile_second[t]), a_row_base[t]); + if (FUSE_MODE == 3u) { + MMA_ACCUM_KPAIRS_GEN([[unroll]], MMA_SG_FENCE, MMA_ACCUM_PRELOADED_MB, mc_u, true, u_row_base[t]); + } + } + } else { + [[unroll]] for (uint t = 0u; t < NT; ++t) { + MMA_ACCUM_KPAIRS_GEN([[unroll]], MMA_NO_FENCE, MMA_ACCUM_PRELOADED_MB, mc, (FUSE_MODE == 2u && tile_second[t]), a_row_base[t]); + if (FUSE_MODE == 3u) { + MMA_ACCUM_KPAIRS_GEN([[unroll]], MMA_NO_FENCE, MMA_ACCUM_PRELOADED_MB, mc_u, true, u_row_base[t]); + } + } + } + } else if (USE_SH_B == 4u) { + const uint total_mats = NT * ((FUSE_MODE == 3u) ? 2u : 1u); + [[dont_unroll]] for (uint mi = 0u; mi < total_mats; ++mi) { + const bool is_u = (FUSE_MODE == 3u) && ((mi & 1u) != 0u); + const uint ti = (FUSE_MODE == 3u) ? (mi >> 1u) : mi; + const uint rbase = is_u + ? ((ti == 0u) ? u_row_base[0] : u_row_base[NT - 1u]) + : ((ti == 0u) ? a_row_base[0] : a_row_base[NT - 1u]); + const bool use_u = is_u || (FUSE_MODE == 2u && ((ti == 0u) ? tile_second[0] : tile_second[NT - 1u])); + coopmat acc_p[RT]; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + acc_p[rt] = is_u + ? ((ti == 0u) ? mc_u[rt][0] : mc_u[rt][NT - 1u]) + : ((ti == 0u) ? mc[rt][0] : mc[rt][NT - 1u]); + } + MMA_ACCUM_KPAIRS_UNROLLED(acc_p, use_u, rbase); + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (is_u) { + if (ti == 0u) { mc_u[rt][0] = acc_p[rt]; } else if (NT > 1u) { mc_u[rt][1] = acc_p[rt]; } + } else { + if (ti == 0u) { mc[rt][0] = acc_p[rt]; } else if (NT > 1u) { mc[rt][1] = acc_p[rt]; } + } + } + } + } else if (use_sg_fence) { + [[unroll]] for (uint t = 0u; t < NT; ++t) { + MMA_ACCUM_KPAIRS_FENCED(mc, (FUSE_MODE == 2u && tile_second[t]), a_row_base[t]); + if (FUSE_MODE == 3u) { + MMA_ACCUM_KPAIRS_FENCED(mc_u, true, u_row_base[t]); + } + } + } else if (USE_SH_B == 12u) { + [[unroll]] for (uint s_kp = 0u; s_kp < K_PAIRS; ++s_kp) { + const uint ci_kp = ((g * K_PAIRS + s_kp) << 2u) + (fn >> 1u); + const uint sub_off = (s_kp << 4u) + k4_lane_base; + if (FUSE_MODE == 3u) { + [[unroll]] for (uint t = 0u; t < NT; ++t) { + MMA_FVEC4 w0, w1, w2, w3; + MMA_FVEC4 uw0, uw1, uw2, uw3; + dequant16(false, a_row_base[t], ci_kp, w0, w1, w2, w3); + dequant16(true, u_row_base[t], ci_kp, uw0, uw1, uw2, uw3); + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + const uint c0 = 8u * rt + fn + 0u; + const uint c1 = 8u * rt + fn + 1u; + const MMA_FVEC4 ba0 = sh_b[c0][sub_off + 0u]; + const MMA_FVEC4 ba1 = sh_b[c0][sub_off + 1u]; + const MMA_FVEC4 bb0 = sh_b[c1][sub_off + 0u]; + const MMA_FVEC4 bb1 = sh_b[c1][sub_off + 1u]; + [[unroll]] for (uint s = 0u; s < 4u; ++s) { + coopmat ma0, ma1, uma0, uma1; + coopmat mb0, mb1; + ma0[0] = w0[s]; ma0[1] = w2[s]; + ma1[0] = w1[s]; ma1[1] = w3[s]; + uma0[0] = uw0[s]; uma0[1] = uw2[s]; + uma1[0] = uw1[s]; uma1[1] = uw3[s]; + mb0[0] = ba0[s]; mb0[1] = bb0[s]; + mb1[0] = ba1[s]; mb1[1] = bb1[s]; + mc[rt][t] = coopMatMulAdd(ma0, mb0, mc[rt][t]); + mc[rt][t] = coopMatMulAdd(ma1, mb1, mc[rt][t]); + mc_u[rt][t] = coopMatMulAdd(uma0, mb0, mc_u[rt][t]); + mc_u[rt][t] = coopMatMulAdd(uma1, mb1, mc_u[rt][t]); + } + } + } + } else if (NT == 2u) { + MMA_FVEC4 w0_0, w1_0, w2_0, w3_0; + MMA_FVEC4 w0_1, w1_1, w2_1, w3_1; + dequant16(FUSE_MODE == 2u && tile_second[0], a_row_base[0], ci_kp, w0_0, w1_0, w2_0, w3_0); + dequant16(FUSE_MODE == 2u && tile_second[1], a_row_base[1], ci_kp, w0_1, w1_1, w2_1, w3_1); + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + const uint c0 = 8u * rt + fn + 0u; + const uint c1 = 8u * rt + fn + 1u; + const MMA_FVEC4 ba0 = sh_b[c0][sub_off + 0u]; + const MMA_FVEC4 ba1 = sh_b[c0][sub_off + 1u]; + const MMA_FVEC4 bb0 = sh_b[c1][sub_off + 0u]; + const MMA_FVEC4 bb1 = sh_b[c1][sub_off + 1u]; + [[unroll]] for (uint s = 0u; s < 4u; ++s) { + coopmat ma0_0, ma1_0, ma0_1, ma1_1; + coopmat mb0, mb1; + ma0_0[0] = w0_0[s]; ma0_0[1] = w2_0[s]; + ma1_0[0] = w1_0[s]; ma1_0[1] = w3_0[s]; + ma0_1[0] = w0_1[s]; ma0_1[1] = w2_1[s]; + ma1_1[0] = w1_1[s]; ma1_1[1] = w3_1[s]; + mb0[0] = ba0[s]; mb0[1] = bb0[s]; + mb1[0] = ba1[s]; mb1[1] = bb1[s]; + mc[rt][0] = coopMatMulAdd(ma0_0, mb0, mc[rt][0]); + mc[rt][0] = coopMatMulAdd(ma1_0, mb1, mc[rt][0]); + mc[rt][1] = coopMatMulAdd(ma0_1, mb0, mc[rt][1]); + mc[rt][1] = coopMatMulAdd(ma1_1, mb1, mc[rt][1]); + } + } + } else { + [[unroll]] for (uint t = 0u; t < NT; ++t) { + MMA_ACCUM_KPAIRS(mc, (FUSE_MODE == 2u && tile_second[t]), a_row_base[t]); + } + } + } + } else { + [[unroll]] for (uint t = 0u; t < NT; ++t) { + MMA_ACCUM_KPAIRS(mc, (FUSE_MODE == 2u && tile_second[t]), a_row_base[t]); + if (FUSE_MODE == 3u) { + MMA_ACCUM_KPAIRS(mc_u, true, u_row_base[t]); + } + } + } + } +#undef MMA_ACCUM_PRELOADED_MB +#undef MMA_ACCUM_KPAIRS_FENCED +#undef MMA_ACCUM_KPAIRS_UNROLLED +#undef MMA_ACCUM_KPAIRS +#undef MMA_ACCUM_KPAIRS_GEN +#undef MMA_NO_FENCE +#undef MMA_SG_FENCE +#undef MMA_ACCUM_SHB +#undef MMA_ACCUM_SHB_1D + } +#if defined(DATA_A_Q8_0) + else if (RT == 1u || (p.K & 63u) != 0u) { + const bool v2_ok = ((p.stride_b & 1u) == 0u) && ((p.batch_stride_b & 1u) == 0u); + const uint b_lane_off = 8u * (fm >> 1u) + 2u * (fm & 1u); + const uint nb = p.K >> 5u; + + for (uint ib = sg_k; ib < nb; ib += NSG) { + MMA_FVEC2 b0[RT][2]; + MMA_FVEC2 b1[RT][2]; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + [[unroll]] for (uint e = 0u; e < 2u; ++e) { +#ifdef MUL_MAT_ID + const uint b_base = mma_id_col_b_base(row_begin, tile_ne1, min(8u * rt + fn + e, n_valid - 1u)); +#else + const uint b_base = b_batch_base + (wg_n0 + min(8u * rt + fn + e, n_valid - 1u)) * p.stride_b; +#endif + const uint base = b_base + (ib << 5u) + b_lane_off; + b0[rt][e] = load_b_mvec2(base, v2_ok, b_is_f16); + b1[rt][e] = load_b_mvec2(base + 4u, v2_ok, b_is_f16); + } + } + } + + [[unroll]] for (uint t = 0u; t < NT; ++t) { + const uint blk_idx = a_row_base[t] + ib; + const uint q_off = 2u * fn; + float d_a; + i8vec4 v0_a, v1_a; + if (FUSE_MODE == 2u && tile_second[t]) { + d_a = float(u_q8_0.data[blk_idx].d); + v0_a = unpack8(int32_t((uint(int(u_q8_0.data[blk_idx].qs[q_off + 0u])) & 0xFFFFu) | (uint(int(u_q8_0.data[blk_idx].qs[q_off + 1u])) << 16u))); + v1_a = unpack8(int32_t((uint(int(u_q8_0.data[blk_idx].qs[q_off + 2u])) & 0xFFFFu) | (uint(int(u_q8_0.data[blk_idx].qs[q_off + 3u])) << 16u))); + } else { + d_a = float(a_q8_0.data[blk_idx].d); + v0_a = unpack8(int32_t((uint(int(a_q8_0.data[blk_idx].qs[q_off + 0u])) & 0xFFFFu) | (uint(int(a_q8_0.data[blk_idx].qs[q_off + 1u])) << 16u))); + v1_a = unpack8(int32_t((uint(int(a_q8_0.data[blk_idx].qs[q_off + 2u])) & 0xFFFFu) | (uint(int(a_q8_0.data[blk_idx].qs[q_off + 3u])) << 16u))); + } + + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + coopmat mp = coopmat(0.0f); + coopmat ma; + coopmat mb; + ma[0] = MMA_FTYPE(v0_a.x); ma[1] = MMA_FTYPE(v0_a.z); mb[0] = b0[rt][0].x; mb[1] = b0[rt][1].x; mp = coopMatMulAdd(ma, mb, mp); + ma[0] = MMA_FTYPE(v0_a.y); ma[1] = MMA_FTYPE(v0_a.w); mb[0] = b0[rt][0].y; mb[1] = b0[rt][1].y; mp = coopMatMulAdd(ma, mb, mp); + ma[0] = MMA_FTYPE(v1_a.x); ma[1] = MMA_FTYPE(v1_a.z); mb[0] = b1[rt][0].x; mb[1] = b1[rt][1].x; mp = coopMatMulAdd(ma, mb, mp); + ma[0] = MMA_FTYPE(v1_a.y); ma[1] = MMA_FTYPE(v1_a.w); mb[0] = b1[rt][0].y; mb[1] = b1[rt][1].y; mp = coopMatMulAdd(ma, mb, mp); + mc[rt][t][0] = fma(d_a, mp[0], mc[rt][t][0]); + mc[rt][t][1] = fma(d_a, mp[1], mc[rt][t][1]); + } + } + + if (FUSE_MODE == 3u) { + const uint u_blk_idx = u_row_base[t] + ib; + const float d_u = float(u_q8_0.data[u_blk_idx].d); + const i8vec4 v0_u = unpack8(int32_t((uint(int(u_q8_0.data[u_blk_idx].qs[q_off + 0u])) & 0xFFFFu) | (uint(int(u_q8_0.data[u_blk_idx].qs[q_off + 1u])) << 16u))); + const i8vec4 v1_u = unpack8(int32_t((uint(int(u_q8_0.data[u_blk_idx].qs[q_off + 2u])) & 0xFFFFu) | (uint(int(u_q8_0.data[u_blk_idx].qs[q_off + 3u])) << 16u))); + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + coopmat mpu = coopmat(0.0f); + coopmat ma; + coopmat mb; + ma[0] = MMA_FTYPE(v0_u.x); ma[1] = MMA_FTYPE(v0_u.z); mb[0] = b0[rt][0].x; mb[1] = b0[rt][1].x; mpu = coopMatMulAdd(ma, mb, mpu); + ma[0] = MMA_FTYPE(v0_u.y); ma[1] = MMA_FTYPE(v0_u.w); mb[0] = b0[rt][0].y; mb[1] = b0[rt][1].y; mpu = coopMatMulAdd(ma, mb, mpu); + ma[0] = MMA_FTYPE(v1_u.x); ma[1] = MMA_FTYPE(v1_u.z); mb[0] = b1[rt][0].x; mb[1] = b1[rt][1].x; mpu = coopMatMulAdd(ma, mb, mpu); + ma[0] = MMA_FTYPE(v1_u.y); ma[1] = MMA_FTYPE(v1_u.w); mb[0] = b1[rt][0].y; mb[1] = b1[rt][1].y; mpu = coopMatMulAdd(ma, mb, mpu); + mc_u[rt][t][0] = fma(d_u, mpu[0], mc_u[rt][t][0]); + mc_u[rt][t][1] = fma(d_u, mpu[1], mc_u[rt][t][1]); + } + } + } + } + } + } +#elif defined(DATA_A_Q4_0) + else if ((p.K & 63u) != 0u) { + const bool v2_ok = ((p.stride_b & 1u) == 0u) && ((p.batch_stride_b & 1u) == 0u); + const uint b_lane_off = 2u * fm; + const uint nb = p.K >> 5u; + + for (uint ib = sg_k; ib < nb; ib += NSG) { + MMA_FVEC2 b0[RT][2]; + MMA_FVEC2 b1[RT][2]; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + [[unroll]] for (uint e = 0u; e < 2u; ++e) { +#ifdef MUL_MAT_ID + const uint b_base = mma_id_col_b_base(row_begin, tile_ne1, min(8u * rt + fn + e, n_valid - 1u)); +#else + const uint b_base = b_batch_base + (wg_n0 + min(8u * rt + fn + e, n_valid - 1u)) * p.stride_b; +#endif + const uint base = b_base + (ib << 5u) + b_lane_off; + b0[rt][e] = load_b_mvec2(base, v2_ok, b_is_f16); + b1[rt][e] = load_b_mvec2(base + 16u, v2_ok, b_is_f16); + } + } + } + + [[unroll]] for (uint t = 0u; t < NT; ++t) { + const uint blk_idx = a_row_base[t] + ib; + float d_a; + uint raw_u; + if (FUSE_MODE == 2u && tile_second[t]) { + d_a = float(u_q4_0.data[blk_idx].d); + raw_u = uint(u_q4_0.data[blk_idx].qs[fn]) | (uint(u_q4_0.data[blk_idx].qs[fn + 1u]) << 16u); + } else { + d_a = float(a_q4_0.data[blk_idx].d); + raw_u = uint(a_q4_0.data[blk_idx].qs[fn]) | (uint(a_q4_0.data[blk_idx].qs[fn + 1u]) << 16u); + } + const u8vec4 lo = unpack8( raw_u & 0x0F0F0F0Fu); + const u8vec4 hi = unpack8((raw_u >> 4u) & 0x0F0F0F0Fu); + + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + coopmat mp = coopmat(0.0f); + coopmat ma; + coopmat mb; + ma[0] = MMA_FTYPE(int(lo.x) - 8); ma[1] = MMA_FTYPE(int(lo.z) - 8); mb[0] = b0[rt][0].x; mb[1] = b0[rt][1].x; mp = coopMatMulAdd(ma, mb, mp); + ma[0] = MMA_FTYPE(int(lo.y) - 8); ma[1] = MMA_FTYPE(int(lo.w) - 8); mb[0] = b0[rt][0].y; mb[1] = b0[rt][1].y; mp = coopMatMulAdd(ma, mb, mp); + ma[0] = MMA_FTYPE(int(hi.x) - 8); ma[1] = MMA_FTYPE(int(hi.z) - 8); mb[0] = b1[rt][0].x; mb[1] = b1[rt][1].x; mp = coopMatMulAdd(ma, mb, mp); + ma[0] = MMA_FTYPE(int(hi.y) - 8); ma[1] = MMA_FTYPE(int(hi.w) - 8); mb[0] = b1[rt][0].y; mb[1] = b1[rt][1].y; mp = coopMatMulAdd(ma, mb, mp); + mc[rt][t][0] = fma(d_a, mp[0], mc[rt][t][0]); + mc[rt][t][1] = fma(d_a, mp[1], mc[rt][t][1]); + } + } + + if (FUSE_MODE == 3u) { + const uint u_blk_idx = u_row_base[t] + ib; + const float d_u = float(u_q4_0.data[u_blk_idx].d); + const uint uraw = uint(u_q4_0.data[u_blk_idx].qs[fn]) | (uint(u_q4_0.data[u_blk_idx].qs[fn + 1u]) << 16u); + const u8vec4 ulo = unpack8( uraw & 0x0F0F0F0Fu); + const u8vec4 uhi = unpack8((uraw >> 4u) & 0x0F0F0F0Fu); + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + coopmat mpu = coopmat(0.0f); + coopmat ma; + coopmat mb; + ma[0] = MMA_FTYPE(int(ulo.x) - 8); ma[1] = MMA_FTYPE(int(ulo.z) - 8); mb[0] = b0[rt][0].x; mb[1] = b0[rt][1].x; mpu = coopMatMulAdd(ma, mb, mpu); + ma[0] = MMA_FTYPE(int(ulo.y) - 8); ma[1] = MMA_FTYPE(int(ulo.w) - 8); mb[0] = b0[rt][0].y; mb[1] = b0[rt][1].y; mpu = coopMatMulAdd(ma, mb, mpu); + ma[0] = MMA_FTYPE(int(uhi.x) - 8); ma[1] = MMA_FTYPE(int(uhi.z) - 8); mb[0] = b1[rt][0].x; mb[1] = b1[rt][1].x; mpu = coopMatMulAdd(ma, mb, mpu); + ma[0] = MMA_FTYPE(int(uhi.y) - 8); ma[1] = MMA_FTYPE(int(uhi.w) - 8); mb[0] = b1[rt][0].y; mb[1] = b1[rt][1].y; mpu = coopMatMulAdd(ma, mb, mpu); + mc_u[rt][t][0] = fma(d_u, mpu[0], mc_u[rt][t][0]); + mc_u[rt][t][1] = fma(d_u, mpu[1], mc_u[rt][t][1]); + } + } + } + } + } + } +#endif + else { + // K-split (MSG == 1, NSG >= 1) 64-weight chunk loop with on-the-fly mb construction + const bool v4_ok = ((p.stride_b & 3u) == 0u) && ((p.batch_stride_b & 3u) == 0u); + const uint b_lane_off = 16u * (fm >> 1u) + 8u * (fm & 1u); + const uint nch = p.K >> 6u; + + uint base0_rt[RT], base1_rt[RT]; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { +#ifdef MUL_MAT_ID + base0_rt[rt] = mma_id_col_b_base(row_begin, tile_ne1, min(8u * rt + fn + 0u, n_valid - 1u)) + b_lane_off; + base1_rt[rt] = mma_id_col_b_base(row_begin, tile_ne1, min(8u * rt + fn + 1u, n_valid - 1u)) + b_lane_off; +#else + base0_rt[rt] = b_batch_base + (wg_n0 + min(8u * rt + fn + 0u, n_valid - 1u)) * p.stride_b + b_lane_off; + base1_rt[rt] = b_batch_base + (wg_n0 + min(8u * rt + fn + 1u, n_valid - 1u)) * p.stride_b + b_lane_off; +#endif + } else { + base0_rt[rt] = 0u; + base1_rt[rt] = 0u; + } + } + + for (uint g = sg_k; g < nch; g += NSG) { + MMA_FVEC4 ba0[RT], ba1[RT], bb0[RT], bb1[RT]; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + const uint base0 = base0_rt[rt] + (g << 6u); + const uint base1 = base1_rt[rt] + (g << 6u); + ba0[rt] = load_b_mvec4(base0, v4_ok, b_is_f16); + ba1[rt] = load_b_mvec4(base0 + 4u, v4_ok, b_is_f16); + bb0[rt] = load_b_mvec4(base1, v4_ok, b_is_f16); + bb1[rt] = load_b_mvec4(base1 + 4u, v4_ok, b_is_f16); + } + } + + const uint ci = (g << 2u) + (fn >> 1u); + + [[unroll]] for (uint t = 0u; t < NT; ++t) { + MMA_FVEC4 w0, w1, w2, w3; + dequant16(FUSE_MODE == 2u && tile_second[t], a_row_base[t], ci, w0, w1, w2, w3); + + [[unroll]] for (uint s = 0u; s < 4u; ++s) { + coopmat ma0, ma1; + ma0[0] = w0[s]; ma0[1] = w2[s]; + ma1[0] = w1[s]; ma1[1] = w3[s]; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + coopmat mb0, mb1; + mb0[0] = ba0[rt][s]; mb0[1] = bb0[rt][s]; + mb1[0] = ba1[rt][s]; mb1[1] = bb1[rt][s]; + mc[rt][t] = coopMatMulAdd(ma0, mb0, mc[rt][t]); + mc[rt][t] = coopMatMulAdd(ma1, mb1, mc[rt][t]); + } + } + } + + if (FUSE_MODE == 3u) { + MMA_FVEC4 uw0, uw1, uw2, uw3; + dequant16(true, u_row_base[t], ci, uw0, uw1, uw2, uw3); + [[unroll]] for (uint s = 0u; s < 4u; ++s) { + coopmat mu0, mu1; + mu0[0] = uw0[s]; mu0[1] = uw2[s]; + mu1[0] = uw1[s]; mu1[1] = uw3[s]; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if (rt == 0u || (8u * rt < n_valid)) { + coopmat mb0, mb1; + mb0[0] = ba0[rt][s]; mb0[1] = bb0[rt][s]; + mb1[0] = ba1[rt][s]; mb1[1] = bb1[rt][s]; + mc_u[rt][t] = coopMatMulAdd(mu0, mb0, mc_u[rt][t]); + mc_u[rt][t] = coopMatMulAdd(mu1, mb1, mc_u[rt][t]); + } + } + } + } + } + } + } + + // Store path: when NSG == 1, write directly from registers with ZERO reduction shmem and ZERO barriers! + if (NSG == 1u) { + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + if ((CSG == 1u && rt == 0u) || (sg_c_off + 8u * rt < n_valid)) { + [[unroll]] for (uint e = 0u; e < 2u; ++e) { +#ifdef MUL_MAT_ID + const uint col_in_tile = sg_c_off + 8u * rt + fn + e; + if (col_in_tile < tile_ne1) { + const uint packed = mma_id_col_packed(row_begin, tile_ne1, col_in_tile); + const u16vec2 rid = u16vec2(packed & 0xFFFFu, packed >> 16u); + const uint d_col_base = uint(rid.y) * p.batch_stride_d + uint(rid.x) * p.stride_d; + float col_scale = 1.0f; + float exp_scale = 1.0f; + if (FUSE_MODE == 3u && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0u) { + exp_scale = data_aux0[expert_idx]; + } else if (FUSE_MODE == 4u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0u) { + exp_scale = data_aux0[expert_idx]; + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1) != 0u) { + if (USE_SH_IDS) { + col_scale = sh_col_scale[col_in_tile]; + } else { + const uint s1_idx = uint(rid.x) + (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1_TOK) != 0u) ? (uint(rid.y) * p.nei0) : 0u); + col_scale = data_aux1[s1_idx]; + } + } + } else if (USE_SH_IDS) { + col_scale = sh_col_scale[col_in_tile]; + } else { + const uint s0_idx = uint(rid.x) + (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE0_TOK) != 0u) ? (uint(rid.y) * p.nei0) : 0u); + col_scale = data_aux0[s0_idx]; + } + } + [[unroll]] for (uint t = 0u; t < NT; ++t) { + const uint r0 = sg_m0 + 8u * t + fm; + if (r0 < p.M) { + const uint d_idx = d_col_base + r0; + float val = mc[rt][t][e]; + if (FUSE_MODE == 3u) { + float u = mc_u[rt][t][e]; + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0u) { + precise float v_exp = val * exp_scale; + precise float u_exp = u * exp_scale; + val = v_exp; + u = u_exp; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SITU_MERGED) != 0u) { + const float beta = p.glu_alpha; + const float lb = p.glu_limit; + const float act = (tanh(val * (1.0f / beta)) * beta) * (1.0f / (1.0f + exp(-val))); + const float u_c = (lb > 0.0f) ? (tanh(u * (1.0f / lb)) * lb) : u; + val = act * u_c; + } else { + val = (val / (1.0f + exp(-val))) * u; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_D_F16_AUX1) != 0u) { + data_d_f16[d_idx] = float16_t(val); + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SKIP_F32_D) == 0u) { + data_d[d_idx] = val; + } + } else { + if (FUSE_MODE == 4u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_EXP_SCALE0) != 0u) { + precise float v_exp = val * exp_scale; + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_SCALE1) != 0u) { + precise float v_out = v_exp * col_scale; + val = v_out; + } else { + val = v_exp; + } + } else { + val *= col_scale; + } + } else if (FUSE_MODE == 1u) { + val = mma_apply_id_epilogue(val, expert_idx, rid, r0, d_idx); + } + data_d[d_idx] = val; + } + } + } + } +#else + const uint col = wg_n0 + 8u * rt + fn + e; + if (col < p.N) { + const uint tok_col = batch_idx * p.N + col; + [[unroll]] for (uint t = 0u; t < NT; ++t) { + const uint r_global = sg_m0 + 8u * t + fm; + if (FUSE_MODE == 2u && tile_second[t]) { + const uint r1 = r_global - p.pair_m0; + const uint m1 = p.M - p.pair_m0; + if (r1 < m1) { + const uint d2_idx = batch_idx * p.batch_stride_d2 + col * p.stride_d2 + r1; + float v2 = mc[rt][t][e]; + if (FUSE_LORA != 0u && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_LORA1) != 0u) { + v2 += mma_eval_lora1(r1, tok_col); + } + data_d2[d2_idx] = mma_apply_dense_epilogue(v2, r1, col, d2_idx, true); + } + } else { + const uint m_lim = (FUSE_MODE == 2u) ? p.pair_m0 : p.M; + if (r_global < m_lim) { + const uint d_idx = batch_idx * p.batch_stride_d + col * p.stride_d + r_global; + float val = mc[rt][t][e]; + if (FUSE_LORA != 0u && FUSE_MODE != 0u && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_LORA0) != 0u) { + val += mma_eval_lora0(r_global, tok_col); + } + if (FUSE_MODE == 3u) { + float u = mc_u[rt][t][e]; + if (FUSE_LORA != 0u && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_LORA1) != 0u) { + u += mma_eval_lora1(r_global, tok_col); + } + val = (val / (1.0f + exp(-val))) * u; + } else if (FUSE_MODE == 4u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0u) { + val += data_aux0[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS1) != 0u) { + val += data_aux1[d_idx]; + } + } else if (FUSE_MODE == 1u || FUSE_MODE == 2u) { + val = mma_apply_dense_epilogue(val, r_global, col, d_idx, false); + } + data_d[d_idx] = val; + } + } + } + } +#endif + } + } + } + return; + } + +#ifndef MUL_MAT_ID + // NSG > 1 (MSG == 1) reduction through shared memory (dense only) + const uint stride_sg = RT * NT * 64u; + [[unroll]] for (uint rt = 0u; rt < RT; ++rt) { + [[unroll]] for (uint t = 0u; t < NT; ++t) { + const uint base = sg_k * stride_sg + (rt * NT + t) * 64u + 2u * lane; + red_shmem[base + 0u] = mc[rt][t][0]; + red_shmem[base + 1u] = mc[rt][t][1]; + if (FUSE_MODE == 3u) { + const uint ubase = NSG * stride_sg + base; + red_shmem[ubase + 0u] = mc_u[rt][t][0]; + red_shmem[ubase + 1u] = mc_u[rt][t][1]; + } + } + } + barrier(); + + for (uint idx = tid; idx < stride_sg; idx += WG_THREADS) { + const uint rt = idx / (NT * 64u); + if (rt > 0u && (8u * rt >= n_valid)) { + continue; + } + const uint t = (idx / 64u) % NT; + const uint l = (idx & 63u) >> 1u; + const uint e = idx & 1u; + + float sum = 0.0f; + float sum_u = 0.0f; + [[unroll]] for (uint sg = 0u; sg < NSG; ++sg) { + sum += red_shmem[sg * stride_sg + idx]; + if (FUSE_MODE == 3u) { + sum_u += red_shmem[(NSG + sg) * stride_sg + idx]; + } + } + + const uint l_fm = mma_lane_fm(l); + const uint l_fn = mma_lane_fn(l); + + const uint col = wg_n0 + 8u * rt + l_fn + e; + if (col < p.N) { + const uint tok_col = batch_idx * p.N + col; + const uint tile_r = sg_m0 + 8u * t; + const uint r_global = tile_r + l_fm; + if (FUSE_MODE == 2u && tile_r >= p.pair_m0) { + const uint r1 = r_global - p.pair_m0; + const uint m1 = p.M - p.pair_m0; + if (r1 < m1) { + const uint d2_idx = batch_idx * p.batch_stride_d2 + col * p.stride_d2 + r1; + float v2 = sum; + if (FUSE_LORA != 0u && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_LORA1) != 0u) { + v2 += mma_eval_lora1(r1, tok_col); + } + data_d2[d2_idx] = mma_apply_dense_epilogue(v2, r1, col, d2_idx, true); + } + } else { + const uint m_lim = (FUSE_MODE == 2u) ? p.pair_m0 : p.M; + if (r_global < m_lim) { + const uint d_idx = batch_idx * p.batch_stride_d + col * p.stride_d + r_global; + float val = sum; + if (FUSE_LORA != 0u && FUSE_MODE != 0u && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_LORA0) != 0u) { + val += mma_eval_lora0(r_global, tok_col); + } + if (FUSE_MODE == 3u) { + float u = sum_u; + if (FUSE_LORA != 0u && (p.fusion_flags & MAT_VEC_FUSION_FLAGS_LORA1) != 0u) { + u += mma_eval_lora1(r_global, tok_col); + } + val = (val / (1.0f + exp(-val))) * u; + } else if (FUSE_MODE == 4u) { + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0u) { + val += data_aux0[d_idx]; + } + if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS1) != 0u) { + val += data_aux1[d_idx]; + } + } else if (FUSE_MODE == 1u || FUSE_MODE == 2u) { + val = mma_apply_dense_epilogue(val, r_global, col, d_idx, false); + } + data_d[d_idx] = val; + } + } + } + } +#endif +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/multi_add_rms_mul.comp b/ggml/src/ggml-vulkan/vulkan-shaders/multi_add_rms_mul.comp new file mode 100644 index 000000000000..48dba71a79ff --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/multi_add_rms_mul.comp @@ -0,0 +1,365 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : enable +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_shuffle : require + +layout(constant_id = 0) const uint NUM_SRCS = 2; +layout(constant_id = 1) const uint RMS_TREE_MODE = 0; +layout(constant_id = 2) const uint DO_MUL = 1; +layout(constant_id = 3) const uint BLOCK_SIZE = 512; + +layout(local_size_x_id = 3, local_size_y = 1, local_size_z = 1) in; + +layout(binding = 0) readonly buffer A0 { float data_a0[]; }; +layout(binding = 0) readonly buffer A0V4 { vec4 data_a0_v4[]; }; +layout(binding = 1) readonly buffer A1 { float data_a1[]; }; +layout(binding = 1) readonly buffer A1V4 { vec4 data_a1_v4[]; }; +layout(binding = 2) readonly buffer A2 { float data_a2[]; }; +layout(binding = 2) readonly buffer A2V4 { vec4 data_a2_v4[]; }; +layout(binding = 3) readonly buffer A3 { float data_a3[]; }; +layout(binding = 3) readonly buffer A3V4 { vec4 data_a3_v4[]; }; +layout(binding = 4) readonly buffer A4 { float data_a4[]; }; +layout(binding = 4) readonly buffer A4V4 { vec4 data_a4_v4[]; }; +layout(binding = 5) readonly buffer A5 { float data_a5[]; }; +layout(binding = 5) readonly buffer A5V4 { vec4 data_a5_v4[]; }; +layout(binding = 6) readonly buffer A6 { float data_a6[]; }; +layout(binding = 6) readonly buffer A6V4 { vec4 data_a6_v4[]; }; +layout(binding = 7) readonly buffer A7 { float data_a7[]; }; +layout(binding = 7) readonly buffer A7V4 { vec4 data_a7_v4[]; }; +layout(binding = 8) readonly buffer A8 { float data_a8[]; }; +layout(binding = 8) readonly buffer A8V4 { vec4 data_a8_v4[]; }; +layout(binding = 9) readonly buffer A9 { float data_a9[]; }; +layout(binding = 9) readonly buffer A9V4 { vec4 data_a9_v4[]; }; +layout(binding = 10) writeonly buffer AddDst { float add_dst[]; }; +layout(binding = 10) writeonly buffer AddDstV4 { vec4 add_dst_v4[]; }; +layout(binding = 11) readonly buffer Weight { float data_w[]; }; +layout(binding = 11) readonly buffer WeightV4 { vec4 data_w_v4[]; }; +layout(binding = 12) writeonly buffer RmsDst { float rms_dst[]; }; +layout(binding = 12) writeonly buffer RmsDstV4 { vec4 rms_dst_v4[]; }; +layout(binding = 13) writeonly buffer RmsDstF16V4 { f16vec4 rms_dst_f16_v4[]; }; + +layout(push_constant) uniform PushConstants { + uint ne0; + uint nrows; + float eps; + uint write_add_dst; + uint nb1[10]; +} p; + +const uint SUMSH_SIZE = (RMS_TREE_MODE == 2u) ? 16u : 512u; +shared float sumsh[SUMSH_SIZE]; + +vec4 load_sum_v4(const uint row, const uint v4_col) { + vec4 s = data_a0_v4[row * (p.nb1[0] >> 2u) + v4_col] + data_a1_v4[row * (p.nb1[1] >> 2u) + v4_col]; + if (NUM_SRCS > 2) s += data_a2_v4[row * (p.nb1[2] >> 2u) + v4_col]; + if (NUM_SRCS > 3) s += data_a3_v4[row * (p.nb1[3] >> 2u) + v4_col]; + if (NUM_SRCS > 4) s += data_a4_v4[row * (p.nb1[4] >> 2u) + v4_col]; + if (NUM_SRCS > 5) s += data_a5_v4[row * (p.nb1[5] >> 2u) + v4_col]; + if (NUM_SRCS > 6) s += data_a6_v4[row * (p.nb1[6] >> 2u) + v4_col]; + if (NUM_SRCS > 7) s += data_a7_v4[row * (p.nb1[7] >> 2u) + v4_col]; + if (NUM_SRCS > 8) s += data_a8_v4[row * (p.nb1[8] >> 2u) + v4_col]; + if (NUM_SRCS > 9) s += data_a9_v4[row * (p.nb1[9] >> 2u) + v4_col]; + return s; +} + +float load_sum(const uint row, const uint col) { + precise float s; + if (NUM_SRCS == 2) { + s = data_a0[row * p.nb1[0] + col] + data_a1[row * p.nb1[1] + col]; + } else { + s = 0.0f; + s += data_a0[row * p.nb1[0] + col]; + s += data_a1[row * p.nb1[1] + col]; + if (NUM_SRCS > 2) s += data_a2[row * p.nb1[2] + col]; + if (NUM_SRCS > 3) s += data_a3[row * p.nb1[3] + col]; + if (NUM_SRCS > 4) s += data_a4[row * p.nb1[4] + col]; + if (NUM_SRCS > 5) s += data_a5[row * p.nb1[5] + col]; + if (NUM_SRCS > 6) s += data_a6[row * p.nb1[6] + col]; + if (NUM_SRCS > 7) s += data_a7[row * p.nb1[7] + col]; + if (NUM_SRCS > 8) s += data_a8[row * p.nb1[8] + col]; + if (NUM_SRCS > 9) s += data_a9[row * p.nb1[9] + col]; + } + return s; +} + +void main() { + const uint row = gl_WorkGroupID.x + gl_WorkGroupID.y * gl_NumWorkGroups.x; + if (row >= p.nrows) { + return; + } + + const uint tid = gl_LocalInvocationID.x; + const uint row_off = row * p.ne0; + + if (RMS_TREE_MODE == 2u) { + const uint ne0_v4 = p.ne0 >> 2u; + const uint row_v4 = row_off >> 2u; + vec4 vals_v4[8]; + float sum = 0.0f; + + const bool do_add = (p.write_add_dst & 1u) != 0u; + const bool do_f16 = (p.write_add_dst & 2u) != 0u; + + if (ne0_v4 <= 4u * BLOCK_SIZE) { + [[unroll]] for (uint idx = 0u; idx < 4u; ++idx) { + const uint v4_col = tid + idx * BLOCK_SIZE; + vec4 xv = vec4(0.0f); + if (v4_col < ne0_v4) { + xv = load_sum_v4(row, v4_col); + if (do_add) { + add_dst_v4[row_v4 + v4_col] = xv; + } + } + vals_v4[idx] = xv; + sum += dot(xv, xv); + } + } else { + [[unroll]] for (uint idx = 0u; idx < 8u; ++idx) { + const uint v4_col = tid + idx * BLOCK_SIZE; + vec4 xv = vec4(0.0f); + if (v4_col < ne0_v4) { + xv = load_sum_v4(row, v4_col); + if (do_add) { + add_dst_v4[row_v4 + v4_col] = xv; + } + } + vals_v4[idx] = xv; + sum += dot(xv, xv); + } + } + + sum = subgroupAdd(sum); + if (subgroupElect()) { + sumsh[gl_SubgroupID] = sum; + } + barrier(); + + float total_sq = 0.0f; + if (gl_NumSubgroups <= 4u) { + [[unroll]] for (uint i = 0u; i < gl_NumSubgroups; ++i) { + total_sq += sumsh[i]; + } + } else { + for (uint i = gl_SubgroupInvocationID; i < gl_NumSubgroups; i += gl_SubgroupSize) { + total_sq += sumsh[i]; + } + total_sq = subgroupAdd(total_sq); + } + + const float scale = inversesqrt(total_sq / float(p.ne0) + p.eps); + if (ne0_v4 <= 4u * BLOCK_SIZE) { + [[unroll]] for (uint idx = 0u; idx < 4u; ++idx) { + const uint v4_col = tid + idx * BLOCK_SIZE; + if (v4_col < ne0_v4) { + const vec4 out_v4 = (DO_MUL != 0u) + ? (scale * vals_v4[idx] * data_w_v4[v4_col]) + : (scale * vals_v4[idx]); + rms_dst_v4[row_v4 + v4_col] = out_v4; + if (do_f16) { + rms_dst_f16_v4[row_v4 + v4_col] = f16vec4(out_v4); + } + } + } + } else { + [[unroll]] for (uint idx = 0u; idx < 8u; ++idx) { + const uint v4_col = tid + idx * BLOCK_SIZE; + if (v4_col < ne0_v4) { + const vec4 out_v4 = (DO_MUL != 0u) + ? (scale * vals_v4[idx] * data_w_v4[v4_col]) + : (scale * vals_v4[idx]); + rms_dst_v4[row_v4 + v4_col] = out_v4; + if (do_f16) { + rms_dst_f16_v4[row_v4 + v4_col] = f16vec4(out_v4); + } + } + } + } + return; + } + + if (RMS_TREE_MODE == 0) { + float vals[8]; + float sum = 0.0f; + + if (p.ne0 <= 2048u) { + [[unroll]] for (uint idx = 0; idx < 4; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + float xi = 0.0f; + if (col < p.ne0) { + xi = load_sum(row, col); + if (p.write_add_dst != 0) { + add_dst[row_off + col] = xi; + } + } + vals[idx] = xi; + sum += xi * xi; + } + } else { + [[unroll]] for (uint idx = 0; idx < 8; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + float xi = 0.0f; + if (col < p.ne0) { + xi = load_sum(row, col); + if (p.write_add_dst != 0) { + add_dst[row_off + col] = xi; + } + } + vals[idx] = xi; + sum += xi * xi; + } + } + + sumsh[tid] = sum; + barrier(); + + if (gl_SubgroupSize == 32) { + if (gl_SubgroupID == 0) { + const uint lane = gl_SubgroupInvocationID; + precise float p0_a = sumsh[lane] + sumsh[lane + 256u]; + precise float p0_b = sumsh[lane + 128u] + sumsh[lane + 384u]; + precise float p1_a = sumsh[lane + 32u] + sumsh[lane + 288u]; + precise float p1_b = sumsh[lane + 160u] + sumsh[lane + 416u]; + precise float p2_a = sumsh[lane + 64u] + sumsh[lane + 320u]; + precise float p2_b = sumsh[lane + 192u] + sumsh[lane + 448u]; + precise float p3_a = sumsh[lane + 96u] + sumsh[lane + 352u]; + precise float p3_b = sumsh[lane + 224u] + sumsh[lane + 480u]; + precise float p0 = p0_a + p0_b; + precise float p1 = p1_a + p1_b; + precise float p2 = p2_a + p2_b; + precise float p3 = p3_a + p3_b; + precise float s_lo = p0 + p2; + precise float s_hi = p1 + p3; + precise float s32 = s_lo + s_hi; + precise float s16 = s32 + subgroupShuffleXor(s32, 16); + precise float s8 = s16 + subgroupShuffleXor(s16, 8); + precise float s4 = s8 + subgroupShuffleXor(s8, 4); + precise float s2 = s4 + subgroupShuffleXor(s4, 2); + precise float s1 = s2 + subgroupShuffleXor(s2, 1); + if (lane == 0) { + sumsh[0] = s1; + } + } + barrier(); + } else { + [[unroll]] for (int s = int(BLOCK_SIZE) / 2; s > 0; s >>= 1) { + if (int(tid) < s) { + sum += sumsh[tid + uint(s)]; + sumsh[tid] = sum; + } + barrier(); + } + } + + const float mean = sumsh[0] / float(p.ne0); + const float scale = inversesqrt(mean + p.eps); + + if (p.ne0 <= 2048u) { + [[unroll]] for (uint idx = 0; idx < 4; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + if (col < p.ne0) { + const float value = (DO_MUL != 0) ? (scale * vals[idx] * data_w[col]) : (scale * vals[idx]); + rms_dst[row_off + col] = value; + } + } + } else { + [[unroll]] for (uint idx = 0; idx < 8; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + if (col < p.ne0) { + const float value = (DO_MUL != 0) ? (scale * vals[idx] * data_w[col]) : (scale * vals[idx]); + rms_dst[row_off + col] = value; + } + } + } + } else { + const uint num_partials = p.ne0 / 512u; + const uint num_iters = (num_partials + 1u) >> 1; + const uint team = tid >> 8; + const uint t256 = tid & 255u; + const uint num_sub_per_team = 256u / gl_SubgroupSize; + const uint sg_in_team = t256 / gl_SubgroupSize; + + float vals_lo[4]; + float vals_hi[4]; + + [[unroll]] for (uint k = 0; k < 4; ++k) { + if (k < num_iters) { + const uint c = k * 2u + team; + float sum_sq = 0.0f; + float s0 = 0.0f; + float s1 = 0.0f; + if (c < num_partials) { + const uint col_lo = c * 512u + t256; + const uint c_off = row_off + c * 512u; + s0 = load_sum(row, col_lo); + if (p.write_add_dst != 0) { + add_dst[c_off + t256] = s0; + } + s1 = load_sum(row, col_lo + 256u); + if (p.write_add_dst != 0) { + add_dst[c_off + t256 + 256u] = s1; + } + precise float sq0 = s0 * s0; + sum_sq = fma(s1, s1, sq0); + } + vals_lo[k] = s0; + vals_hi[k] = s1; + + sum_sq = subgroupAdd(sum_sq); + if (gl_SubgroupInvocationID == 0 && c < num_partials) { + sumsh[c * 16u + sg_in_team] = sum_sq; + } + } + } + barrier(); + + if (gl_SubgroupID == 0) { + const uint lane = gl_SubgroupInvocationID; + float psum = 0.0f; + if (gl_SubgroupSize == 32) { + if (lane < num_partials) { + const uint base = lane * 16u; + precise float a0 = sumsh[base + 0u] + sumsh[base + 4u]; + precise float a1 = sumsh[base + 1u] + sumsh[base + 5u]; + precise float a2 = sumsh[base + 2u] + sumsh[base + 6u]; + precise float a3 = sumsh[base + 3u] + sumsh[base + 7u]; + precise float b0 = a0 + a2; + precise float b1 = a1 + a3; + psum += (b0 + b1); + } + } else { + for (uint i = lane; i < num_partials; i += gl_SubgroupSize) { + const uint base = i * 16u; + float c_sum = 0.0f; + for (uint s = 0u; s < num_sub_per_team; ++s) { + c_sum += sumsh[base + s]; + } + psum += c_sum; + } + } + psum = subgroupAdd(psum); + if (lane == 0u) { + sumsh[0] = psum; + } + } + barrier(); + + const float mean = sumsh[0] / float(p.ne0); + const float scale = inversesqrt(mean + p.eps); + + [[unroll]] for (uint k = 0; k < 4; ++k) { + if (k < num_iters) { + const uint c = k * 2u + team; + if (c < num_partials) { + const uint col_lo = c * 512u + t256; + const uint col_hi = col_lo + 256u; + rms_dst[row_off + col_lo] = (DO_MUL != 0) ? (scale * vals_lo[k] * data_w[col_lo]) : (scale * vals_lo[k]); + rms_dst[row_off + col_hi] = (DO_MUL != 0) ? (scale * vals_hi[k] * data_w[col_hi]) : (scale * vals_hi[k]); + } + } + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/repack_planar.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/repack_planar.glsl new file mode 100644 index 000000000000..dae106327fb4 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/repack_planar.glsl @@ -0,0 +1,76 @@ +// Shared 16B-aligned Compact 1-Superblock 0-ULP Planar layout constants & +// magic-bias decoders for Vulkan_Repack (Q4_K, Q5_K, Q6_K). +// +// Each 1-superblock (256-weight) planar block contains: +// Q4_K (144 B = 9 uvec4 = 36 uint32, 0% bloat): +// uvec4[0]: exact raw { dm (u32), scales[0..3], scales[4..7], scales[8..11] } +// uvec4[1..8]: qs lane-interleaved: itid8=0..7 -> uvec4(qs[itid8], qs[itid8+8], qs[itid8+16], qs[itid8+24]) +// Q5_K (176 B = 11 uvec4 = 44 uint32, 0% bloat): +// uvec4[0]: exact raw { dm (u32), scales[0..3], scales[4..7], scales[8..11] } +// uvec4[1..8]: qs lane-interleaved: itid8=0..7 -> uvec4(qs[itid8], qs[itid8+8], qs[itid8+16], qs[itid8+24]) +// uvec4[9..10]: 8 qh uint32s (u32[36 + itid8] = qh[itid8]) +// Q6_K (224 B = 14 uvec4 = 56 uint32): +// uvec4[0]: exact raw scales[0..15] (16 int8_t) +// uvec4[1]: { d (u16 in .x low 16 bits), 0, 0, 0 } +// uvec4[2..9]: ql lane-interleaved: itid8=0..7 -> uvec4(ql[itid8], ql[itid8+8], ql[itid8+16], ql[itid8+24]) +// uvec4[10..13]: 8 qh uvec2s (u32[40 + itid8*2 + h] = qh[itid8 + 8*h]) + +#define REPACK_HDR_OFF_U4 0u +#define REPACK_HDR_OFF_U32 0u +#define REPACK_QS_OFF_U4 1u +#define REPACK_QS_OFF_U32 4u + +#define REPACK_Q4_K_SB_U4 9u +#define REPACK_Q4_K_SB_U32 36u + +#define REPACK_Q5_K_QH_OFF_U4 9u +#define REPACK_Q5_K_QH_OFF_U32 36u +#define REPACK_Q5_K_SB_U4 11u +#define REPACK_Q5_K_SB_U32 44u + +#define REPACK_Q6_K_SC_OFF_U4 0u +#define REPACK_Q6_K_SC_OFF_U32 0u +#define REPACK_Q6_K_D_OFF_U4 1u +#define REPACK_Q6_K_D_OFF_U32 4u +#define REPACK_Q6_K_QL_OFF_U4 2u +#define REPACK_Q6_K_QL_OFF_U32 8u +#define REPACK_Q6_K_QH_OFF_U4 10u +#define REPACK_Q6_K_QH_OFF_U32 40u +#define REPACK_Q6_K_SB_U4 14u +#define REPACK_Q6_K_SB_U32 56u + +vec4 repack_magic_u4(const uint q4) { + const f16vec2 p02 = unpackFloat2x16((q4 & 0x000F000Fu) | 0x64006400u) - f16vec2(1024.0); + const f16vec2 p13 = unpackFloat2x16(((q4 >> 8u) & 0x000F000Fu) | 0x64006400u) - f16vec2(1024.0); + return vec4(float(p02.x), float(p13.x), float(p02.y), float(p13.y)); +} + +f16vec4 repack_magic_u4_h(const uint q4) { + const f16vec2 p02 = unpackFloat2x16((q4 & 0x000F000Fu) | 0x64006400u) - f16vec2(1024.0); + const f16vec2 p13 = unpackFloat2x16(((q4 >> 8u) & 0x000F000Fu) | 0x64006400u) - f16vec2(1024.0); + return f16vec4(p02.x, p13.x, p02.y, p13.y); +} + +vec4 repack_magic_u5(const uint q5_02, const uint q5_13) { + const f16vec2 p02 = unpackFloat2x16((q5_02 & 0x001F001Fu) | 0x64006400u) - f16vec2(1024.0); + const f16vec2 p13 = unpackFloat2x16((q5_13 & 0x001F001Fu) | 0x64006400u) - f16vec2(1024.0); + return vec4(float(p02.x), float(p13.x), float(p02.y), float(p13.y)); +} + +f16vec4 repack_magic_u5_h(const uint q5_02, const uint q5_13) { + const f16vec2 p02 = unpackFloat2x16((q5_02 & 0x001F001Fu) | 0x64006400u) - f16vec2(1024.0); + const f16vec2 p13 = unpackFloat2x16((q5_13 & 0x001F001Fu) | 0x64006400u) - f16vec2(1024.0); + return f16vec4(p02.x, p13.x, p02.y, p13.y); +} + +vec4 repack_magic_q6(const uint q6_02, const uint q6_13) { + const f16vec2 p02 = unpackFloat2x16((q6_02 & 0x003F003Fu) | 0x64006400u) - f16vec2(1056.0); + const f16vec2 p13 = unpackFloat2x16((q6_13 & 0x003F003Fu) | 0x64006400u) - f16vec2(1056.0); + return vec4(float(p02.x), float(p13.x), float(p02.y), float(p13.y)); +} + +f16vec4 repack_magic_q6_h(const uint q6_02, const uint q6_13) { + const f16vec2 p02 = unpackFloat2x16((q6_02 & 0x003F003Fu) | 0x64006400u) - f16vec2(1056.0); + const f16vec2 p13 = unpackFloat2x16((q6_13 & 0x003F003Fu) | 0x64006400u) - f16vec2(1056.0); + return f16vec4(p02.x, p13.x, p02.y, p13.y); +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp index b73fdeca48fd..b6c840fd6eb6 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp @@ -7,6 +7,10 @@ #if USE_SUBGROUP_ADD #extension GL_KHR_shader_subgroup_basic : require #extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#else +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_shuffle : enable #endif layout (constant_id = 3) const int BLOCK_SIZE = 512; @@ -38,6 +42,7 @@ layout (binding = 6) readonly buffer R_I {uvec2 rope_data_i[];}; // indices for #define GGML_ROPE_TYPE_NEOX 2 #define GGML_ROPE_TYPE_MROPE 8 #define GGML_ROPE_TYPE_VISION 24 +#define GGML_ROPE_TYPE_IMROPE 40 #elif RMS_NORM_ADD_FUSION @@ -47,7 +52,39 @@ layout (binding = 4) readonly buffer E {float data_e[];}; #elif RMS_NORM_SET_ROWS_FUSION layout (binding = 3) readonly buffer I {uvec2 data_i[];}; +#if USE_SUBGROUP_ADD +layout (binding = 0) readonly buffer A_V4 {vec4 data_a_v4[];}; +layout (binding = 2) writeonly buffer D_SET_V4 {SET_ROWS_D_V4 data_d_set_v4[];}; +#endif + +#elif RMS_NORM_SILU_GATE_FUSION + +// gen: (rms_norm(x) * w) * silu(z), z laid out like dst (the Gated-DeltaNet output norm) +layout (binding = 3) readonly buffer Z {float data_z[];}; +#if USE_SUBGROUP_ADD +layout (binding = 3) readonly buffer Z_V4 {vec4 data_z_v4[];}; +layout (binding = 4) writeonly buffer D_F16_V4 {f16vec4 data_d_f16_v4[];}; +#endif + +#elif RMS_NORM_SCALE_FUSION + +layout (binding = 3) writeonly buffer D2 {D_TYPE data_d2[];}; +#if USE_SUBGROUP_ADD +layout (binding = 3) writeonly buffer D2_V4 {vec4 data_d2_v4[];}; +#endif + +#else + +#if USE_SUBGROUP_ADD +layout (binding = 3) writeonly buffer D_F16_V4 {f16vec4 data_d_f16_v4[];}; +#endif + +#endif +#if USE_SUBGROUP_ADD && !RMS_NORM_ROPE_FUSION && !RMS_NORM_SET_ROWS_FUSION && !RMS_NORM_ADD_FUSION +layout (binding = 0) readonly buffer A_V4 {vec4 data_a_v4[];}; +layout (binding = 1) readonly buffer B_V4 {vec4 data_b_v4[];}; +layout (binding = 2) writeonly buffer D_V4 {vec4 data_d_v4[];}; #endif layout (constant_id = 1) const bool do_multiply = false; @@ -55,9 +92,53 @@ layout (constant_id = 1) const bool do_multiply = false; layout (constant_id = 2) const bool do_post_multiply = false; #endif +#if USE_SUBGROUP_ADD +const int SUMSH_SIZE = (BLOCK_SIZE <= 32) ? 1 : (BLOCK_SIZE / 32); +shared FLOAT_TYPE sumsh[SUMSH_SIZE]; +#else shared FLOAT_TYPE sumsh[BLOCK_SIZE]; +#endif + +void write_rms_col(const uint col, const FLOAT_TYPE scale, const uint32_t a_offset, const uint32_t b_offset, const uint32_t d_offset, const bool use_fastmod) { + if (do_multiply) { + const uint b_col = use_fastmod ? fastmod(col, p.ne10) : col; + FLOAT_TYPE value = scale * FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col])) * FLOAT_TYPE(B_TO_FLOAT(data_b[b_offset + b_col])); +#if RMS_NORM_ADD_FUSION + value += FLOAT_TYPE(C_TO_FLOAT(data_c[d_offset + col])); + if (do_post_multiply) { + value *= FLOAT_TYPE(data_e[0]); + } +#endif +#if RMS_NORM_SILU_GATE_FUSION + { + // same expressions and roundings as rms_norm_mul (store) then silu_mul (unary.comp op_silu) + precise float gen_n = float(D_TYPE(value)); + precise float gen_zv = data_z[d_offset + col]; + precise float gen_g = gen_zv / (1.0f + exp(-gen_zv)); + precise FLOAT_TYPE gen_o = FLOAT_TYPE(gen_g) * FLOAT_TYPE(gen_n); + value = gen_o; + } +#endif + data_d[d_offset + col] = FLOAT_TO_D(value); + } else { +#if RMS_NORM_SCALE_FUSION + // gen: rms_norm followed by scale(param2, bias 0), same expressions as scale.comp + // precise: no contraction or reassociation, so the two roundings match rms_norm + scale run separately + precise FLOAT_TYPE gen_v = scale * FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col])); + precise FLOAT_TYPE gen_s = gen_v * FLOAT_TYPE(p.param2); + precise FLOAT_TYPE gen_o = gen_s + FLOAT_TYPE(0.0f); + if ((p.param3 & 1) != 0 && gl_WorkGroupID.x >= p.ne21) { + data_d2[d_offset + col] = FLOAT_TO_D(gen_o); + } else { + data_d[d_offset + col] = FLOAT_TO_D(gen_o); + } +#else + data_d[d_offset + col] = FLOAT_TO_D(scale * FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col]))); +#endif + } +} -void rms_norm(uint num_iters) { +void main() { const uint ncols = p.ne00; const uint nrows = gl_NumWorkGroups.x; const uint nchannels = p.ne02; @@ -69,11 +150,14 @@ void rms_norm(uint num_iters) { const uint stride_row = p.nb01; const uint stride_channel = p.nb02; const uint stride_sample = p.nb03; + const uint num_blocks = (ncols + BLOCK_SIZE - 1) / BLOCK_SIZE; // grid.y/z are clamped to the device workgroup limit, iterate over the excess channels/samples for (uint samp = gl_WorkGroupID.z; samp < nsamples; samp += gl_NumWorkGroups.z) { for (uint channel = gl_WorkGroupID.y; channel < nchannels; channel += gl_NumWorkGroups.y) { - barrier(); + if (BLOCK_SIZE > 32 && (samp != gl_WorkGroupID.z || channel != gl_WorkGroupID.y)) { + barrier(); + } uint32_t a_offset = samp*stride_sample + channel*stride_channel + row*stride_row + get_aoffset(); uint32_t b_offset = src1_idx(0, row, channel, samp) + get_boffset(); @@ -81,24 +165,208 @@ void rms_norm(uint num_iters) { // Per-row offset in shared memory uint32_t d_offset = 0; #elif RMS_NORM_SET_ROWS_FUSION - uint32_t d_offset = data_i[channel].x*p.nb21 + row*ncols + get_doffset(); + const uint i_misalign = uint(p.param3) >> 16u; + uint32_t d_offset = data_i[i_misalign + channel].x*p.nb21 + row*ncols + get_doffset(); +#if USE_SUBGROUP_ADD + if ((uint(p.param3) & 2u) != 0u && !do_multiply && (ncols >> 2u) == uint(BLOCK_SIZE)) { + const uint a_v4 = a_offset >> 2u; + const uint d_v4 = d_offset >> 2u; + const vec4 xv = data_a_v4[a_v4 + tid]; + float sum_sq = subgroupAdd(dot(xv, xv)); + if (BLOCK_SIZE > 32) { + if (subgroupElect()) { + sumsh[gl_SubgroupID] = sum_sq; + } + barrier(); + sum_sq = 0.0f; + [[unroll]] for (uint i = 0u; i < gl_NumSubgroups; ++i) { + sum_sq += sumsh[i]; + } + } + const float scale = inversesqrt(sum_sq / float(ncols) + p.param1); + const vec4 out_v4 = scale * xv; + data_d_set_v4[d_v4 + tid] = SET_ROWS_D_V4(out_v4); + continue; + } +#endif +#elif RMS_NORM_SCALE_FUSION + const bool is_d2 = (p.param3 & 1) != 0 && row >= p.ne21; + const uint eff_nrows = (p.param3 & 1) != 0 ? p.ne21 : nrows; + const uint eff_row = is_d2 ? (row - p.ne21) : row; + uint32_t d_offset = ((samp*nchannels + channel)*eff_nrows + eff_row)*ncols + (is_d2 ? uint(p.param3 >> 8) : get_doffset()); #else uint32_t d_offset = ((samp*nchannels + channel)*nrows + row)*ncols + get_doffset(); #endif + +#if USE_SUBGROUP_ADD && !RMS_NORM_ROPE_FUSION && !RMS_NORM_SET_ROWS_FUSION && !RMS_NORM_ADD_FUSION + if ((uint(p.param3) & 2u) != 0u) { + const uint a_v4 = a_offset >> 2u; + const uint b_v4 = b_offset >> 2u; + const uint d_v4 = d_offset >> 2u; + const uint ncols_v4 = ncols >> 2u; + const uint ne10_v4 = p.ne10 >> 2u; + const bool same_w = (ncols_v4 == ne10_v4); +#if !RMS_NORM_SCALE_FUSION + const bool do_f16 = (uint(p.param3) & 4u) != 0u; + const bool skip_f32 = (uint(p.param3) & 8u) != 0u; +#endif + if (ncols_v4 == uint(BLOCK_SIZE)) { + const vec4 xv = data_a_v4[a_v4 + tid]; + float sum_sq = subgroupAdd(dot(xv, xv)); + if (BLOCK_SIZE > 32) { + if (subgroupElect()) { + sumsh[gl_SubgroupID] = sum_sq; + } + barrier(); + sum_sq = 0.0f; + [[unroll]] for (uint i = 0u; i < gl_NumSubgroups; ++i) { + sum_sq += sumsh[i]; + } + } + const float scale = inversesqrt(sum_sq / float(ncols) + p.param1); + if (do_multiply) { + const uint w_idx = same_w ? tid : (tid % ne10_v4); + vec4 out_v4 = (scale * xv) * data_b_v4[b_v4 + w_idx]; +#if RMS_NORM_SILU_GATE_FUSION + const vec4 zv = data_z_v4[d_v4 + tid]; + out_v4 = (zv / (vec4(1.0f) + exp(-zv))) * out_v4; +#endif +#if !RMS_NORM_SCALE_FUSION + if (do_f16) { + data_d_f16_v4[d_v4 + tid] = f16vec4(out_v4); + } + if (!skip_f32) { + data_d_v4[d_v4 + tid] = out_v4; + } +#endif + } else { +#if RMS_NORM_SCALE_FUSION + const vec4 out_v4 = (scale * xv) * p.param2; + if (is_d2) { + data_d2_v4[d_v4 + tid] = out_v4; + } else { + data_d_v4[d_v4 + tid] = out_v4; + } +#else + const vec4 out_v4 = scale * xv; + if (do_f16) { + data_d_f16_v4[d_v4 + tid] = f16vec4(out_v4); + } + if (!skip_f32) { + data_d_v4[d_v4 + tid] = out_v4; + } +#endif + } + } else { + vec4 xv[4]; + float sum_sq = 0.0f; + [[unroll]] for (uint idx = 0u; idx < 4u; ++idx) { + const uint v4_col = tid + idx * uint(BLOCK_SIZE); + xv[idx] = data_a_v4[a_v4 + v4_col]; + sum_sq += dot(xv[idx], xv[idx]); + } + sum_sq = subgroupAdd(sum_sq); + if (BLOCK_SIZE > 32) { + if (subgroupElect()) { + sumsh[gl_SubgroupID] = sum_sq; + } + barrier(); + sum_sq = 0.0f; + if (gl_NumSubgroups <= 4u) { + [[unroll]] for (uint i = 0u; i < gl_NumSubgroups; ++i) { + sum_sq += sumsh[i]; + } + } else { + for (uint i = gl_SubgroupInvocationID; i < gl_NumSubgroups; i += gl_SubgroupSize) { + sum_sq += sumsh[i]; + } + sum_sq = subgroupAdd(sum_sq); + } + } + const float scale = inversesqrt(sum_sq / float(ncols) + p.param1); + [[unroll]] for (uint idx = 0u; idx < 4u; ++idx) { + const uint v4_col = tid + idx * uint(BLOCK_SIZE); + if (do_multiply) { + const uint w_idx = same_w ? v4_col : (v4_col % ne10_v4); + vec4 out_v4 = (scale * xv[idx]) * data_b_v4[b_v4 + w_idx]; +#if RMS_NORM_SILU_GATE_FUSION + const vec4 zv = data_z_v4[d_v4 + v4_col]; + out_v4 = (zv / (vec4(1.0f) + exp(-zv))) * out_v4; +#endif +#if !RMS_NORM_SCALE_FUSION + if (do_f16) { + data_d_f16_v4[d_v4 + v4_col] = f16vec4(out_v4); + } + if (!skip_f32) { + data_d_v4[d_v4 + v4_col] = out_v4; + } +#endif + } else { +#if RMS_NORM_SCALE_FUSION + const vec4 out_v4 = (scale * xv[idx]) * p.param2; + if (is_d2) { + data_d2_v4[d_v4 + v4_col] = out_v4; + } else { + data_d_v4[d_v4 + v4_col] = out_v4; + } +#else + const vec4 out_v4 = scale * xv[idx]; + if (do_f16) { + data_d_f16_v4[d_v4 + v4_col] = f16vec4(out_v4); + } + if (!skip_f32) { + data_d_v4[d_v4 + v4_col] = out_v4; + } +#endif + } + } + } + continue; + } +#endif FLOAT_TYPE sum = FLOAT_TYPE(0.0f); // partial sum for thread in warp #if RMS_NORM_ROPE_FUSION - for (uint col = tid; col < ncols; col += BLOCK_SIZE) { - const FLOAT_TYPE xi = FLOAT_TYPE(data_a[a_offset + col]); + if (num_blocks == 1) { + FLOAT_TYPE xi = FLOAT_TYPE(0); + if (tid < ncols) { + xi = FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + tid])); + } sum += xi * xi; + } else { + [[unroll]] for (uint idx = 0; idx < 2; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + FLOAT_TYPE xi = FLOAT_TYPE(0); + if (col < ncols) { + xi = FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col])); + } + sum += xi * xi; + } } #else - [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { + if (num_blocks == 1) { FLOAT_TYPE xi = FLOAT_TYPE(0); - if (col < ncols) { - xi = FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col])); + if (tid < ncols) { + xi = FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + tid])); } sum += xi * xi; + } else if (num_blocks == 4) { + [[unroll]] for (uint idx = 0; idx < 4; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + FLOAT_TYPE xi = FLOAT_TYPE(0); + if (col < ncols) { + xi = FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col])); + } + sum += xi * xi; + } + } else { + [[dont_unroll]] for (uint col = tid, idx = 0; idx < num_blocks; col += BLOCK_SIZE, ++idx) { + FLOAT_TYPE xi = FLOAT_TYPE(0); + if (col < ncols) { + xi = FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col])); + } + sum += xi * xi; + } } #endif @@ -125,64 +393,150 @@ void rms_norm(uint num_iters) { sumsh[tid] = sum; // sum up partial sums and write back result barrier(); - [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) { - if (tid < s) { - sum += sumsh[tid + s]; - sumsh[tid] = sum; + if (BLOCK_SIZE == 512 && gl_SubgroupSize == 32) { + if (gl_SubgroupID == 0) { + const uint lane = gl_SubgroupInvocationID; + precise FLOAT_TYPE p0_a = sumsh[lane] + sumsh[lane + 256u]; + precise FLOAT_TYPE p0_b = sumsh[lane + 128u] + sumsh[lane + 384u]; + precise FLOAT_TYPE p1_a = sumsh[lane + 32u] + sumsh[lane + 288u]; + precise FLOAT_TYPE p1_b = sumsh[lane + 160u] + sumsh[lane + 416u]; + precise FLOAT_TYPE p2_a = sumsh[lane + 64u] + sumsh[lane + 320u]; + precise FLOAT_TYPE p2_b = sumsh[lane + 192u] + sumsh[lane + 448u]; + precise FLOAT_TYPE p3_a = sumsh[lane + 96u] + sumsh[lane + 352u]; + precise FLOAT_TYPE p3_b = sumsh[lane + 224u] + sumsh[lane + 480u]; + precise FLOAT_TYPE p0 = p0_a + p0_b; + precise FLOAT_TYPE p1 = p1_a + p1_b; + precise FLOAT_TYPE p2 = p2_a + p2_b; + precise FLOAT_TYPE p3 = p3_a + p3_b; + precise FLOAT_TYPE s_lo = p0 + p2; + precise FLOAT_TYPE s_hi = p1 + p3; + precise FLOAT_TYPE s32 = s_lo + s_hi; + precise FLOAT_TYPE s16 = s32 + subgroupShuffleXor(s32, 16); + precise FLOAT_TYPE s8 = s16 + subgroupShuffleXor(s16, 8); + precise FLOAT_TYPE s4 = s8 + subgroupShuffleXor(s8, 4); + precise FLOAT_TYPE s2 = s4 + subgroupShuffleXor(s4, 2); + precise FLOAT_TYPE s1 = s2 + subgroupShuffleXor(s2, 1); + if (lane == 0) { + sumsh[0] = s1; + } } barrier(); + } else if (BLOCK_SIZE == 256 && gl_SubgroupSize == 32) { + if (gl_SubgroupID == 0) { + const uint lane = gl_SubgroupInvocationID; + precise FLOAT_TYPE p0 = sumsh[lane] + sumsh[lane + 128u]; + precise FLOAT_TYPE p1 = sumsh[lane + 32u] + sumsh[lane + 160u]; + precise FLOAT_TYPE p2 = sumsh[lane + 64u] + sumsh[lane + 192u]; + precise FLOAT_TYPE p3 = sumsh[lane + 96u] + sumsh[lane + 224u]; + precise FLOAT_TYPE s_lo = p0 + p2; + precise FLOAT_TYPE s_hi = p1 + p3; + precise FLOAT_TYPE s32 = s_lo + s_hi; + precise FLOAT_TYPE s16 = s32 + subgroupShuffleXor(s32, 16); + precise FLOAT_TYPE s8 = s16 + subgroupShuffleXor(s16, 8); + precise FLOAT_TYPE s4 = s8 + subgroupShuffleXor(s8, 4); + precise FLOAT_TYPE s2 = s4 + subgroupShuffleXor(s4, 2); + precise FLOAT_TYPE s1 = s2 + subgroupShuffleXor(s2, 1); + if (lane == 0) { + sumsh[0] = s1; + } + } + barrier(); + } else if (BLOCK_SIZE >= 128 && gl_SubgroupSize == 32) { + [[unroll]] for (int s = BLOCK_SIZE / 2; s >= 128; s >>= 1) { + if (tid < s) { + sum += sumsh[tid + s]; + sumsh[tid] = sum; + } + barrier(); + } + // Exact 0-ULP match to the s = 64, 32, 16, 8, 4, 2, 1 shared-memory tree reduction + if (gl_SubgroupID == 0) { + const uint lane = gl_SubgroupInvocationID; + precise FLOAT_TYPE s_lo = sumsh[lane] + sumsh[lane + 64]; + precise FLOAT_TYPE s_hi = sumsh[lane + 32] + sumsh[lane + 96]; + precise FLOAT_TYPE s32 = s_lo + s_hi; + precise FLOAT_TYPE s16 = s32 + subgroupShuffleXor(s32, 16); + precise FLOAT_TYPE s8 = s16 + subgroupShuffleXor(s16, 8); + precise FLOAT_TYPE s4 = s8 + subgroupShuffleXor(s8, 4); + precise FLOAT_TYPE s2 = s4 + subgroupShuffleXor(s4, 2); + precise FLOAT_TYPE s1 = s2 + subgroupShuffleXor(s2, 1); + if (lane == 0) { + sumsh[0] = s1; + } + } + barrier(); + } else { + [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) { + if (tid < s) { + sum += sumsh[tid + s]; + sumsh[tid] = sum; + } + barrier(); + } } sum = sumsh[0]; #endif const FLOAT_TYPE mean = sum / FLOAT_TYPE(ncols); const FLOAT_TYPE scale = inversesqrt(mean + FLOAT_TYPE(p.param1)); + const bool use_fastmod = (ncols > p.ne10); #if RMS_NORM_ROPE_FUSION - for (uint col = tid; col < ncols; col += BLOCK_SIZE) { - FLOAT_TYPE value = scale * FLOAT_TYPE(data_a[a_offset + col]); - if (do_multiply) { - value *= FLOAT_TYPE(data_b[b_offset + fastmod(col, p.ne10)]); + if (num_blocks == 1) { + if (tid < ncols) { + write_rms_col(tid, scale, a_offset, b_offset, d_offset, use_fastmod); + } + } else { + if (use_fastmod) { + [[unroll]] for (uint idx = 0; idx < 2; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + if (col < ncols) { + write_rms_col(col, scale, a_offset, b_offset, d_offset, true); + } + } + } else { + [[unroll]] for (uint idx = 0; idx < 2; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + if (col < ncols) { + write_rms_col(col, scale, a_offset, b_offset, d_offset, false); + } + } } - data_d[d_offset + col] = D_TYPE(value); } #else - if (do_multiply) { - if (ncols > p.ne10) { - [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { - if (col >= ncols) { - continue; - } - FLOAT_TYPE value = scale * FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col])) * FLOAT_TYPE(B_TO_FLOAT(data_b[b_offset + fastmod(col, p.ne10)])); -#if RMS_NORM_ADD_FUSION - value += FLOAT_TYPE(C_TO_FLOAT(data_c[d_offset + col])); - if (do_post_multiply) { - value *= FLOAT_TYPE(data_e[0]); + if (num_blocks == 1) { + if (tid < ncols) { + write_rms_col(tid, scale, a_offset, b_offset, d_offset, use_fastmod); + } + } else if (num_blocks == 4) { + if (use_fastmod) { + [[unroll]] for (uint idx = 0; idx < 4; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + if (col < ncols) { + write_rms_col(col, scale, a_offset, b_offset, d_offset, true); } -#endif - data_d[d_offset + col] = FLOAT_TO_D(value); } } else { - [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { - if (col >= ncols) { - continue; + [[unroll]] for (uint idx = 0; idx < 4; ++idx) { + const uint col = tid + idx * BLOCK_SIZE; + if (col < ncols) { + write_rms_col(col, scale, a_offset, b_offset, d_offset, false); } - FLOAT_TYPE value = scale * FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col])) * FLOAT_TYPE(B_TO_FLOAT(data_b[b_offset + col])); -#if RMS_NORM_ADD_FUSION - value += FLOAT_TYPE(C_TO_FLOAT(data_c[d_offset + col])); - if (do_post_multiply) { - value *= FLOAT_TYPE(data_e[0]); - } -#endif - data_d[d_offset + col] = FLOAT_TO_D(value); } } } else { - [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { - if (col >= ncols) { - continue; + if (use_fastmod) { + [[dont_unroll]] for (uint col = tid, idx = 0; idx < num_blocks; col += BLOCK_SIZE, ++idx) { + if (col < ncols) { + write_rms_col(col, scale, a_offset, b_offset, d_offset, true); + } + } + } else { + [[dont_unroll]] for (uint col = tid, idx = 0; idx < num_blocks; col += BLOCK_SIZE, ++idx) { + if (col < ncols) { + write_rms_col(col, scale, a_offset, b_offset, d_offset, false); + } } - data_d[d_offset + col] = FLOAT_TO_D(scale * FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col]))); } } #endif @@ -194,41 +548,11 @@ void rms_norm(uint num_iters) { rope_neox(t, row, channel, samp, rp); } else if (rp.rope_mode == GGML_ROPE_TYPE_NORMAL) { rope_norm(t, row, channel, samp, rp); + } else if (rp.rope_mode == GGML_ROPE_TYPE_MROPE || rp.rope_mode == GGML_ROPE_TYPE_IMROPE) { + rope_multi(t, row, channel, samp, rp); } } #endif } } } - -void main() { -#if RMS_NORM_ROPE_FUSION - const uint num_blocks = (p.ne00 + BLOCK_SIZE - 1) / BLOCK_SIZE; - rms_norm(num_blocks); -#else - // instantiate the rms_norm function for several different - // dimensions, to allow loop unrolling - uint num_blocks = (p.ne00 + BLOCK_SIZE - 1) / BLOCK_SIZE; - if (!UNROLL || num_blocks > 32) { - rms_norm(num_blocks); - } else if (num_blocks > 16) { - rms_norm(32); - } else if (num_blocks > 12) { - rms_norm(16); - } else if (num_blocks > 10) { - rms_norm(12); - } else if (num_blocks > 8) { - rms_norm(10); - } else if (num_blocks > 4) { - rms_norm(8); - } else if (num_blocks == 4) { - rms_norm(4); - } else if (num_blocks == 3) { - rms_norm(3); - } else if (num_blocks == 2) { - rms_norm(2); - } else if (num_blocks == 1) { - rms_norm(1); - } -#endif -} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm_partials.comp b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm_partials.comp index cf7ab21f261d..3318c301bb76 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm_partials.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm_partials.comp @@ -23,16 +23,13 @@ layout (binding = 4) readonly buffer C {float data_c[];}; layout (binding = 5) readonly buffer E {float data_e[];}; #endif -shared FLOAT_TYPE sumsh[BLOCK_SIZE]; - void main() { const uint ncols = p.ne00; - const uint nrows = gl_NumWorkGroups.x; - const uint nchannels = gl_NumWorkGroups.y; - - const uint row = 0; - const uint channel = gl_WorkGroupID.y; - const uint samp = gl_WorkGroupID.z; + // gen: one workgroup row (y) per tensor row (rows > 1 only in GGML_VK_BATCH_INVARIANT mode); a row's partials are + // num_partials consecutive values after the previous rows' + const uint row = gl_WorkGroupID.y; + const uint channel = 0; + const uint samp = 0; // The work is split across multiple workgroups in the x dimension. Each invocation // processes one element const uint tid = gl_GlobalInvocationID.x; @@ -43,13 +40,13 @@ void main() { uint32_t a_offset = samp*stride_sample + channel*stride_channel + row*stride_row + get_aoffset(); uint32_t b_offset = src1_idx(0, row, channel, samp) + get_boffset(); - uint32_t d_offset = ((samp*nchannels + channel)*nrows + row)*ncols + get_doffset(); + uint32_t d_offset = row*ncols + get_doffset(); FLOAT_TYPE sum = FLOAT_TYPE(0.0f); // partial sum for thread in warp uint32_t num_partials = p.param3; for (uint32_t i = gl_SubgroupInvocationID; i < num_partials; i += gl_SubgroupSize) { - sum += partial_sums[i]; + sum += partial_sums[row * num_partials + i]; } sum = subgroupAdd(sum); diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm_set_rows_q8_0.comp b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm_set_rows_q8_0.comp new file mode 100644 index 000000000000..d6a956591063 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm_set_rows_q8_0.comp @@ -0,0 +1,83 @@ +#version 450 +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_shuffle : require +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#extension GL_EXT_control_flow_attributes : require + +layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in; + +struct block_q8_0_u16 { + float16_t d; + uint16_t qs16[16]; +}; + +layout(binding = 0) readonly buffer BufA { float data_a[]; }; +layout(binding = 0) readonly buffer BufAV4 { vec4 data_a_v4[]; }; +layout(binding = 1) readonly buffer BufB { float data_b[]; }; +layout(binding = 2) writeonly buffer BufDQ8 { block_q8_0_u16 data_d_q8[]; }; +layout(binding = 3) readonly buffer BufIdx { uvec2 data_i[]; }; + +layout(push_constant) uniform PushConstants { + uint ne; + uint ne00; uint ne01; uint ne02; uint ne03; uint nb00; uint nb01; uint nb02; uint nb03; + uint ne10; uint ne11; uint ne12; uint ne13; uint nb10; uint nb11; uint nb12; uint nb13; + uint ne20; uint ne21; uint ne22; uint ne23; uint nb20; uint nb21; uint nb22; uint nb23; + uint misalign_offsets; + float param1; + float param2; + int param3; +} p; + +void main() { + const uint ncols = p.ne00; + const uint nchannels = p.ne02; + const uint nsamples = p.ne03; + const uint row = gl_WorkGroupID.x; + const uint tid = gl_LocalInvocationID.x; + + const uint a_misalign = p.misalign_offsets >> 16u; + const uint p3 = uint(p.param3); + const uint i_misalign = p3 >> 16u; + const bool v4_ok = (p3 & 0x8000u) != 0u; + const uint d_blk_off = p3 & 0x7FFFu; + const uint n_blks = ncols >> 5u; + + for (uint samp = gl_WorkGroupID.z; samp < nsamples; samp += gl_NumWorkGroups.z) { + for (uint channel = gl_WorkGroupID.y; channel < nchannels; channel += gl_NumWorkGroups.y) { + const uint a_offset = samp * p.nb03 + channel * p.nb02 + row * p.nb01 + a_misalign; + float sum_sq = 0.0f; + if (v4_ok && ncols == 128u) { + const vec4 xv = data_a_v4[(a_offset >> 2u) + tid]; + sum_sq = subgroupAdd(dot(xv, xv)); + } else { + for (uint col = tid; col < ncols; col += 32u) { + const float x = data_a[a_offset + col]; + sum_sq += x * x; + } + sum_sq = subgroupAdd(sum_sq); + } + const float scale = inversesqrt(sum_sq / float(ncols) + p.param1); + const uint dst_blk_base = data_i[i_misalign + channel].x * p.nb21 + row * n_blks + d_blk_off; + + for (uint b = 0u; b < n_blks; ++b) { + const float out_v = scale * data_a[a_offset + (b << 5u) + tid]; + const float amax = subgroupMax(abs(out_v)); + const float d = amax / 127.0f; + const float id = (d != 0.0f) ? (1.0f / d) : 0.0f; + const uint qlo = uint(int(round(out_v * id))) & 0xFFu; + const uint qhi = subgroupShuffleXor(qlo, 1u); + const uint bi = dst_blk_base + b; + if (tid == 0u) { + data_d_q8[bi].d = float16_t(d); + } + if ((tid & 1u) == 0u) { + data_d_q8[bi].qs16[tid >> 1u] = uint16_t(qlo | (qhi << 8u)); + } + } + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp b/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp index 0313f2fed90a..0b5656e6f9f6 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp @@ -5,6 +5,8 @@ const uint num_threads = 128; +layout(constant_id = 0) const bool ZERO_FILL = false; + layout(local_size_x = num_threads, local_size_y = 1, local_size_z = 1) in; void main() { @@ -18,7 +20,11 @@ void main() { continue; } - 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)); + if (ZERO_FILL) { + data_d[get_doffset() + dst_idx(idx)] = FLOAT_TO_D(0.0f); + } else { + 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; } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/situ.comp b/ggml/src/ggml-vulkan/vulkan-shaders/situ.comp new file mode 100644 index 000000000000..f65391df5770 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/situ.comp @@ -0,0 +1,14 @@ +#version 450 + +#include "glu_head.glsl" + +float op(float a, float b) { + const float beta = p.alpha; + const float lb = p.limit; + const float inv_beta = 1.0f / beta; + const float act = (tanh(a * inv_beta) * beta) * (1.0f / (1.0f + exp(-a))); + const float u = (lb > 0.0f) ? (tanh(b * (1.0f / lb)) * lb) : b; + return act * u; +} + +#include "glu_main.glsl" diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_conv.comp b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_conv.comp index 4cd9b8da3596..c7d7388f7f3b 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_conv.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_conv.comp @@ -8,6 +8,9 @@ layout(constant_id = 0) const uint BLOCK_SIZE = 32; layout(constant_id = 1) const uint TOKENS_PER_WG = 16; layout(constant_id = 2) const bool APPLY_BIAS = false; layout(constant_id = 3) const bool APPLY_SILU = false; +layout(constant_id = 4) const bool WRITE_STATE_OUT = false; +layout(constant_id = 5) const bool CONCAT_SLIDING = false; +layout(constant_id = 6) const uint TOK_PER_THREAD = 1; layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z = 1) in; @@ -15,19 +18,120 @@ layout(binding = 0) readonly buffer Src0 { float src0[]; }; layout(binding = 1) readonly buffer Src1 { float src1[]; }; layout(binding = 2) readonly buffer Bias { float bias[]; }; layout(binding = 3) buffer Dst { float dst[]; }; +layout(binding = 4) writeonly buffer StateOut { float state_out[]; }; layout(push_constant) uniform PushConstants { uint nb01; uint nb02; uint nb11; uint dst_nb0; uint dst_nb1; uint dst_nb2; uint nc; uint ncs; uint nr; uint n_t; uint n_s; + uint st_nb1; uint st_nb2; + uint qkv_nb0; uint qkv_nb1; uint qkv_nb2; + uint st_k; uint st_slot_nb; }; void main() { const uint i1 = gl_GlobalInvocationID.x; - const uint i2 = gl_WorkGroupID.y * TOKENS_PER_WG + gl_LocalInvocationID.y; const uint i3 = gl_WorkGroupID.z; + if (CONCAT_SLIDING) { + const bool zero_state = (st_k & 0x80000000u) != 0u; + const uint eff_st_k = st_k & 0x7FFFFFFFu; + if (TOKENS_PER_WG > 1u) { + const uint i2_base = (gl_WorkGroupID.y * TOKENS_PER_WG + gl_LocalInvocationID.y) * TOK_PER_THREAD; + if (i1 >= nr || i2_base >= n_t || i3 >= n_s) { + return; + } + const uint os_base = i3 * (nb02 / 4) + i1 * (nb01 / 4); + const uint q_base = i3 * (qkv_nb2 / 4) + i1 * (qkv_nb1 / 4); + const uint q_step = qkv_nb0 / 4; + const uint w_base = i1 * (nb11 / 4); + const vec4 w = vec4(src1[w_base], src1[w_base + 1], src1[w_base + 2], src1[w_base + 3]); + const uint d_base = i3 * (dst_nb2 / 4) + i1 * (dst_nb0 / 4); + const uint d_step = dst_nb1 / 4; + const uint st_base = i3 * (st_nb2 / 4) + i1 * (st_nb1 / 4); + + float s0 = (i2_base < 3u) ? (zero_state ? 0.0f : src0[os_base + i2_base]) : bias[q_base + (i2_base - 3u) * q_step]; + float s1 = (i2_base + 1u < 3u) ? (zero_state ? 0.0f : src0[os_base + i2_base + 1u]) : bias[q_base + (i2_base - 2u) * q_step]; + float s2 = (i2_base + 2u < 3u) ? (zero_state ? 0.0f : src0[os_base + i2_base + 2u]) : bias[q_base + (i2_base - 1u) * q_step]; + + [[unroll]] for (uint tt = 0u; tt < TOK_PER_THREAD; ++tt) { + const uint i2 = i2_base + tt; + if (i2 < n_t) { + const float x3 = bias[q_base + i2 * q_step]; + float sum = dot(vec4(s0, s1, s2, x3), w); + if (APPLY_SILU) { + sum = sum / (1.0f + exp(-sum)); + } + dst[d_base + i2 * d_step] = sum; + s0 = s1; + s1 = s2; + s2 = x3; + + if (eff_st_k > 0u) { + const int target_slot = int(n_t) - 1 - int(i2); + if (target_slot >= 0 && target_slot < int(eff_st_k)) { + const uint st_dst = uint(target_slot) * (st_slot_nb / 4) + st_base; + state_out[st_dst ] = s0; + state_out[st_dst + 1] = s1; + state_out[st_dst + 2] = s2; + } + } else if (i2 + 1u == n_t) { + state_out[st_base ] = s0; + state_out[st_base + 1] = s1; + state_out[st_base + 2] = s2; + } + } + } + return; + } + if (i1 >= nr || i3 >= n_s) { + return; + } + const uint os_base = i3 * (nb02 / 4) + i1 * (nb01 / 4); + const uint w_base = i1 * (nb11 / 4); + const vec4 w = vec4(src1[w_base], src1[w_base + 1], src1[w_base + 2], src1[w_base + 3]); + float s0 = zero_state ? 0.0f : src0[os_base]; + float s1 = zero_state ? 0.0f : src0[os_base + 1]; + float s2 = zero_state ? 0.0f : src0[os_base + 2]; + + const uint q_base = i3 * (qkv_nb2 / 4) + i1 * (qkv_nb1 / 4); + const uint q_step = qkv_nb0 / 4; + const uint d_base = i3 * (dst_nb2 / 4) + i1 * (dst_nb0 / 4); + const uint d_step = dst_nb1 / 4; + + const uint st_base = i3 * (st_nb2 / 4) + i1 * (st_nb1 / 4); + for (uint t = 0; t < n_t; ++t) { + const float x = bias[q_base + t * q_step]; + float sum = dot(vec4(s0, s1, s2, x), w); + if (APPLY_SILU) { + sum = sum / (1.0f + exp(-sum)); + } + dst[d_base + t * d_step] = sum; + s0 = s1; + s1 = s2; + s2 = x; + if (eff_st_k > 0u) { + const int target_slot = int(n_t) - 1 - int(t); + if (target_slot >= 0 && target_slot < int(eff_st_k)) { + const uint st_dst = uint(target_slot) * (st_slot_nb / 4) + st_base; + state_out[st_dst ] = s0; + state_out[st_dst + 1] = s1; + state_out[st_dst + 2] = s2; + } + } + } + + if (eff_st_k == 0u) { + state_out[st_base ] = s0; + state_out[st_base + 1] = s1; + state_out[st_base + 2] = s2; + } + return; + } + + const uint i2 = gl_WorkGroupID.y * TOKENS_PER_WG + gl_LocalInvocationID.y; + if (i1 >= nr || i2 >= n_t || i3 >= n_s) { return; } @@ -38,14 +142,31 @@ void main() { float sum = 0.0; if (nc == 4) { + const float x0 = src0[src0_base]; + const float x1 = src0[src0_base + 1]; + const float x2 = src0[src0_base + 2]; + const float x3 = src0[src0_base + 3]; sum = dot( - vec4(src0[src0_base], src0[src0_base + 1], src0[src0_base + 2], src0[src0_base + 3]), + vec4(x0, x1, x2, x3), vec4(src1[src1_base], src1[src1_base + 1], src1[src1_base + 2], src1[src1_base + 3]) ); + if (WRITE_STATE_OUT && i2 + 1 == n_t) { + const uint st_dst = i3 * (st_nb2 / 4) + i1 * (st_nb1 / 4); + state_out[st_dst ] = x1; + state_out[st_dst + 1] = x2; + state_out[st_dst + 2] = x3; + } } else { [[unroll]] for (uint i0 = 0; i0 < nc; i0++) { sum += src0[src0_base + i0] * src1[src1_base + i0]; } + if (WRITE_STATE_OUT && i2 + 1 == n_t) { + const uint st_src = i3 * (nb02 / 4) + n_t + i1 * (nb01 / 4); + const uint st_dst = i3 * (st_nb2 / 4) + i1 * (st_nb1 / 4); + for (uint c = 0; c + 1 < nc; ++c) { + state_out[st_dst + c] = src0[st_src + c]; + } + } } if (APPLY_BIAS) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/topk_moe.comp b/ggml/src/ggml-vulkan/vulkan-shaders/topk_moe.comp index d219201fda0a..b3282bb1ccdf 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/topk_moe.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/topk_moe.comp @@ -24,13 +24,24 @@ layout (push_constant) uniform parameter uint with_norm; float output_scale; float output_bias; +#ifdef TOPK_EMIT_COUNTS + uint count_bn; + uint row_ids_offset; +#endif }; +#ifdef TOPK_EMIT_COUNTS +layout(local_size_x_id = 0, local_size_y_id = 3, local_size_z = 1) in; +#else layout(local_size_x_id = 0, local_size_y = 4, local_size_z = 1) in; +#endif layout(constant_id = 0) const uint WARP_SIZE = 32; layout(constant_id = 1) const uint n_experts_spec = 512; layout(constant_id = 2) const bool nexperts_use_push = false; +#ifdef TOPK_EMIT_COUNTS +layout(constant_id = 3) const uint ROWS_PER_WG = 8; +#endif uint n_experts = nexperts_use_push ? n_experts_push : n_experts_spec; @@ -42,6 +53,13 @@ layout (binding = 0, std430) readonly buffer Logits {float logits[];}; layout (binding = 1, std430) readonly buffer BiasProbs {float bias[];}; layout (binding = 2, std430) writeonly buffer Weights {float weights[];}; layout (binding = 3, std430) writeonly buffer Ids {uint ids[];}; +#ifdef TOPK_EMIT_COUNTS +layout (binding = 4, std430) writeonly buffer ExpertCounts {uint data_exp_d[];}; +shared uint sh_sel_ids[16 * 32]; +shared uint sh_vals[256]; +shared uint sh_offsets[256]; +shared uint sh_cursors[256]; +#endif const float INFINITY = 1.0 / 0.0; @@ -91,9 +109,13 @@ void softmax_warp_inplace(inout float vals[experts_per_thread], const uint limit void main() { const uint row = gl_WorkGroupID.x * gl_WorkGroupSize.y + gl_SubgroupID; +#ifdef TOPK_EMIT_COUNTS + if (row < n_rows) { +#else if (row >= n_rows) { return; } +#endif const uint logits_offset = n_experts * row; const uint bias_offset = 0; // 1D @@ -103,39 +125,34 @@ void main() { float probs[experts_per_thread]; [[unroll]] - for (int i = 0; i < experts_per_thread; i++) { - probs[i] = -INFINITY; - } - - [[unroll]] - for (uint i = 0; i < n_experts; i += WARP_SIZE) { - const uint expert = i + lane; - probs[i / WARP_SIZE] = (n_experts % WARP_SIZE == 0 || expert < n_experts) ? logits[logits_offset + expert] : -INFINITY; + for (uint idx = 0; idx < experts_per_thread; idx++) { + const uint expert = idx * WARP_SIZE + lane; + probs[idx] = ((!nexperts_use_push && (n_experts_spec % WARP_SIZE == 0)) || expert < n_experts) ? logits[logits_offset + expert] : -INFINITY; } if (gating_func == GATING_FUNC_SOFTMAX) { softmax_warp_inplace(probs, n_experts, lane, nexperts_use_push); } else if (gating_func == GATING_FUNC_SIGMOID) { [[unroll]] - for (uint i = 0; i < n_experts; i += WARP_SIZE) { - const uint expert = i + lane; - probs[i / WARP_SIZE] = (n_experts % WARP_SIZE == 0 || expert < n_experts) ? 1.f / (1.f + exp(-probs[i / WARP_SIZE])) : -INFINITY; + for (uint idx = 0; idx < experts_per_thread; idx++) { + const uint expert = idx * WARP_SIZE + lane; + probs[idx] = ((!nexperts_use_push && (n_experts_spec % WARP_SIZE == 0)) || expert < n_experts) ? 1.f / (1.f + exp(-probs[idx])) : -INFINITY; } } else if (gating_func == GATING_FUNC_SQRT_SOFTPLUS) { [[unroll]] - for (uint i = 0; i < n_experts; i += WARP_SIZE) { - const uint expert = i + lane; - const float val = probs[i / WARP_SIZE]; - probs[i / WARP_SIZE] = (n_experts % WARP_SIZE == 0 || expert < n_experts) ? sqrt(val > 20.0f ? val : log(1.0f + exp(val))) : -INFINITY; + for (uint idx = 0; idx < experts_per_thread; idx++) { + const uint expert = idx * WARP_SIZE + lane; + const float val = probs[idx]; + probs[idx] = ((!nexperts_use_push && (n_experts_spec % WARP_SIZE == 0)) || expert < n_experts) ? sqrt(val > 20.0f ? val : log(1.0f + exp(val))) : -INFINITY; } } float selection_probs[experts_per_thread]; if (has_bias != 0) { [[unroll]] - for (uint i = 0; i < n_experts; i += WARP_SIZE) { - const uint expert = i + lane; - selection_probs[i / WARP_SIZE] = (n_experts % WARP_SIZE == 0 || expert < n_experts) ? probs[i / WARP_SIZE] + bias[bias_offset + expert] : -INFINITY; + for (uint idx = 0; idx < experts_per_thread; idx++) { + const uint expert = idx * WARP_SIZE + lane; + selection_probs[idx] = ((!nexperts_use_push && (n_experts_spec % WARP_SIZE == 0)) || expert < n_experts) ? probs[idx] + bias[bias_offset + expert] : -INFINITY; } } else { [[unroll]] @@ -163,11 +180,11 @@ void main() { uint max_expert = lane; [[unroll]] - for (uint i = WARP_SIZE; i < n_experts; i += WARP_SIZE) { - const uint expert = i + lane; - if ((n_experts % WARP_SIZE == 0 || expert < n_experts) && selection_probs[i / WARP_SIZE] > max_val_s) { - max_val = probs[i / WARP_SIZE]; - max_val_s = selection_probs[i / WARP_SIZE]; + for (uint idx = 1; idx < experts_per_thread; idx++) { + const uint expert = idx * WARP_SIZE + lane; + if (((!nexperts_use_push && (n_experts_spec % WARP_SIZE == 0)) || expert < n_experts) && selection_probs[idx] > max_val_s) { + max_val = probs[idx]; + max_val_s = selection_probs[idx]; max_expert = expert; } } @@ -184,26 +201,46 @@ void main() { } } - if ((k & (WARP_SIZE - 1)) == lane) { - output_weights[k / WARP_SIZE] = max_val; + [[unroll]] + for (uint idx = 0; idx < experts_per_thread; idx++) { + if (uint(k) == idx * WARP_SIZE + lane) { + output_weights[idx] = max_val; + } + if (max_expert == idx * WARP_SIZE + lane) { + selection_probs[idx] = -INFINITY; + } } if ((max_expert & (WARP_SIZE - 1)) == lane) { - selection_probs[max_expert / WARP_SIZE] = -INFINITY; - ids[ids_offset + k] = max_expert; wt_sum += max_val; } +#ifdef TOPK_EMIT_COUNTS + if (lane == 0u) { + sh_sel_ids[row * n_expert_used + uint(k)] = max_expert; + } +#endif } if (with_norm != 0) { - wt_sum = subgroupAdd(wt_sum); - wt_sum = clamp(wt_sum, clamp_min, clamp_max); - const float inv_sum = 1.0f / wt_sum; + if (n_expert_used <= WARP_SIZE) { + // Series 18 (0-ULP): Match sum_rows.comp BLOCK_SIZE=32 strided halving tree in rank order k=0..n_expert_used-1 + precise float lane_w = (lane < n_expert_used) ? (0.0f + output_weights[0]) : 0.0f; + [[unroll]] for (uint s = WARP_SIZE / 2; s > 0; s >>= 1) { + precise float shuf_w = subgroupShuffleXor(lane_w, s); + precise float next_w = lane_w + shuf_w; + lane_w = next_w; + } + wt_sum = subgroupShuffle(lane_w, 0u); + } else { + wt_sum = subgroupAdd(wt_sum); + } + precise float denom = (clamp_max < 0.0f) ? (wt_sum + clamp_min) : clamp(wt_sum, clamp_min, clamp_max); [[unroll]] for (uint i = 0; i < experts_per_thread; ++i) { - output_weights[i] *= inv_sum; + precise float wn = output_weights[i] / denom; + output_weights[i] = wn; } } @@ -215,7 +252,65 @@ void main() { for (uint i = 0; i < experts_per_thread; ++i) { uint idx = i * WARP_SIZE + lane; if (idx < n_expert_used) { - weights[weights_offset + idx] = output_scale * output_weights[i] + output_bias; + precise float ws = output_scale * output_weights[i]; + precise float wo = ws + output_bias; + weights[weights_offset + idx] = wo; + } + } +#ifdef TOPK_EMIT_COUNTS + } // end if (row < n_rows) + + const uint lane_e = gl_SubgroupInvocationID; + const uint tid = gl_SubgroupID * WARP_SIZE + lane_e; + const uint wg_threads = ROWS_PER_WG * WARP_SIZE; + + for (uint e = tid; e < n_experts; e += wg_threads) { + sh_vals[e] = 0u; + } + barrier(); + + const uint num_sel = n_rows * n_expert_used; + for (uint idx = tid; idx < num_sel; idx += wg_threads) { + const uint exp_id = sh_sel_ids[idx]; + if (exp_id < n_experts) { + atomicAdd(sh_vals[exp_id], 1u); + } + } + barrier(); + + if (gl_SubgroupID == 0u) { + const uint n_experts_padded = (n_experts + WARP_SIZE - 1u) & ~(WARP_SIZE - 1u); + uint base = 0u; + for (uint e = lane_e; e < n_experts_padded; e += WARP_SIZE) { + const bool in_range = e < n_experts; + const uint count = in_range ? sh_vals[e] : 0u; + const uint n_tiles = (count + count_bn - 1u) / count_bn; + const uint tile_begin = base + subgroupExclusiveAdd(n_tiles); + if (in_range) { + sh_offsets[e] = tile_begin * count_bn; + sh_cursors[e] = 0u; + for (uint t = 0u; t < n_tiles; ++t) { + const uint desc = 1u + 2u * (tile_begin + t); + data_exp_d[desc] = e; + data_exp_d[desc + 1u] = min(count_bn, count - t * count_bn); + } + } + base += subgroupAdd(n_tiles); + } + if (lane_e == 0u) { + data_exp_d[0] = base; + } + } + barrier(); + + for (uint idx = tid; idx < num_sel; idx += wg_threads) { + const uint i01 = idx / n_expert_used; + const uint i00 = idx - i01 * n_expert_used; + const uint exp_id = sh_sel_ids[idx]; + if (exp_id < n_experts) { + const uint r = atomicAdd(sh_cursors[exp_id], 1u); + data_exp_d[row_ids_offset + sh_offsets[exp_id] + r] = (i01 << 16u) | i00; } } +#endif } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl index b7e5a31aaf1b..3d3a660ff8b6 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl @@ -1911,49 +1911,38 @@ i32vec2 iq4nl_to_i8x8(uint32_t vui) { #endif #if defined(DATA_A_MXFP4) || defined(DATA_A_NVFP4) -#if !defined(USE_OCP_FP4) -const int8_t kvalues_mxfp4_const[16] = { - int8_t(0), int8_t(1), int8_t(2), int8_t(3), int8_t(4), int8_t(6), int8_t(8), int8_t(12), - int8_t(0), int8_t(-1), int8_t(-2), int8_t(-3), int8_t(-4), int8_t(-6), int8_t(-8), int8_t(-12), -}; +int mxfp4_kval(uint nib) { + const int mag = int((0xC8643210u >> ((nib & 7u) * 4u)) & 0xFu); + return ((nib & 8u) != 0u) ? -mag : mag; +} -shared int8_t kvalues_mxfp4[16]; -#endif +uint nvfp4_e2m1_pair_fp16_bits(const uint q) { + // Decodes low nibbles of byte 0 (bits 3..0) and byte 2 (bits 19..16) into exact IEEE-754 normal FP16 u16x2 + // (0 -> 0x0000, 0.5 -> 0x3800, 1..6 -> normal e_fp16 in 15..17; zero FP16 denormals -> FTZ-safe on AGX coopmat!). + const uint s = (q & 0x00080008u) << 12u; + const uint x = q & 0x00070007u; + const uint has_e = ((x & 0x00060006u) + 0x00060006u) & 0x00080008u; + const uint has_m = (x + 0x00070007u) & 0x00080008u; + const uint xm = x & (0x00060006u | (has_e >> 3u)); + return s | ((xm << 9u) + has_m * 0x0700u); +} #if defined(DATA_A_NVFP4) && !defined(USE_OCP_FP4) -// Cover all scale bytes accepted by ggml_validate_row_data. -// ue4m3_to_fp32_build() masks the exponent and mantissa, but checks the full byte for 0 and 0x7F. -shared float ue4m3_fp32_lut[256]; - float ue4m3_to_fp32_build(uint u) { if (u == 0u || u == 127u) { - return 0.0; + return 0.0f; } - const uint exp = (u >> 3) & 15u; + const uint exp = (u >> 3u) & 15u; const uint man = u & 7u; - if (exp == 0u) { - return float(man) * (1.0 / 512.0); - } - const uint bits = (exp + 120u) << 23 | (man << 20); - return uintBitsToFloat(bits); + return (exp == 0u) + ? (float(man) * (1.0f / 512.0f)) + : uintBitsToFloat(((exp + 120u) << 23u) | (man << 20u)); } #endif -#if (defined(DATA_A_MXFP4) || defined(DATA_A_NVFP4)) && !defined(USE_OCP_FP4) -#define NEEDS_INIT_IQ_SHMEM -void init_iq_shmem(uvec3 wgsize) -{ - // copy the table into shared memory and sync - for (uint i = gl_LocalInvocationIndex.x; i < kvalues_mxfp4.length(); i += wgsize.x) { - kvalues_mxfp4[i] = kvalues_mxfp4_const[i]; - } -#if defined(DATA_A_NVFP4) - for (uint i = gl_LocalInvocationIndex.x; i < 256u; i += wgsize.x) { - ue4m3_fp32_lut[i] = ue4m3_to_fp32_build(i); - } -#endif - barrier(); -} +#if !defined(USE_OCP_FP4) +// Series 17: Zero shared memory and zero barrier for MXFP4 / NVFP4; keep empty stub for callers in dequant/mul_mm. +void init_iq_shmem(uvec3 wgsize) {} #endif #endif @@ -2024,7 +2013,7 @@ float ue4m3_to_fp32(uint8_t x) { #if defined(USE_OCP_FP4) return float(ue4m3_from_bits(x)); #else - return ue4m3_fp32_lut[uint(x)]; + return ue4m3_to_fp32_build(uint(x)); #endif } #endif diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index fb99f8f48729..814c9daef411 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -568,10 +568,18 @@ void matmul_shaders(bool fp16, MatMulIdType matmul_id_type, bool coopmat, bool c {"FLOAT_TYPEV8", FLOAT_TYPE(8, "f16")}, }; + const bool emit_cm1_fused = coopmat && !coopmat2 && !f16acc && !dot2; + // Shaders with f16 B_TYPE string_to_spv(shader_name + "_f32_f16" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, float_type_dict_f16), {{"DATA_A_F32", "1"}, {"LOAD_VEC_A", load_vec}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + if (emit_cm1_fused) { + string_to_spv(shader_name + "_f32_f16_fused", source_name, merge_maps(merge_maps(base_dict, float_type_dict_f16), {{"MM_FUSED", "1"}, {"DATA_A_F32", "1"}, {"LOAD_VEC_A", load_vec}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + } string_to_spv(shader_name + "_f16" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, float_type_dict_f16), {{"DATA_A_F16", "1"}, {"LOAD_VEC_A", load_vec}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + if (emit_cm1_fused) { + string_to_spv(shader_name + "_f16_fused", source_name, merge_maps(merge_maps(base_dict, float_type_dict_f16), {{"MM_FUSED", "1"}, {"DATA_A_F16", "1"}, {"LOAD_VEC_A", load_vec}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + } // bf16 { @@ -616,6 +624,9 @@ void matmul_shaders(bool fp16, MatMulIdType matmul_id_type, bool coopmat, bool c if (!coopmat2) { string_to_spv(shader_name + "_" + tname + "_f32" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{data_a_key, "1"}, {"LOAD_VEC_A", load_vec}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f32}, {"B_TYPE_SCALAR", "float"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + if (emit_cm1_fused) { + string_to_spv(shader_name + "_" + tname + "_f32_fused", source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{"MM_FUSED", "1"}, {data_a_key, "1"}, {"LOAD_VEC_A", load_vec}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f32}, {"B_TYPE_SCALAR", "float"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + } } continue; } @@ -643,9 +654,15 @@ void matmul_shaders(bool fp16, MatMulIdType matmul_id_type, bool coopmat, bool c std::string lva = lut_load_vec_a(tname); string_to_spv(shader_name + "_" + tname + "_f16" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{data_a_key, "1"}, {"LOAD_VEC_A", lva}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + if (emit_cm1_fused && (tname == "iq4_xs" || tname == "iq4_nl")) { + string_to_spv(shader_name + "_" + tname + "_f16_fused", source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{"MM_FUSED", "1"}, {data_a_key, "1"}, {"LOAD_VEC_A", lva}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + } if (!coopmat2) { string_to_spv(shader_name + "_" + tname + "_f32" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{data_a_key, "1"}, {"LOAD_VEC_A", lva}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f32}, {"B_TYPE_SCALAR", "float"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + if (emit_cm1_fused && (tname == "iq4_xs" || tname == "iq4_nl")) { + string_to_spv(shader_name + "_" + tname + "_f32_fused", source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{"MM_FUSED", "1"}, {data_a_key, "1"}, {"LOAD_VEC_A", lva}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f32}, {"B_TYPE_SCALAR", "float"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + } } #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) @@ -675,9 +692,15 @@ void matmul_shaders(bool fp16, MatMulIdType matmul_id_type, bool coopmat, bool c }; string_to_spv(shader_name + "_quant_f16" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, quant_float_type_dict), {{"MULMAT_QUANT", "1"}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + if (emit_cm1_fused) { + string_to_spv(shader_name + "_quant_f16_fused", source_name, merge_maps(merge_maps(base_dict, quant_float_type_dict), {{"MM_FUSED", "1"}, {"MULMAT_QUANT", "1"}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + } if (!coopmat2) { string_to_spv(shader_name + "_quant_f32" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, quant_float_type_dict), {{"MULMAT_QUANT", "1"}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f32}, {"B_TYPE_SCALAR", "float"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + if (emit_cm1_fused) { + string_to_spv(shader_name + "_quant_f32_fused", source_name, merge_maps(merge_maps(base_dict, quant_float_type_dict), {{"MM_FUSED", "1"}, {"MULMAT_QUANT", "1"}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f32}, {"B_TYPE_SCALAR", "float"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc); + } } } } @@ -741,11 +764,14 @@ void process_shaders() { #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) string_to_spv("flash_attn_f32_f16", "flash_attn_cm1.comp", merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"COOPMAT", "1"}}), fp16, true, false, f16acc); - std::map fa_flip_dict = fa_base_dict; fa_flip_dict.erase("DATA_A_IQ4_NL"); string_to_spv("flash_attn_f32_f16_flip", "flash_attn_cm1_flip.comp", merge_maps(fa_flip_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"COOPMAT", "1"}}), fp16, true, false, f16acc); + if (!f16acc) { + string_to_spv("flash_attn_f32_f16_8x8", "flash_attn_cm1.comp", + merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"COOPMAT", "1"}, {"COOPMAT_8X8", "1"}}), fp16, true, false, false); + } #endif } @@ -755,6 +781,14 @@ void process_shaders() { if (fp16) { string_to_spv("flash_attn_f32_f16_dot2", "flash_attn.comp", merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"DOT2_F16", "1"}}), fp16, false, false, f16acc); + if (!f16acc) { + std::map fa_mhm_dict = fa_base_dict; + fa_mhm_dict.erase("DATA_A_IQ4_NL"); + string_to_spv("flash_attn_vec_mhm_f32_f16", "flash_attn_vec_mhm.comp", + merge_maps(fa_mhm_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}}), fp16, false, false, false); + string_to_spv("flash_attn_vec_mhm_f32_f16_dot2", "flash_attn_vec_mhm.comp", + merge_maps(fa_mhm_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"DOT2_F16", "1"}}), fp16, false, false, false); + } } #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) @@ -781,6 +815,22 @@ void process_shaders() { string_to_spv("flash_attn_f32_f16_bf16_flip", "flash_attn_cm1_flip.comp", merge_maps(fa_bf16_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"COOPMAT", "1"}}), true, true, false, false); + string_to_spv("flash_attn_f32_f16_bf16_8x8", "flash_attn_cm1.comp", + merge_maps(fa_bf16_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"COOPMAT", "1"}, {"COOPMAT_8X8", "1"}}), + true, true, false, false); +#endif + +#if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) + string_to_spv("mul_mv_mma_f32_f16", "mul_mv_mma.comp", {{"FLOAT16", "1"}, {"DATA_A_F32_F16", "1"}}, true, true, false, false); + for (const std::string & mma_t : {"f32", "f16", "q4_0", "q4_1", "q5_0", "q5_1", "q8_0", "q4_k", "q5_k", "q6_k", "iq4_xs", "iq4_nl", "nvfp4"}) { + const std::string mma_def = "DATA_A_" + to_uppercase(mma_t); + string_to_spv("mul_mv_mma_" + mma_t, "mul_mv_mma.comp", {{"FLOAT16", "1"}, {mma_def, "1"}}, true, true, false, false); + string_to_spv("mul_mv_mma_id_" + mma_t, "mul_mv_mma.comp", {{"FLOAT16", "1"}, {"MUL_MAT_ID", "1"}, {mma_def, "1"}}, true, true, false, false); + if (mma_t == "q4_k" || mma_t == "q5_k" || mma_t == "q6_k" || mma_t == "nvfp4") { + string_to_spv("mul_mv_mma_" + mma_t + "_repack", "mul_mv_mma.comp", {{"FLOAT16", "1"}, {mma_def, "1"}, {"REPACK_PLANAR", "1"}}, true, true, false, false); + string_to_spv("mul_mv_mma_id_" + mma_t + "_repack", "mul_mv_mma.comp", {{"FLOAT16", "1"}, {"MUL_MAT_ID", "1"}, {mma_def, "1"}, {"REPACK_PLANAR", "1"}}, true, true, false, false); + } + } #endif #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) @@ -822,6 +872,12 @@ void process_shaders() { string_to_spv("mul_mat_vec_id_" + tname + "_f32_f32", shader, merge_maps(base_dict, {{"MUL_MAT_ID", "1"}, {data_a_key, "1"}, {"B_TYPE", "float"}, {"B_TYPEV2", "vec2"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}})); string_to_spv("mul_mat_vec_id_" + tname + "_f32_f32_subgroup", shader, merge_maps(base_dict, {{"MUL_MAT_ID", "1"}, {data_a_key, "1"}, {"B_TYPE", "float"}, {"B_TYPEV2", "vec2"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}})); string_to_spv("mul_mat_vec_id_" + tname + "_f32_f32_subgroup_no_shmem", shader, merge_maps(base_dict, {{"MUL_MAT_ID", "1"}, {data_a_key, "1"}, {"B_TYPE", "float"}, {"B_TYPEV2", "vec2"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}, {"USE_SUBGROUP_ADD_NO_SHMEM", "1"}})); + if (tname == "q4_k" || tname == "q5_k" || tname == "q6_k" || tname == "nvfp4") { + const std::string id_fast_kq = (tname == "q4_k") ? "2" : "1"; + string_to_spv("mul_mat_vec_" + tname + "_repack_f32_f32_subgroup_no_shmem", shader, merge_maps(base_dict, {{data_a_key, "1"}, {"REPACK_PLANAR", "1"}, {"REPACK_FAST_KQ", "2"}, {"B_TYPE", "float"}, {"B_TYPEV2", "vec2"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}, {"USE_SUBGROUP_ADD_NO_SHMEM", "1"}})); + string_to_spv("mul_mat_vec_" + tname + "_repack_f16_f32_subgroup_no_shmem", shader, merge_maps(base_dict, {{data_a_key, "1"}, {"REPACK_PLANAR", "1"}, {"REPACK_FAST_KQ", "2"}, {"B_TYPE", "float16_t"}, {"B_TYPEV2", "f16vec2"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}, {"USE_SUBGROUP_ADD_NO_SHMEM", "1"}})); + string_to_spv("mul_mat_vec_id_" + tname + "_repack_f32_f32_subgroup_no_shmem", shader, merge_maps(base_dict, {{"MUL_MAT_ID", "1"}, {data_a_key, "1"}, {"REPACK_PLANAR", "1"}, {"REPACK_FAST_KQ", id_fast_kq}, {"B_TYPE", "float"}, {"B_TYPEV2", "vec2"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}, {"USE_SUBGROUP_ADD_NO_SHMEM", "1"}})); + } // mul mat vec with integer dot product #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) @@ -840,6 +896,9 @@ void process_shaders() { if (tname != "f16" && tname != "bf16") { string_to_spv("dequant_" + tname, "dequant_" + tname + ".comp", merge_maps(base_dict, {{data_a_key, "1"}, {"D_TYPE", "float16_t"}})); } + if (tname == "q4_k" || tname == "q5_k" || tname == "q6_k" || tname == "nvfp4") { + string_to_spv("dequant_" + tname + "_repack", "dequant_repack.comp", merge_maps(base_dict, {{data_a_key, "1"}, {"D_TYPE", "float16_t"}})); + } // Fused dequant+transpose variant for FA quant-KV (per-head-contiguous f16 scratch). if (tname == "q8_0") { string_to_spv("dequant_" + tname + "_transpose", "dequant_" + tname + ".comp", merge_maps(base_dict, {{data_a_key, "1"}, {"D_TYPE", "float16_t"}, {"DEQUANT_TRANSPOSE", "1"}})); @@ -870,11 +929,13 @@ void process_shaders() { const auto rms_bf16_dict = merge_maps(base_dict, {{"A_TYPE", "uint16_t"}, {"B_TYPE", "float"}, {"C_TYPE", "float"}, {"D_TYPE", "uint16_t"}, {"DATA_A_BF16", "1"}, {"DATA_D_BF16", "1"}, {"USE_SUBGROUP_ADD", use_subgroups ? "1" : "0"}}); string_to_spv("rms_norm_f32" + suffix, "rms_norm.comp", rms_dict); string_to_spv("rms_norm_bf16" + suffix, "rms_norm.comp", rms_bf16_dict); + string_to_spv("rms_norm_scale_f32" + suffix, "rms_norm.comp", merge_maps(rms_dict, {{"RMS_NORM_SCALE_FUSION", "1"}})); string_to_spv("rms_norm_mul_add_f32" + suffix, "rms_norm.comp", merge_maps(rms_dict, {{"RMS_NORM_ADD_FUSION", "1"}})); + string_to_spv("rms_norm_mul_silu_f32" + suffix, "rms_norm.comp", merge_maps(rms_dict, {{"RMS_NORM_SILU_GATE_FUSION", "1"}})); string_to_spv("rms_norm_mul_add_bf16_f32" + suffix, "rms_norm.comp", merge_maps(rms_bf16_dict, {{"RMS_NORM_ADD_FUSION", "1"}})); string_to_spv("rms_norm_mul_add_bf16_bf16" + suffix, "rms_norm.comp", merge_maps({{"C_TYPE", "uint16_t"}, {"DATA_C_BF16", "1"}, {"RMS_NORM_ADD_FUSION", "1"}}, rms_bf16_dict)); - string_to_spv("rms_norm_set_rows_f32_f32" + suffix, "rms_norm.comp", merge_maps(rms_dict, {{"RMS_NORM_SET_ROWS_FUSION", "1"}})); - string_to_spv("rms_norm_set_rows_f32_f16" + suffix, "rms_norm.comp", merge_maps({{"D_TYPE", "float16_t"}, {"RMS_NORM_SET_ROWS_FUSION", "1"}}, rms_dict)); // keep rms_dict last so 'merge_maps' overwrites the value for key 'D_TYPE' + string_to_spv("rms_norm_set_rows_f32_f32" + suffix, "rms_norm.comp", merge_maps(rms_dict, {{"RMS_NORM_SET_ROWS_FUSION", "1"}, {"SET_ROWS_D_V4", "vec4"}})); + string_to_spv("rms_norm_set_rows_f32_f16" + suffix, "rms_norm.comp", merge_maps({{"D_TYPE", "float16_t"}, {"RMS_NORM_SET_ROWS_FUSION", "1"}, {"SET_ROWS_D_V4", "f16vec4"}}, rms_dict)); // keep rms_dict last so 'merge_maps' overwrites the value for key 'D_TYPE' string_to_spv("rms_norm_mul_rope_f32_f32" + suffix, "rms_norm.comp", merge_maps(rms_dict, {{"ROPE_D_TYPE", "float"}, {"RMS_NORM_ROPE_FUSION", "1"}})); string_to_spv("rms_norm_mul_rope_f32_f16" + suffix, "rms_norm.comp", merge_maps(rms_dict, {{"ROPE_D_TYPE", "float16_t"}, {"RMS_NORM_ROPE_FUSION", "1"}})); } @@ -1005,7 +1066,7 @@ void process_shaders() { "elu", "xielu", "sgn", "softplus", "step", "round", "ceil", "floor", "trunc"}) { string_to_spv(op + "_" + t, "unary.comp", merge_maps(dict, {{"OP", "op_" + op}})); } - for (const std::string op : {"geglu", "reglu", "swiglu", "swiglu_oai", "swiglu_clamp", "geglu_erf", "geglu_quick"}) { + for (const std::string op : {"geglu", "reglu", "swiglu", "swiglu_oai", "swiglu_clamp", "situ", "geglu_erf", "geglu_quick"}) { string_to_spv(op + "_" + t, op + ".comp", dict); } string_to_spv("log_" + t, "log.comp", dict); @@ -1100,6 +1161,23 @@ void process_shaders() { } string_to_spv("out_prod_f32", "out_prod.comp", {}); + string_to_spv("inkling_l2_clip", "inkling_l2_clip.comp", {}); + string_to_spv("inkling_conv", "inkling_conv.comp", {}); + string_to_spv("inkling_conv_scopy", "inkling_conv_scopy.comp", {}); + string_to_spv("inkling_rel_gather", "inkling_rel_gather.comp", {}); + string_to_spv("inkling_depth_mix", "inkling_depth_mix.comp", {}); + string_to_spv("inkling_depth_mix_rms", "inkling_depth_mix_rms.comp", {}); + string_to_spv("inkling_rms2_concat", "inkling_rms2_concat.comp", {}); + string_to_spv("inkling_ctrl_apply", "inkling_ctrl_apply.comp", {}); + // S19_WAVE3: mode = 11, 12 shaders + string_to_spv("inkling_ctrl_apply_rms_mul", "inkling_ctrl_apply_rms_mul.comp", {}); + string_to_spv("inkling_l2_clip_qr", "inkling_l2_clip_qr.comp", {}); + string_to_spv("inkling_dspark_concat4", "inkling_dspark_concat4.comp", {}); + string_to_spv("inkling_dspark_gru", "inkling_dspark_gru.comp", {}); + string_to_spv("inkling_softcap", "inkling_softcap.comp", {}); + string_to_spv("inkling_dspark_joint_gru", "inkling_dspark_joint_gru.comp", {}); + string_to_spv("inkling_dspark_inject_mix", "inkling_dspark_inject_mix.comp", {}); + string_to_spv("rms_norm_set_rows_q8_0", "rms_norm_set_rows_q8_0.comp", {}); string_to_spv("timestep_embedding_f32", "timestep_embedding.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); @@ -1130,6 +1208,9 @@ void process_shaders() { string_to_spv("gated_delta_net_f32", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}, {"USE_SUBGROUP_CLUSTERED", "1"}})); string_to_spv("gated_delta_net_f32_nocluster", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}, {"USE_SUBGROUP_CLUSTERED", "0"}})); string_to_spv("gated_delta_net_f32_shmem", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "0"}, {"USE_SUBGROUP_CLUSTERED", "0"}})); + string_to_spv("gated_delta_net_f32_sout", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}, {"USE_SUBGROUP_CLUSTERED", "1"}, {"STATE_OUT", "1"}})); + string_to_spv("gated_delta_net_f32_nocluster_sout", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}, {"USE_SUBGROUP_CLUSTERED", "0"}, {"STATE_OUT", "1"}})); + string_to_spv("gated_delta_net_f32_shmem_sout", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "0"}, {"USE_SUBGROUP_CLUSTERED", "0"}, {"STATE_OUT", "1"}})); #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) string_to_spv("gated_delta_net_f32", "gated_delta_net_cm2.comp", base_dict, true, false, true); @@ -1225,6 +1306,7 @@ void process_shaders() { string_to_spv("multi_add_f32", "multi_add.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}, {"ADD_RMS" , "0"}}); string_to_spv("multi_add_rms_f32", "multi_add.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}, {"ADD_RMS" , "1"}}); + string_to_spv("multi_add_rms_mul_f32", "multi_add_rms_mul.comp", {}); string_to_spv("ssm_scan_f32", "ssm_scan.comp", {{"A_TYPE", "float"}}); string_to_spv("ssm_scan_subgroup_f32", "ssm_scan.comp", {{"A_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}}); @@ -1232,6 +1314,7 @@ void process_shaders() { string_to_spv("ssm_conv_f32", "ssm_conv.comp", {{"A_TYPE", "float"}}); string_to_spv("topk_moe_f32", "topk_moe.comp", {}); + string_to_spv("topk_moe_count_f32", "topk_moe.comp", {{"TOPK_EMIT_COUNTS", "1"}}); for (auto &c : compiles) { c.wait(); diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index c616fa39bf96..1d8f4ed5dfa0 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -1118,9 +1118,10 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "SLEEP", "SIGMOID_BACK", + "INKLING_FUSED", }; -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "none", @@ -1235,9 +1236,10 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "sleep(x)", "sigmoid_back(x)", + "inkling_fused(x)", }; -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2"); @@ -1276,9 +1278,10 @@ static const char * GGML_GLU_OP_NAME[GGML_GLU_OP_COUNT] = { "GEGLU_ERF", "GEGLU_QUICK", "SWIGLU_CLAMP", + "SITU", }; -static_assert(GGML_GLU_OP_COUNT == 7, "GGML_GLU_OP_COUNT != 7"); +static_assert(GGML_GLU_OP_COUNT == 8, "GGML_GLU_OP_COUNT != 8"); static_assert(sizeof(struct ggml_object)%GGML_MEM_ALIGN == 0, "ggml_object size must be a multiple of GGML_MEM_ALIGN"); static_assert(sizeof(struct ggml_tensor)%GGML_MEM_ALIGN == 0, "ggml_tensor size must be a multiple of GGML_MEM_ALIGN"); @@ -3145,6 +3148,350 @@ struct ggml_tensor * ggml_swiglu_clamp( return result; } +struct ggml_tensor * ggml_situ( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + float beta, + float linear_beta) { + struct ggml_tensor * result = ggml_glu_impl(ctx, a, b, GGML_GLU_OP_SITU, false); + ggml_set_op_params_f32(result, 2, beta); + ggml_set_op_params_f32(result, 3, linear_beta); + + return result; +} + +struct ggml_tensor * ggml_inkling_l2_clip( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * scale, + struct ggml_tensor * tau, + float threshold, + float eps) { + struct ggml_tensor * result = ggml_dup_tensor(ctx, cur); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = cur; + result->src[1] = scale; + result->src[2] = tau; + ggml_set_op_params_i32(result, 0, 0); + ggml_set_op_params_f32(result, 1, threshold); + ggml_set_op_params_f32(result, 2, eps); + return result; +} + +struct ggml_tensor * ggml_inkling_conv( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * history, + struct ggml_tensor * weight, + struct ggml_tensor * dynamic, + struct ggml_tensor * state, + int32_t ch_offset, + int32_t n_seq_tokens, + int32_t n_seqs, + int32_t n_heads, + int32_t st_base_f32, + int32_t st_seq_stride, + int32_t st_slot_stride, + int32_t st_kw, + float scale_out) { + struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, cur->ne[0], (int64_t)n_seq_tokens * n_seqs); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = cur; + result->src[1] = history; + result->src[2] = weight; + result->src[3] = dynamic; + result->src[4] = state; + ggml_set_op_params_i32(result, 0, 1); + ggml_set_op_params_i32(result, 1, ch_offset); + ggml_set_op_params_i32(result, 2, n_seq_tokens); + ggml_set_op_params_i32(result, 3, n_seqs); + ggml_set_op_params_i32(result, 4, n_heads); + ggml_set_op_params_i32(result, 5, st_base_f32); + ggml_set_op_params_i32(result, 6, st_seq_stride); + ggml_set_op_params_i32(result, 7, st_slot_stride); + ggml_set_op_params_i32(result, 8, st_kw); + ggml_set_op_params_f32(result, 9, scale_out); + return result; +} + +struct ggml_tensor * ggml_inkling_rel_gather( + struct ggml_context * ctx, + struct ggml_tensor * table, + struct ggml_tensor * sinks, + struct ggml_tensor * rel_pos, + int64_t n_kv, + int64_t nr, + int64_t n_head, + int64_t n_stream, + int32_t n_seq_tokens, + int32_t r0, + int32_t extent) { + struct ggml_tensor * result = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, n_kv, nr, n_head, n_stream); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = table; + result->src[1] = sinks; + result->src[2] = rel_pos; + ggml_set_op_params_i32(result, 0, 2); + ggml_set_op_params_i32(result, 1, n_seq_tokens); + ggml_set_op_params_i32(result, 2, r0); + ggml_set_op_params_i32(result, 3, extent); + ggml_set_op_params_i32(result, 4, 0); + return result; +} + +struct ggml_tensor * ggml_inkling_rel_gather_f16( + struct ggml_context * ctx, + struct ggml_tensor * kq_b, + struct ggml_tensor * kq_mask, + int32_t mask_r0) { + GGML_ASSERT(kq_b != NULL && kq_b->op == GGML_OP_INKLING_FUSED && ggml_get_op_params_i32(kq_b, 0) == 2); + struct ggml_tensor * result = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, kq_b->ne[0], kq_b->ne[1], kq_b->ne[2], kq_b->ne[3]); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = kq_b->src[0]; + result->src[1] = kq_b->src[1]; + result->src[2] = kq_b->src[2]; + result->src[3] = kq_mask; + ggml_set_op_params_i32(result, 0, 2); + ggml_set_op_params_i32(result, 1, ggml_get_op_params_i32(kq_b, 1)); + ggml_set_op_params_i32(result, 2, ggml_get_op_params_i32(kq_b, 2)); + ggml_set_op_params_i32(result, 3, ggml_get_op_params_i32(kq_b, 3)); + ggml_set_op_params_i32(result, 4, mask_r0); + return result; +} + +// S19_WAVE3: mode = 3, 4 extensions + mode = 11, 12 constructors +struct ggml_tensor * ggml_inkling_depth_mix_rms( + struct ggml_context * ctx, + struct ggml_tensor * const * states, + int n_states, + struct ggml_tensor * query, + struct ggml_tensor * rms_w, + float eps, + float rms_eps) { + GGML_ASSERT(n_states >= 1 && n_states <= 6); + const int64_t n_embd = states[0]->ne[0]; + const int64_t n_tokens = states[0]->ne[1] * states[0]->ne[2]; + const int64_t Q = query->ne[1]; + GGML_ASSERT(!rms_w || (rms_w->ne[0] == n_embd && (rms_w->ne[1] == 1 || rms_w->ne[1] == Q))); + struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, n_tokens, Q); + result->op = GGML_OP_INKLING_FUSED; + for (int i = 0; i < n_states; ++i) { + result->src[i] = states[i]; + } + result->src[n_states] = query; + result->src[n_states + 1] = rms_w; + ggml_set_op_params_i32(result, 0, 3); + ggml_set_op_params_i32(result, 1, n_states); + ggml_set_op_params_f32(result, 2, eps); + ggml_set_op_params_f32(result, 3, rms_eps); + return result; +} + +struct ggml_tensor * ggml_inkling_depth_mix( + struct ggml_context * ctx, + struct ggml_tensor * const * states, + int n_states, + struct ggml_tensor * query, + float eps) { + return ggml_inkling_depth_mix_rms(ctx, states, n_states, query, NULL, eps, 0.0f); +} + +struct ggml_tensor * ggml_inkling_rms2_concat( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * message, + float eps) { + GGML_ASSERT(cur->ne[0] == message->ne[0] && cur->ne[1] == message->ne[1]); + GGML_ASSERT(cur->ne[2] == 1 || cur->ne[2] == message->ne[2]); + const int64_t C = message->ne[2]; + struct ggml_tensor * result = C > 1 + ? ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 2 * cur->ne[0], cur->ne[1], C) + : ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 2 * cur->ne[0], cur->ne[1]); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = cur; + result->src[1] = message; + ggml_set_op_params_i32(result, 0, 4); + ggml_set_op_params_f32(result, 1, eps); + return result; +} + +struct ggml_tensor * ggml_inkling_ctrl_apply( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * message, + struct ggml_tensor * raw_gain, + struct ggml_tensor * raw_forget) { + struct ggml_tensor * result = ggml_dup_tensor(ctx, cur); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = cur; + result->src[1] = message; + result->src[2] = raw_gain; + result->src[3] = raw_forget; + ggml_set_op_params_i32(result, 0, 5); + return result; +} + +struct ggml_tensor * ggml_inkling_ctrl_apply_rms_mul( + struct ggml_context * ctx, + struct ggml_tensor * cur, + struct ggml_tensor * message, + struct ggml_tensor * up_gf, + struct ggml_tensor * rms_w, + float eps) { + const int64_t n_embd = message->ne[0]; + const int64_t n_tokens = message->ne[1]; + const int64_t C = message->ne[2]; + GGML_ASSERT(cur->ne[0] == n_embd && cur->ne[1] == n_tokens && (cur->ne[2] == 1 || cur->ne[2] == C)); + GGML_ASSERT(up_gf->ne[0] == 2 * n_embd && up_gf->ne[1] == n_tokens && up_gf->ne[2] == C); + GGML_ASSERT(rms_w->ne[0] == n_embd && (rms_w->ne[1] == 1 || rms_w->ne[1] == C)); + struct ggml_tensor * result = C > 1 + ? ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, n_tokens, C) + : ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_tokens); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = cur; + result->src[1] = message; + result->src[2] = up_gf; + result->src[3] = rms_w; + ggml_set_op_params_i32(result, 0, 11); + ggml_set_op_params_f32(result, 1, eps); + return result; +} + +struct ggml_tensor * ggml_inkling_l2_clip_qr( + struct ggml_context * ctx, + struct ggml_tensor * q_cur, + struct ggml_tensor * r_cur, + struct ggml_tensor * q_scale, + struct ggml_tensor * r_scale, + struct ggml_tensor * mul_tau, + float q_threshold, + float r_threshold, + float eps) { + GGML_ASSERT(q_cur->ne[1] == r_cur->ne[1] && q_cur->ne[2] == r_cur->ne[2]); + const int64_t q_dim = q_cur->ne[0]; + const int64_t r_dim = r_cur->ne[0]; + const int64_t n_head = q_cur->ne[1]; + const int64_t n_tokens = q_cur->ne[2]; + struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, (q_dim + r_dim) * n_head, n_tokens); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = q_cur; + result->src[1] = r_cur; + result->src[2] = q_scale; + result->src[3] = r_scale; + result->src[4] = mul_tau; + ggml_set_op_params_i32(result, 0, 12); + ggml_set_op_params_f32(result, 1, q_threshold); + ggml_set_op_params_f32(result, 2, r_threshold); + ggml_set_op_params_f32(result, 3, eps); + return result; +} + +struct ggml_tensor * ggml_inkling_dspark_concat4( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + struct ggml_tensor * d) { + GGML_ASSERT(a->ne[1] == b->ne[1] && a->ne[1] == c->ne[1] && a->ne[1] == d->ne[1]); + struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, a->ne[0] + b->ne[0] + c->ne[0] + d->ne[0], a->ne[1]); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = a; + result->src[1] = b; + result->src[2] = c; + result->src[3] = d; + ggml_set_op_params_i32(result, 0, 6); // MODE_DSPARK_CONCAT4 + return result; +} + +struct ggml_tensor * ggml_inkling_dspark_gru( + struct ggml_context * ctx, + struct ggml_tensor * joint, + struct ggml_tensor * state_in) { + GGML_ASSERT(joint->ne[0] == 3 * state_in->ne[0] && joint->ne[1] == state_in->ne[1]); + struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, state_in->ne[0], state_in->ne[1], 2); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = joint; + result->src[1] = state_in; + ggml_set_op_params_i32(result, 0, 7); // MODE_DSPARK_GRU + return result; +} + +struct ggml_tensor * ggml_inkling_softcap( + struct ggml_context * ctx, + struct ggml_tensor * a, + float inv_cap, + float cap) { + struct ggml_tensor * result = ggml_dup_tensor(ctx, a); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = a; + ggml_set_op_params_i32(result, 0, 8); // MODE_SOFTCAP + ggml_set_op_params_f32(result, 1, inv_cap); + ggml_set_op_params_f32(result, 2, cap); + return result; +} + +struct ggml_tensor * ggml_inkling_dspark_joint_gru( + struct ggml_context * ctx, + struct ggml_tensor * prev, + struct ggml_tensor * markov_w1, + struct ggml_tensor * state_in, + struct ggml_tensor * hidden, + struct ggml_tensor * context, + struct ggml_tensor * joint_proj, + struct ggml_tensor * joint_proj_b) { + const int64_t rank = state_in->ne[0]; + const int64_t nb = state_in->ne[1]; + const int64_t n_embd = hidden->ne[0]; + GGML_ASSERT(markov_w1->ne[0] == rank && prev->ne[0] == nb); + GGML_ASSERT(hidden->ne[1] == nb && context->ne[0] == n_embd && context->ne[1] == nb); + GGML_ASSERT(joint_proj->ne[0] == 2 * rank + 2 * n_embd && joint_proj->ne[1] == 3 * rank); + struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, rank, nb, 2); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = prev; + result->src[1] = markov_w1; + result->src[2] = state_in; + result->src[3] = hidden; + result->src[4] = context; + result->src[5] = joint_proj; + result->src[6] = joint_proj_b; + ggml_set_op_params_i32(result, 0, 9); // MODE_DSPARK_JOINT_GRU + return result; +} + +struct ggml_tensor * ggml_inkling_dspark_inject_mix( + struct ggml_context * ctx, + struct ggml_tensor * features, + struct ggml_tensor * fuse_w, + struct ggml_tensor * norm0, + struct ggml_tensor * norm1, + struct ggml_tensor * norm2, + struct ggml_tensor * norm3, + struct ggml_tensor * positions, + struct ggml_tensor * ring_dst, + int32_t ring_seq_offset, + int32_t ring_rows, + float eps) { + const int64_t n_embd = norm0->ne[0]; + const int64_t n_tokens = features->ne[1]; + GGML_ASSERT(features->ne[0] == 4 * n_embd && fuse_w->ne[0] == 4 && fuse_w->ne[1] == 4); + struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, n_tokens, 4); + result->op = GGML_OP_INKLING_FUSED; + result->src[0] = features; + result->src[1] = fuse_w; + result->src[2] = norm0; + result->src[3] = norm1; + result->src[4] = norm2; + result->src[5] = norm3; + result->src[6] = positions; + result->src[7] = ring_dst; + ggml_set_op_params_i32(result, 0, 10); // MODE_DSPARK_INJECT_MIX + ggml_set_op_params_i32(result, 1, ring_seq_offset); + ggml_set_op_params_i32(result, 2, ring_rows); + ggml_set_op_params_f32(result, 3, eps); + return result; +} + // ggml_norm static struct ggml_tensor * ggml_norm_impl( @@ -5546,7 +5893,7 @@ void ggml_flash_attn_ext_add_sinks( } bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) { - return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0; + return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) == 1; } void ggml_flash_attn_ext_add_indexed_bias( @@ -5557,7 +5904,7 @@ void ggml_flash_attn_ext_add_indexed_bias( GGML_ASSERT((table == NULL) == (indices == NULL)); a->src[6] = table; a->src[7] = indices; - ggml_set_op_params_i32(a, 5, table != NULL); + ggml_set_op_params_i32(a, 5, table != NULL ? 1 : 0); if (!table) { return; } @@ -5572,6 +5919,35 @@ void ggml_flash_attn_ext_add_indexed_bias( GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]); } +bool ggml_flash_attn_ext_has_banded_rel_bias(const struct ggml_tensor * a) { + return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) == 2; +} + +void ggml_flash_attn_ext_add_banded_rel_bias( + struct ggml_tensor * a, + struct ggml_tensor * table, + struct ggml_tensor * pos_info, + int32_t extent) { + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); + GGML_ASSERT((table == NULL) == (pos_info == NULL)); + a->src[6] = table; + a->src[7] = pos_info; + ggml_set_op_params_i32(a, 5, table != NULL ? 2 : 0); + ggml_set_op_params_i32(a, 6, table != NULL ? extent : 0); + if (!table) { + return; + } + + const struct ggml_tensor * q = a->src[0]; + const struct ggml_tensor * mask = a->src[3]; + GGML_ASSERT(extent > 0 && extent <= 65535); + GGML_ASSERT(mask && mask->ne[0] == a->src[1]->ne[1] && mask->ne[1] == q->ne[1]); + GGML_ASSERT(mask->ne[3] == q->ne[3]); + GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table)); + GGML_ASSERT(table->ne[0] > 0 && table->ne[0] <= 65535 && table->ne[1] == q->ne[2] && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1); + GGML_ASSERT(pos_info->type == GGML_TYPE_I32 && ggml_is_contiguous(pos_info) && ggml_is_vector(pos_info)); +} + // ggml_flash_attn_back struct ggml_tensor * ggml_flash_attn_back( diff --git a/include/llama.h b/include/llama.h index 9cc17a82b529..652aa4607a7e 100644 --- a/include/llama.h +++ b/include/llama.h @@ -522,6 +522,8 @@ extern "C" { ggml_threadpool_t threadpool_batch); LLAMA_API void llama_detach_threadpool(struct llama_context * ctx); + LLAMA_API ggml_threadpool_t llama_get_threadpool(struct llama_context * ctx); + LLAMA_API ggml_threadpool_t llama_get_threadpool_batch(struct llama_context * ctx); typedef void (*llama_model_set_tensor_data_t)(struct ggml_tensor * tensor, void * userdata); @@ -1155,6 +1157,7 @@ extern "C" { // Negative indices can be used to access logits in reverse order, -1 is the last logit. // returns NULL for invalid ids. LLAMA_API float * llama_get_logits_ith(struct llama_context * ctx, int32_t i); + LLAMA_API const float * llama_get_logits_ith_ro(struct llama_context * ctx, int32_t i); // Get all output token embeddings. // when pooling_type == LLAMA_POOLING_TYPE_NONE or when using a generative model, @@ -1673,6 +1676,12 @@ extern "C" { // return token; // Returns the sampled token LLAMA_API llama_token llama_sampler_sample(struct llama_sampler * smpl, struct llama_context * ctx, int32_t idx); + LLAMA_API bool llama_sampler_grammar_is_dormant(const struct llama_sampler * smpl); + LLAMA_API bool llama_sampler_chain_is_pure_greedy(const struct llama_sampler * chain); + LLAMA_API bool llama_sampler_chain_is_pure_temp_dist(const struct llama_sampler * chain, float * out_temp, struct llama_sampler ** out_dist); + LLAMA_API bool llama_sampler_chain_is_bias_temp_dist(const struct llama_sampler * chain, float * out_temp, struct llama_sampler ** out_dist, struct llama_sampler ** out_logit_bias); + LLAMA_API llama_token llama_sampler_temp_dist_sample_raw_0ulp(struct llama_sampler * dist_smpl, const float * logits_row, int32_t n_vocab, float temp); + LLAMA_API llama_token llama_sampler_temp_dist_probs_raw_0ulp(struct llama_sampler * dist_smpl, struct llama_sampler * lb_smpl, const float * logits_row, int32_t n_vocab, float temp, const float ** out_unnorm_p, double * out_sum_p); // TODO: extend in the future //LLAMA_API void llama_decode_with_sampler(struct llama_context * ctx, struct llama_sampler * smpl, struct llama_batch batch, ...); diff --git a/src/llama-adapter.cpp b/src/llama-adapter.cpp index 824601ed6f6a..8219accae921 100644 --- a/src/llama-adapter.cpp +++ b/src/llama-adapter.cpp @@ -342,18 +342,43 @@ static void llama_adapter_lora_init_impl(llama_model & model, FILE * file, llama auto * buft = ggml_backend_buffer_get_type(model_tensor->buffer); - // do not load loras to extra buffer types (i.e. bufts for repacking) -> use the CPU in that case - for (auto & ex : buft_extra) { - if (ex == buft) { - LLAMA_LOG_WARN("%s: lora for '%s' cannot use buft '%s', fallback to CPU\n", __func__, model_tensor->name, ggml_backend_buft_name(buft)); - - auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); - if (!cpu_dev) { - throw std::runtime_error(format("%s: no CPU backend found", __func__)); + // do not load loras to extra buffer types (i.e. bufts for repacking): + // for GPU extra bufts (e.g. Vulkan_Repack), use the device's default buft (e.g. Vulkan0); + // for CPU extra bufts, use the default CPU buft. + bool remapped = false; + if (auto * dev = ggml_backend_buft_get_device(buft)) { + if (auto * reg = ggml_backend_dev_backend_reg(dev)) { + auto get_extra_fn = (ggml_backend_dev_get_extra_bufts_t) + ggml_backend_reg_get_proc_address(reg, "ggml_backend_dev_get_extra_bufts"); + if (get_extra_fn) { + ggml_backend_buffer_type_t * extra_bufts = get_extra_fn(dev); + while (extra_bufts && *extra_bufts) { + if (*extra_bufts == buft) { + auto * fallback_buft = ggml_backend_dev_buffer_type(dev); + LLAMA_LOG_WARN("%s: lora for '%s' cannot use buft '%s', remap to '%s'\n", + __func__, model_tensor->name, ggml_backend_buft_name(buft), ggml_backend_buft_name(fallback_buft)); + buft = fallback_buft; + remapped = true; + break; + } + ++extra_bufts; + } + } + } + } + if (!remapped) { + for (auto & ex : buft_extra) { + if (ex == buft) { + LLAMA_LOG_WARN("%s: lora for '%s' cannot use buft '%s', fallback to CPU\n", __func__, model_tensor->name, ggml_backend_buft_name(buft)); + + auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); + if (!cpu_dev) { + throw std::runtime_error(format("%s: no CPU backend found", __func__)); + } + buft = ggml_backend_dev_buffer_type(cpu_dev); + + break; } - buft = ggml_backend_dev_buffer_type(cpu_dev); - - break; } } diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 4b00c3d381c2..8e93f62c08d1 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -7,6 +7,8 @@ #include "llama-batch.h" #include "llama-io.h" #include "llama-memory.h" +#include "llama-memory-hybrid-iswa.h" +#include "llama-memory-recurrent.h" #include "llama-mmap.h" #include "llama-model.h" #include "llama-moe-cache.h" @@ -20,6 +22,7 @@ #include #include #include +#include #include #include @@ -639,9 +642,90 @@ llama_context::llama_context( } } +namespace { +struct s19_dspark_sched_entry { + bool is_embd = false; + uint32_t n_tokens = 0; + int32_t n_outputs = 0; + llm_graph_type gtype = LLM_GRAPH_TYPE_DEFAULT; + llama_seq_id first_seq_id = 0; + llm_graph_result_ptr res; + ggml_backend_sched_ptr sched; + ggml_tensor * tree_meta = nullptr; + bool allocated = false; +}; + +struct s19_ctx_ext { + bool greedy_argmax_req = false; + bool built_greedy[2] = { false, false }; + bool built_direct_scopy[2] = { false, false }; + ggml_tensor * active_tree_meta = nullptr; + float tree_meta_host[32] = {}; + int32_t tree_meta_count = 0; + ggml_backend_sched_ptr primary_sched; + std::vector dspark_pool; +}; + +static std::mutex g_s19_ctx_mu; +static std::unordered_map g_s19_ctx_map; +static thread_local bool g_s19_building_greedy_argmax = false; +static thread_local ggml_tensor * g_s23_built_tree_meta = nullptr; + +static s19_ctx_ext & s19_get_ext(const llama_context * ctx) { + std::lock_guard lk(g_s19_ctx_mu); + return g_s19_ctx_map[ctx]; +} +} // namespace + +extern "C" LLAMA_API void llama_s23_set_dspark_tree_meta(ggml_tensor * t); +extern "C" LLAMA_API void llama_s23_set_dspark_tree_meta(ggml_tensor * t) { + g_s23_built_tree_meta = t; +} + +extern "C" LLAMA_API int32_t llama_s23_get_dspark_tree_meta(const llama_context * ctx, float * out, int32_t max_n); +extern "C" LLAMA_API int32_t llama_s23_get_dspark_tree_meta(const llama_context * ctx, float * out, int32_t max_n) { + if (!ctx || !out || max_n <= 0) { + return 0; + } + std::lock_guard lk(g_s19_ctx_mu); + auto it = g_s19_ctx_map.find(ctx); + if (it == g_s19_ctx_map.end() || it->second.tree_meta_count <= 0) { + return 0; + } + const int32_t n = std::min(max_n, it->second.tree_meta_count); + std::memcpy(out, it->second.tree_meta_host, (size_t) n * sizeof(float)); + return n; +} + +extern "C" void llama_s19_set_greedy_argmax_only(llama_context * ctx, bool enabled); +extern "C" void llama_s19_set_greedy_argmax_only(llama_context * ctx, bool enabled) { + if (!ctx) { + return; + } + std::lock_guard lk(g_s19_ctx_mu); + g_s19_ctx_map[ctx].greedy_argmax_req = enabled; +} + +bool llama_s19_is_building_greedy_argmax(void); +bool llama_s19_is_building_greedy_argmax(void) { + return g_s19_building_greedy_argmax; +} + llama_context::~llama_context() { // wait for any pending asynchronous copies into the output buffers before they are freed synchronize(); + { + std::lock_guard lk(g_s19_ctx_mu); + auto it = g_s19_ctx_map.find(this); + if (it != g_s19_ctx_map.end()) { + if (it->second.primary_sched) { + std::swap(this->sched, it->second.primary_sched); + it->second.primary_sched.reset(); + } + it->second.dspark_pool.clear(); + g_s19_ctx_map.erase(it); + } + } // when training, ggml_opt allocates extra buffers through the scheduler, so the sizes no longer match the expectation if (!model.no_alloc() && !opt_ctx) { @@ -809,6 +893,16 @@ void llama_context::sched_reserve() { LLAMA_LOG_DEBUG("%s: max_nodes = %zu\n", __func__, max_nodes); gf_res_prev_active = nullptr; + { + auto & ext = s19_get_ext(this); + if (ext.primary_sched) { + std::swap(this->sched, ext.primary_sched); + ext.primary_sched.reset(); + } + ext.dspark_pool.clear(); + ext.built_greedy[0] = false; + ext.built_greedy[1] = false; + } gf_res_reserve->set_max_nodes(max_nodes); gf_res_reserve->reset(); @@ -1095,7 +1189,19 @@ enum llama_pooling_type llama_context::pooling_type() const { return cparams.pooling_type; } +void llama_context::materialize_logits_uma_view() { + if (logits_uma_view != nullptr) { + synchronize(); + if (logits.data != nullptr && logits_uma_n_floats > 0) { + memcpy(logits.data, logits_uma_view, logits_uma_n_floats * sizeof(float)); + } + logits_uma_view = nullptr; + logits_uma_n_floats = 0; + } +} + float * llama_context::get_logits() { + materialize_logits_uma_view(); output_reorder(); return logits.data; @@ -1130,7 +1236,28 @@ int64_t llama_context::output_resolve_row(int32_t i) const { return j; } +const float * llama_context::get_logits_ith_ro(int32_t i) { + output_reorder(); + + if (logits_uma_view != nullptr && output_swaps.empty() && !sampling.logits.has_data()) { + try { + const int64_t j = output_resolve_row(i); + return logits_uma_view + j * model.vocab.n_tokens(); + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what()); +#ifndef NDEBUG + GGML_ABORT("fatal error"); +#else + return nullptr; +#endif + } + } + + return get_logits_ith(i); +} + float * llama_context::get_logits_ith(int32_t i) { + materialize_logits_uma_view(); output_reorder(); try { @@ -1824,19 +1951,123 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll return nullptr; } - auto * res = get_gf_res_prev(); - auto * gf = res->get_gf(); + auto & ext = s19_get_ext(this); + const bool is_dspark_ctx = model.hparams.dspark_f_rnn; + const int prev_slot = (n_outputs > 0) ? 1 : 0; + const bool want_greedy_argmax = !is_dspark_ctx && (n_outputs > 0) && + ext.greedy_argmax_req && sampling.samplers.empty() && !cparams.embeddings; + + bool cur_direct_scopy = false; + if (!is_dspark_ctx && ubatch.n_seq_tokens <= 16) { + const llama_memory_recurrent_context * recr_mctx = nullptr; + if (const auto * hyb = dynamic_cast(mctx)) { + recr_mctx = hyb->get_recr(); + } else { + recr_mctx = dynamic_cast(mctx); + } + if (recr_mctx) { + const int64_t rs_k = cparams.n_rs_seq == 0 ? 1 : ((int64_t) cparams.n_rs_seq + 1); + const uint32_t rs_kw = (uint32_t) std::min(ubatch.n_seq_tokens, rs_k); + cur_direct_scopy = recr_mctx->can_direct_scopy(ubatch.n_seqs, rs_kw); + } + } + + s19_dspark_sched_entry * pool_entry = nullptr; + llm_graph_result * res = nullptr; + + if (is_dspark_ctx) { + if (!ext.primary_sched) { + ext.primary_sched = std::move(this->sched); + } else if (this->sched) { + // Return active pool sched back to its owner slot before selecting the new slot + for (auto & e : ext.dspark_pool) { + if (!e.sched && e.allocated) { + e.sched = std::move(this->sched); + break; + } + } + if (this->sched) { + ext.primary_sched = std::move(this->sched); + } + } + const bool is_embd = (ubatch.embd != nullptr || ubatch.embd_row != nullptr); + const llama_seq_id first_sid = (ubatch.n_tokens > 0 && ubatch.seq_id && ubatch.seq_id[0]) ? ubatch.seq_id[0][0] : 0; + for (auto & e : ext.dspark_pool) { + if (e.is_embd == is_embd && e.n_tokens == ubatch.n_tokens && + (uint32_t) e.n_outputs == n_outputs && + e.gtype == gtype && e.first_seq_id == first_sid) { + pool_entry = &e; + break; + } + } + if (!pool_entry) { + if (ext.dspark_pool.size() >= 12) { + if (ext.primary_sched) { + ggml_backend_sched_synchronize(ext.primary_sched.get()); + } + ext.dspark_pool.erase(ext.dspark_pool.begin()); + } + const size_t max_nodes = this->graph_max_nodes(); + s19_dspark_sched_entry ne; + ne.is_embd = is_embd; + ne.n_tokens = ubatch.n_tokens; + ne.n_outputs = n_outputs; + ne.gtype = gtype; + ne.first_seq_id = first_sid; + ne.res = std::make_unique(max_nodes); + ne.sched.reset(ggml_backend_sched_new( + backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), + max_nodes, cparams.pipeline_parallel, cparams.op_offload)); + ggml_backend_sched_set_copy_callback(ne.sched.get(), sched_copy_experts, this); + ne.allocated = false; + ext.dspark_pool.push_back(std::move(ne)); + pool_entry = &ext.dspark_pool.back(); + } + this->sched = std::move(pool_entry->sched); + res = pool_entry->res.get(); + } else { + if (ext.primary_sched) { + if (this->sched) { + for (auto & e : ext.dspark_pool) { + if (!e.sched && e.allocated) { + e.sched = std::move(this->sched); + break; + } + } + } + this->sched = std::move(ext.primary_sched); + } + res = get_gf_res_prev(); + } + + auto * gf = res->get_gf(); + + struct s19_greedy_tls_guard { + s19_greedy_tls_guard(bool v) { g_s19_building_greedy_argmax = v; } + ~s19_greedy_tls_guard() { g_s19_building_greedy_argmax = false; } + } greedy_guard(want_greedy_argmax); // the new graph parameters // in order to correctly reuse a graph, it's full topology has to be uniquely determined by these parameters const auto gparams = graph_params(res, ubatch, mctx, gtype); - if (!graph_reuse_disable && gf_res_prev_active == res && res->can_reuse(gparams)) { + const bool can_reuse_slot = is_dspark_ctx + ? (pool_entry->allocated && res->can_reuse(gparams)) + : (gf_res_prev_active == res && + ext.built_greedy[prev_slot] == want_greedy_argmax && + ext.built_direct_scopy[prev_slot] == cur_direct_scopy && + res->can_reuse(gparams)); + + if (!graph_reuse_disable && can_reuse_slot) { //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__); n_reused++; } else { - gf_res_prev_active = nullptr; + if (is_dspark_ctx) { + pool_entry->allocated = false; + } else { + gf_res_prev_active = nullptr; + } res->reset(); ggml_backend_sched_reset(sched.get()); @@ -1844,6 +2075,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll //const auto t_start_us = ggml_time_us(); + g_s23_built_tree_meta = nullptr; gf = model.build_graph(gparams); //LLAMA_LOG_INFO("graph build time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0); @@ -1860,9 +2092,18 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll return nullptr; } - gf_res_prev_active = res; + if (is_dspark_ctx) { + pool_entry->allocated = true; + pool_entry->tree_meta = g_s23_built_tree_meta; + } else { + gf_res_prev_active = res; + ext.built_greedy[prev_slot] = want_greedy_argmax; + ext.built_direct_scopy[prev_slot] = cur_direct_scopy; + } } + ext.active_tree_meta = (is_dspark_ctx && pool_entry) ? pool_entry->tree_meta : nullptr; + // set the input data for the input tensors { //const auto t_start_us = ggml_time_us(); @@ -1886,6 +2127,8 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll } int llama_context::encode(const llama_batch_ext & batch_inp) { + logits_uma_view = nullptr; + logits_uma_n_floats = 0; if (batch_inp.tokens.empty()) { LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); return -1; @@ -2138,6 +2381,8 @@ static bool needs_raw_logits(const llama_ubatch & ubatch, const std::map s19_dspark_warmup_padded; + const llama_batch_ext * s19_batch_ptr = &batch_inp; + if (model.hparams.dspark_f_rnn && batch_inp.state.empty() && + batch_inp.n_embd == 0 && batch_inp.tokens[0].embd_row < 0 && + batch_inp.tokens.size() < model.hparams.dflash_block_size) { + s19_dspark_warmup_padded = std::make_unique(batch_inp); + const uint32_t block = model.hparams.dflash_block_size; + auto last_tok = s19_dspark_warmup_padded->tokens.back(); + const llama_seq_id sid = last_tok.seq_ids.empty() ? 0 : *last_tok.seq_ids.begin(); + for (size_t k = 0; k < s19_dspark_warmup_padded->tokens.size(); ++k) { + s19_dspark_warmup_padded->tokens[k].seq_ids = { sid }; + s19_dspark_warmup_padded->tokens[k].output = false; + } + while (s19_dspark_warmup_padded->tokens.size() < block) { + auto pad_tok = last_tok; + pad_tok.seq_ids = { sid }; + pad_tok.pos[0] = s19_dspark_warmup_padded->tokens.back().pos[0] + 1; + pad_tok.output = (s19_dspark_warmup_padded->tokens.size() + 1 == block); + if (pad_tok.id == LLAMA_TOKEN_NULL) { + pad_tok.id = 0; + } + s19_dspark_warmup_padded->tokens.push_back(pad_tok); + } + if (s19_dspark_warmup_padded->state.empty() && s19_dspark_warmup_padded->tokens.size() > 1) { + s19_dspark_warmup_padded->tokens[1].id = 0; + } + s19_batch_ptr = s19_dspark_warmup_padded.get(); + } + if (batch_inp.n_embd > 0 && batch_inp.n_embd != batch_inp.n_embd_inp) { LLAMA_LOG_ERROR("%s: embd row width %zu does not match the decoder input %zu\n", __func__, batch_inp.n_embd, batch_inp.n_embd_inp); @@ -2207,7 +2481,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { } } - if (!balloc->init(batch_inp, vocab, output_all)) { + if (!balloc->init(*s19_batch_ptr, vocab, output_all)) { LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__); return -1; } @@ -2339,6 +2613,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { } } const bool write_h_nextn = cparams.embeddings_nextn_dev && h_nextn_dev != nullptr; + bool wrote_h_nextn = false; if (write_h_nextn && ev_h_nextn_read_recorded) { ggml_backend_event_wait(h_nextn_backend, ev_h_nextn_read.get()); } @@ -2421,7 +2696,25 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { if (n_outputs) { GGML_ASSERT( n_outputs_prev + n_outputs <= n_outputs_all); GGML_ASSERT((n_outputs_prev + n_outputs)*n_vocab <= (int64_t) logits.size); - ggml_backend_tensor_get_async(backend_res, t_logits, logits_out, 0, n_outputs*n_vocab*sizeof(float)); + // Series 20 (Pillar S20.5 + X-1): Zero-copy cached UMA view on final ubatch when contiguous F32 + const void * uma_ptr = nullptr; + const bool is_final_ubatch = (n_tokens_prev + (int64_t) ubatch.n_tokens == (int64_t) n_tokens_all); + if (is_final_ubatch && n_outputs_prev == 0 && n_outputs == n_outputs_all && + output_swaps.empty() && t_logits->type == GGML_TYPE_F32 && ggml_is_contiguous(t_logits)) { + using get_uma_ptr_fn = const void * (*)(ggml_backend_t, const ggml_tensor *); + ggml_backend_dev_t dev = ggml_backend_get_device(backend_res); + ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr; + auto fn = reg ? (get_uma_ptr_fn) ggml_backend_reg_get_proc_address(reg, "ggml_backend_get_cached_uma_ptr") : nullptr; + if (fn) { + uma_ptr = fn(backend_res, t_logits); + } + } + if (uma_ptr != nullptr) { + logits_uma_view = (const float *) uma_ptr; + logits_uma_n_floats = (size_t) n_outputs * (size_t) n_vocab; + } else { + ggml_backend_tensor_get_async(backend_res, t_logits, logits_out, 0, n_outputs*n_vocab*sizeof(float)); + } } } @@ -2524,6 +2817,40 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { copy_tensor_async_rows(res->t_sampled_logits, sampling.logits, stride, n_outputs_prev, sched.get(), &sampling.logits_count); copy_tensor_async_rows(res->t_sampled_probs, sampling.probs, stride, n_outputs_prev, sched.get(), &sampling.probs_count); copy_tensor_async_rows(res->t_candidates, sampling.candidates, stride, n_outputs_prev, sched.get(), &sampling.candidates_count); + if (!write_h_nextn) { + auto & ext = s19_get_ext(this); + if (ext.active_tree_meta != nullptr) { + ggml_tensor * tm_t = ext.active_tree_meta; + const int32_t tm_n = (int32_t) std::min(32, ggml_nelements(tm_t)); + ggml_backend_t tm_b = ggml_backend_sched_get_tensor_backend(sched.get(), tm_t); + if (tm_b && tm_n > 0) { + ggml_backend_tensor_get_async(tm_b, tm_t, ext.tree_meta_host, 0, (size_t) tm_n * sizeof(float)); + ext.tree_meta_count = tm_n; + } else { + ext.tree_meta_count = 0; + } + ext.active_tree_meta = nullptr; + } else if (ubatch.embd == nullptr && ubatch.embd_row == nullptr) { + ext.tree_meta_count = 0; + } + } + } else if (!res->t_sampled.empty() && sampling.sampled.has_data() && n_outputs > 0) { + if (res->t_sampled.size() == 1 && (int64_t) ggml_nelements(res->t_sampled[0]) == n_outputs) { + ggml_tensor * tensor = res->t_sampled[0]; + GGML_ASSERT(ggml_is_contiguous(tensor)); + GGML_ASSERT((size_t) (n_outputs_prev + n_outputs) <= sampling.sampled.size); + ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched.get(), tensor); + ggml_backend_tensor_get_async(backend, tensor, sampling.sampled.data + n_outputs_prev, 0, ggml_nbytes(tensor)); + } else { + copy_tensor_async_rows(res->t_sampled, sampling.sampled, 1, n_outputs_prev, sched.get()); + } + } else if (sampling.sampled.has_data() && n_outputs > 0) { + GGML_ASSERT((size_t) (n_outputs_prev + n_outputs) <= sampling.sampled.size); + std::fill_n(sampling.sampled.data + n_outputs_prev, n_outputs, LLAMA_TOKEN_NULL); + } + + if (write_h_nextn && res->get_h_nextn() != nullptr) { + wrote_h_nextn = true; } n_outputs_prev += n_outputs; @@ -2533,7 +2860,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { if (layer_inp_dev && ev_layer_inp_written) { ggml_backend_event_record(ev_layer_inp_written.get(), layer_inp_backend); } - if (write_h_nextn) { + if (wrote_h_nextn) { ggml_backend_event_record(ev_h_nextn_written.get(), h_nextn_backend); ev_h_nextn_written_recorded = true; } @@ -2615,6 +2942,8 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { // uint32_t llama_context::output_reserve(int32_t n_outputs) { + logits_uma_view = nullptr; + logits_uma_n_floats = 0; const auto & hparams = model.hparams; const auto & vocab = model.vocab; @@ -2660,6 +2989,8 @@ uint32_t llama_context::output_reserve(int32_t n_outputs) { if (has_sampling) { backend_float_count = 2 * n_vocab * n_outputs_max; // logits + probs backend_token_count = (1 + n_vocab) * n_outputs_max; // sampled + candidates + } else if (n_outputs_max > 0) { + backend_token_count = n_outputs_max; // lightweight t_sampled slot (e.g. DSpark greedy IDs) } if (output_ids.empty()) { @@ -2758,12 +3089,18 @@ uint32_t llama_context::output_reserve(int32_t n_outputs) { } else { sampling.logits = {nullptr, 0}; sampling.probs = {nullptr, 0}; - sampling.sampled = {nullptr, 0}; + sampling.sampled = n_outputs_max > 0 + ? buffer_view{(llama_token *) (base + offset), (size_t) n_outputs_max} + : buffer_view{nullptr, 0}; + offset += sampling.sampled.size * sizeof(llama_token); sampling.candidates = {nullptr, 0}; sampling.logits_count.clear(); sampling.probs_count.clear(); sampling.candidates_count.clear(); + if (sampling.sampled.data) { + std::fill_n(sampling.sampled.data, sampling.sampled.size, LLAMA_TOKEN_NULL); + } } // set all ids as invalid (negative) @@ -2813,6 +3150,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to } void llama_context::output_reorder() { + if (!output_swaps.empty()) { + materialize_logits_uma_view(); + } const uint64_t n_vocab = model.vocab.n_tokens(); const uint64_t n_embd = model.hparams.n_embd; const uint64_t n_embd_out = model.hparams.n_embd_out(); @@ -2864,6 +3204,8 @@ void llama_context::output_reorder() { std::swap(sampling.logits_count[i0], sampling.logits_count[i1]); std::swap(sampling.probs_count[i0], sampling.probs_count[i1]); std::swap(sampling.candidates_count[i0], sampling.candidates_count[i1]); + } else if (sampling.sampled.size > 0) { + std::swap(sampling.sampled.data[i0], sampling.sampled.data[i1]); } } @@ -2988,6 +3330,7 @@ static void ubatch_prepare_reserve( ggml_cgraph * llama_context::graph_reserve( uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx, bool split_only, size_t * sizes) { + materialize_logits_uma_view(); LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs); GGML_ASSERT(n_outputs >= 1); @@ -4636,6 +4979,14 @@ void llama_detach_threadpool(llama_context * ctx) { ctx->detach_threadpool(); } +ggml_threadpool_t llama_get_threadpool(llama_context * ctx) { + return ctx->get_threadpool(); +} + +ggml_threadpool_t llama_get_threadpool_batch(llama_context * ctx) { + return ctx->get_threadpool_batch(); +} + void llama_set_n_threads(llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) { ctx->set_n_threads(n_threads, n_threads_batch); } @@ -4688,6 +5039,16 @@ float * llama_get_logits_ith(llama_context * ctx, int32_t i) { return res; } +const float * llama_get_logits_ith_ro(llama_context * ctx, int32_t i) { + ctx->synchronize(); + + const float * res = ctx->get_sampled_logits_ith(i); + if (!res) { + res = ctx->get_logits_ith_ro(i); + } + return res; +} + float * llama_get_embeddings(llama_context * ctx) { ctx->synchronize(); diff --git a/src/llama-context.h b/src/llama-context.h index 3e3921c7df28..465af09b8bca 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -83,6 +83,7 @@ struct llama_context { float * get_logits(); float * get_logits_ith(int32_t i); + const float * get_logits_ith_ro(int32_t i); float * get_embeddings(); float * get_embeddings_ith(int32_t i); @@ -115,6 +116,8 @@ struct llama_context { ggml_threadpool_t threadpool_batch); void detach_threadpool(); + ggml_threadpool_t get_threadpool() const { return threadpool; } + ggml_threadpool_t get_threadpool_batch() const { return threadpool_batch; } void set_n_threads(int32_t n_threads, int32_t n_threads_batch); @@ -250,6 +253,7 @@ struct llama_context { uint32_t output_reserve(int32_t n_outputs); void output_reorder(); + void materialize_logits_uma_view(); // map the output row index `i` to batch index int64_t output_resolve_row(int32_t i) const; @@ -348,6 +352,8 @@ struct llama_context { // decode output (2-dimensional array: [n_outputs][n_vocab]) buffer_view logits = {nullptr, 0}; + const float * logits_uma_view = nullptr; + size_t logits_uma_n_floats = 0; // embeddings output (2-dimensional array: [n_outputs][n_embd]) // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 5fef4c42168a..3bae102d4473 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2,6 +2,7 @@ #include "llama-impl.h" #include "llama-model.h" +#include "llama-model-loader.h" #include "llama-moe-cache.h" #include "llama-batch.h" #include "llama-cparams.h" @@ -529,7 +530,7 @@ void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) { void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) { const int64_t n_rs = mctx->get_n_rs(); - if (s_copy) { + if (s_copy && s_copy->buffer) { // gen: unused (no buffer) when every state is viewed in place GGML_ASSERT(ggml_backend_buffer_is_host(s_copy->buffer)); int32_t * data = (int32_t *) s_copy->data; @@ -568,6 +569,36 @@ void llm_graph_input_rs::set_input_rep(const llama_memory_recurrent_context * mc } } +int llm_graph_input_rs::gen_compute_identity(const llama_memory_recurrent_context * mctx, int64_t n_seqs, uint32_t n_rs_seq) { + static const bool enabled = getenv("GGML_GEN_GDN_INPLACE") ? (atoi(getenv("GGML_GEN_GDN_INPLACE")) != 0) : true; + if (!enabled) { + return -1; + } + // with rollback snapshots (speculative decoding) s_copy() consumes the per-sequence rollback index, so it must + // only be called by set_input; the in-place view is not used in that mode anyway + if (n_rs_seq != 0) { + return 0; + } + if ((int64_t) mctx->get_n_rs() != n_seqs) { + return 0; + } + for (int64_t i = 0; i < n_seqs; i++) { + if (mctx->s_copy((int) i) != (int32_t) (mctx->get_head() + i)) { + return 0; + } + } + return 1; +} + +bool llm_graph_input_rs::compute_direct_scopy(const llama_memory_recurrent_context * mctx, const llama_ubatch & ubatch, const llama_cparams & cparams) { + if (!mctx || ubatch.n_seq_tokens > 16) { + return false; + } + const int64_t rs_k = cparams.n_rs_seq == 0 ? 1 : ((int64_t) cparams.n_rs_seq + 1); + const uint32_t rs_kw = (uint32_t) std::min(ubatch.n_seq_tokens, rs_k); + return mctx->can_direct_scopy(ubatch.n_seqs, rs_kw); +} + bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) { const auto * mctx = static_cast(params.mctx); @@ -575,6 +606,9 @@ bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) { bool res = true; + res &= gen_identity == gen_compute_identity(mctx, params.ubatch.n_seqs, params.cparams.n_rs_seq); + res &= direct_scopy == compute_direct_scopy(mctx, params.ubatch, params.cparams); + res &= s_copy->ne[0] == mctx->get_n_rs(); res &= s_copy_main->ne[0] == params.ubatch.n_seqs; @@ -1278,7 +1312,7 @@ void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { const int64_t n_rs = mctx->get_recr()->get_n_rs(); - if (inp_rs->s_copy) { + if (inp_rs->s_copy && inp_rs->s_copy->buffer) { // gen: unused when states are viewed in place GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); int32_t * data = (int32_t *) inp_rs->s_copy->data; @@ -1309,6 +1343,8 @@ bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { res &= inp_rs->head == mctx->get_recr()->get_head(); res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); + res &= inp_rs->gen_identity == llm_graph_input_rs::gen_compute_identity(mctx->get_recr(), params.ubatch.n_seqs, params.cparams.n_rs_seq); + res &= inp_rs->direct_scopy == llm_graph_input_rs::compute_direct_scopy(mctx->get_recr(), params.ubatch, params.cparams); return res; } @@ -1326,7 +1362,7 @@ void llm_graph_input_mem_hybrid_k::set_input(const llama_ubatch * ubatch) { const int64_t n_rs = mctx->get_recr()->get_n_rs(); - if (inp_rs->s_copy) { + if (inp_rs->s_copy && inp_rs->s_copy->buffer) { // gen: unused when states are viewed in place GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); int32_t * data = (int32_t *) inp_rs->s_copy->data; @@ -1356,6 +1392,8 @@ bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) { res &= inp_rs->head == mctx->get_recr()->get_head(); res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); + res &= inp_rs->gen_identity == llm_graph_input_rs::gen_compute_identity(mctx->get_recr(), params.ubatch.n_seqs, params.cparams.n_rs_seq); + res &= inp_rs->direct_scopy == llm_graph_input_rs::compute_direct_scopy(mctx->get_recr(), params.ubatch, params.cparams); return res; } @@ -1385,7 +1423,7 @@ void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) { const int64_t n_rs = mctx->get_recr()->get_n_rs(); - if (inp_rs->s_copy) { + if (inp_rs->s_copy && inp_rs->s_copy->buffer) { // gen: unused when states are viewed in place GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); int32_t * data = (int32_t *) inp_rs->s_copy->data; @@ -1429,6 +1467,8 @@ bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) res &= inp_rs->head == mctx->get_recr()->get_head(); res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); + res &= inp_rs->gen_identity == llm_graph_input_rs::gen_compute_identity(mctx->get_recr(), params.ubatch.n_seqs, params.cparams.n_rs_seq); + res &= inp_rs->direct_scopy == llm_graph_input_rs::compute_direct_scopy(mctx->get_recr(), params.ubatch, params.cparams); return res; } @@ -1446,9 +1486,12 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) attn_ctx->get_base()->set_input_attn_mask(inp_attn->self_attn_mask, ubatch, cparams.causal_attn); } - if (self_rel_pos->buffer) { + if (self_rel_pos && self_rel_pos->buffer) { attn_ctx->get_base()->set_input_relative_pos(self_rel_pos, ubatch, extent); } + if (self_rel_pos_pack && self_rel_pos_pack->buffer) { + attn_ctx->get_base()->set_input_rel_pos_pack(self_rel_pos_pack, ubatch, n_stream_rel); + } // swa tensors may not be allocated if there are no SWA attention layers if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { @@ -1460,13 +1503,16 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) attn_ctx->get_swa()->set_input_attn_mask(inp_attn->self_attn_mask_swa, ubatch, cparams.causal_attn); } - if (self_rel_pos_swa->buffer) { + if (self_rel_pos_swa && self_rel_pos_swa->buffer) { attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, ubatch, extent_swa); } + if (self_rel_pos_pack_swa && self_rel_pos_pack_swa->buffer) { + attn_ctx->get_swa()->set_input_rel_pos_pack(self_rel_pos_pack_swa, ubatch, n_stream_rel_swa); + } const int64_t n_rs = mctx->get_recr()->get_n_rs(); - if (inp_rs->s_copy) { + if (inp_rs->s_copy && inp_rs->s_copy->buffer) { GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); int32_t * data = (int32_t *) inp_rs->s_copy->data; @@ -1497,8 +1543,17 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par res &= can_reuse_kq_mask(inp_attn->self_attn_mask.raw, attn_ctx->get_base(), params.ubatch, params.cparams); - res &= self_rel_pos->ne[0] == attn_ctx->get_base()->get_n_kv(); - res &= self_rel_pos->ne[1] == params.ubatch.n_tokens; + if (self_rel_pos) { + res &= self_rel_pos->ne[0] == attn_ctx->get_base()->get_n_kv(); + res &= self_rel_pos->ne[1] == params.ubatch.n_tokens; + } + if (self_rel_pos_pack) { + const uint32_t n_kv_b = attn_ctx->get_base()->get_n_kv(); + const uint32_t n_strm_b = (uint32_t) inp_attn->self_attn_mask.raw->ne[3]; + const int64_t req_b = (int64_t) n_strm_b * n_kv_b + params.ubatch.n_tokens + (int64_t) n_strm_b * ((n_kv_b + 63) / 64) * 2; + res &= n_stream_rel == n_strm_b; + res &= self_rel_pos_pack->ne[0] == req_b; + } // swa tensors may not be allocated if there are no SWA attention layers if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { @@ -1507,8 +1562,17 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par res &= can_reuse_kq_mask(inp_attn->self_attn_mask_swa.raw, attn_ctx->get_swa(), params.ubatch, params.cparams); - res &= self_rel_pos_swa->ne[0] == attn_ctx->get_swa()->get_n_kv(); - res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; + if (self_rel_pos_swa) { + res &= self_rel_pos_swa->ne[0] == attn_ctx->get_swa()->get_n_kv(); + res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; + } + if (self_rel_pos_pack_swa) { + const uint32_t n_kv_s = attn_ctx->get_swa()->get_n_kv(); + const uint32_t n_strm_s = (uint32_t) inp_attn->self_attn_mask_swa.raw->ne[3]; + const int64_t req_s = (int64_t) n_strm_s * n_kv_s + params.ubatch.n_tokens + (int64_t) n_strm_s * ((n_kv_s + 63) / 64) * 2; + res &= n_stream_rel_swa == n_strm_s; + res &= self_rel_pos_pack_swa->ne[0] == req_s; + } res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); @@ -1516,6 +1580,8 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par res &= inp_rs->head == mctx->get_recr()->get_head(); res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); + res &= inp_rs->gen_identity == llm_graph_input_rs::gen_compute_identity(mctx->get_recr(), params.ubatch.n_seqs, params.cparams.n_rs_seq); + res &= inp_rs->direct_scopy == llm_graph_input_rs::compute_direct_scopy(mctx->get_recr(), params.ubatch, params.cparams); return res; } @@ -1850,6 +1916,14 @@ ggml_tensor * llm_graph_context::build_lora_mm( // a Hadamard-folded weight reads the transformed input; a LoRA delta lives in the primal basis and reads `cur` ggml_tensor * cur_mm = build_hadamard_input(w, cur); + // gen: weights the loader stored as BF16 only because they are bf16-exact (GGML_GEN_BF16_EXACT) go through + // the matrix-vector kernels as BF16 (same per-row arithmetic as F32, half the bytes). Above + // GGML_GEN_BF16_CAST_ABOVE columns (default 8, <= the backend's mat-vec limit) they are cast back to F32 so + // the tiled matmul sees exactly the original F32 operands. + if (w->type == GGML_TYPE_BF16 && cur_mm->ne[1]*cur_mm->ne[2]*cur_mm->ne[3] > llama_gen_bf16_cast_above() && + llama_gen_bf16_converted(ggml_get_name(w))) { + w = ggml_cast(ctx0, w, GGML_TYPE_F32); + } ggml_tensor * res = ggml_mul_mat(ctx0, w, cur_mm); if (w->type == GGML_TYPE_NVFP4) { @@ -1946,7 +2020,9 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( const int64_t n_expert = w_s->ne[0]; const int64_t n_tokens = cur->ne[2]; ggml_tensor * s = ggml_reshape_3d(ctx0, w_s, 1, n_expert, 1); - s = ggml_repeat_4d(ctx0, s, 1, n_expert, n_tokens, 1); + if (n_tokens > 1) { + s = ggml_repeat_4d(ctx0, s, 1, n_expert, n_tokens, 1); + } s = ggml_get_rows(ctx0, s, ids); res = ggml_mul(ctx0, res, s); } @@ -2572,11 +2648,16 @@ ggml_tensor * llm_graph_context::build_moe_ffn( cb(gate_up, "ffn_moe_gate_up_biased", il); } - const int64_t n_ff = gate_up->ne[0] / 2; - cur = ggml_view_3d(ctx0, gate_up, n_ff, gate_up->ne[1], gate_up->ne[2], gate_up->nb[1], gate_up->nb[2], 0); - cb(cur, "ffn_moe_gate", il); - up = ggml_view_3d(ctx0, gate_up, n_ff, gate_up->ne[1], gate_up->ne[2], gate_up->nb[1], gate_up->nb[2], n_ff * gate_up->nb[0]); - cb(up, "ffn_moe_up", il); + if (type_op == LLM_FFN_SITU) { + cur = gate_up; + up = nullptr; + } else { + const int64_t n_ff = gate_up->ne[0] / 2; + cur = ggml_view_3d(ctx0, gate_up, n_ff, gate_up->ne[1], gate_up->ne[2], gate_up->nb[1], gate_up->nb[2], 0); + cb(cur, "ffn_moe_gate", il); + up = ggml_view_3d(ctx0, gate_up, n_ff, gate_up->ne[1], gate_up->ne[2], gate_up->nb[1], gate_up->nb[2], n_ff * gate_up->nb[0]); + cb(up, "ffn_moe_up", il); + } } else { // separate gate and up path up = build_lora_mm_id(up_exps, cur, ids, mm_ids, cached); // [n_ff, n_expert_used, n_tokens] @@ -2637,15 +2718,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( { // situ(gate, up) = beta*tanh(gate/beta)*sigmoid(gate) * lb*tanh(up/lb) GGML_ASSERT(has_gate); - const float beta = hparams.situ_beta; - const float lb = hparams.situ_linear_beta; - - ggml_tensor * act = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/beta)), beta); - act = ggml_mul(ctx0, act, ggml_sigmoid(ctx0, cur)); - if (lb > 0.0f) { - up = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, up, 1.0f/lb)), lb); - } - cur = ggml_mul(ctx0, act, up); + cur = ggml_situ(ctx0, cur, up, hparams.situ_beta, hparams.situ_linear_beta); cb(cur, "ffn_moe_situ", il); } break; case LLM_FFN_GELU: @@ -2743,6 +2816,13 @@ ggml_tensor * llm_graph_context::build_moe_ffn( // the large-add-nodes issue for uniform arches; for Puzzle the per-layer // value is correct). ref: https://github.com/ggml-org/llama.cpp/pull/14753 const uint32_t n_expert_used_il = hparams.n_expert_used(il); + if ((arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) && + hparams.n_shortconv_l_cache == 4 && ubatch.n_seq_tokens <= 8 && n_tokens <= 8 && + n_expert_used_il > 1 && ggml_is_contiguous(experts) && + !getenv("GGML_INKLING_NO_FUSE") && !getenv("GGML_VK_DISABLE_S19_CONV_SUM")) { + cb(experts, "ffn_moe_out", il); + return experts; + } for (uint32_t i = 0; i < n_expert_used_il; ++i) { cur_experts[i] = ggml_view_2d(ctx0, experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1]); @@ -3148,7 +3228,10 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * v_mla, int64_t n_kv_max, float kq_scale, - int il) const { + int il, + ggml_tensor * rel_table, + ggml_tensor * rel_pos_pack, + int32_t rel_extent) const { const bool v_trans = v->nb[1] > v->nb[2]; // split the batch into streams if needed @@ -3193,6 +3276,9 @@ ggml_tensor * llm_graph_context::build_attn_mha( res->add_fused_node({kv_rows ? LLM_FUSED_OP_FLASH_ATTN_KV_ROWS : LLM_FUSED_OP_FLASH_ATTN, cur, il}); ggml_flash_attn_ext_add_sinks(cur, sinks); + if (rel_table != nullptr) { + ggml_flash_attn_ext_add_banded_rel_bias(cur, rel_table, rel_pos_pack, rel_extent); + } GGML_ASSERT(n_kv_max >= 0 && n_kv_max <= INT32_MAX); ggml_flash_attn_ext_set_n_kv_max(cur, static_cast(n_kv_max)); ggml_prec_set_acc(cur, GGML_PREC_F32); @@ -3725,7 +3811,10 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * sinks, ggml_tensor * v_mla, float kq_scale, - int il) { + int il, + ggml_tensor * rel_table = nullptr, + ggml_tensor * rel_pos_pack = nullptr, + int32_t rel_extent = 0) { ggml_context * ctx0 = gctx.ctx0; ggml_cgraph * gf = gctx.gf; @@ -3758,14 +3847,6 @@ static ggml_tensor * build_attn_iswa_impl( // by doing so, the number of splits in the graph is reduced ggml_build_forward_expand(gf, q_cur); - if (k_cur) { - ggml_build_forward_expand(gf, k_cur); - } - - if (v_cur) { - ggml_build_forward_expand(gf, v_cur); - } - // whole seq fits into batch in training mode const bool use_kv_cur = cparams.training && k_cur && v_cur; if (use_kv_cur) { @@ -3774,24 +3855,27 @@ static ggml_tensor * build_attn_iswa_impl( const bool store_kv = !use_kv_cur || hparams.n_layer_kv_from_start >= 0; - // optionally store to KV cache - if (store_kv && k_cur) { - const auto & k_idxs = is_swa ? inp->get_k_idxs_swa() : inp->get_k_idxs(); - - ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); + if (k_cur) { + ggml_build_forward_expand(gf, k_cur); + if (store_kv) { + const auto & k_idxs = is_swa ? inp->get_k_idxs_swa() : inp->get_k_idxs(); + ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); + } } - if (store_kv && v_cur) { - const auto & v_idxs = is_swa ? inp->get_v_idxs_swa() : inp->get_v_idxs(); - - ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); + if (v_cur) { + ggml_build_forward_expand(gf, v_cur); + if (store_kv) { + const auto & v_idxs = is_swa ? inp->get_v_idxs_swa() : inp->get_v_idxs(); + ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); + } } ggml_tensor * q = q_cur; ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); + ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il, rel_table, rel_pos_pack, rel_extent); cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il); gctx.cb(cur, "kqv_out", il); @@ -4188,6 +4272,8 @@ static std::unique_ptr build_rs_inp_impl( inp->head = mctx_cur->get_head(); inp->rs_z = mctx_cur->get_rs_z(); + inp->gen_identity = llm_graph_input_rs::gen_compute_identity(mctx_cur, n_seqs, cparams.n_rs_seq); + inp->direct_scopy = llm_graph_input_rs::compute_direct_scopy(mctx_cur, ubatch, cparams); inp->has_rep = mctx_cur->get_rs_replay(); if (inp->has_rep) { @@ -4233,6 +4319,17 @@ ggml_tensor * llm_graph_context::build_rs( const llm_graph_get_rows_fn & get_state_rows) const { const auto * kv_state = inp->mctx; + // gen (GGML_GEN_GDN_INPLACE): when every state is read from its own cell, view the cache rows instead of + // gathering them (same values); the backend can then also update them in place + if (inp->gen_identity == 1 && !get_state_rows && cparams.n_rs_seq == 0 && + (int64_t) kv_state->get_n_rs() == (int64_t) n_seqs) { + ggml_tensor * states = ggml_reshape_2d(ctx0, s, state_size, s->ne[1]); + const int32_t rs_zero = kv_state->get_rs_z(); + ggml_tensor * state_zero = ggml_view_1d(ctx0, states, state_size*(rs_zero >= 0), rs_zero*states->nb[1]*(rs_zero >= 0)); + ggml_build_forward_expand(gf, ggml_scale_inplace(ctx0, state_zero, 0)); + return ggml_view_2d(ctx0, states, state_size, n_seqs, states->nb[1], (size_t) kv_state->get_head()*states->nb[1]); + } + // a custom getter reads the states of the ubatch straight from the cache, so the gather skips the first // state: it still holds the n_rs - n_seqs extra states and copies no state of a single sequence ubatch ggml_tensor * state_copy = get_state_rows ? inp->s_copy_tail : inp->s_copy; @@ -4435,13 +4532,32 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur, extent, extent_swa); - inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_base()->get_n_kv(), ubatch.n_tokens); - ggml_set_input(inp->self_rel_pos); - ggml_set_name(inp->self_rel_pos, "attn_inp_rel_pos"); + const bool use_rel_pack = cparams.flash_attn && !getenv("GGML_INKLING_LEGACY_KQB") && !getenv("GGML_INKLING_NO_FUSE"); + if (use_rel_pack) { + const uint32_t n_kv_b = attn_ctx->get_base()->get_n_kv(); + const uint32_t n_strm_b = (uint32_t) inp->inp_attn->self_attn_mask.raw->ne[3]; + inp->n_stream_rel = n_strm_b; + const int64_t pack_b = (int64_t) n_strm_b * n_kv_b + ubatch.n_tokens + (int64_t) n_strm_b * ((n_kv_b + 63) / 64) * 2; + inp->self_rel_pos_pack = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, pack_b); + ggml_set_input(inp->self_rel_pos_pack); + ggml_set_name(inp->self_rel_pos_pack, "attn_inp_rel_pos_pack"); + + const uint32_t n_kv_s = attn_ctx->get_swa()->get_n_kv(); + const uint32_t n_strm_s = (uint32_t) inp->inp_attn->self_attn_mask_swa.raw->ne[3]; + inp->n_stream_rel_swa = n_strm_s; + const int64_t pack_s = (int64_t) n_strm_s * n_kv_s + ubatch.n_tokens + (int64_t) n_strm_s * ((n_kv_s + 63) / 64) * 2; + inp->self_rel_pos_pack_swa = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, pack_s); + ggml_set_input(inp->self_rel_pos_pack_swa); + ggml_set_name(inp->self_rel_pos_pack_swa, "attn_inp_rel_pos_pack_swa"); + } else { + inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_base()->get_n_kv(), ubatch.n_tokens); + ggml_set_input(inp->self_rel_pos); + ggml_set_name(inp->self_rel_pos, "attn_inp_rel_pos"); - inp->self_rel_pos_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_swa()->get_n_kv(), ubatch.n_tokens); - ggml_set_input(inp->self_rel_pos_swa); - ggml_set_name(inp->self_rel_pos_swa, "attn_inp_rel_pos_swa"); + inp->self_rel_pos_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_swa()->get_n_kv(), ubatch.n_tokens); + ggml_set_input(inp->self_rel_pos_swa); + ggml_set_name(inp->self_rel_pos_swa, "attn_inp_rel_pos_swa"); + } return (llm_graph_input_mem_hybrid_iswa_rel *) res->add_input(std::move(inp)); } @@ -4457,7 +4573,11 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * kq_b, ggml_tensor * sinks, float kq_scale, - int il) const { + int il, + int64_t i_row, + ggml_tensor * rel_table, + ggml_tensor * rel_pos_pack, + int32_t rel_extent) const { const bool is_swa = hparams.is_swa(il); auto * inp_attn = inp->get_attn(); @@ -4470,12 +4590,33 @@ ggml_tensor * llm_graph_context::build_attn( // a mask per head, in the dense layout of the input mask, which flash attention takes in F16 ggml_tensor * kq_mask = attn_mask.raw; - if (kq_mask->type != GGML_TYPE_F32) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + if (rel_table != nullptr) { + GGML_ASSERT(cparams.flash_attn && kq_b == nullptr && rel_pos_pack != nullptr); + if (kq_mask && kq_mask->type != GGML_TYPE_F16) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + } + return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, kq_mask, nullptr, sinks, nullptr, kq_scale, il, rel_table, rel_pos_pack, rel_extent); } - kq_mask = ggml_add(ctx0, kq_b, kq_mask); - if (cparams.flash_attn) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + if (cparams.flash_attn && kq_b && kq_b->op == GGML_OP_INKLING_FUSED && + kq_b->op_params[0] == 2 && kq_mask && kq_mask->type == GGML_TYPE_F16 && + ggml_is_contiguous(kq_mask) && kq_mask->ne[0] == kq_b->ne[0] && + !getenv("GGML_INKLING_NO_F16_KQB")) { + kq_mask = ggml_inkling_rel_gather_f16(ctx0, kq_b, kq_mask, (int32_t) i_row); + } else { + if (kq_b->ne[1] != kq_mask->ne[1]) { + ggml_tensor *& dev = inp->self_kq_mask_dev[is_swa]; + if (!dev) { + dev = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + } + kq_mask = ggml_view_4d(ctx0, dev, dev->ne[0], kq_b->ne[1], dev->ne[2], dev->ne[3], + dev->nb[1], dev->nb[2], dev->nb[3], i_row*dev->nb[1]); + } else if (kq_mask->type != GGML_TYPE_F32) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + } + kq_mask = ggml_add(ctx0, kq_b, kq_mask); + if (cparams.flash_attn) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + } } cb(kq_mask, "kq_mask_rel_pos", il); diff --git a/src/llama-graph.h b/src/llama-graph.h index ff155f14d2f6..5b5e0b631a0e 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -341,6 +341,14 @@ class llm_graph_input_rs : public llm_graph_input_i { // used in view offsets, need to match for valid graph reuse uint32_t head; int32_t rs_z; + + // gen (GGML_GEN_GDN_INPLACE): 1 when every state of the ubatch is read from its own cell (identity copy), + // so build_rs can view the cache instead of gathering; -1 when the feature is off + int gen_identity = -1; + static int gen_compute_identity(const llama_memory_recurrent_context * mctx, int64_t n_seqs, uint32_t n_rs_seq); + + bool direct_scopy = false; + static bool compute_direct_scopy(const llama_memory_recurrent_context * mctx, const llama_ubatch & ubatch, const llama_cparams & cparams); }; class llm_graph_input_cross_embd : public llm_graph_input_i { @@ -817,8 +825,16 @@ class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { llm_graph_input_rs * get_recr() const { return inp_rs.get(); } // distance from the token to the cell, extent for the empty, future and more distant cells - ggml_tensor * self_rel_pos = nullptr; // I32 [n_kv, n_batch] - ggml_tensor * self_rel_pos_swa = nullptr; // I32 [n_kv_swa, n_batch] + ggml_tensor * self_rel_pos = nullptr; // I32 [n_kv, n_batch] + ggml_tensor * self_rel_pos_swa = nullptr; // I32 [n_kv_swa, n_batch] + ggml_tensor * self_rel_pos_pack = nullptr; // I32 [n_stream*n_kv + n_tokens + n_stream*ceil(n_kv/64)*2] + ggml_tensor * self_rel_pos_pack_swa = nullptr; // I32 [n_stream*n_kv_swa + n_tokens + n_stream*ceil(n_kv_swa/64)*2] + uint32_t n_stream_rel = 1; + uint32_t n_stream_rel_swa = 1; + + // [base, swa] device copies, made once per graph + ggml_tensor * self_rel_pos_dev[2] = { nullptr, nullptr }; + ggml_tensor * self_kq_mask_dev[2] = { nullptr, nullptr }; const uint32_t extent; const uint32_t extent_swa; @@ -1345,11 +1361,14 @@ struct llm_graph_context { ggml_tensor * kq_b, ggml_tensor * kq_mask, ggml_tensor * kv_rows, // [n_kv, n_stream], k and v are shared by the streams - ggml_tensor * sinks, // [n_head_q] + ggml_tensor * sinks, // [n_head_q] or [n_head_q, n_tokens] ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] int64_t n_kv_max, float kq_scale, - int il) const; + int il, + ggml_tensor * rel_table = nullptr, + ggml_tensor * rel_pos_pack = nullptr, + int32_t rel_extent = 0) const; llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; @@ -1556,10 +1575,14 @@ struct llm_graph_context { ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] - ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] - ggml_tensor * sinks, // [n_head_q] + ggml_tensor * kq_b, // [n_kv, n_rows, n_head_q, n_stream] + ggml_tensor * sinks, // [n_head_q] or [n_head_q, n_tokens] float kq_scale, - int il) const; + int il, + int64_t i_row = 0, // first mask row of q_cur and kq_b + ggml_tensor * rel_table = nullptr, + ggml_tensor * rel_pos_pack = nullptr, + int32_t rel_extent = 0) const; // // pooling diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index bb546f7cdec8..93635b5220cf 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2010,7 +2010,8 @@ bool llama_kv_cache::has_cell_ext() const { void llama_kv_cache::set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const { GGML_ASSERT(dst->type == GGML_TYPE_I32); const int64_t n_kv = dst->ne[0]; - std::vector data(n_kv * ubatch->n_tokens); + rel_pos_buf.resize((size_t)(n_kv * ubatch->n_tokens)); + auto & data = rel_pos_buf; for (uint32_t i = 0; i < ubatch->n_tokens; ++i) { const auto & cells = v_cells.at(seq_to_stream.at(ubatch->seq_id[i][0])); for (int64_t j = 0; j < n_kv; ++j) { @@ -2021,6 +2022,64 @@ void llama_kv_cache::set_input_relative_pos(ggml_tensor * dst, const llama_ubatc ggml_backend_tensor_set(dst, data.data(), 0, ggml_nbytes(dst)); } +void llama_kv_cache::set_input_rel_pos_pack(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t n_kv, uint32_t n_stream_ub) const { + GGML_ASSERT(dst->type == GGML_TYPE_I32); + const uint32_t n_tokens = ubatch->n_tokens; + GGML_ASSERT(n_stream_ub > 0 && n_tokens % n_stream_ub == 0); + const uint32_t n_tps = n_tokens / n_stream_ub; + const uint32_t n_tiles64 = (n_kv + 63u) / 64u; + const size_t total_i32 = (size_t)n_stream_ub * n_kv + n_tokens + (size_t)n_stream_ub * n_tiles64 * 2u; + GGML_ASSERT((size_t)dst->ne[0] == total_i32); + + const bool direct_host = dst->buffer && ggml_backend_buffer_is_host(dst->buffer); + int32_t * out = nullptr; + if (direct_host) { + out = (int32_t *)dst->data; + } else { + rel_pos_buf.resize(total_i32); + out = rel_pos_buf.data(); + } + int32_t * cell_pos = out; + int32_t * q_pos = out + (size_t)n_stream_ub * n_kv; + int32_t * t_minmax = q_pos + n_tokens; + + constexpr int32_t POS_EMPTY_CELL = -1073741824; + constexpr int32_t POS_INF_MIN = 1073741824; + + for (uint32_t s = 0; s < n_stream_ub; ++s) { + const uint32_t strm = seq_to_stream.at(ubatch->seq_id[s * n_tps][0]); + const auto & cells = v_cells.at(strm); + int32_t * cp_s = cell_pos + (size_t)s * n_kv; + int32_t * tm_s = t_minmax + (size_t)s * n_tiles64 * 2u; + for (uint32_t b = 0; b < n_tiles64; ++b) { + const uint32_t j0 = b * 64u; + const uint32_t j1 = std::min(n_kv, j0 + 64u); + int32_t bmin = POS_INF_MIN; + int32_t bmax = POS_EMPTY_CELL; + for (uint32_t j = j0; j < j1; ++j) { + if (cells.is_empty(j)) { + cp_s[j] = POS_EMPTY_CELL; + } else { + const int32_t p = (int32_t)cells.pos_get(j); + cp_s[j] = p; + if (p < bmin) bmin = p; + if (p > bmax) bmax = p; + } + } + tm_s[b * 2u + 0u] = bmin; + tm_s[b * 2u + 1u] = bmax; + } + for (uint32_t ii = 0; ii < n_tps; ++ii) { + const uint32_t i = s * n_tps + ii; + GGML_ASSERT(seq_to_stream.at(ubatch->seq_id[i][0]) == strm); + q_pos[i] = (int32_t)ubatch->pos[i]; + } + } + if (!direct_host) { + ggml_backend_tensor_set(dst, out, 0, total_i32 * sizeof(int32_t)); + } +} + void llama_kv_cache::get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const { const uint32_t n_tokens = ubatch.n_tokens; @@ -3052,6 +3111,10 @@ uint32_t llama_kv_cache_context::get_n_kv() const { return n_kv; } +uint32_t llama_kv_cache_context::get_size() const { + return kv->get_size(); +} + uint32_t llama_kv_cache_context::get_n_kv_rows() const { return n_kv_rows; } @@ -3128,6 +3191,10 @@ void llama_kv_cache_context::set_input_relative_pos(ggml_tensor * dst, const lla kv->set_input_relative_pos(dst, ubatch, extent); } +void llama_kv_cache_context::set_input_rel_pos_pack(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t n_stream_ub) const { + kv->set_input_rel_pos_pack(dst, ubatch, (uint32_t)n_kv, n_stream_ub); +} + void llama_kv_cache_context::get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const { kv->get_prev_tokens(ubatch, n, res); } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 1b40f6fc41d5..c288f6e99125 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -250,6 +250,8 @@ class llama_kv_cache : public llama_memory_i { void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; + void set_input_rel_pos_pack(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t n_kv, uint32_t n_stream_ub) const; + mutable std::vector rel_pos_buf; // true if llama_kv_cell_ext holds information that has to survive a state save/restore bool has_cell_ext() const; @@ -419,6 +421,7 @@ class llama_kv_cache_context : public llama_memory_context_i { uint32_t get_n_kv() const; uint32_t get_n_kv_rows() const; + uint32_t get_size() const; ggml_type type_k() const; ggml_type type_v() const; @@ -455,6 +458,7 @@ class llama_kv_cache_context : public llama_memory_context_i { void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; + void set_input_rel_pos_pack(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t n_stream_ub) const; // see llama_kv_cache::get_prev_tokens() void get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const; diff --git a/src/llama-memory-hybrid-iswa.cpp b/src/llama-memory-hybrid-iswa.cpp index 569a09ee2192..5e6779a69a5c 100644 --- a/src/llama-memory-hybrid-iswa.cpp +++ b/src/llama-memory-hybrid-iswa.cpp @@ -8,6 +8,12 @@ // llama_memory_hybrid_iswa // +static thread_local bool g_s23_single_slot_tree_swa = false; +extern "C" LLAMA_API void llama_s23_set_single_slot_tree_swa(bool v); +extern "C" LLAMA_API void llama_s23_set_single_slot_tree_swa(bool v) { + g_s23_single_slot_tree_swa = v; +} + llama_memory_hybrid_iswa::llama_memory_hybrid_iswa( const llama_model & model, bool no_alloc, @@ -42,7 +48,10 @@ llama_memory_hybrid_iswa::llama_memory_hybrid_iswa( unified, kv_size, n_seq_max, - n_ubatch, + (g_s23_single_slot_tree_swa && unified && n_seq_max == 2 && !swa_full && + model.hparams.n_swa > 0 && n_ubatch > model.hparams.n_swa) + ? (n_ubatch - model.hparams.n_swa) + : n_ubatch, nullptr, filter_attn == nullptr ? [&](int32_t il) { return !hparams.is_recr(il); } @@ -157,6 +166,22 @@ bool llama_memory_hybrid_iswa::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_p } void llama_memory_hybrid_iswa::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) { + if (p0 >= 0) { + mem_attn->seq_rm(seq_id_dst, p0, -1); + mem_attn->seq_cp(seq_id_src, seq_id_dst, p0, p1); + mem_recr->seq_cp(seq_id_src, seq_id_dst, p0, p1); + return; + } + if (p0 < 0 && hparams.n_swa > 0 && mem_attn->get_swa() != nullptr) { + const llama_pos pos_max = mem_attn->get_swa()->seq_pos_max(seq_id_src); + if (pos_max > (llama_pos) hparams.n_swa + 4) { + const llama_pos swa_p0 = pos_max - (llama_pos) hparams.n_swa - 4; + mem_attn->get_base()->seq_cp(seq_id_src, seq_id_dst, p0, p1); + mem_attn->get_swa()->seq_cp(seq_id_src, seq_id_dst, swa_p0, p1); + mem_recr->seq_cp(seq_id_src, seq_id_dst, p0, p1); + return; + } + } mem_attn->seq_cp(seq_id_src, seq_id_dst, p0, p1); mem_recr->seq_cp(seq_id_src, seq_id_dst, p0, p1); } diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index bab6276f65d2..c65a5cfec477 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -336,6 +336,11 @@ void llama_memory_recurrent::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id cell_src.seq_id.insert(seq_id_dst); tail_dst.tail = tail_src.tail; } + if (n_rs_seq > 0 && + seq_id_src >= 0 && (size_t) seq_id_src < rs_idx.size() && + seq_id_dst >= 0 && (size_t) seq_id_dst < rs_idx.size()) { + rs_idx[seq_id_dst] = rs_idx[seq_id_src]; + } } } @@ -1516,3 +1521,52 @@ int32_t llama_memory_recurrent_context::s_copy(int i) const { } return (int32_t)(idx * mem->size) + src0; } + +int32_t llama_memory_recurrent_context::peek_s_copy(int i) const { + if (is_full) { + return i; + } + const uint32_t cell_idx = (uint32_t) i + mem->head; + const int32_t src0 = mem->cells[cell_idx].src0; + + if (mem->n_rs_seq == 0) { + return src0; + } + + uint32_t idx = 0; + if (!mem->cells[cell_idx].seq_id.empty()) { + const llama_seq_id seq = *mem->cells[cell_idx].seq_id.begin(); + if (seq >= 0 && (size_t) seq < mem->rs_idx.size()) { + idx = mem->rs_idx[seq]; + } + } + return (int32_t)(idx * mem->size) + src0; +} + +bool llama_memory_recurrent_context::can_direct_scopy(uint32_t n_seqs, uint32_t kw) const { + if (is_full || n_seqs == 0 || get_n_rs() != n_seqs) { + return false; + } + const uint32_t head = get_head(); + const uint32_t size = get_size(); + if (head + n_seqs > size) { + return false; + } + for (uint32_t i = 0; i < n_seqs; ++i) { + const int32_t src_i = peek_s_copy((int) i); + if (src_i < 0) { + return false; + } + for (uint32_t j = 0; j < n_seqs; ++j) { + if (i == j) { + continue; + } + for (uint32_t slot = 0; slot < kw; ++slot) { + if (src_i == (int32_t)(slot * size + head + j)) { + return false; + } + } + } + } + return true; +} diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index 5efe9c3b49ce..e61210c1715a 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -201,6 +201,8 @@ class llama_memory_recurrent_context : public llama_memory_context_i { ggml_tensor * get_spgb_l(int32_t il) const; int32_t s_copy(int i) const; + int32_t peek_s_copy(int i) const; + bool can_direct_scopy(uint32_t n_seqs, uint32_t kw) const; bool get_rs_replay() const; uint32_t get_rs_rep(int i) const; // pending tokens replayed by ubatch seq i diff --git a/src/llama-mmap.cpp b/src/llama-mmap.cpp index 02e4ede7c4d6..c5416e89676e 100644 --- a/src/llama-mmap.cpp +++ b/src/llama-mmap.cpp @@ -402,14 +402,14 @@ struct llama_file::impl { #else impl(const char * fname, const char * mode, [[maybe_unused]] const bool use_direct_io = false) : fname(fname) { #ifdef __linux__ - // Try unbuffered I/O for read only if (use_direct_io && std::strcmp(mode, "rb") == 0) { + drop_page_cache = true; if (init_fd()) { LLAMA_LOG_INFO("%s: file '%s' opened with direct I/O (alignment: %zu bytes)\n", __func__, fname, alignment); return; } - LLAMA_LOG_WARN("Failed to open file '%s' with unbuffered I/O: %s. Falling back to buffered I/O\n", + LLAMA_LOG_WARN("Failed to open file '%s' with unbuffered I/O: %s. Falling back to buffered I/O + POSIX_FADV_DONTNEED\n", fname, strerror(errno)); } #endif @@ -418,14 +418,44 @@ struct llama_file::impl { #ifdef __linux__ bool init_fd() { - fd = open(fname.c_str(), O_RDONLY | O_DIRECT); + fd = open(fname.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC); if (fd != -1) { struct stat file_stats{}; - fstat(fd, &file_stats); + if (fstat(fd, &file_stats) != 0) { + close(fd); + fd = -1; + return false; + } + + size = (size_t) file_stats.st_size; + const long page_sz = sysconf(_SC_PAGESIZE); + size_t dio_mem_align = 4096; + size_t dio_off_align = 4096; +#if defined(STATX_DIOALIGN) && defined(AT_EMPTY_PATH) + struct statx stx{}; + if (statx(fd, "", AT_EMPTY_PATH, STATX_DIOALIGN, &stx) == 0 && (stx.stx_mask & STATX_DIOALIGN)) { + if (stx.stx_dio_mem_align > 0) { dio_mem_align = stx.stx_dio_mem_align; } + if (stx.stx_dio_offset_align > 0) { dio_off_align = stx.stx_dio_offset_align; } + } +#endif + alignment = std::max({ + (size_t) file_stats.st_blksize, + page_sz > 0 ? (size_t) page_sz : (size_t) 4096, + dio_mem_align, + dio_off_align, + (size_t) 4096 + }); + if ((alignment & (alignment - 1)) != 0) { + size_t p2 = 4096; + while (p2 < alignment) { + p2 <<= 1; + } + alignment = p2; + } - size = file_stats.st_size; - alignment = file_stats.st_blksize; + // Evict any header/readahead pages cached earlier by gguf_init_from_file or prior runs + (void) posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); off_t ret = lseek(fd, 0, SEEK_SET); if (ret == -1) { @@ -435,8 +465,53 @@ struct llama_file::impl { } return false; } + + void read_tail_nocache(size_t file_off, void * dst, size_t len) { + if (len == 0) { + return; + } + int tfd = open(fname.c_str(), O_RDONLY | O_CLOEXEC); + if (tfd == -1) { + throw std::runtime_error(format("failed to open tail fd for %s: %s", fname.c_str(), strerror(errno))); + } + size_t done = 0; + while (done < len) { + ssize_t r = ::pread(tfd, reinterpret_cast(dst) + done, len - done, (off_t) (file_off + done)); + if (r == -1) { + if (errno == EINTR) { + continue; + } + int saved = errno; + close(tfd); + throw std::runtime_error(format("tail pread error: %s", strerror(saved))); + } + if (r == 0) { + close(tfd); + throw std::runtime_error("unexpectedly reached end of file in tail pread"); + } + done += (size_t) r; + } + (void) posix_fadvise(tfd, (off_t) (file_off & ~(alignment - 1)), 0, POSIX_FADV_DONTNEED); + close(tfd); + } #endif + void * ensure_dio_buf(size_t need) { + if (dio_buf && dio_buf_cap >= need) { + return dio_buf; + } + free(dio_buf); + dio_buf = nullptr; + dio_buf_cap = 0; + const size_t alloc_sz = (need + alignment - 1) & ~(alignment - 1); + if (posix_memalign(&dio_buf, alignment, alloc_sz) != 0) { + dio_buf = nullptr; + return nullptr; + } + dio_buf_cap = alloc_sz; + return dio_buf; + } + void init_fp(const char * mode) { fp = ggml_fopen(fname.c_str(), mode); if (fp == NULL) { @@ -490,96 +565,170 @@ struct llama_file::impl { errno = 0; if (fd == -1) { const size_t read_offset = tell(); + if (read_offset > size) { + throw std::runtime_error("unexpectedly reached end of file"); + } const size_t to_read = std::min(len, size - read_offset); - std::size_t ret = std::fread(ptr, to_read, 1, fp); - if (ferror(fp)) { - throw std::runtime_error(format("read error: %s", strerror(errno))); + if (to_read > 0) { + std::size_t ret = std::fread(ptr, to_read, 1, fp); + if (ferror(fp)) { + throw std::runtime_error(format("read error: %s", strerror(errno))); + } + if (ret != 1) { + throw std::runtime_error("unexpectedly reached end of file"); + } +#ifdef __linux__ + if (drop_page_cache) { + const long ps = sysconf(_SC_PAGESIZE); + const size_t page_sz = ps > 0 ? (size_t) ps : (size_t) 4096; + const size_t drop_beg = read_offset & ~(page_sz - 1); + const size_t drop_end = (read_offset + to_read) & ~(page_sz - 1); + if (drop_end > drop_beg) { + (void) posix_fadvise(::fileno(fp), (off_t) drop_beg, (off_t) (drop_end - drop_beg), POSIX_FADV_DONTNEED); + } + } +#endif } - if (to_read > 0 && ret != 1) { - throw std::runtime_error("unexpectedly reached end of file"); + if (len > to_read) { + std::memset(reinterpret_cast(ptr) + to_read, 0, len - to_read); } } else { - size_t bytes_read = 0; - while (bytes_read < len) { - const size_t to_read = len - bytes_read; - ssize_t ret = ::read(fd, reinterpret_cast(ptr) + bytes_read, to_read); + const size_t start_offset = tell(); + if (start_offset > size) { + throw std::runtime_error("unexpectedly reached end of file"); + } + const size_t avail = std::min(len, size - start_offset); + if (avail == 0) { + std::memset(ptr, 0, len); + return; + } + + const bool is_aligned = + ((start_offset & (alignment - 1)) == 0) && + ((len & (alignment - 1)) == 0) && + ((reinterpret_cast(ptr) & (alignment - 1)) == 0); + + if (!is_aligned && !in_aligned_bounce) { + read_aligned_chunk(ptr, avail); + if (len > avail) { + std::memset(reinterpret_cast(ptr) + avail, 0, len - avail); + } + return; + } + + const size_t aligned_eof = size & ~(alignment - 1); + const size_t req_end = start_offset + len; + const size_t dio_end = std::min(req_end, aligned_eof); + const size_t max_dio_io = ((size_t) 1 << 30) & ~(alignment - 1); + + size_t cur_off = start_offset; + while (cur_off < dio_end) { + const size_t to_read = std::min(dio_end - cur_off, max_dio_io); + char * dst_cur = reinterpret_cast(ptr) + (cur_off - start_offset); + ssize_t ret = ::pread(fd, dst_cur, to_read, (off_t) cur_off); if (ret == -1) { if (errno == EINTR) { continue; } + // EFAULT happens when ptr is a DRM GEM / vkMapMemory (VM_PFNMAP | VM_IO) buffer: + // bounce through anonymous posix_memalign dio_buf while keeping O_DIRECT fd alive! + if (errno == EFAULT && !in_aligned_bounce) { + seek(start_offset, SEEK_SET); + read_aligned_chunk(ptr, avail); + if (len > avail) { + std::memset(reinterpret_cast(ptr) + avail, 0, len - avail); + } + return; + } if (errno == EFAULT || errno == EINVAL || errno == EIO) { LLAMA_LOG_WARN("%s: file '%s' falling back to buffered I/O due to %s\n", __func__, fname.c_str(), strerror(errno)); - const size_t read_offset = tell(); close(fd); fd = -1; alignment = 1; + drop_page_cache = true; init_fp("rb"); - seek(read_offset, SEEK_SET); - read_raw_unsafe(static_cast(ptr) + bytes_read, to_read); + seek(start_offset, SEEK_SET); + read_raw_unsafe(ptr, len); return; } throw std::runtime_error(format("read error: %s", strerror(errno))); } if (ret == 0) { - off_t pos = lseek(fd, 0, SEEK_CUR); - if (pos != -1 && (size_t) pos == size) { - std::memset(reinterpret_cast(ptr) + bytes_read, 0, len - bytes_read); - return; - } throw std::runtime_error("unexpectedly reached end of file"); } + cur_off += (size_t) ret; + if ((ret & (ssize_t) (alignment - 1)) != 0) { + break; + } + } - bytes_read += (size_t) ret; +#ifdef __linux__ + if (start_offset + avail > cur_off) { + read_tail_nocache(cur_off, + reinterpret_cast(ptr) + (cur_off - start_offset), + (start_offset + avail) - cur_off); + } +#endif + if (len > avail) { + std::memset(reinterpret_cast(ptr) + avail, 0, len - avail); } + seek(start_offset + avail, SEEK_SET); } } void read_aligned_chunk(void * dest, size_t len) { - size_t offset = tell(); - off_t aligned_offset = offset & ~(alignment - 1); - off_t offset_from_alignment = offset - aligned_offset; - size_t bytes_to_read = (offset_from_alignment + len + alignment - 1) & ~(alignment - 1); + if (len == 0) { + return; + } + const size_t offset = tell(); + if (offset > size || len > size - offset) { + throw std::runtime_error("unexpectedly reached end of file"); + } + const size_t aligned_offset = offset & ~(alignment - 1); + const size_t offset_from_alignment = offset - aligned_offset; + const size_t bytes_to_read = (offset_from_alignment + len + alignment - 1) & ~(alignment - 1); - // stage through a bounded buffer, so that a large tensor is not held in memory twice while it loads + // Reuse a single bounded 64 MiB aligned anonymous buffer across calls (zero mmap/munmap churn) const size_t buffer_size = std::min(bytes_to_read, LLAMA_DIRECT_IO_BUFFER_SIZE); - - void * raw_buffer = nullptr; - int ret = posix_memalign(&raw_buffer, alignment, buffer_size); - if (ret != 0) { - LLAMA_LOG_WARN("%s: file '%s' falling back to buffered I/O due to %s\n", - __func__, fname.c_str(), strerror(ret)); + void * raw_buffer = ensure_dio_buf(buffer_size); + if (!raw_buffer) { + LLAMA_LOG_WARN("%s: file '%s' falling back to buffered I/O due to ENOMEM\n", + __func__, fname.c_str()); close(fd); fd = -1; alignment = 1; + drop_page_cache = true; init_fp("rb"); seek(offset, SEEK_SET); read_raw_unsafe(dest, len); return; } - struct aligned_buffer_deleter { - void operator()(void * p) const { free(p); } - }; - std::unique_ptr buffer(raw_buffer); - seek(aligned_offset, SEEK_SET); + in_aligned_bounce = true; size_t skip = offset_from_alignment; size_t copied = 0; - for (size_t done = 0; done < bytes_to_read; ) { - const size_t n = std::min(buffer_size, bytes_to_read - done); - read_raw_unsafe(buffer.get(), n); + try { + for (size_t done = 0; done < bytes_to_read; ) { + const size_t n = std::min(buffer_size, bytes_to_read - done); + read_raw_unsafe(raw_buffer, n); - const size_t count = std::min(n - skip, len - copied); - memcpy(reinterpret_cast(dest) + copied, reinterpret_cast(buffer.get()) + skip, count); + const size_t count = std::min(n - skip, len - copied); + memcpy(reinterpret_cast(dest) + copied, reinterpret_cast(raw_buffer) + skip, count); - copied += count; - skip = 0; - done += n; + copied += count; + skip = 0; + done += n; + } + } catch (...) { + in_aligned_bounce = false; + throw; } + in_aligned_bounce = false; seek(offset + len, SEEK_SET); } @@ -618,13 +767,29 @@ struct llama_file::impl { } ~impl() { + free(dio_buf); + dio_buf = nullptr; + dio_buf_cap = 0; if (fd != -1) { +#ifdef __linux__ + (void) posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); +#endif close(fd); } else if (fp && owns_fp) { +#ifdef __linux__ + if (drop_page_cache) { + std::fflush(fp); + (void) posix_fadvise(::fileno(fp), 0, 0, POSIX_FADV_DONTNEED); + } +#endif std::fclose(fp); } } - int fd = -1; + int fd = -1; + void * dio_buf = nullptr; + size_t dio_buf_cap = 0; + bool in_aligned_bounce = false; + bool drop_page_cache = false; std::string fname; #endif diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp index 808fb44d881f..ebc8c373c086 100644 --- a/src/llama-model-loader.cpp +++ b/src/llama-model-loader.cpp @@ -1,5 +1,7 @@ #include "llama-model-loader.h" +#include + #include "ggml-alloc.h" #include "ggml.h" #include "gguf.h" @@ -1208,6 +1210,19 @@ bool llama_model_loader::lazy_read::add(const std::string & name, const ggml_ten return true; } +static std::mutex g_gen_bf16_mutex; +static std::set g_gen_bf16_names; + +bool llama_gen_bf16_converted(const char * name) { + std::lock_guard lock(g_gen_bf16_mutex); + return g_gen_bf16_names.count(name) != 0; +} + +int64_t llama_gen_bf16_cast_above() { + static const int64_t v = getenv("GGML_GEN_BF16_CAST_ABOVE") ? atoll(getenv("GGML_GEN_BF16_CAST_ABOVE")) : 8; + return v; +} + struct ggml_tensor * llama_model_loader::create_tensor( const llama_hparams & hparams, const buft_list_t * buft_list_cpu, const buft_list_t * buft_list_input, const buft_list_t * buft_list_output, const buft_list_t * buft_list_layer, const LLM_TN_IMPL & tn, const std::initializer_list & ne, int flags) { @@ -1455,11 +1470,80 @@ struct ggml_tensor * llama_model_loader::create_tensor( GGML_ASSERT(ggml_nbytes(&t_meta) == ggml_nbytes(cur)); + // gen: GGML_GEN_BF16_EXACT=1 stores the F32 router / shared-expert gate / ssm_alpha / ssm_beta weights as + // BF16 when every value is exactly representable (low 16 bits zero), checked here per tensor from the file. + // The values are unchanged, so the matrix-vector product gives the same result with half the bytes. + bool gen_to_bf16 = false; + { + static const bool gen_bf16_exact = getenv("GGML_GEN_BF16_EXACT") != nullptr && atoi(getenv("GGML_GEN_BF16_EXACT")) != 0; + const std::string name = tn.str(); + auto ends_with = [&](const char * suf) { + const size_t n = strlen(suf); + return name.size() >= n && name.compare(name.size() - n, n, suf) == 0; + }; + if (gen_bf16_exact && !is_lazy && !(flags & TENSOR_DUPLICATED) && t_meta.type == GGML_TYPE_F32 && + t_meta.ne[0] % 2 == 0 && + (ends_with(".ffn_gate_inp.weight") || ends_with(".ffn_gate_inp_shexp.weight") || + ends_with(".ssm_alpha.weight") || ends_with(".ssm_beta.weight") || + ends_with(".ssm_beta_alpha.weight") || ends_with(".ssm_ba.weight"))) { + const auto & w = require_weight(name.c_str()); + std::vector vals(ggml_nelements(&t_meta)); + files.at(w.idx)->seek(w.offs, SEEK_SET); + files.at(w.idx)->read_raw(vals.data(), ggml_nbytes(&t_meta)); + bool exact = true; + for (uint32_t v : vals) { + if (v & 0xffffu) { + exact = false; + break; + } + } + if (exact) { + t_meta.type = GGML_TYPE_BF16; + t_meta.nb[0] = ggml_type_size(GGML_TYPE_BF16); + t_meta.nb[1] = ggml_row_size(GGML_TYPE_BF16, t_meta.ne[0]); + for (int dim = 2; dim < GGML_MAX_DIMS; dim++) { + t_meta.nb[dim] = t_meta.ne[dim-1]*t_meta.nb[dim-1]; + } + gen_to_bf16 = true; + } else { + LLAMA_LOG_WARN("%s: %s is not bf16-exact, kept as F32\n", __func__, name.c_str()); + } + } + } + ggml_backend_buffer_type_t buft = buft_for_tensor(&t_meta); if (buft == nullptr) { return nullptr; } + // Under mmap, only keep BF16 compaction when the target buffer type is NOT + // mmap-aliased directly from the file via buffer_from_host_ptr (e.g. Vulkan0). + if (gen_to_bf16 && use_mmap) { + ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft); + if (!dev) { + dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); + } + bool may_mmap_alias = false; + if (dev) { + ggml_backend_dev_props props; + ggml_backend_dev_get_props(dev, &props); + may_mmap_alias = props.caps.buffer_from_host_ptr && (buft == ggml_backend_dev_buffer_type(dev)); + } + if (may_mmap_alias) { + t_meta.type = GGML_TYPE_F32; + t_meta.nb[0] = ggml_type_size(GGML_TYPE_F32); + t_meta.nb[1] = ggml_row_size(GGML_TYPE_F32, t_meta.ne[0]); + for (int dim = 2; dim < GGML_MAX_DIMS; dim++) { + t_meta.nb[dim] = t_meta.ne[dim-1]*t_meta.nb[dim-1]; + } + gen_to_bf16 = false; + buft = buft_for_tensor(&t_meta); + if (buft == nullptr) { + return nullptr; + } + } + } + ggml_context * ctx = ctx_for_buft(buft); // if duplicated, check if the original tensor was allocated in the same buffer type context and avoid creating a new one @@ -1475,6 +1559,12 @@ struct ggml_tensor * llama_model_loader::create_tensor( struct ggml_tensor * tensor = ggml_dup_tensor(ctx, &t_meta); ggml_set_name(tensor, ggml_get_name(&t_meta)); + if (gen_to_bf16) { + gen_bf16_tensors.insert(ggml_get_name(tensor)); + std::lock_guard lock(g_gen_bf16_mutex); + g_gen_bf16_names.insert(ggml_get_name(tensor)); + } + if (duplicated) { size_data += ggml_nbytes(&t_meta); } else { @@ -1658,6 +1748,10 @@ bool llama_model_loader::load_all_data( } GGML_ASSERT(size_data != 0 && "call init_mappings() first"); + if (!gen_bf16_tensors.empty()) { + fprintf(stderr, "gen: %zu bf16-exact F32 weight tensors stored as BF16 (GGML_GEN_BF16_EXACT)\n", gen_bf16_tensors.size()); + } + std::vector>> validation_result; // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives. @@ -1676,44 +1770,63 @@ bool llama_model_loader::load_all_data( std::vector events; std::vector host_ptrs; size_t buffer_idx = 0; // buffer to use for async loads - ggml_backend_t upload_backend = [&](const char * func) -> ggml_backend_t { - if (use_mmap || check_tensors) { - return nullptr; - } - // When not using mmaped io use async uploads from pinned memory to GPU memory. - // First determine if the backend supports the necessary features for async uploads. - auto * buf = bufs.empty() ? nullptr : bufs[0]; + ggml_backend_buffer_type_t default_dev_buft = nullptr; + for (auto * buf : bufs) { if (!buf) { - LLAMA_LOG_DEBUG("%s: no buffer found for async uploads\n", func); - return nullptr; + continue; } - - auto * buft = ggml_backend_buffer_get_type(buf); - auto * dev = ggml_backend_buft_get_device(buft); - if (!dev) { - LLAMA_LOG_DEBUG("%s: no device found for buffer type %s for async uploads\n", func, - ggml_backend_buft_name(buft)); - return nullptr; + auto * buft = ggml_backend_buffer_get_type(buf); + auto * b_dev = ggml_backend_buft_get_device(buft); + if (b_dev && buft == ggml_backend_dev_buffer_type(b_dev)) { + default_dev_buft = buft; + break; } + } - if (buft != ggml_backend_dev_buffer_type(dev)) { - LLAMA_LOG_DEBUG("%s: buffer type %s is not the default buffer type for device %s for async uploads\n", func, - ggml_backend_buft_name(buft), ggml_backend_dev_name(dev)); + ggml_backend_t upload_backend = [&](const char * func) -> ggml_backend_t { + // Skip pinned-GPU-host-buffer (vkMapMemory / VM_PFNMAP) async staging when using mmap, check_tensors, + // or Direct I/O (alignment != 1: Linux O_DIRECT pin_user_pages rejects VM_PFNMAP VMAs with EFAULT). + if (use_mmap || check_tensors || alignment != 1) { return nullptr; } - - ggml_backend_dev_props props; - ggml_backend_dev_get_props(dev, &props); - if (!props.caps.async || !props.caps.host_buffer || !props.caps.events) { - LLAMA_LOG_DEBUG("%s: device %s does not support async, host buffers or events\n", func, - ggml_backend_dev_name(dev)); + // When not using mmaped io use async uploads from pinned memory to GPU memory. + // First determine if any buffer's backend supports the necessary features for async uploads. + if (bufs.empty()) { + LLAMA_LOG_DEBUG("%s: no buffer found for async uploads\n", func); return nullptr; } - auto * host_buft = ggml_backend_dev_host_buffer_type(dev); - if (!host_buft) { - LLAMA_LOG_DEBUG("%s: no host buffer type found for device %s\n", func, - ggml_backend_dev_name(dev)); + ggml_backend_dev_t dev = nullptr; + ggml_backend_buffer_type_t host_buft = nullptr; + for (auto * buf : bufs) { + if (!buf) { + continue; + } + auto * buft = ggml_backend_buffer_get_type(buf); + auto * b_dev = ggml_backend_buft_get_device(buft); + if (!b_dev || buft != ggml_backend_dev_buffer_type(b_dev)) { + continue; + } + ggml_backend_dev_props props; + ggml_backend_dev_get_props(b_dev, &props); + // On UMA iGPUs (e.g. Apple AGX), set_tensor_async is a synchronous CPU memcpy into unified memory; + // allocating 4 * 64 MiB of Vulkan_Host buffers is pure memory/memcpy overhead. + if (props.type == GGML_BACKEND_DEVICE_TYPE_IGPU) { + continue; + } + if (!props.caps.async || !props.caps.host_buffer || !props.caps.events) { + continue; + } + auto * h_buft = ggml_backend_dev_host_buffer_type(b_dev); + if (!h_buft) { + continue; + } + dev = b_dev; + host_buft = h_buft; + break; + } + if (!dev) { + LLAMA_LOG_DEBUG("%s: no device supporting async uploads found in model buffers\n", func); return nullptr; } @@ -1750,10 +1863,13 @@ bool llama_model_loader::load_all_data( return backend; }(__func__); + ggml_backend_buffer_type_t upload_buft = upload_backend + ? ggml_backend_dev_buffer_type(ggml_backend_get_device(upload_backend)) + : nullptr; if (upload_backend) { LLAMA_LOG_DEBUG("%s: using async uploads for device %s, buffer type %s, backend %s\n", __func__, ggml_backend_dev_name(ggml_backend_get_device(upload_backend)), - ggml_backend_buft_name(ggml_backend_buffer_get_type(bufs[0])), + ggml_backend_buft_name(upload_buft), ggml_backend_name(upload_backend)); } @@ -1793,6 +1909,26 @@ bool llama_model_loader::load_all_data( size_t n_size = ggml_nbytes(cur); + if (!gen_bf16_tensors.empty() && gen_bf16_tensors.count(ggml_get_name(cur))) { + // gen: the file holds F32; convert (exactly, see create_tensor) and upload as BF16 + const auto & file = files.at(weight->idx); + const int64_t n = ggml_nelements(cur); + std::vector f32(n); + std::vector bf16(n); + file->seek(weight->offs, SEEK_SET); + file->read_raw(f32.data(), n * sizeof(uint32_t)); + for (int64_t i = 0; i < n; i++) { + GGML_ASSERT((f32[i] & 0xffffu) == 0); + bf16[i] = (uint16_t) (f32[i] >> 16); + } + if (upload_backend) { + ggml_backend_synchronize(upload_backend); + } + ggml_backend_tensor_set(cur, bf16.data(), 0, n_size); + size_done += n * sizeof(uint32_t); + continue; + } + const bool from_mapping = use_mmap || lazy.has(cur); if (from_mapping) { @@ -1844,7 +1980,7 @@ bool llama_model_loader::load_all_data( } } else { // If upload_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU. - if (upload_backend) { + if (upload_backend && cur->buffer && ggml_backend_buffer_get_type(cur->buffer) == upload_buft) { size_t offset = weight->offs; alignment = file->read_alignment(); size_t aligned_offset = offset & ~(alignment - 1); @@ -1896,7 +2032,42 @@ bool llama_model_loader::load_all_data( ++buffer_idx; buffer_idx %= n_buffers; } + } else if (!check_tensors && default_dev_buft && cur->buffer && + ggml_backend_buffer_get_type(cur->buffer) == default_dev_buft && + n_size > LLAMA_DIRECT_IO_BUFFER_SIZE) { + // Stream large default-device tensors (e.g. Vulkan0 on UMA) in 64 MiB aligned O_DIRECT chunks + // instead of allocating a full-tensor multi-hundred-MiB bounce buffer. + const size_t align = file->read_alignment(); + const size_t aligned_offset = weight->offs & ~(align - 1); + const size_t pad_head = weight->offs - aligned_offset; + const size_t total_aligned = (pad_head + n_size + align - 1) & ~(align - 1); + const size_t chunk_cap = LLAMA_DIRECT_IO_BUFFER_SIZE; + const size_t alloc_need = chunk_cap + align - 1; + + const size_t cur_rb_size = read_buf ? ggml_backend_buffer_get_size(read_buf.get()) : 0; + if (!read_buf || cur_rb_size < alloc_need) { + read_buf.reset(); + read_buf.reset(ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), alloc_need)); + if (!read_buf) { + throw std::runtime_error(format("failed to allocate a %zu-byte staging buffer", alloc_need)); + } + } + uint8_t * read_dst = (uint8_t *) GGML_PAD((uintptr_t) ggml_backend_buffer_get_base(read_buf.get()), align); + file->seek(aligned_offset, SEEK_SET); + + size_t skip = pad_head; + size_t copied = 0; + for (size_t done = 0; done < total_aligned; ) { + const size_t n = std::min(chunk_cap, total_aligned - done); + file->read_raw_unsafe(read_dst, n); + const size_t count = std::min(n - skip, n_size - copied); + ggml_backend_tensor_set(cur, read_dst + skip, copied, count); + copied += count; + skip = 0; + done += n; + } } else { + // Repack buffers (e.g. Vulkan0_Repack) require full-tensor set_tensor(offset=0, size=n_size) // with direct IO read the aligned range around the tensor and use the data inside it, so no bounce buffer is needed const size_t align = file->read_alignment(); const size_t aligned_offset = weight->offs & ~(align - 1); diff --git a/src/llama-model-loader.h b/src/llama-model-loader.h index ed59079a4ead..01a862ba545a 100644 --- a/src/llama-model-loader.h +++ b/src/llama-model-loader.h @@ -27,6 +27,10 @@ enum llama_fver { const char * llama_file_version_name(llama_fver version); +// gen: names of F32 weights stored as BF16 by GGML_GEN_BF16_EXACT (filled at load, read during graph build) +bool llama_gen_bf16_converted(const char * name); +int64_t llama_gen_bf16_cast_above(); + struct llama_model_loader { // Holds information on a model weight struct llama_tensor_weight { @@ -222,6 +226,9 @@ struct llama_model_loader { const llama_tensor_weight & require_weight(const char * name) const; + // gen: F32 weights stored as BF16 because every value is exactly representable (GGML_GEN_BF16_EXACT=1) + std::set gen_bf16_tensors; + struct ggml_tensor * get_tensor_meta(const char * name) const; struct ggml_tensor * require_tensor_meta(const std::string & name) const; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 74abd222de58..237e18ab2e79 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -1371,7 +1371,7 @@ static buft_list_t make_cpu_buft_list(const std::vector & devices, } // GPU: split if LLAMA_SPLIT_MODE_ROW -> GPU -static buft_list_t make_gpu_buft_list(ggml_backend_dev_t dev, llama_split_mode split_mode, const float * tensor_split) { +static buft_list_t make_gpu_buft_list(ggml_backend_dev_t dev, llama_split_mode split_mode, const float * tensor_split, bool use_extra_bufts) { buft_list_t buft_list; // add the device split buffer type if requested and available @@ -1398,24 +1398,27 @@ static buft_list_t make_gpu_buft_list(ggml_backend_dev_t dev, llama_split_mode s } } - // add the device default buffer type - buft_list.emplace_back(dev, ggml_backend_dev_buffer_type(dev)); - - // add the device extra buffer type (if any) - ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev); - if (reg) { - auto ggml_backend_dev_get_extra_bufts_fn = (ggml_backend_dev_get_extra_bufts_t) - ggml_backend_reg_get_proc_address(reg, "ggml_backend_dev_get_extra_bufts"); - - if (ggml_backend_dev_get_extra_bufts_fn) { - ggml_backend_buffer_type_t * extra_bufts = ggml_backend_dev_get_extra_bufts_fn(dev); - while (extra_bufts && *extra_bufts) { - buft_list.emplace_back(dev, *extra_bufts); - ++extra_bufts; + // add the device extra buffer type (if any) before the default buffer type so + // select_weight_buft prefers repacked GPU layouts when supported + if (use_extra_bufts) { + ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev); + if (reg) { + auto ggml_backend_dev_get_extra_bufts_fn = (ggml_backend_dev_get_extra_bufts_t) + ggml_backend_reg_get_proc_address(reg, "ggml_backend_dev_get_extra_bufts"); + + if (ggml_backend_dev_get_extra_bufts_fn) { + ggml_backend_buffer_type_t * extra_bufts = ggml_backend_dev_get_extra_bufts_fn(dev); + while (extra_bufts && *extra_bufts) { + buft_list.emplace_back(dev, *extra_bufts); + ++extra_bufts; + } } } } + // add the device default buffer type + buft_list.emplace_back(dev, ggml_backend_dev_buffer_type(dev)); + return buft_list; } @@ -1855,7 +1858,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { // build a list of buffer types for the CPU and GPU devices pimpl->cpu_buft_list = make_cpu_buft_list(devices, params.use_extra_bufts, params.no_host); for (const auto & dev : devices) { - buft_list_t buft_list = make_gpu_buft_list(dev.dev, split_mode, tensor_split); + buft_list_t buft_list = make_gpu_buft_list(dev.dev, split_mode, tensor_split, params.use_extra_bufts); // add CPU buffer types as a fallback buft_list.insert(buft_list.end(), pimpl->cpu_buft_list.begin(), pimpl->cpu_buft_list.end()); pimpl->gpu_buft_list.emplace(dev.dev, std::move(buft_list)); @@ -2545,9 +2548,9 @@ void llama_model_base::load_tensors_hadamard() { } ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(weight->buffer); - // CPU extra buffer types (e.g. CPU_REPACK) only accept tensors they can repack + // Extra buffer types (e.g. CPU_REPACK, Vulkan_Repack) only accept tensors they can repack if (ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft)) { - if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) { + if (buft != ggml_backend_dev_buffer_type(dev)) { buft = ggml_backend_dev_buffer_type(dev); } } diff --git a/src/llama-model.h b/src/llama-model.h index e0273d7d106b..75839c63c05a 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -676,6 +676,14 @@ struct llama_layer { // gemma4 layer output scale, reused for talkie embedding skip scale struct ggml_tensor * out_scale = nullptr; + // S19_WAVE3: stacked FullAttn [attn_q_inp_norm; attn_k_inp_norm; attn_v_inp_norm] [n_embd, 3] + struct ggml_tensor * s19_attn_qkv_inp_norm = nullptr; + // Coalesced Q8_0 attention projections [wq | wqkv_gate | attn_rel (| wk | wv on SWA)] + struct ggml_tensor * s19_attn_in_proj_q8 = nullptr; + // Coalesced 3D [wk; wv] [n_embd, m_kv, 2] Q8_0 and [attn_k_conv_proj; attn_v_conv_proj] [n_embd, m_dyn, 2] + struct ggml_tensor * s19_attn_wk_wv_q8 = nullptr; + struct ggml_tensor * s19_attn_kv_conv_proj = nullptr; + // metis16 per-pass hyper-connection mixes, attention pass LoRA, expert route embeddings struct ggml_tensor * hc_attn_mix = nullptr; struct ggml_tensor * hc_attn_read = nullptr; @@ -961,6 +969,18 @@ struct llama_model { struct ggml_tensor * dspark_markov_ctx_mix = nullptr; // rnn markov head: f_rnn from target features struct ggml_tensor * dspark_markov_ctx_norm = nullptr; + // Series 19 (W1.2): Persistent GPU-resident f_rnn context ring ([n_embd, 64 * n_seq] F32) + mutable ggml_context_ptr dspark_ring_ctx; + mutable ggml_backend_buffer_ptr dspark_ring_buf; + mutable struct ggml_tensor * dspark_f_rnn_ring = nullptr; + mutable uint32_t dspark_ring_n_seq = 0; + + // Series 23 (B1): SLC-resident quantized dspark_markov_w2 ([rank, n_vocab_draft]) + mutable ggml_context_ptr dspark_w2_q_ctx; + mutable ggml_backend_buffer_ptr dspark_w2_q_buf; + mutable struct ggml_tensor * dspark_markov_w2_q = nullptr; + mutable bool dspark_markov_w2_ready = false; + // zaya1 struct ggml_tensor * res_scale_in = nullptr; struct ggml_tensor * res_scale_in_b = nullptr; @@ -1004,6 +1024,19 @@ struct llama_model { std::vector layers; + // S19_WAVE3: lazily materialized coalesced BF16/F32 weights for Inkling-2 looped-core & FullAttn norms + struct s19_loop_coalesced { + struct ggml_tensor * ctrl_down_qkv = nullptr; // [2*n_embd, rank, 3] + struct ggml_tensor * ctrl_up_qkv = nullptr; // [rank, 2*n_embd, 3] ([gain; forget]) + struct ggml_tensor * ctrl_down_ffn = nullptr; // [2*n_embd, rank] + struct ggml_tensor * ctrl_up_ffn = nullptr; // [rank, 2*n_embd] ([gain; forget]) + }; + mutable ggml_context_ptr s19_inkling_ctx; + mutable ggml_backend_buffer_ptr s19_inkling_buf; + mutable struct ggml_tensor * s19_pass_msg_query = nullptr; + mutable std::vector s19_loop_layers; + mutable bool s19_inkling_ready = false; + //Dense linear projections for SentenceTransformers models like embeddinggemma // For Sentence Transformers models structure see // https://sbert.net/docs/sentence_transformer/usage/custom_models.html#structure-of-sentence-transformer-models diff --git a/src/llama-sampler.cpp b/src/llama-sampler.cpp index d8cd441a5583..0321e488d870 100644 --- a/src/llama-sampler.cpp +++ b/src/llama-sampler.cpp @@ -2824,6 +2824,20 @@ struct llama_sampler * llama_sampler_init_grammar_lazy_patterns( return llama_sampler_init_grammar_impl(vocab, grammar_str, grammar_root, /* lazy= */ true, trigger_tokens, num_trigger_tokens, trigger_patterns, num_trigger_patterns); } +bool llama_sampler_grammar_is_dormant(const struct llama_sampler * smpl) { + if (!smpl) { + return true; + } + if (smpl->iface != &llama_sampler_grammar_i) { + return false; + } + const auto * ctx = (const llama_sampler_grammar *) smpl->ctx; + if (!ctx->grammar) { + return true; + } + return ctx->grammar->vocab != nullptr && ctx->grammar->lazy && ctx->grammar->awaiting_trigger; +} + // penalties struct llama_sampler_penalties : public llama_sampler_backend { @@ -4379,3 +4393,237 @@ void llama_perf_sampler_reset(struct llama_sampler * chain) { ctx->t_sample_us = 0; ctx->n_sample = 0; } + + +// Series 20 (Pillar S20.5 + Micro-Defect X-5): 0-ULP + 0-RNG-drift raw-logit pure temp+dist verifier & sampler +bool llama_sampler_chain_is_bias_temp_dist( + const struct llama_sampler * chain, float * out_temp, struct llama_sampler ** out_dist, struct llama_sampler ** out_logit_bias) { + if (!chain || chain->iface != &llama_sampler_chain_i) { + return false; + } + const int32_t n_sc = llama_sampler_chain_n(chain); + if (n_sc < 1) { + return false; + } + struct llama_sampler * last = llama_sampler_chain_get(const_cast(chain), n_sc - 1); + if (!last || last->iface != &llama_sampler_dist_i) { + return false; + } + const auto * dctx = (const llama_sampler_dist *) last->ctx; + if (dctx->backend_transactional) { + return false; + } + + float eff_temp = 1.0f; + bool seen_active_temp = false; + struct llama_sampler * lb_smpl = nullptr; + for (int32_t k = 0; k < n_sc - 1; ++k) { + struct llama_sampler * s = llama_sampler_chain_get(const_cast(chain), k); + if (!s) { + return false; + } + const char * nm = llama_sampler_name(s); + if (s->iface == &llama_sampler_empty_i || (nm && nm[0] == '?')) { + continue; + } + if (s->iface == &llama_sampler_logit_bias_i) { + if (seen_active_temp || lb_smpl != nullptr) { + return false; + } + lb_smpl = s; + continue; + } + if (s->iface == &llama_sampler_temp_i) { + const float t = ((const llama_sampler_temp *) s->ctx)->temp; + if (t <= 0.0f) { + return false; + } + if (t != 1.0f) { + if (seen_active_temp) { + return false; + } + eff_temp = t; + seen_active_temp = true; + } + continue; + } + if (s->iface == &llama_sampler_temp_ext_i) { + const auto * ext = (const llama_sampler_temp_ext *) s->ctx; + if (ext->delta > 0.0f || ext->temp <= 0.0f) { + return false; + } + if (ext->temp != 1.0f) { + if (seen_active_temp) { + return false; + } + eff_temp = ext->temp; + seen_active_temp = true; + } + continue; + } + return false; + } + + if (out_temp) { + *out_temp = eff_temp; + } + if (out_dist) { + *out_dist = last; + } + if (out_logit_bias) { + *out_logit_bias = lb_smpl; + } + return true; +} + +bool llama_sampler_chain_is_pure_temp_dist( + const struct llama_sampler * chain, float * out_temp, struct llama_sampler ** out_dist) { + struct llama_sampler * lb_smpl = nullptr; + if (!llama_sampler_chain_is_bias_temp_dist(chain, out_temp, out_dist, &lb_smpl)) { + return false; + } + return lb_smpl == nullptr; +} + +bool llama_sampler_chain_is_pure_greedy(const struct llama_sampler * chain) { + if (!chain || chain->iface != &llama_sampler_chain_i) { + return false; + } + const int32_t n_sc = llama_sampler_chain_n(chain); + if (n_sc < 1) { + return false; + } + struct llama_sampler * last = llama_sampler_chain_get(const_cast(chain), n_sc - 1); + if (!last || last->iface != &llama_sampler_greedy_i) { + return false; + } + for (int32_t k = 0; k < n_sc - 1; ++k) { + struct llama_sampler * s = llama_sampler_chain_get(const_cast(chain), k); + if (!s) { + return false; + } + const char * nm = llama_sampler_name(s); + if (s->iface == &llama_sampler_empty_i || (nm && nm[0] == '?')) { + continue; + } + if (s->iface == &llama_sampler_temp_i) { + const float t = ((const llama_sampler_temp *) s->ctx)->temp; + if (t <= 0.0f || t == 1.0f) { + continue; + } + return false; + } + if (s->iface == &llama_sampler_temp_ext_i) { + const auto * ext = (const llama_sampler_temp_ext *) s->ctx; + if (ext->delta <= 0.0f && (ext->temp <= 0.0f || ext->temp == 1.0f)) { + continue; + } + return false; + } + return false; + } + return true; +} + +llama_token llama_sampler_temp_dist_probs_raw_0ulp( + struct llama_sampler * dist_smpl, struct llama_sampler * lb_smpl, + const float * logits_row, int32_t n_vocab, float temp, + const float ** out_unnorm_p, double * out_sum_p) { + GGML_ASSERT(dist_smpl && dist_smpl->iface == &llama_sampler_dist_i && logits_row && n_vocab > 0); + auto * ctx = (llama_sampler_dist *) dist_smpl->ctx; + std::uniform_real_distribution dist(0.0f, 1.0f); + + if (n_vocab == 1) { + static const float one = 1.0f; + (void) dist(ctx->rng); + if (out_unnorm_p) { *out_unnorm_p = &one; } + if (out_sum_p) { *out_sum_p = 1.0; } + return 0; + } + + static thread_local std::vector p_buf; + if ((int32_t) p_buf.size() < n_vocab) { + p_buf.resize(n_vocab); + } + float * __restrict p_arr = p_buf.data(); + + if (lb_smpl == nullptr && temp == 1.0f) { + float max_l = logits_row[0]; + for (int32_t i = 1; i < n_vocab; ++i) { + max_l = std::max(max_l, logits_row[i]); + } + double sum_cum = 0.0; + for (int32_t i = 0; i < n_vocab; ++i) { + const float p = expf(logits_row[i] - max_l); + p_arr[i] = p; + sum_cum += p; + } + if (out_unnorm_p) { *out_unnorm_p = p_arr; } + if (out_sum_p) { *out_sum_p = sum_cum; } + const double rnd = dist(ctx->rng); + const double sum_tgt = sum_cum * rnd; + double sum_run = 0.0; + llama_token selected = n_vocab - 1; + for (int32_t i = 0; i < n_vocab; ++i) { + sum_run += p_arr[i]; + if (sum_run >= sum_tgt) { + selected = i; + break; + } + } + return selected; + } + + std::memcpy(p_arr, logits_row, (size_t) n_vocab * sizeof(float)); + if (lb_smpl != nullptr) { + GGML_ASSERT(lb_smpl->iface == &llama_sampler_logit_bias_i); + const auto * lb_ctx = (const llama_sampler_logit_bias *) lb_smpl->ctx; + for (const auto & lb : lb_ctx->logit_bias) { + if (lb.token >= 0 && lb.token < n_vocab) { + p_arr[lb.token] += lb.bias; + } + } + } + + float max_l; + if (temp == 1.0f) { + max_l = p_arr[0]; + for (int32_t i = 1; i < n_vocab; ++i) { + max_l = std::max(max_l, p_arr[i]); + } + } else { + p_arr[0] /= temp; + max_l = p_arr[0]; + for (int32_t i = 1; i < n_vocab; ++i) { + const float sl = p_arr[i] / temp; + p_arr[i] = sl; + max_l = std::max(max_l, sl); + } + } + + double sum_cum = 0.0; + for (int32_t i = 0; i < n_vocab; ++i) { + const float p = expf(p_arr[i] - max_l); + p_arr[i] = p; + sum_cum += p; + } + if (out_unnorm_p) { *out_unnorm_p = p_arr; } + if (out_sum_p) { *out_sum_p = sum_cum; } + const double rnd = dist(ctx->rng); + const double sum_tgt = sum_cum * rnd; + double sum_run = 0.0; + llama_token selected = n_vocab - 1; + for (int32_t i = 0; i < n_vocab; ++i) { + sum_run += p_arr[i]; + if (sum_run >= sum_tgt) { + selected = i; + break; + } + } + return selected; +} + +llama_token llama_sampler_temp_dist_sample_raw_0ulp( + struct llama_sampler * dist_smpl, const float * logits_row, int32_t n_vocab, float temp) { + return llama_sampler_temp_dist_probs_raw_0ulp(dist_smpl, nullptr, logits_row, n_vocab, temp, nullptr, nullptr); +} diff --git a/src/models/dflash.cpp b/src/models/dflash.cpp index 6200b6c44809..3a8f638ffddc 100644 --- a/src/models/dflash.cpp +++ b/src/models/dflash.cpp @@ -79,6 +79,11 @@ void llama_model_dflash::load_arch_hparams(llama_model_loader & ml) { // DFlash has a single rope, so the SWA rope == main rope. hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + if (variant == VARIANT_DSPARK && hparams.dspark_f_rnn && getenv("LLAMA_DSPARK_FORCE_ALL_SWA")) { + for (uint32_t il = 0; il < hparams.n_layer_all; ++il) { + hparams.is_swa_impl[il] = true; + } + } hparams.rope_freq_base_train_swa = hparams.rope_freq_base_train; hparams.rope_freq_scale_train_swa = hparams.rope_freq_scale_train; } @@ -555,12 +560,21 @@ ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tok } ggml_tensor * llama_model_dflash::graph_base::build_logits(ggml_tensor * cur) { - const auto [output, output_s] = get_lm_head(*this, model); + auto [output, output_s] = get_lm_head(*this, model); + const int64_t n_vocab_unpadded = model.vocab.n_tokens(); + if (!model.d2t && output->ne[1] > n_vocab_unpadded && + (!hdmd || hdmd->rot.find(output) == hdmd->rot.end()) && + (!loras || loras->empty())) { + output = ggml_view_2d(ctx0, output, output->ne[0], n_vocab_unpadded, output->nb[1], 0); + if (output_s) { + output_s = ggml_view_1d(ctx0, output_s, n_vocab_unpadded, 0); + } + } cur = build_lora_mm(output, cur, output_s); // a padded lm head (e.g. shared from the target): drop the rows past the vocabulary - if (!model.d2t && cur->ne[0] > (int64_t) model.vocab.n_tokens()) { - cur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, model.vocab.n_tokens(), cur->ne[1], cur->nb[1], 0)); + if (!model.d2t && cur->ne[0] > n_vocab_unpadded) { + cur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_vocab_unpadded, cur->ne[1], cur->nb[1], 0)); } // DFlash2 feeds these logits to the selector, so they need the target's output diff --git a/src/models/dspark.cpp b/src/models/dspark.cpp index 81ededc794c0..68b92cf27e1e 100644 --- a/src/models/dspark.cpp +++ b/src/models/dspark.cpp @@ -4,6 +4,177 @@ #include "llama-kv-cache.h" #include "llama-kv-cache-iswa.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" + +#include +#include +#include +#include +#include +#include + +extern "C" void llama_s23_set_dspark_tree_meta(ggml_tensor * t); + +// Series 23 (B1): Lazily quantize BF16/F16/F32 dspark_markov_w2 ([256, 200058] = 102.4 MB) into Q4_K/Q5_K/Q6_K +// so the entire Markov output projection fits inside Apple M4 Max's 48 MiB SLC across chained draft steps. +static void s23_ensure_dspark_w2_quant(const llama_model & model) { + if (model.dspark_markov_w2_ready) { + return; + } + static std::mutex s23_w2_mtx; + std::lock_guard lock(s23_w2_mtx); + if (model.dspark_markov_w2_ready) { + return; + } + + const ggml_tensor * w2 = model.dspark_markov_w2; + if (!w2 || !w2->buffer || ggml_backend_buffer_get_size(w2->buffer) == 0) { + return; + } + + ggml_type qtype = GGML_TYPE_Q8_0; + if (const char * env_t = getenv("LLAMA_DSPARK_W2_TYPE")) { + if (env_t[0] != '\0') { + if (strcasecmp(env_t, "raw") == 0 || strcasecmp(env_t, "bf16") == 0 || + strcasecmp(env_t, "none") == 0 || strcmp(env_t, "0") == 0) { + model.dspark_markov_w2_ready = true; + return; + } else if (strcasecmp(env_t, "q4_k") == 0) { + qtype = GGML_TYPE_Q4_K; + } else if (strcasecmp(env_t, "q5_k") == 0) { + qtype = GGML_TYPE_Q5_K; + } else if (strcasecmp(env_t, "q6_k") == 0) { + qtype = GGML_TYPE_Q6_K; + } else if (strcasecmp(env_t, "q8_0") == 0) { + qtype = GGML_TYPE_Q8_0; + } else if (strcasecmp(env_t, "q4_0") == 0) { + qtype = GGML_TYPE_Q4_0; + } else if (strcasecmp(env_t, "nvfp4") == 0) { + qtype = GGML_TYPE_NVFP4; + } + } + } + + const bool supported_src = + w2->type == GGML_TYPE_BF16 || w2->type == GGML_TYPE_F16 || w2->type == GGML_TYPE_F32; + const int64_t ne0 = w2->ne[0]; + const int64_t ne1 = w2->ne[1]; + if (!supported_src || w2->ne[2] != 1 || w2->ne[3] != 1 || !ggml_is_contiguous(w2) || + model.dspark_markov_w2_s != nullptr || !model.loras.empty() || + model.hdmd.rot.find(w2) != model.hdmd.rot.end() || + (ne0 % ggml_blck_size(qtype)) != 0) { + model.dspark_markov_w2_ready = true; + return; + } + + const auto * src_traits = ggml_get_type_traits(w2->type); + if (w2->type != GGML_TYPE_F32 && (!src_traits || !src_traits->to_float)) { + model.dspark_markov_w2_ready = true; + return; + } + + ggml_init_params params = { ggml_tensor_overhead() * 4, nullptr, true }; + ggml_context_ptr ctx(ggml_init(params)); + if (!ctx) { + model.dspark_markov_w2_ready = true; + return; + } + + ggml_tensor * w2_q = ggml_new_tensor_2d(ctx.get(), qtype, ne0, ne1); + ggml_set_name(w2_q, "markov_w2.weight.s23_q"); + + ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(w2->buffer); + if ((qtype == GGML_TYPE_Q4_K || qtype == GGML_TYPE_Q5_K || + qtype == GGML_TYPE_Q6_K || qtype == GGML_TYPE_NVFP4) && + !getenv("LLAMA_DSPARK_W2_NO_REPACK")) { + ggml_backend_dev_t dev = buft ? ggml_backend_buft_get_device(buft) : nullptr; + ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr; + auto get_extra_bufts = reg + ? reinterpret_cast( + ggml_backend_reg_get_proc_address(reg, "ggml_backend_dev_get_extra_bufts")) + : nullptr; + if (get_extra_bufts) { + ggml_backend_buffer_type_t * extra = get_extra_bufts(dev); + for (size_t bi = 0; extra && extra[bi] != nullptr; ++bi) { + const char * bname = ggml_backend_buft_name(extra[bi]); + if (bname && std::strstr(bname, "_Repack") != nullptr && + ggml_backend_buft_get_alloc_size(extra[bi], w2_q) > 0) { + buft = extra[bi]; + break; + } + } + } + } + ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors_from_buft(ctx.get(), buft)); + if (!buf) { + model.dspark_markov_w2_ready = true; + return; + } + ggml_backend_buffer_set_usage(buf.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS); + + const size_t src_bytes = ggml_nbytes(w2); + const size_t dst_bytes = ggml_nbytes(w2_q); + const size_t alloc_bytes = ggml_backend_buffer_get_alloc_size(buf.get(), w2_q); + const size_t src_row_bytes = ggml_row_size(w2->type, ne0); + const size_t dst_row_bytes = ggml_row_size(qtype, ne0); + + std::vector raw_stage(src_bytes); + std::vector q_stage(dst_bytes); + ggml_backend_tensor_get(w2, raw_stage.data(), 0, src_bytes); + + ggml_quantize_init(qtype); + + const unsigned hw_threads = std::thread::hardware_concurrency(); + const int64_t n_workers = (int64_t) std::min(8u, std::max(1u, hw_threads)); + const int64_t rows_per_w = (ne1 + n_workers - 1) / n_workers; + + auto quant_worker = [&](int64_t r_beg, int64_t r_end) { + constexpr int64_t TILE_ROWS = 256; + std::vector f32_tile((size_t) (TILE_ROWS * ne0)); + for (int64_t r0 = r_beg; r0 < r_end; r0 += TILE_ROWS) { + const int64_t nr = std::min(TILE_ROWS, r_end - r0); + const uint8_t * s_ptr = raw_stage.data() + (size_t) r0 * src_row_bytes; + uint8_t * d_ptr = q_stage.data() + (size_t) r0 * dst_row_bytes; + const float * f_ptr = nullptr; + if (w2->type == GGML_TYPE_F32) { + f_ptr = reinterpret_cast(s_ptr); + } else { + src_traits->to_float(s_ptr, f32_tile.data(), nr * ne0); + f_ptr = f32_tile.data(); + } + ggml_quantize_chunk(qtype, f_ptr, d_ptr, 0, nr, ne0, nullptr); + } + }; + + std::vector workers; + workers.reserve((size_t) std::max(0, n_workers - 1)); + for (int64_t w = 1; w < n_workers; ++w) { + const int64_t r_beg = w * rows_per_w; + const int64_t r_end = std::min(ne1, r_beg + rows_per_w); + if (r_beg < r_end) { + workers.emplace_back(quant_worker, r_beg, r_end); + } + } + quant_worker(0, std::min(ne1, rows_per_w)); + for (auto & th : workers) { + th.join(); + } + + ggml_backend_tensor_set(w2_q, q_stage.data(), 0, dst_bytes); + + model.dspark_w2_q_ctx = std::move(ctx); + model.dspark_w2_q_buf = std::move(buf); + model.dspark_markov_w2_q = w2_q; + model.dspark_markov_w2_ready = true; + + LLAMA_LOG_INFO("%s: quantized dspark_markov_w2 [%lld, %lld] %s (%.2f MiB) -> %s on %s (%.2f MiB) for SLC residency\n", + __func__, (long long) ne0, (long long) ne1, + ggml_type_name(w2->type), (double) src_bytes / (1024.0 * 1024.0), + ggml_type_name(qtype), ggml_backend_buft_name(buft), + (double) alloc_bytes / (1024.0 * 1024.0)); +} + // DeepSeek-V4 DSpark backbone: stages are full DSV4 blocks, uniform sliding window (the draft KV ring) void llama_model_dflash::load_hparams_dsv4(llama_model_loader & ml) { ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q); @@ -207,8 +378,9 @@ ggml_tensor * llama_model_dflash::build_dspark_inp_block(const llm_graph_context return ggml_get_rows(ctx0, tok_embd, inp_tokens); } - ggml_tensor * anchors = ggml_view_2d(ctx0, inp_tokens, 1, n_blocks, (size_t) block_drafts * inp_tokens->nb[0], 0); - anchors = ggml_get_rows(ctx0, tok_embd, ggml_cont_1d(ctx0, anchors, n_blocks)); + ggml_tensor * anchors_v = ggml_view_2d(ctx0, inp_tokens, 1, n_blocks, (size_t) block_drafts * inp_tokens->nb[0], 0); + ggml_tensor * anchors = (n_blocks == 1) ? ggml_reshape_1d(ctx0, anchors_v, 1) : ggml_cont_1d(ctx0, anchors_v, n_blocks); + anchors = ggml_get_rows(ctx0, tok_embd, anchors); if (model.tok_norm) { anchors = g.build_norm(anchors, model.tok_norm, nullptr, LLM_NORM_RMS, -1); } @@ -234,8 +406,12 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & ggml_context * ctx0 = g.ctx0; auto & res = g.res; + if (!model.dspark_markov_w2_ready) { + s23_ensure_dspark_w2_quant(model); + } + ggml_tensor * w1 = model.dspark_markov_w1; - ggml_tensor * w2 = model.dspark_markov_w2; + ggml_tensor * w2 = model.dspark_markov_w2_q ? model.dspark_markov_w2_q : model.dspark_markov_w2; GGML_ASSERT(w1 && w2 && "DSpark markov weights not loaded"); // confidence head is optional @@ -247,7 +423,7 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & ggml_tensor * base = res->t_logits; // [n_vocab, n_tokens] const int64_t n_vocab = base->ne[0]; - const int64_t n_tok = base->ne[1]; + const int64_t n_tok = tokens->ne[0]; const auto it = model.gguf_kv.find("dflash.block_size"); GGML_ASSERT(it != model.gguf_kv.end() && "DSpark draft requires 'dflash.block_size' in GGUF metadata"); @@ -267,12 +443,15 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & return; } + const bool base_trimmed = !sample_from_anchor && base->ne[1] == n_blocks * (block_drafts - i_draft_beg); + GGML_ASSERT(base->ne[1] == n_tok || base_trimmed); + // anchor (committed last) token of every block: token 0 of each block, i.e. a strided view const size_t token_stride = (size_t) block_drafts * tokens->nb[0]; - const size_t base_stride = (size_t) block_drafts * base->nb[1]; + const size_t base_stride = (size_t) (base_trimmed ? (block_drafts - i_draft_beg) : block_drafts) * base->nb[1]; - ggml_tensor * prev = ggml_view_2d(ctx0, tokens, 1, n_blocks, token_stride, 0); - prev = ggml_cont_1d(ctx0, prev, n_blocks); + ggml_tensor * prev_v = ggml_view_2d(ctx0, tokens, 1, n_blocks, token_stride, 0); + ggml_tensor * prev = (n_blocks == 1) ? ggml_reshape_1d(ctx0, prev_v, 1) : ggml_cont_1d(ctx0, prev_v, n_blocks); const int64_t n_embd = g.hparams.n_embd; @@ -329,15 +508,295 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & return ggml_pad(ctx0, row, n_embd - row->ne[0], 0, 0, 0); }; - const float softcap = softcap_after_bias ? g.hparams.f_final_logit_softcapping : 0.0f; + float softcap = 0.0f; + if (softcap_after_bias) { + softcap = g.hparams.f_final_logit_softcapping; + if (softcap == 0.0f && g.cparams.ctx_other != nullptr) { + softcap = llama_get_model(g.cparams.ctx_other)->hparams.f_final_logit_softcapping; + } + } + + const bool ids_only = rnn_state != nullptr && !sample_from_anchor && !has_conf && + g.ubatch.output != nullptr && g.ubatch.output[0] == 0 && + g.n_outputs > 0 && g.n_outputs == n_blocks * (block_drafts - i_draft_beg); + const int64_t n_draft = block_drafts - i_draft_beg; + if (ids_only) { + res->t_sampled.assign(n_draft * n_blocks, nullptr); + } + + const bool ids_tree = ids_only && n_blocks == 1 && n_draft >= 2 && model.d2t == nullptr && + getenv("LLAMA_DSPARK_ENABLE_2BRANCH") && !getenv("LLAMA_DSPARK_NO_TREE"); + const bool ids_margin = ids_only && n_blocks == 1 && n_draft >= 4 && model.d2t == nullptr && + !ids_tree && getenv("LLAMA_DSPARK_ENABLE_MARGIN") && !getenv("LLAMA_DSPARK_NO_MARGIN"); + if (ids_margin) { + ggml_tensor * state_m = nullptr; + ggml_tensor * margs_m[4] = { nullptr, nullptr, nullptr, nullptr }; + const int64_t n_marg = std::min(n_draft, 4); + + for (int64_t s = 0; s < n_draft; ++s) { + const int64_t i = i_draft_beg + s; + const int64_t bi = base_trimmed ? s : i; + ggml_tensor * w1_prev = ggml_get_rows(ctx0, w1, prev); + ggml_tensor * markov = w1_prev; + if (is_rnn) { + const int64_t rank = w1_prev->ne[0]; + if (state_m == nullptr) { + state_m = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, rank, 1), 0.0f); + } + ggml_tensor * hid_i = hidden ? ggml_view_2d(ctx0, hidden, hidden->ne[0], 1, + (size_t) block_drafts * hidden->nb[1], i * hidden->nb[1]) : nullptr; + ggml_tensor * hid_c = (hid_i && !ggml_is_contiguous(hid_i)) ? ggml_cont(ctx0, hid_i) : hid_i; + const bool can_fuse_joint_gru = + f_rnn != nullptr && + !getenv("GGML_INKLING_NO_FUSE") && + (!g.loras || g.loras->empty()) && + (!g.hdmd || g.hdmd->rot.find(model.dspark_joint_proj) == g.hdmd->rot.end()) && + (model.dspark_markov_w1->type == GGML_TYPE_BF16 || model.dspark_markov_w1->type == GGML_TYPE_F32) && + (model.dspark_joint_proj->type == GGML_TYPE_BF16 || model.dspark_joint_proj->type == GGML_TYPE_F32) && + ggml_is_contiguous(prev) && ggml_is_contiguous(state_m) && + ggml_is_contiguous(hid_c) && ggml_is_contiguous(f_rnn); + if (can_fuse_joint_gru) { + ggml_tensor * st_lat = ggml_inkling_dspark_joint_gru( + ctx0, prev, model.dspark_markov_w1, state_m, hid_c, f_rnn, + model.dspark_joint_proj, model.dspark_joint_proj_b); + state_m = ggml_view_2d(ctx0, st_lat, rank, 1, st_lat->nb[1], 0); + markov = ggml_view_2d(ctx0, st_lat, rank, 1, st_lat->nb[1], st_lat->nb[2]); + } else { + ggml_tensor * joint = ggml_concat(ctx0, ggml_concat(ctx0, state_m, w1_prev, 0), hid_c, 0); + if (f_rnn) { + joint = ggml_concat(ctx0, joint, f_rnn, 0); + } + joint = ggml_add(ctx0, ggml_mul_mat(ctx0, model.dspark_joint_proj, joint), model.dspark_joint_proj_b); + const auto chunk = [&](int64_t k) { + return ggml_cont(ctx0, ggml_view_2d(ctx0, joint, rank, 1, joint->nb[1], k*rank*ggml_element_size(joint))); + }; + ggml_tensor * gate = ggml_sigmoid(ctx0, chunk(0)); + ggml_tensor * cand = ggml_tanh(ctx0, chunk(1)); + state_m = ggml_add(ctx0, cand, ggml_mul(ctx0, gate, ggml_sub(ctx0, state_m, cand))); + markov = ggml_tanh(ctx0, chunk(2)); + } + } + ggml_tensor * bias = g.build_lora_mm(w2, markov, model.dspark_markov_w2_s); + if (model.dspark_markov_w2_b) { + bias = ggml_add(ctx0, bias, model.dspark_markov_w2_b); + } + ggml_tensor * base_i = ggml_view_2d(ctx0, base, n_vocab, 1, base_stride, bi * base->nb[1]); + ggml_tensor * raw_s = ggml_add(ctx0, base_i, bias); + ggml_tensor * col_s = (softcap > 0.0f) + ? ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, raw_s, 1.0f/softcap)), softcap) + : raw_s; + prev = ggml_argmax(ctx0, col_s); + ggml_set_output(prev); + res->t_sampled[s] = prev; + ggml_build_forward_expand(g.gf, prev); + + if (s < n_marg) { + ggml_tensor * raw_rows = ggml_reshape_2d(ctx0, raw_s, 1, n_vocab); + ggml_tensor * v0 = ggml_get_rows(ctx0, raw_rows, prev); + ggml_build_forward_expand(g.gf, v0); + ggml_tensor * neg_inf = ggml_scale_bias(ctx0, ggml_clamp(ctx0, v0, 0.0f, 0.0f), 1.0f, -1e9f); + ggml_tensor * masked_rows = ggml_set_rows(ctx0, raw_rows, neg_inf, prev); + ggml_tensor * alt_i32 = ggml_argmax(ctx0, ggml_reshape_2d(ctx0, masked_rows, n_vocab, 1)); + ggml_tensor * v1 = ggml_get_rows(ctx0, masked_rows, alt_i32); + ggml_tensor * t2_raw = ggml_concat(ctx0, ggml_reshape_1d(ctx0, v0, 1), ggml_reshape_1d(ctx0, v1, 1), 0); + ggml_tensor * t2_vals = (softcap > 0.0f) + ? ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, t2_raw, 1.0f/softcap)), softcap) + : t2_raw; + margs_m[s] = ggml_sub(ctx0, ggml_view_1d(ctx0, t2_vals, 1, 0), ggml_view_1d(ctx0, t2_vals, 1, sizeof(float))); + } + } + + ggml_tensor * tree_meta = ggml_concat(ctx0, margs_m[0], margs_m[1], 0); + tree_meta = ggml_concat(ctx0, tree_meta, margs_m[2], 0); + tree_meta = ggml_concat(ctx0, tree_meta, margs_m[3], 0); + ggml_set_output(tree_meta); + ggml_build_forward_expand(g.gf, tree_meta); + llama_s23_set_dspark_tree_meta(tree_meta); + + res->t_logits = nullptr; + return; + } + if (ids_tree) { + const int64_t env_m_s = getenv("LLAMA_DSPARK_TREE_DRAFT_LEN") + ? std::max(2, std::atoi(getenv("LLAMA_DSPARK_TREE_DRAFT_LEN"))) + : 2; + const int64_t env_m_l = getenv("LLAMA_DSPARK_TREE_DRAFT_LEN_LONG") + ? std::max(2, std::atoi(getenv("LLAMA_DSPARK_TREE_DRAFT_LEN_LONG"))) + : 3; + const int64_t tree_m = std::min(n_draft, (n_draft >= 6) ? env_m_l : env_m_s); + + auto step_markov = [&](ggml_tensor * prev_in, ggml_tensor *& state_io, ggml_tensor * hid_in, + ggml_tensor * frnn_in, int64_t nb_cur) -> ggml_tensor * { + ggml_tensor * w1_prev = ggml_get_rows(ctx0, w1, prev_in); + ggml_tensor * markov = w1_prev; + if (is_rnn) { + const int64_t rank = w1_prev->ne[0]; + if (state_io == nullptr) { + state_io = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, rank, nb_cur), 0.0f); + } + ggml_tensor * hid_c = ggml_is_contiguous(hid_in) ? hid_in : ggml_cont(ctx0, hid_in); + const bool can_fuse_joint_gru = + frnn_in != nullptr && + !getenv("GGML_INKLING_NO_FUSE") && + (!g.loras || g.loras->empty()) && + (!g.hdmd || g.hdmd->rot.find(model.dspark_joint_proj) == g.hdmd->rot.end()) && + (model.dspark_markov_w1->type == GGML_TYPE_BF16 || model.dspark_markov_w1->type == GGML_TYPE_F32) && + (model.dspark_joint_proj->type == GGML_TYPE_BF16 || model.dspark_joint_proj->type == GGML_TYPE_F32) && + ggml_is_contiguous(prev_in) && ggml_is_contiguous(state_io) && + ggml_is_contiguous(hid_c) && ggml_is_contiguous(frnn_in); + if (can_fuse_joint_gru) { + ggml_tensor * st_lat = ggml_inkling_dspark_joint_gru( + ctx0, prev_in, model.dspark_markov_w1, state_io, hid_c, frnn_in, + model.dspark_joint_proj, model.dspark_joint_proj_b); + state_io = ggml_view_2d(ctx0, st_lat, rank, st_lat->ne[1], st_lat->nb[1], 0); + markov = ggml_view_2d(ctx0, st_lat, rank, st_lat->ne[1], st_lat->nb[1], st_lat->nb[2]); + } else if (frnn_in != nullptr && !getenv("GGML_INKLING_NO_FUSE") && + ggml_is_contiguous(state_io) && ggml_is_contiguous(hid_c) && ggml_is_contiguous(frnn_in)) { + ggml_tensor * joint = ggml_inkling_dspark_concat4(ctx0, state_io, w1_prev, hid_c, frnn_in); + joint = ggml_add(ctx0, ggml_mul_mat(ctx0, model.dspark_joint_proj, joint), model.dspark_joint_proj_b); + ggml_tensor * st_lat = ggml_inkling_dspark_gru(ctx0, joint, state_io); + state_io = ggml_view_2d(ctx0, st_lat, rank, st_lat->ne[1], st_lat->nb[1], 0); + markov = ggml_view_2d(ctx0, st_lat, rank, st_lat->ne[1], st_lat->nb[1], st_lat->nb[2]); + } else { + ggml_tensor * joint = ggml_concat(ctx0, ggml_concat(ctx0, state_io, w1_prev, 0), hid_c, 0); + if (frnn_in) { + joint = ggml_concat(ctx0, joint, frnn_in, 0); + } + joint = ggml_add(ctx0, ggml_mul_mat(ctx0, model.dspark_joint_proj, joint), model.dspark_joint_proj_b); + const auto chunk = [&](int64_t k) { + return ggml_cont(ctx0, ggml_view_2d(ctx0, joint, rank, nb_cur, joint->nb[1], k*rank*ggml_element_size(joint))); + }; + ggml_tensor * gate = ggml_sigmoid(ctx0, chunk(0)); + ggml_tensor * cand = ggml_tanh(ctx0, chunk(1)); + state_io = ggml_add(ctx0, cand, ggml_mul(ctx0, gate, ggml_sub(ctx0, state_io, cand))); + markov = ggml_tanh(ctx0, chunk(2)); + } + } + ggml_tensor * bias = g.build_lora_mm(w2, markov, model.dspark_markov_w2_s); + if (model.dspark_markov_w2_b) { + bias = ggml_add(ctx0, bias, model.dspark_markov_w2_b); + } + return bias; + }; + + ggml_tensor * state_2b = nullptr; + ggml_tensor * marg_0 = nullptr; + ggml_tensor * alt_0_f = nullptr; + std::vector b1_cont_f; + + // Step s = 0 (nb = 1) + 2-dispatch masked-argmax Top-2 extraction (zero bitonic sort!) + { + const int64_t i = i_draft_beg; + const int64_t bi = base_trimmed ? 0 : i; + ggml_tensor * hid_0 = hidden ? ggml_view_2d(ctx0, hidden, hidden->ne[0], 1, + (size_t) block_drafts * hidden->nb[1], i * hidden->nb[1]) : nullptr; + ggml_tensor * bias_0 = step_markov(prev, state_2b, hid_0, f_rnn, 1); + ggml_tensor * base_0 = ggml_view_2d(ctx0, base, n_vocab, 1, base_stride, bi * base->nb[1]); + ggml_tensor * raw_0 = ggml_add(ctx0, base_0, bias_0); + ggml_tensor * col_0 = (softcap > 0.0f) + ? ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, raw_0, 1.0f/softcap)), softcap) + : raw_0; + ggml_tensor * prev_0 = ggml_argmax(ctx0, col_0); + ggml_set_output(prev_0); + res->t_sampled[0] = prev_0; + ggml_build_forward_expand(g.gf, prev_0); + + // Extract v0 = raw_0[prev_0], mask raw_0[prev_0] = -1e9f in-place strictly after v0, then argmax for alt_0 + ggml_tensor * raw_0_rows = ggml_reshape_2d(ctx0, raw_0, 1, n_vocab); + ggml_tensor * v0 = ggml_get_rows(ctx0, raw_0_rows, prev_0); + ggml_build_forward_expand(g.gf, v0); + ggml_tensor * neg_inf = ggml_scale_bias(ctx0, ggml_clamp(ctx0, v0, 0.0f, 0.0f), 1.0f, -1e9f); + ggml_tensor * masked_rows = ggml_set_rows(ctx0, raw_0_rows, neg_inf, prev_0); + ggml_tensor * masked_0 = ggml_reshape_2d(ctx0, masked_rows, n_vocab, 1); + ggml_tensor * alt_0_i32 = ggml_argmax(ctx0, masked_0); + ggml_tensor * v1 = ggml_get_rows(ctx0, masked_rows, alt_0_i32); + + ggml_tensor * t2_raw = ggml_concat(ctx0, ggml_reshape_1d(ctx0, v0, 1), ggml_reshape_1d(ctx0, v1, 1), 0); + ggml_tensor * t2_vals = (softcap > 0.0f) + ? ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, t2_raw, 1.0f/softcap)), softcap) + : t2_raw; + marg_0 = ggml_sub(ctx0, ggml_view_1d(ctx0, t2_vals, 1, 0), ggml_view_1d(ctx0, t2_vals, 1, sizeof(float))); + alt_0_f = ggml_cast(ctx0, alt_0_i32, GGML_TYPE_F32); + + prev = ggml_concat(ctx0, prev_0, alt_0_i32, 0); // I32 [2]: [beam0, alt_0_cont] + if (state_2b) { + state_2b = ggml_repeat_4d(ctx0, ggml_cont(ctx0, state_2b), state_2b->ne[0], 2, 1, 1); + } + } + + // Steps s = 1 .. tree_m - 1 (nb = 2 <= col_tile = 4: single SLC-resident dmmv_repack pass for both beams) + ggml_tensor * f_rnn_2 = f_rnn ? ggml_repeat_4d(ctx0, f_rnn, n_embd, 2, 1, 1) : nullptr; + for (int64_t s = 1; s < tree_m; ++s) { + const int64_t i = i_draft_beg + s; + const int64_t bi = base_trimmed ? s : i; + ggml_tensor * hid_i = hidden ? ggml_view_2d(ctx0, hidden, hidden->ne[0], 1, + (size_t) block_drafts * hidden->nb[1], i * hidden->nb[1]) : nullptr; + ggml_tensor * hid_2 = hid_i + ? ggml_repeat_4d(ctx0, ggml_is_contiguous(hid_i) ? hid_i : ggml_cont(ctx0, hid_i), hidden->ne[0], 2, 1, 1) + : nullptr; + ggml_tensor * bias_2 = step_markov(prev, state_2b, hid_2, f_rnn_2, 2); + ggml_tensor * base_i = ggml_view_2d(ctx0, base, n_vocab, 1, base_stride, bi * base->nb[1]); + ggml_tensor * raw_2 = ggml_add(ctx0, bias_2, base_i); + ggml_tensor * col_2 = (softcap > 0.0f) + ? ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, raw_2, 1.0f/softcap)), softcap) + : raw_2; + prev = ggml_argmax(ctx0, col_2); // I32 [2] + + ggml_tensor * prev_b0 = ggml_view_1d(ctx0, prev, 1, 0); + ggml_set_output(prev_b0); + res->t_sampled[s] = prev_b0; + ggml_build_forward_expand(g.gf, prev_b0); + + b1_cont_f.push_back(ggml_cast(ctx0, ggml_view_1d(ctx0, prev, 1, sizeof(int32_t)), GGML_TYPE_F32)); + } + + // Steps s = tree_m .. n_draft - 1 (nb = 1: single primary beam with full ADD_SOFTCAP_ARGMAX fusion) + if (tree_m < n_draft) { + prev = ggml_view_1d(ctx0, prev, 1, 0); + if (state_2b) { + state_2b = ggml_view_2d(ctx0, state_2b, state_2b->ne[0], 1, state_2b->nb[1], 0); + } + for (int64_t s = tree_m; s < n_draft; ++s) { + const int64_t i = i_draft_beg + s; + const int64_t bi = base_trimmed ? s : i; + ggml_tensor * hid_i = hidden ? ggml_view_2d(ctx0, hidden, hidden->ne[0], 1, + (size_t) block_drafts * hidden->nb[1], i * hidden->nb[1]) : nullptr; + ggml_tensor * bias_1 = step_markov(prev, state_2b, hid_i, f_rnn, 1); + ggml_tensor * base_i = ggml_view_2d(ctx0, base, n_vocab, 1, base_stride, bi * base->nb[1]); + ggml_tensor * raw_1 = ggml_add(ctx0, base_i, bias_1); + ggml_tensor * col_1 = (softcap > 0.0f) + ? ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, raw_1, 1.0f/softcap)), softcap) + : raw_1; + prev = ggml_argmax(ctx0, col_1); // I32 [1] + ggml_set_output(prev); + res->t_sampled[s] = prev; + ggml_build_forward_expand(g.gf, prev); + } + } + + ggml_tensor * tree_meta = ggml_concat(ctx0, marg_0, alt_0_f, 0); + for (ggml_tensor * cf : b1_cont_f) { + tree_meta = ggml_concat(ctx0, tree_meta, cf, 0); + } + ggml_set_output(tree_meta); + ggml_build_forward_expand(g.gf, tree_meta); + llama_s23_set_dspark_tree_meta(tree_meta); + + res->t_logits = nullptr; + return; + } ggml_tensor * cat = nullptr; ggml_tensor * cat_conf = nullptr; ggml_tensor * cat_draw = nullptr; + const bool draws_only = !ids_only && rnn_state != nullptr && !sample_from_anchor && !has_conf && + !getenv("LLAMA_DSPARK_HOST_LOGITS"); - if (!sample_from_anchor) { + if (!sample_from_anchor && !ids_only) { // bonus anchor slot: pass the logits through unbiased, pad the (unread) confidence column - cat = ggml_cont(ctx0, ggml_view_2d(ctx0, base, n_vocab, n_blocks, base_stride, 0)); + if (!draws_only) { + cat = ggml_cont(ctx0, ggml_view_2d(ctx0, base, n_vocab, n_blocks, base_stride, 0)); + } if (has_conf) { cat_conf = ggml_sigmoid(ctx0, ggml_view_2d(ctx0, base, 1, n_blocks, base_stride, 0)); } @@ -362,21 +821,46 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & ggml_tensor * hidden_i = ggml_view_2d(ctx0, hidden, hidden->ne[0], n_blocks, (size_t) block_drafts * hidden->nb[1], i*hidden->nb[1]); - ggml_tensor * joint = ggml_concat(ctx0, ggml_concat(ctx0, state, w1_prev, 0), ggml_cont(ctx0, hidden_i), 0); - if (f_rnn) { - joint = ggml_concat(ctx0, joint, f_rnn, 0); + ggml_tensor * hidden_c = ggml_is_contiguous(hidden_i) ? hidden_i : ggml_cont(ctx0, hidden_i); + const bool can_fuse_joint_gru = + f_rnn != nullptr && + !getenv("GGML_INKLING_NO_FUSE") && + (!g.loras || g.loras->empty()) && + (!g.hdmd || g.hdmd->rot.find(model.dspark_joint_proj) == g.hdmd->rot.end()) && + (model.dspark_markov_w1->type == GGML_TYPE_BF16 || model.dspark_markov_w1->type == GGML_TYPE_F32) && + (model.dspark_joint_proj->type == GGML_TYPE_BF16 || model.dspark_joint_proj->type == GGML_TYPE_F32) && + ggml_is_contiguous(prev) && ggml_is_contiguous(state) && + ggml_is_contiguous(hidden_c) && ggml_is_contiguous(f_rnn); + if (can_fuse_joint_gru) { + ggml_tensor * st_lat = ggml_inkling_dspark_joint_gru( + ctx0, prev, model.dspark_markov_w1, state, hidden_c, f_rnn, + model.dspark_joint_proj, model.dspark_joint_proj_b); + state = ggml_view_2d(ctx0, st_lat, rank, st_lat->ne[1], st_lat->nb[1], 0); + markov = ggml_view_2d(ctx0, st_lat, rank, st_lat->ne[1], st_lat->nb[1], st_lat->nb[2]); + } else if (f_rnn != nullptr && !getenv("GGML_INKLING_NO_FUSE") && + ggml_is_contiguous(state) && ggml_is_contiguous(hidden_c) && ggml_is_contiguous(f_rnn)) { + ggml_tensor * joint = ggml_inkling_dspark_concat4(ctx0, state, w1_prev, hidden_c, f_rnn); + joint = ggml_add(ctx0, ggml_mul_mat(ctx0, model.dspark_joint_proj, joint), model.dspark_joint_proj_b); + ggml_tensor * st_lat = ggml_inkling_dspark_gru(ctx0, joint, state); + state = ggml_view_2d(ctx0, st_lat, rank, st_lat->ne[1], st_lat->nb[1], 0); + markov = ggml_view_2d(ctx0, st_lat, rank, st_lat->ne[1], st_lat->nb[1], st_lat->nb[2]); + } else { + ggml_tensor * joint = ggml_concat(ctx0, ggml_concat(ctx0, state, w1_prev, 0), hidden_c, 0); + if (f_rnn) { + joint = ggml_concat(ctx0, joint, f_rnn, 0); + } + joint = ggml_add(ctx0, ggml_mul_mat(ctx0, model.dspark_joint_proj, joint), model.dspark_joint_proj_b); // [3R, n_blocks] + + const auto chunk = [&](int64_t k) { + return ggml_cont(ctx0, ggml_view_2d(ctx0, joint, rank, n_blocks, joint->nb[1], k*rank*ggml_element_size(joint))); + }; + ggml_tensor * gate = ggml_sigmoid(ctx0, chunk(0)); + ggml_tensor * cand = ggml_tanh(ctx0, chunk(1)); + + // state = gate * state + (1 - gate) * cand + state = ggml_add(ctx0, cand, ggml_mul(ctx0, gate, ggml_sub(ctx0, state, cand))); + markov = ggml_tanh(ctx0, chunk(2)); } - joint = ggml_add(ctx0, ggml_mul_mat(ctx0, model.dspark_joint_proj, joint), model.dspark_joint_proj_b); // [3R, n_blocks] - - const auto chunk = [&](int64_t k) { - return ggml_cont(ctx0, ggml_view_2d(ctx0, joint, rank, n_blocks, joint->nb[1], k*rank*ggml_element_size(joint))); - }; - ggml_tensor * gate = ggml_sigmoid(ctx0, chunk(0)); - ggml_tensor * cand = ggml_tanh(ctx0, chunk(1)); - - // state = gate * state + (1 - gate) * cand - state = ggml_add(ctx0, cand, ggml_mul(ctx0, gate, ggml_sub(ctx0, state, cand))); - markov = ggml_tanh(ctx0, chunk(2)); } ggml_tensor * bias = g.build_lora_mm(w2, markov, model.dspark_markov_w2_s); // [n_vocab_draft, n_blocks] @@ -394,13 +878,20 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & } // position i of every block: strided view [n_vocab, n_blocks] - ggml_tensor * base_i = ggml_view_2d(ctx0, base, n_vocab, n_blocks, base_stride, i*base->nb[1]); + const int64_t bi = base_trimmed ? (i - i_draft_beg) : i; + ggml_tensor * base_i = ggml_view_2d(ctx0, base, n_vocab, n_blocks, base_stride, bi*base->nb[1]); ggml_tensor * col = ggml_add(ctx0, base_i, bias); if (softcap > 0.0f) { - col = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, col, 1.0f/softcap)), softcap); + if (!ids_only && !getenv("GGML_INKLING_NO_FUSE") && ggml_is_contiguous(col)) { + col = ggml_inkling_softcap(ctx0, col, 1.0f/softcap, softcap); + } else { + col = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, col, 1.0f/softcap)), softcap); + } } - cat = cat ? ggml_concat(ctx0, cat, col, 1) : col; + if (!ids_only && !draws_only) { + cat = cat ? ggml_concat(ctx0, cat, col, 1) : col; + } if (has_conf) { // confidence head input: predicts per-position acceptance @@ -418,7 +909,21 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & cat_conf = cat_conf ? ggml_concat(ctx0, cat_conf, conf, 1) : conf; } - if (rnn_state) { + if (ids_only) { + prev = ggml_argmax(ctx0, col); + if (n_blocks == 1) { + ggml_set_output(prev); + res->t_sampled[i - i_draft_beg] = prev; + ggml_build_forward_expand(g.gf, prev); + } else { + for (int64_t s = 0; s < n_blocks; ++s) { + ggml_tensor * ps = ggml_view_1d(ctx0, prev, 1, s * prev->nb[0]); + ggml_set_output(ps); + res->t_sampled[s * n_draft + (i - i_draft_beg)] = ps; + ggml_build_forward_expand(g.gf, ps); + } + } + } else if (rnn_state) { ggml_tensor * packed = draw(col, i, prev); cat_draw = cat_draw ? ggml_concat(ctx0, cat_draw, packed, 1) : packed; } else if (i + 1 < block_drafts) { @@ -426,12 +931,21 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & } } + if (ids_only) { + res->t_logits = nullptr; + return; + } + if (cat_draw) { // position-major like cat; restore ubatch block-major order ggml_tensor * draws = ggml_reshape_3d(ctx0, cat_draw, n_embd, n_blocks, block_drafts); draws = ggml_cont(ctx0, ggml_permute(ctx0, draws, 0, 2, 1, 3)); res->t_h_nextn = ggml_reshape_2d(ctx0, draws, n_embd, n_tok); ggml_build_forward_expand(g.gf, res->t_h_nextn); + if (draws_only) { + res->t_logits = nullptr; + return; + } } // cat is position-major; restore ubatch block-major order @@ -486,7 +1000,20 @@ llama_model_dflash::graph_dspark::graph_dspark(const llm_graph_params & params) ggml_tensor * cur = build_layers(inp_tokens); - build_logits(cur); + const auto it_anchor = model.gguf_kv.find("dflash.sample_from_anchor"); + const bool sample_from_anchor = it_anchor == model.gguf_kv.end() || it_anchor->second == "true"; + const bool trim_anchor_logits = + hparams.dspark_f_rnn && rnn_state != nullptr && !sample_from_anchor && + model.dspark_conf_proj == nullptr && !model.dflash_selector_hidden && + ubatch.n_seqs_unq == 1 && n_tokens > 1 && + ubatch.output != nullptr && ubatch.output[0] == 0 && + n_outputs > 0 && (int64_t) n_outputs == n_tokens - 1 && + !getenv("GGML_INKLING_NO_FUSE") && ggml_is_contiguous(cur); + ggml_tensor * cur_logits = trim_anchor_logits + ? ggml_view_2d(ctx0, cur, cur->ne[0], n_tokens - 1, cur->nb[1], cur->nb[1]) + : cur; + + build_logits(cur_logits); // bias the draft logits with the Markov head if (!hparams.dspark_f_rnn) { diff --git a/src/models/inkling2-loop.cpp b/src/models/inkling2-loop.cpp index 1b9455b52229..298aea9574cf 100644 --- a/src/models/inkling2-loop.cpp +++ b/src/models/inkling2-loop.cpp @@ -1,4 +1,46 @@ #include "models.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" + +#include +#include +#include +#include + +static inline ggml_bf16_t s19_fp32_to_bf16_rne(float x) { + uint32_t u = 0; + memcpy(&u, &x, sizeof(u)); + if ((u & 0x7fffffffU) > 0x7f800000U) { + return ggml_bf16_t{ (uint16_t)((u >> 16) | 0x0040U) }; + } + return ggml_bf16_t{ (uint16_t)((u + (0x7fffU + ((u >> 16) & 1U))) >> 16) }; +} + +static void s19_upload_ctrl_slice( + const ggml_tensor * src, + ggml_tensor * dst, + size_t dst_byte_off, + std::vector & stage, + std::vector & stage_bf16) { + const size_t src_bytes = ggml_nbytes(src); + if (stage.size() < src_bytes) { + stage.resize(src_bytes); + } + ggml_backend_tensor_get(src, stage.data(), 0, src_bytes); + if (src->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_BF16) { + const size_t n_el = src_bytes / sizeof(float); + if (stage_bf16.size() < n_el) { + stage_bf16.resize(n_el); + } + const float * pf = (const float *)stage.data(); + for (size_t i = 0; i < n_el; ++i) { + stage_bf16[i] = s19_fp32_to_bf16_rne(pf[i]); + } + ggml_backend_tensor_set(dst, stage_bf16.data(), dst_byte_off, n_el * sizeof(ggml_bf16_t)); + } else { + ggml_backend_tensor_set(dst, stage.data(), dst_byte_off, src_bytes); + } +} int llama_model_inkling2_loop::layer_phys(int il) const { return il < n_phys ? il : core_start + (il - n_phys) % (core_end - core_start); @@ -78,6 +120,226 @@ llama_model_inkling2_loop::graph::graph(const llm_graph_params & params) : llama const int start = m.core_start; const int end = m.core_end; + // S19_WAVE3: lazily materialize pass_msg_query [n_embd, 48], QKV/FFN coalesced loop weights, & FullAttn norms + if (!m.s19_inkling_ready && !getenv("GGML_INKLING_NO_FUSE") && !m.layers.empty()) { + static std::mutex s19_loop_mtx; + std::lock_guard lock(s19_loop_mtx); + const ggml_tensor * ref = m.layers[start].ffn_norm; + if (!m.s19_inkling_ready && ref && ref->buffer && ref->data && + ggml_backend_buffer_get_size(ref->buffer) > 0) { + const int n_loop = end - start; + const int64_t rank = m.gate_rank; + const bool cast_loop_bf16 = !getenv("GGML_INKLING_F32_LOOP_CTRL"); + const bool coal_attn_q8 = !getenv("GGML_INKLING_NO_COAL_ATTN") && m.loras.empty(); + auto can_coal_q8_w = [&](const ggml_tensor * w) -> bool { + return w && w->type == GGML_TYPE_Q8_0 && w->ne[0] == n_embd && (n_embd % 32) == 0 && + w->ne[2] == 1 && w->ne[3] == 1 && ggml_is_contiguous(w) && + m.w_scales.find(w) == m.w_scales.end() && m.hdmd.rot.find(w) == m.hdmd.rot.end(); + }; + auto can_coal_kvd_pair = [&](const llama_layer & lp) -> bool { + const ggml_tensor * kc = lp.attn_k_conv_proj; + const ggml_tensor * vc = lp.attn_v_conv_proj; + return coal_attn_q8 && kc && vc && kc->type == vc->type && + (kc->type == GGML_TYPE_BF16 || kc->type == GGML_TYPE_F32) && + kc->ne[0] == n_embd && vc->ne[0] == n_embd && kc->ne[1] == vc->ne[1] && + kc->ne[2] == 1 && vc->ne[2] == 1 && kc->ne[3] == 1 && vc->ne[3] == 1 && + ggml_is_contiguous(kc) && ggml_is_contiguous(vc) && + m.w_scales.find(kc) == m.w_scales.end() && m.w_scales.find(vc) == m.w_scales.end() && + m.hdmd.rot.find(kc) == m.hdmd.rot.end() && m.hdmd.rot.find(vc) == m.hdmd.rot.end(); + }; + int n_full = 0; + int n_coal_attn = 0; + int n_coal_wkv = 0; + int n_coal_kvd = 0; + for (int p = 0; p < m.n_phys; ++p) { + if (!m.hparams.is_swa(p) && m.layers[p].attn_q_inp_norm) { + ++n_full; + } + if (coal_attn_q8 && can_coal_q8_w(m.layers[p].wq) && + can_coal_q8_w(m.layers[p].wqkv_gate) && can_coal_q8_w(m.layers[p].attn_rel)) { + ++n_coal_attn; + } + if (coal_attn_q8 && (!m.hparams.is_swa(p) || (p >= start && p < end)) && + can_coal_q8_w(m.layers[p].wk) && can_coal_q8_w(m.layers[p].wv) && + m.layers[p].wk->ne[1] == m.layers[p].wv->ne[1]) { + ++n_coal_wkv; + } + if (!m.hparams.is_swa(p) && can_coal_kvd_pair(m.layers[p])) { + ++n_coal_kvd; + } + } + const size_t max_tensors = (size_t)(1 + 4 * n_loop + n_full + n_coal_attn + n_coal_wkv + n_coal_kvd + 8); + ggml_init_params init_p = { ggml_tensor_overhead() * max_tensors, nullptr, true }; + ggml_context_ptr ctx(ggml_init(init_p)); + + ggml_tensor * pass_mq = ggml_new_tensor_2d(ctx.get(), GGML_TYPE_F32, n_embd, (int64_t)LOOP_CTRL_COUNT * n_loop); + std::vector coalesced(m.n_phys); + for (int ip = start; ip < end; ++ip) { + const auto & ll = m.loop_layers[ip - start]; + const ggml_type down_t = ll.ctrl_down[0]->type; + const ggml_type up_t = ll.ctrl_gain[0]->type; + const ggml_type ffn_down_t = ll.ctrl_down[3]->type; + const ggml_type ffn_t = ll.ctrl_gain[3]->type; + const ggml_type dst_down_t = (cast_loop_bf16 && down_t == GGML_TYPE_F32) ? GGML_TYPE_BF16 : down_t; + const ggml_type dst_up_t = (cast_loop_bf16 && up_t == GGML_TYPE_F32) ? GGML_TYPE_BF16 : up_t; + const ggml_type dst_fdown_t = (cast_loop_bf16 && ffn_down_t == GGML_TYPE_F32) ? GGML_TYPE_BF16 : ffn_down_t; + const ggml_type dst_ffn_t = (cast_loop_bf16 && ffn_t == GGML_TYPE_F32) ? GGML_TYPE_BF16 : ffn_t; + if (ll.ctrl_down[1]->type == down_t && ll.ctrl_down[2]->type == down_t && + ll.ctrl_gain[1]->type == up_t && ll.ctrl_gain[2]->type == up_t && + ll.ctrl_forget[0]->type == up_t && ll.ctrl_forget[1]->type == up_t && ll.ctrl_forget[2]->type == up_t && + ll.ctrl_forget[3]->type == ffn_t) { + coalesced[ip].ctrl_down_qkv = ggml_new_tensor_3d(ctx.get(), dst_down_t, 2 * n_embd, rank, 3); + coalesced[ip].ctrl_up_qkv = ggml_new_tensor_3d(ctx.get(), dst_up_t, rank, 2 * n_embd, 3); + coalesced[ip].ctrl_down_ffn = ggml_new_tensor_2d(ctx.get(), dst_fdown_t, 2 * n_embd, rank); + coalesced[ip].ctrl_up_ffn = ggml_new_tensor_2d(ctx.get(), dst_ffn_t, rank, 2 * n_embd); + } + } + std::vector> full_norms; + std::vector> attn_projs; + std::vector> wkv_projs; + std::vector> kvd_projs; + for (int p = 0; p < m.n_phys; ++p) { + const auto & lp = m.layers[p]; + if (!m.hparams.is_swa(p) && lp.attn_q_inp_norm) { + ggml_tensor * t = ggml_new_tensor_2d(ctx.get(), GGML_TYPE_F32, n_embd, 3); + const_cast(m.layers[p]).s19_attn_qkv_inp_norm = t; + full_norms.push_back({ p, t }); + } + if (coal_attn_q8 && can_coal_q8_w(lp.wq) && can_coal_q8_w(lp.wqkv_gate) && can_coal_q8_w(lp.attn_rel)) { + const bool inc_kv = m.hparams.is_swa(p) && can_coal_q8_w(lp.wk) && can_coal_q8_w(lp.wv); + const int64_t m_rows = lp.wq->ne[1] + lp.wqkv_gate->ne[1] + lp.attn_rel->ne[1] + + (inc_kv ? (lp.wk->ne[1] + lp.wv->ne[1]) : 0); + ggml_tensor * t = ggml_new_tensor_2d(ctx.get(), GGML_TYPE_Q8_0, n_embd, m_rows); + const_cast(m.layers[p]).s19_attn_in_proj_q8 = t; + attn_projs.emplace_back(p, t, inc_kv); + } + if (coal_attn_q8 && (!m.hparams.is_swa(p) || (p >= start && p < end)) && + can_coal_q8_w(lp.wk) && can_coal_q8_w(lp.wv) && lp.wk->ne[1] == lp.wv->ne[1]) { + ggml_tensor * t = ggml_new_tensor_3d(ctx.get(), GGML_TYPE_Q8_0, n_embd, lp.wk->ne[1], 2); + const_cast(m.layers[p]).s19_attn_wk_wv_q8 = t; + wkv_projs.push_back({ p, t }); + } + if (!m.hparams.is_swa(p) && can_coal_kvd_pair(lp)) { + ggml_tensor * t = ggml_new_tensor_3d(ctx.get(), lp.attn_k_conv_proj->type, n_embd, lp.attn_k_conv_proj->ne[1], 2); + const_cast(m.layers[p]).s19_attn_kv_conv_proj = t; + kvd_projs.push_back({ p, t }); + } + } + for (int il = m.n_phys; il < (int)m.layers.size(); ++il) { + const int p = m.layer_phys(il); + const_cast(m.layers[il]).s19_attn_qkv_inp_norm = m.layers[p].s19_attn_qkv_inp_norm; + const_cast(m.layers[il]).s19_attn_in_proj_q8 = m.layers[p].s19_attn_in_proj_q8; + const_cast(m.layers[il]).s19_attn_wk_wv_q8 = m.layers[p].s19_attn_wk_wv_q8; + const_cast(m.layers[il]).s19_attn_kv_conv_proj = m.layers[p].s19_attn_kv_conv_proj; + } + + ggml_backend_buffer_type_t buft = ggml_backend_dev_buffer_type(m.dev_layer(start)); + if (!buft) { + buft = ggml_backend_buffer_get_type(ref->buffer); + } + ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors_from_buft(ctx.get(), buft)); + if (!buf) { + for (auto & layer : m.layers) { + const_cast(layer).s19_attn_qkv_inp_norm = nullptr; + const_cast(layer).s19_attn_in_proj_q8 = nullptr; + const_cast(layer).s19_attn_wk_wv_q8 = nullptr; + const_cast(layer).s19_attn_kv_conv_proj = nullptr; + } + } else { + ggml_backend_buffer_set_usage(buf.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS); + + std::vector stage; + std::vector stage_bf16; + const size_t mq_bytes = (size_t)(LOOP_CTRL_COUNT * n_embd * sizeof(float)); + stage.resize(mq_bytes); + for (int li = 0; li < n_loop; ++li) { + ggml_backend_tensor_get(m.loop_layers[li].msg_query, stage.data(), 0, mq_bytes); + ggml_backend_tensor_set(pass_mq, stage.data(), (size_t)li * mq_bytes, mq_bytes); + } + + for (int ip = start; ip < end; ++ip) { + const auto & ll = m.loop_layers[ip - start]; + auto & dst_c = coalesced[ip]; + if (!dst_c.ctrl_down_qkv) { + continue; + } + const size_t down_dst_sl = ggml_nbytes(dst_c.ctrl_down_qkv) / 3; + for (int c = 0; c < 3; ++c) { + s19_upload_ctrl_slice(ll.ctrl_down[c], dst_c.ctrl_down_qkv, (size_t)c * down_dst_sl, stage, stage_bf16); + } + const size_t up_dst_half = ggml_nbytes(dst_c.ctrl_up_qkv) / 6; + for (int c = 0; c < 3; ++c) { + const size_t base = (size_t)c * 2 * up_dst_half; + s19_upload_ctrl_slice(ll.ctrl_gain[c], dst_c.ctrl_up_qkv, base, stage, stage_bf16); + s19_upload_ctrl_slice(ll.ctrl_forget[c], dst_c.ctrl_up_qkv, base + up_dst_half, stage, stage_bf16); + } + s19_upload_ctrl_slice(ll.ctrl_down[3], dst_c.ctrl_down_ffn, 0, stage, stage_bf16); + const size_t ffn_dst_half = ggml_nbytes(dst_c.ctrl_up_ffn) / 2; + s19_upload_ctrl_slice(ll.ctrl_gain[3], dst_c.ctrl_up_ffn, 0, stage, stage_bf16); + s19_upload_ctrl_slice(ll.ctrl_forget[3], dst_c.ctrl_up_ffn, ffn_dst_half, stage, stage_bf16); + } + + const size_t norm_bytes = (size_t)(n_embd * sizeof(float)); + if (stage.size() < 3 * norm_bytes) stage.resize(3 * norm_bytes); + for (const auto & pr : full_norms) { + const auto & l = m.layers[pr.first]; + ggml_backend_tensor_get(l.attn_q_inp_norm, stage.data() + 0 * norm_bytes, 0, norm_bytes); + ggml_backend_tensor_get(l.attn_k_inp_norm, stage.data() + 1 * norm_bytes, 0, norm_bytes); + ggml_backend_tensor_get(l.attn_v_inp_norm, stage.data() + 2 * norm_bytes, 0, norm_bytes); + ggml_backend_tensor_set(pr.second, stage.data(), 0, 3 * norm_bytes); + } + + for (const auto & ap : attn_projs) { + const auto & l = m.layers[std::get<0>(ap)]; + ggml_tensor * dst = std::get<1>(ap); + const bool inc_kv = std::get<2>(ap); + const ggml_tensor * srcs[5] = { l.wq, l.wqkv_gate, l.attn_rel, l.wk, l.wv }; + const int n_srcs = inc_kv ? 5 : 3; + size_t dst_off = 0; + for (int si = 0; si < n_srcs; ++si) { + const size_t nb = ggml_nbytes(srcs[si]); + if (stage.size() < nb) { + stage.resize(nb); + } + ggml_backend_tensor_get(srcs[si], stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), dst_off, nb); + dst_off += nb; + } + } + for (const auto & wp : wkv_projs) { + const auto & l = m.layers[wp.first]; + ggml_tensor * dst = wp.second; + const size_t nb = ggml_nbytes(l.wk); + if (stage.size() < nb) { + stage.resize(nb); + } + ggml_backend_tensor_get(l.wk, stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), 0, nb); + ggml_backend_tensor_get(l.wv, stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), nb, nb); + } + for (const auto & kp : kvd_projs) { + const auto & l = m.layers[kp.first]; + ggml_tensor * dst = kp.second; + const size_t nb = ggml_nbytes(l.attn_k_conv_proj); + if (stage.size() < nb) { + stage.resize(nb); + } + ggml_backend_tensor_get(l.attn_k_conv_proj, stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), 0, nb); + ggml_backend_tensor_get(l.attn_v_conv_proj, stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), nb, nb); + } + + m.s19_inkling_ctx = std::move(ctx); + m.s19_inkling_buf = std::move(buf); + m.s19_pass_msg_query = pass_mq; + m.s19_loop_layers = std::move(coalesced); + m.s19_inkling_ready = true; + } + } + } + auto * cur = build_inputs(); std::vector blocks; @@ -96,11 +358,15 @@ llama_model_inkling2_loop::graph::graph(const llm_graph_params & params) : llama // the bank of the previous pass: its blocks after the first core block, and its output std::vector bank; ggml_tensor * bank_out = nullptr; + ggml_tensor * pass_msgs = nullptr; if (pass > 0) { bank.assign(blocks.begin() + prelude_blocks.size() + 1, blocks.end()); bank_out = cur; cur = prelude; blocks = prelude_blocks; + if (n_tokens <= 64 && !getenv("GGML_INKLING_NO_FUSE") && !getenv("S19_NO_INK_W3") && !getenv("S19_NO_PASS_MSG") && m.s19_inkling_ready && m.s19_pass_msg_query) { + pass_msgs = mix(bank, bank_out, m.s19_pass_msg_query); + } } for (int ip = start; ip < end; ++ip) { const int il = pass == 0 ? ip : m.n_phys + (pass - 1)*(end - start) + (ip - start); @@ -110,7 +376,12 @@ llama_model_inkling2_loop::graph::graph(const llm_graph_params & params) : llama continue; } const auto & loop = m.loop_layers[ip - start]; - cur = build_layer(il, ip, cur, blocks, mix(bank, bank_out, loop.msg_query), &loop); + ggml_tensor * msgs = pass_msgs + ? ggml_view_3d(ctx0, pass_msgs, n_embd, n_tokens, LOOP_CTRL_COUNT, + pass_msgs->nb[1], pass_msgs->nb[2], + (size_t)((ip - start) * LOOP_CTRL_COUNT) * pass_msgs->nb[2]) + : mix(bank, bank_out, loop.msg_query); + cur = build_layer(il, ip, cur, blocks, msgs, &loop); } } diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index bdd1f18d67ed..932859ec7194 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -1,6 +1,234 @@ #include "models.h" #include "../llama-memory-hybrid-iswa.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" + +#include +#include +#include +#include +#include + +// S19_WAVE3: lazily materialize stacked FullAttn Q/K/V input norms & coalesced Q8_0 attention weights for standalone inkling2 +static void s19_ensure_inkling2_norms(const llama_model & model) { + if (model.s19_inkling_ready || getenv("GGML_INKLING_NO_FUSE") || model.layers.empty()) { + return; + } + static std::mutex s19_mtx; + std::lock_guard lock(s19_mtx); + if (model.s19_inkling_ready) { + return; + } + const ggml_tensor * ref = model.layers[0].ffn_norm; + if (!ref || !ref->buffer || !ref->data || ggml_backend_buffer_get_size(ref->buffer) == 0) { + return; + } + const int n_all = (int)model.layers.size(); + const int64_t ne = model.hparams.n_embd; + const bool coal_attn_q8 = !getenv("GGML_INKLING_NO_COAL_ATTN") && model.loras.empty(); + auto can_coal_q8_w = [&](const ggml_tensor * w) -> bool { + return w && w->type == GGML_TYPE_Q8_0 && w->ne[0] == ne && (ne % 32) == 0 && + w->ne[2] == 1 && w->ne[3] == 1 && ggml_is_contiguous(w) && + model.w_scales.find(w) == model.w_scales.end() && model.hdmd.rot.find(w) == model.hdmd.rot.end(); + }; + auto can_coal_kvd_pair = [&](const llama_layer & li) -> bool { + const ggml_tensor * kc = li.attn_k_conv_proj; + const ggml_tensor * vc = li.attn_v_conv_proj; + return coal_attn_q8 && kc && vc && kc->type == vc->type && + (kc->type == GGML_TYPE_BF16 || kc->type == GGML_TYPE_F32) && + kc->ne[0] == ne && vc->ne[0] == ne && kc->ne[1] == vc->ne[1] && + kc->ne[2] == 1 && vc->ne[2] == 1 && kc->ne[3] == 1 && vc->ne[3] == 1 && + ggml_is_contiguous(kc) && ggml_is_contiguous(vc) && + model.w_scales.find(kc) == model.w_scales.end() && model.w_scales.find(vc) == model.w_scales.end() && + model.hdmd.rot.find(kc) == model.hdmd.rot.end() && model.hdmd.rot.find(vc) == model.hdmd.rot.end(); + }; + int n_full = 0; + int n_coal = 0; + int n_wkv = 0; + int n_kvd = 0; + for (int i = 0; i < n_all; ++i) { + if (!model.hparams.is_swa(i) && model.layers[i].attn_q_inp_norm) { + ++n_full; + } + if (coal_attn_q8 && can_coal_q8_w(model.layers[i].wq) && + can_coal_q8_w(model.layers[i].wqkv_gate) && can_coal_q8_w(model.layers[i].attn_rel)) { + ++n_coal; + } + if (coal_attn_q8 && !model.hparams.is_swa(i) && + can_coal_q8_w(model.layers[i].wk) && can_coal_q8_w(model.layers[i].wv) && + model.layers[i].wk->ne[1] == model.layers[i].wv->ne[1]) { + ++n_wkv; + } + if (!model.hparams.is_swa(i) && can_coal_kvd_pair(model.layers[i])) { + ++n_kvd; + } + } + if (n_full == 0 && n_coal == 0 && n_wkv == 0 && n_kvd == 0) { + model.s19_inkling_ready = true; + return; + } + ggml_init_params params = { ggml_tensor_overhead() * (size_t)(n_full + n_coal + n_wkv + n_kvd + 4), nullptr, true }; + ggml_context_ptr ctx(ggml_init(params)); + std::vector> created; + std::vector> created_coal; + std::vector> created_wkv; + std::vector> created_kvd; + for (int i = 0; i < n_all; ++i) { + const auto & li = model.layers[i]; + if (!model.hparams.is_swa(i) && li.attn_q_inp_norm) { + bool dup = false; + for (const auto & pr : created) { + if (model.layers[pr.first].attn_q_inp_norm == li.attn_q_inp_norm) { + const_cast(model.layers[i]).s19_attn_qkv_inp_norm = pr.second; + dup = true; + break; + } + } + if (!dup) { + ggml_tensor * t = ggml_new_tensor_2d(ctx.get(), GGML_TYPE_F32, ne, 3); + const_cast(model.layers[i]).s19_attn_qkv_inp_norm = t; + created.push_back({ i, t }); + } + } + if (coal_attn_q8 && can_coal_q8_w(li.wq) && can_coal_q8_w(li.wqkv_gate) && can_coal_q8_w(li.attn_rel)) { + bool dup = false; + for (const auto & ap : created_coal) { + if (model.layers[std::get<0>(ap)].wq == li.wq) { + const_cast(model.layers[i]).s19_attn_in_proj_q8 = std::get<1>(ap); + dup = true; + break; + } + } + if (!dup) { + const bool inc_kv = model.hparams.is_swa(i) && can_coal_q8_w(li.wk) && can_coal_q8_w(li.wv); + const int64_t m_rows = li.wq->ne[1] + li.wqkv_gate->ne[1] + li.attn_rel->ne[1] + + (inc_kv ? (li.wk->ne[1] + li.wv->ne[1]) : 0); + ggml_tensor * t = ggml_new_tensor_2d(ctx.get(), GGML_TYPE_Q8_0, ne, m_rows); + const_cast(model.layers[i]).s19_attn_in_proj_q8 = t; + created_coal.emplace_back(i, t, inc_kv); + } + } + if (coal_attn_q8 && !model.hparams.is_swa(i) && + can_coal_q8_w(li.wk) && can_coal_q8_w(li.wv) && li.wk->ne[1] == li.wv->ne[1]) { + bool dup = false; + for (const auto & wp : created_wkv) { + if (model.layers[wp.first].wk == li.wk) { + const_cast(model.layers[i]).s19_attn_wk_wv_q8 = wp.second; + dup = true; + break; + } + } + if (!dup) { + ggml_tensor * t = ggml_new_tensor_3d(ctx.get(), GGML_TYPE_Q8_0, ne, li.wk->ne[1], 2); + const_cast(model.layers[i]).s19_attn_wk_wv_q8 = t; + created_wkv.push_back({ i, t }); + } + } + if (!model.hparams.is_swa(i) && can_coal_kvd_pair(li)) { + bool dup = false; + for (const auto & kp : created_kvd) { + if (model.layers[kp.first].attn_k_conv_proj == li.attn_k_conv_proj) { + const_cast(model.layers[i]).s19_attn_kv_conv_proj = kp.second; + dup = true; + break; + } + } + if (!dup) { + ggml_tensor * t = ggml_new_tensor_3d(ctx.get(), li.attn_k_conv_proj->type, ne, li.attn_k_conv_proj->ne[1], 2); + const_cast(model.layers[i]).s19_attn_kv_conv_proj = t; + created_kvd.push_back({ i, t }); + } + } + } + ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(ref->buffer); + ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors_from_buft(ctx.get(), buft)); + if (!buf) { + for (int i = 0; i < n_all; ++i) { + const_cast(model.layers[i]).s19_attn_qkv_inp_norm = nullptr; + const_cast(model.layers[i]).s19_attn_in_proj_q8 = nullptr; + const_cast(model.layers[i]).s19_attn_wk_wv_q8 = nullptr; + const_cast(model.layers[i]).s19_attn_kv_conv_proj = nullptr; + } + return; + } + ggml_backend_buffer_set_usage(buf.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS); + std::vector stage((size_t)(3 * ne * sizeof(float))); + const size_t row_bytes = (size_t)(ne * sizeof(float)); + for (const auto & pr : created) { + const auto & l = model.layers[pr.first]; + ggml_backend_tensor_get(l.attn_q_inp_norm, stage.data() + 0 * row_bytes, 0, row_bytes); + ggml_backend_tensor_get(l.attn_k_inp_norm, stage.data() + 1 * row_bytes, 0, row_bytes); + ggml_backend_tensor_get(l.attn_v_inp_norm, stage.data() + 2 * row_bytes, 0, row_bytes); + ggml_backend_tensor_set(pr.second, stage.data(), 0, 3 * row_bytes); + } + for (const auto & ap : created_coal) { + const auto & l = model.layers[std::get<0>(ap)]; + ggml_tensor * dst = std::get<1>(ap); + const bool inc_kv = std::get<2>(ap); + const ggml_tensor * srcs[5] = { l.wq, l.wqkv_gate, l.attn_rel, l.wk, l.wv }; + const int n_srcs = inc_kv ? 5 : 3; + size_t dst_off = 0; + for (int si = 0; si < n_srcs; ++si) { + const size_t nb = ggml_nbytes(srcs[si]); + if (stage.size() < nb) { + stage.resize(nb); + } + ggml_backend_tensor_get(srcs[si], stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), dst_off, nb); + dst_off += nb; + } + } + for (const auto & wp : created_wkv) { + const auto & l = model.layers[wp.first]; + ggml_tensor * dst = wp.second; + const size_t nb = ggml_nbytes(l.wk); + if (stage.size() < nb) { + stage.resize(nb); + } + ggml_backend_tensor_get(l.wk, stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), 0, nb); + ggml_backend_tensor_get(l.wv, stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), nb, nb); + } + for (const auto & kp : created_kvd) { + const auto & l = model.layers[kp.first]; + ggml_tensor * dst = kp.second; + const size_t nb = ggml_nbytes(l.attn_k_conv_proj); + if (stage.size() < nb) { + stage.resize(nb); + } + ggml_backend_tensor_get(l.attn_k_conv_proj, stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), 0, nb); + ggml_backend_tensor_get(l.attn_v_conv_proj, stage.data(), 0, nb); + ggml_backend_tensor_set(dst, stage.data(), nb, nb); + } + model.s19_inkling_ctx = std::move(ctx); + model.s19_inkling_buf = std::move(buf); + model.s19_inkling_ready = true; +} + +static ggml_tensor * s19_inkling_mix_rms( + ggml_context * ctx0, + const std::vector & blocks, + ggml_tensor * cur, + ggml_tensor * query, + ggml_tensor * rms_w, + float rms_eps) { + GGML_ASSERT(blocks.size() + 1 <= 6); + ggml_tensor * st[6] = {}; + const size_t nb_blk = blocks.size(); + for (size_t i = 0; i < nb_blk; ++i) { + st[i] = blocks[nb_blk - 1 - i]; + } + st[nb_blk] = cur; + return ggml_inkling_depth_mix_rms(ctx0, st, (int)(nb_blk + 1), query, rms_w, 1e-6f, rms_eps); +} + +// max elements of the dense relative bias per attention call, and max chunks per layer +static constexpr int64_t n_kq_bias_max = int64_t(1) << 29; +static constexpr int64_t n_kq_chunk_max = 64; + void llama_model_inkling2::load_arch_hparams(llama_model_loader & ml) { ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); ml.get_key(LLM_KV_ATTENTION_QK_CLIP, hparams.f_qk_clip); @@ -162,13 +390,17 @@ std::unique_ptr llama_model_inkling2::build_arch_graph(const } // scale each row down to an L2 norm of at most threshold, after the optional per-channel scale -ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * scale, float threshold) { +ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * scale, float threshold, ggml_tensor * mul_tau) { + if (!getenv("GGML_INKLING_NO_FUSE")) { + return ggml_inkling_l2_clip(ctx0, cur, scale, mul_tau, threshold, 1e-6f); + } if (scale) { cur = ggml_mul(ctx0, cur, scale); } // x*min(1, t/|x|) = t*x/max(|x|, t), and l2_norm(x, eps) = x/max(|x|, eps) - return ggml_scale(ctx0, ggml_l2_norm(ctx0, cur, threshold), threshold); + ggml_tensor * res = ggml_scale(ctx0, ggml_l2_norm(ctx0, cur, threshold), threshold); + return mul_tau ? ggml_mul(ctx0, res, mul_tau) : res; } // the normalized states of list, last first: [norm(l_n-1), ..., norm(l_0)] @@ -188,7 +420,19 @@ ggml_tensor * llama_model_inkling2::graph::mix_stack(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query) { + if (!getenv("GGML_INKLING_NO_FUSE") && blocks.size() + 1 <= 6) { + ggml_tensor * st[6] = {}; + const size_t nb_blk = blocks.size(); + // Exact reverse-prepended order (blocks.reverse ++ [cur]) + for (size_t i = 0; i < nb_blk; ++i) { + st[i] = blocks[nb_blk - 1 - i]; + } + st[nb_blk] = cur; + return ggml_inkling_depth_mix(ctx0, st, (int)(nb_blk + 1), query, 1e-6f); + } + // [norm(b_n-1), ..., norm(b_0), norm(cur)] ggml_tensor * states = mix_stack({cur}); if (!blocks.empty()) { @@ -202,7 +446,9 @@ ggml_tensor * llama_model_inkling2::graph::mix(const std::vector ggml_tensor * scores = ggml_mul_mat(ctx0, states, queries); scores = ggml_soft_max_ext(ctx0, scores, nullptr, 1.0f/sqrtf(n_embd), 0.0f); - return ggml_mul_mat(ctx0, scores, ggml_cont(ctx0, ggml_transpose(ctx0, states))); // [n_queries, n_embd, n_tokens] + // [n_queries, n_embd, n_tokens] -> [n_embd, n_tokens, n_queries] + ggml_tensor * out = ggml_mul_mat(ctx0, scores, ggml_cont(ctx0, ggml_transpose(ctx0, states))); + return ggml_cont(ctx0, ggml_permute(ctx0, out, 2, 0, 1, 3)); } // causal short convolution with a residual; dynamic adds input-dependent taps per head @@ -220,6 +466,40 @@ ggml_tensor * llama_model_inkling2::graph::convolve( const int64_t n_seq_tokens = ubatch.n_seq_tokens; const int64_t n_seqs = ubatch.n_seqs; + if (cur->ne[2] > 1 || cur->ne[1] != n_tokens) { + const bool fuse_conv_sum = !getenv("GGML_INKLING_NO_FUSE") && !getenv("GGML_VK_DISABLE_S19_CONV_SUM") && + n_conv == 4 && n_seq_tokens <= 16 && inp != nullptr; + if (!fuse_conv_sum) { + const int64_t n_exp = cur->ne[1]; + ggml_tensor * s = ggml_view_2d(ctx0, cur, n_channels, n_tokens, cur->nb[2], 0); + for (int64_t e = 1; e < n_exp; ++e) { + s = ggml_add(ctx0, s, ggml_view_2d(ctx0, cur, n_channels, n_tokens, cur->nb[2], e * cur->nb[1])); + } + cur = s; + } + } + if (!getenv("GGML_INKLING_NO_FUSE") && n_conv == 4) { + const auto * mctx_cur = inp->mctx; + const size_t row_size = state->nb[1]; + const size_t cell_offs = mctx_cur->get_head() * row_size + offset * (n_conv - 1) * sizeof(float); + const int64_t K = cparams.n_rs_seq == 0 ? 1 : ((int64_t)cparams.n_rs_seq + 1); + const int64_t Kw = std::min(n_seq_tokens, K); + const int32_t n_heads = dynamic ? (int32_t)(dynamic->ne[0] / n_conv) : 0; + const float scale_out = 1.0f / sqrtf((dynamic ? 2 : 1) * n_conv + 1); + ggml_tensor * conv = ggml_inkling_conv( + ctx0, cur, history, weight, dynamic, state, + (int32_t)offset, (int32_t)n_seq_tokens, (int32_t)n_seqs, n_heads, + (int32_t)(cell_offs / sizeof(float)), + (int32_t)(row_size / sizeof(float)), + (int32_t)(((size_t)mctx_cur->get_size() * row_size) / sizeof(float)), + (int32_t)Kw, scale_out); + const ggml_tensor * vs = history ? history->view_src : nullptr; + if (inp && inp->s_copy && n_seq_tokens <= 16 && !getenv("S19_NO_SCOPY_BIND") && vs == state) { + conv->src[6] = inp->s_copy; + } + return conv; + } + ggml_tensor * past = ggml_view_3d(ctx0, history, n_conv - 1, n_channels, n_seqs, history->nb[1], history->nb[2], offset*history->nb[1]); ggml_tensor * x = ggml_transpose(ctx0, ggml_reshape_3d(ctx0, cur, n_channels, n_seq_tokens, n_seqs)); @@ -253,6 +533,13 @@ ggml_tensor * llama_model_inkling2::graph::convolve( // mix a cross-pass message into a looped layer input: (1 - forget)*cur + gain*message, both gated on cur and message ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tensor * message, const loop_layer & loop, int ctrl) { + if (!getenv("GGML_INKLING_NO_FUSE")) { + ggml_tensor * gate = ggml_inkling_rms2_concat(ctx0, cur, message, 1e-6f); + gate = build_lora_mm(loop.ctrl_down[ctrl], gate); + ggml_tensor * raw_gain = build_lora_mm(loop.ctrl_gain[ctrl], gate); + ggml_tensor * raw_forget = build_lora_mm(loop.ctrl_forget[ctrl], gate); + return ggml_inkling_ctrl_apply(ctx0, cur, message, raw_gain, raw_forget); + } // cur and message as two rows of one rms_norm, then side by side: [norm(cur); norm(message)] ggml_tensor * gate = ggml_concat(ctx0, ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens), ggml_reshape_3d(ctx0, message, n_embd, 1, n_tokens), 1); gate = ggml_reshape_2d(ctx0, ggml_rms_norm(ctx0, gate, 1e-6f), 2*n_embd, n_tokens); @@ -291,6 +578,9 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens ggml_tensor * messages, const loop_layer * loop) { GGML_ASSERT(!messages == !loop); + if (!model.s19_inkling_ready && !messages) { + s19_ensure_inkling2_norms(model); + } const auto & layer = model.layers[il]; const bool is_swa = hparams.is_swa(il); @@ -299,101 +589,366 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens const int64_t n_embd_head = hparams.n_embd_head_k(il); const int64_t n_embd_k_gqa = n_embd_head*n_head_kv; - // the message of controller ctrl, [n_embd, n_tokens] + // the message of controller ctrl, [n_embd, n_tokens] (contiguous slice of [n_embd, n_tokens, LOOP_CTRL_COUNT]!) auto message = [&](int ctrl) { - return ggml_reshape_2d(ctx0, ggml_cont(ctx0, ggml_view_3d(ctx0, messages, 1, n_embd, n_tokens, messages->nb[1], messages->nb[2], ctrl*messages->nb[0])), n_embd, n_tokens); + return ggml_view_2d(ctx0, messages, n_embd, n_tokens, messages->nb[1], ctrl*messages->nb[2]); }; ggml_tensor * state = recr->mctx->get_r_l(il); - ggml_tensor * history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); - history = ggml_reshape_3d(ctx0, history, hparams.n_shortconv_l_cache - 1, hparams.n_sconv_channels, ubatch.n_seqs); + ggml_tensor * history = nullptr; + const bool direct_scopy = recr && recr->s_copy && hparams.n_shortconv_l_cache == 4 && + recr->direct_scopy && + !getenv("GGML_INKLING_NO_FUSE") && !getenv("S19_NO_SCOPY_BIND"); + if (direct_scopy) { + ggml_tensor * states = ggml_reshape_2d(ctx0, state, hparams.n_embd_r(), state->ne[1]); + const int32_t rs_zero = recr->mctx->get_rs_z(); + ggml_tensor * state_zero = ggml_view_1d(ctx0, states, hparams.n_embd_r() * (rs_zero >= 0), rs_zero * states->nb[1] * (rs_zero >= 0)); + ggml_build_forward_expand(gf, ggml_fill_inplace(ctx0, state_zero, 0.0f)); + history = ggml_view_3d(ctx0, state, hparams.n_shortconv_l_cache - 1, hparams.n_sconv_channels, ubatch.n_seqs, + (hparams.n_shortconv_l_cache - 1) * sizeof(float), state->nb[1], + (size_t)recr->mctx->get_head() * state->nb[1]); + } else { + history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); + history = ggml_reshape_3d(ctx0, history, hparams.n_shortconv_l_cache - 1, hparams.n_sconv_channels, ubatch.n_seqs); + } ggml_tensor * inpSA = cur; + const bool fuse_s19 = n_tokens <= 4096 && !getenv("GGML_INKLING_NO_FUSE") && !getenv("S19_NO_INK_W3") && blocks.size() + 1 <= 6 && model.s19_inkling_ready; + const bool fuse_mix_rms = fuse_s19 && !getenv("S19_NO_MIX_RMS"); + const bool has_s19_loop = fuse_s19 && !getenv("S19_NO_CTRL_RMS") && messages && n_tokens <= 4096 && model.loras.empty() && + ip >= 0 && (size_t)ip < model.s19_loop_layers.size() && + model.s19_loop_layers[ip].ctrl_down_qkv != nullptr; + // attention inputs: SWA layers mix one, full-attention layers one each for Q, K and V ggml_tensor * inputs[3] = {cur, cur, cur}; - if (layer.attn_res_query) { - ggml_tensor * mixed = mix(blocks, cur, layer.attn_res_query); + ggml_tensor * kv_in_3d = nullptr; + ggml_tensor * qkv_rms_w = is_swa ? layer.attn_norm : layer.s19_attn_qkv_inp_norm; + if (!messages && fuse_mix_rms && layer.attn_res_query && qkv_rms_w) { + ggml_tensor * mixed = s19_inkling_mix_rms(ctx0, blocks, cur, layer.attn_res_query, qkv_rms_w, hparams.f_norm_rms_eps); + if (is_swa) { + inputs[0] = ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[1], 0); + inputs[1] = inputs[2] = inputs[0]; + } else { + for (int j = 0; j < 3; ++j) { + inputs[j] = ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[1], j*mixed->nb[2]); + } + kv_in_3d = ggml_view_3d(ctx0, mixed, n_embd, n_tokens, 2, mixed->nb[1], mixed->nb[2], mixed->nb[2]); + } + } else if (has_s19_loop && layer.attn_res_query && qkv_rms_w) { + const auto & s19_l = model.s19_loop_layers[ip]; + ggml_tensor * mixed = mix(blocks, cur, layer.attn_res_query); + ggml_tensor * msgs_qkv = ggml_view_3d(ctx0, messages, n_embd, n_tokens, 3, messages->nb[1], messages->nb[2], 0); + ggml_tensor * gate_in = ggml_inkling_rms2_concat(ctx0, mixed, msgs_qkv, 1e-6f); + ggml_tensor * gate = ggml_mul_mat(ctx0, s19_l.ctrl_down_qkv, gate_in); + ggml_tensor * up_gf = ggml_mul_mat(ctx0, s19_l.ctrl_up_qkv, gate); + ggml_tensor * normed = ggml_inkling_ctrl_apply_rms_mul(ctx0, mixed, msgs_qkv, up_gf, qkv_rms_w, hparams.f_norm_rms_eps); for (int j = 0; j < 3; ++j) { - inputs[j] = ggml_reshape_2d(ctx0, ggml_cont(ctx0, ggml_view_3d(ctx0, mixed, 1, n_embd, n_tokens, mixed->nb[1], mixed->nb[2], (is_swa ? 0 : j)*mixed->nb[0])), n_embd, n_tokens); + inputs[j] = ggml_view_2d(ctx0, normed, n_embd, n_tokens, normed->nb[1], j*normed->nb[2]); + } + kv_in_3d = ggml_view_3d(ctx0, normed, n_embd, n_tokens, 2, normed->nb[1], normed->nb[2], normed->nb[2]); + } else { + if (layer.attn_res_query) { + ggml_tensor * mixed = mix(blocks, cur, layer.attn_res_query); + for (int j = 0; j < 3; ++j) { + inputs[j] = ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[1], (is_swa ? 0 : j)*mixed->nb[2]); + } } - } - if (messages) { - // the messages make the Q, K and V inputs of a SWA layer differ - for (int j = 0; j < 3; ++j) { - inputs[j] = control(inputs[j], message(LOOP_CTRL_Q + j), *loop, LOOP_CTRL_Q + j); + if (messages) { + // the messages make the Q, K and V inputs of a SWA layer differ + for (int j = 0; j < 3; ++j) { + inputs[j] = control(inputs[j], message(LOOP_CTRL_Q + j), *loop, LOOP_CTRL_Q + j); + } } - } - if (is_swa && messages) { - for (int j = 0; j < 3; ++j) { - inputs[j] = build_norm(inputs[j], layer.attn_norm, nullptr, LLM_NORM_RMS, il); + if (is_swa && messages) { + for (int j = 0; j < 3; ++j) { + inputs[j] = build_norm(inputs[j], layer.attn_norm, nullptr, LLM_NORM_RMS, il); + } + } else if (is_swa) { + inputs[0] = build_norm(inputs[0], layer.attn_norm, nullptr, LLM_NORM_RMS, il); + inputs[1] = inputs[2] = inputs[0]; + } else { + inputs[0] = build_norm(inputs[0], layer.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[1] = build_norm(inputs[1], layer.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[2] = build_norm(inputs[2], layer.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); } - } else if (is_swa) { - inputs[0] = build_norm(inputs[0], layer.attn_norm, nullptr, LLM_NORM_RMS, il); - inputs[1] = inputs[2] = inputs[0]; - } else { - inputs[0] = build_norm(inputs[0], layer.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[1] = build_norm(inputs[1], layer.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[2] = build_norm(inputs[2], layer.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); } // self-attention { - ggml_tensor * Qcur = build_lora_mm(layer.wq, inputs[0]); - ggml_tensor * Kcur = convolve(build_lora_mm(layer.wk, inputs[1]), layer.attn_k_conv, - is_swa ? nullptr : build_lora_mm(layer.attn_k_conv_proj, inputs[1]), state, history, recr, 0); - ggml_tensor * Vcur = convolve(build_lora_mm(layer.wv, inputs[2]), layer.attn_v_conv, - is_swa ? nullptr : build_lora_mm(layer.attn_v_conv_proj, inputs[2]), state, history, recr, n_embd_k_gqa); - ggml_tensor * Rcur = build_lora_mm(layer.attn_rel, inputs[0]); - - Qcur = clip(ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), layer.attn_q_clip, hparams.f_qk_clip); - Kcur = clip(ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), nullptr, hparams.f_qk_clip); - Vcur = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens), hparams.f_norm_rms_eps); - Rcur = clip(ggml_reshape_3d(ctx0, Rcur, hparams.n_relative, n_head, n_tokens), layer.attn_rel_clip, hparams.f_relative_clip); + const int64_t m_q = layer.wq->ne[1]; + const int64_t m_qg = layer.wqkv_gate->ne[1]; + const int64_t m_rel = layer.attn_rel->ne[1]; + const int64_t m_qgr = m_q + m_qg + m_rel; + const int64_t m_k = layer.wk->ne[1]; + const int64_t m_v = layer.wv->ne[1]; + const bool use_coal_q8 = layer.s19_attn_in_proj_q8 != nullptr && model.loras.empty() && + !getenv("GGML_INKLING_NO_FUSE") && !getenv("GGML_INKLING_NO_COAL_ATTN"); + + ggml_tensor * Qcur = nullptr; + ggml_tensor * Q3 = nullptr; + ggml_tensor * Qgate = nullptr; + ggml_tensor * Qgate_raw_2d = nullptr; + ggml_tensor * Rcur = nullptr; + ggml_tensor * R3 = nullptr; + ggml_tensor * sinks = nullptr; + ggml_tensor * Kraw = nullptr; + ggml_tensor * Kdyn = nullptr; + ggml_tensor * Vraw = nullptr; + ggml_tensor * Vdyn = nullptr; + + if (use_coal_q8) { + const bool coal_has_kv = (inputs[0] == inputs[1] && inputs[0] == inputs[2]) && + (layer.s19_attn_in_proj_q8->ne[1] == m_qgr + m_k + m_v); + ggml_tensor * w_in = coal_has_kv + ? layer.s19_attn_in_proj_q8 + : (layer.s19_attn_in_proj_q8->ne[1] == m_qgr + ? layer.s19_attn_in_proj_q8 + : ggml_view_2d(ctx0, layer.s19_attn_in_proj_q8, n_embd, m_qgr, layer.s19_attn_in_proj_q8->nb[1], 0)); + ggml_tensor * mm_in = ggml_mul_mat(ctx0, w_in, inputs[0]); + Q3 = ggml_view_3d(ctx0, mm_in, n_embd_head, n_head, n_tokens, + n_embd_head * sizeof(float), mm_in->nb[1], 0); + Qgate_raw_2d = ggml_view_2d(ctx0, mm_in, m_qg, n_tokens, + n_tokens == 1 ? (size_t)m_qg * sizeof(float) : mm_in->nb[1], + (size_t)m_q * sizeof(float)); + R3 = ggml_view_3d(ctx0, mm_in, hparams.n_relative, n_head, n_tokens, + hparams.n_relative * sizeof(float), mm_in->nb[1], (size_t)(m_q + m_qg) * sizeof(float)); + if (coal_has_kv) { + Kraw = ggml_view_2d(ctx0, mm_in, m_k, n_tokens, mm_in->nb[1], (size_t)m_qgr * sizeof(float)); + Vraw = ggml_view_2d(ctx0, mm_in, m_v, n_tokens, mm_in->nb[1], (size_t)(m_qgr + m_k) * sizeof(float)); + } else if (kv_in_3d && layer.s19_attn_wk_wv_q8 && !getenv("GGML_INKLING_NO_COAL_WKV")) { + ggml_tensor * mm_kv = ggml_mul_mat(ctx0, layer.s19_attn_wk_wv_q8, kv_in_3d); + Kraw = ggml_view_2d(ctx0, mm_kv, m_k, n_tokens, mm_kv->nb[1], 0); + Vraw = ggml_view_2d(ctx0, mm_kv, m_v, n_tokens, mm_kv->nb[1], mm_kv->nb[2]); + } else { + Kraw = build_lora_mm(layer.wk, inputs[1]); + Vraw = build_lora_mm(layer.wv, inputs[2]); + } + sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); + if (!is_swa) { + if (kv_in_3d && layer.s19_attn_kv_conv_proj && !getenv("GGML_INKLING_NO_COAL_WKV")) { + ggml_tensor * mm_kvd = ggml_mul_mat(ctx0, layer.s19_attn_kv_conv_proj, kv_in_3d); + Kdyn = ggml_view_2d(ctx0, mm_kvd, layer.attn_k_conv_proj->ne[1], n_tokens, mm_kvd->nb[1], 0); + Vdyn = ggml_view_2d(ctx0, mm_kvd, layer.attn_v_conv_proj->ne[1], n_tokens, mm_kvd->nb[1], mm_kvd->nb[2]); + } else { + Kdyn = build_lora_mm(layer.attn_k_conv_proj, inputs[1]); + Vdyn = build_lora_mm(layer.attn_v_conv_proj, inputs[2]); + } + } + } else { + Qcur = build_lora_mm(layer.wq, inputs[0]); + ggml_tensor * Qgate_raw = build_lora_mm(layer.wqkv_gate, inputs[0]); + Qgate = ggml_sigmoid(ctx0, Qgate_raw); + if (n_tokens <= 8 && !getenv("S19_NO_WKV_REORDER")) { + Kraw = build_lora_mm(layer.wk, inputs[1]); + Vraw = build_lora_mm(layer.wv, inputs[2]); + Rcur = build_lora_mm(layer.attn_rel, inputs[0]); + sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); + Kdyn = is_swa ? nullptr : build_lora_mm(layer.attn_k_conv_proj, inputs[1]); + Vdyn = is_swa ? nullptr : build_lora_mm(layer.attn_v_conv_proj, inputs[2]); + } else { + Rcur = build_lora_mm(layer.attn_rel, inputs[0]); + sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); + Kraw = build_lora_mm(layer.wk, inputs[1]); + Kdyn = is_swa ? nullptr : build_lora_mm(layer.attn_k_conv_proj, inputs[1]); + Vraw = build_lora_mm(layer.wv, inputs[2]); + Vdyn = is_swa ? nullptr : build_lora_mm(layer.attn_v_conv_proj, inputs[2]); + } + Q3 = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens); + R3 = ggml_reshape_3d(ctx0, Rcur, hparams.n_relative, n_head, n_tokens); + } - if (!is_swa) { - Qcur = ggml_mul(ctx0, Qcur, tau); - Rcur = ggml_mul(ctx0, Rcur, tau); + ggml_tensor * Kcur = convolve(Kraw, layer.attn_k_conv, Kdyn, state, history, recr, 0); + ggml_tensor * Vcur = convolve(Vraw, layer.attn_v_conv, Vdyn, state, history, recr, n_embd_k_gqa); + + ggml_tensor * opt_tau = is_swa ? nullptr : tau; + if (!getenv("GGML_VK_DISABLE_S19_CLIP_QR") && !getenv("GGML_INKLING_NO_FUSE") && !getenv("S19_NO_INK_W3")) { + ggml_tensor * qr_clip = ggml_inkling_l2_clip_qr( + ctx0, Q3, R3, layer.attn_q_clip, layer.attn_rel_clip, opt_tau, + hparams.f_qk_clip, hparams.f_relative_clip, 1e-6f); + Qcur = ggml_view_3d(ctx0, qr_clip, n_embd_head, n_head, n_tokens, + n_embd_head * sizeof(float), n_embd_head * n_head * sizeof(float), 0); + Rcur = ggml_view_3d(ctx0, qr_clip, hparams.n_relative, n_head, n_tokens, + hparams.n_relative * sizeof(float), hparams.n_relative * n_head * sizeof(float), + (size_t)(n_embd_head * n_head * n_tokens) * sizeof(float)); + } else { + if (!ggml_is_contiguous(Q3)) { + Q3 = ggml_cont(ctx0, Q3); + } + if (!ggml_is_contiguous(R3)) { + R3 = ggml_cont(ctx0, R3); + } + Qcur = clip(Q3, layer.attn_q_clip, hparams.f_qk_clip, opt_tau); + Rcur = clip(R3, layer.attn_rel_clip, hparams.f_relative_clip, opt_tau); } + Kcur = clip(ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), nullptr, hparams.f_qk_clip, nullptr); + Vcur = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens), hparams.f_norm_rms_eps); cb(Qcur, "Qcur", il); cb(Kcur, "Kcur", il); cb(Vcur, "Vcur", il); cb(Rcur, "Rcur", il); - ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; - - const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; - const int64_t n_kv = rel_pos->ne[0]; - - ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); - - // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head - ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); - - // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink - table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); - table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); - - ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); - kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); - kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); - cb(kq_b, "kq_b", il); - - // one zero tensor per head count for the whole graph - ggml_tensor *& zero = zero_sinks[n_head]; - if (!zero) { - zero = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; + ggml_tensor * rel_pos_pack = is_swa ? inp->self_rel_pos_pack_swa : inp->self_rel_pos_pack; + + const ggml_tensor * raw_mask = is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw; + const int64_t n_stream = raw_mask->ne[3]; + const int64_t n_kv = raw_mask->ne[0]; + + const int64_t n_extent = layer.attn_rel_bias->ne[1]; + const int64_t n_seq_tokens = n_tokens/n_stream; + const bool fuse_rel = !getenv("GGML_INKLING_NO_FUSE"); + const bool use_banded_fa = cparams.flash_attn && fuse_rel && rel_pos_pack != nullptr && !getenv("GGML_INKLING_LEGACY_KQB"); + + ggml_tensor * sinks_raw = sinks; + ggml_tensor * table = nullptr; + int64_t eff_rows = n_extent; + ggml_tensor * rel_bias_v = layer.attn_rel_bias; + if (fuse_rel) { + if (!is_swa && ubatch.pos != nullptr && ubatch.n_tokens > 0) { + llama_pos max_p = 0; + bool non_neg = true; + for (uint32_t ti = 0; ti < ubatch.n_tokens; ++ti) { + if (ubatch.pos[ti] < 0) { non_neg = false; break; } + if (ubatch.pos[ti] > max_p) max_p = ubatch.pos[ti]; + } + if (non_neg) { + eff_rows = std::min(n_extent, std::max(256, GGML_PAD((int64_t)max_p + 1, 256))); + } + } + rel_bias_v = eff_rows < n_extent + ? ggml_view_2d(ctx0, layer.attn_rel_bias, layer.attn_rel_bias->ne[0], eff_rows, layer.attn_rel_bias->nb[1], 0) + : layer.attn_rel_bias; + } + auto mul_rel_bias = [&](ggml_tensor * rb, ggml_tensor * rc) -> ggml_tensor * { + if (rc->ne[2] >= 32 && ggml_is_contiguous(rc) && !getenv("GGML_INKLING_NO_FLAT_REL")) { + ggml_tensor * rc2 = ggml_reshape_2d(ctx0, rc, rc->ne[0], rc->ne[1] * rc->ne[2]); + ggml_tensor * tb2 = ggml_mul_mat(ctx0, rb, rc2); + return ggml_reshape_3d(ctx0, tb2, rb->ne[1], rc->ne[1], rc->ne[2]); + } + return ggml_mul_mat(ctx0, rb, rc); + }; + + if (use_banded_fa) { + table = mul_rel_bias(rel_bias_v, Rcur); + cur = build_attn(inp, + nullptr, nullptr, nullptr, + Qcur, Kcur, Vcur, nullptr, sinks_raw, 1.0f/sqrtf(n_embd_head), il, 0, + table, rel_pos_pack, (int32_t) n_extent); + } else { + const int64_t n_kv_max = std::max(n_kv, (is_swa ? attn->mctx->get_swa() : attn->mctx->get_base())->get_size()); + int64_t n_rows_max = std::max({ int64_t(1), n_kq_bias_max/(n_kv_max*n_head*n_stream), + (n_seq_tokens + n_kq_chunk_max - 1)/n_kq_chunk_max }); + if (n_rows_max < n_seq_tokens) { + const int64_t n_chunks = (n_seq_tokens + n_rows_max - 1)/n_rows_max; + n_rows_max = std::min(n_seq_tokens, GGML_PAD((n_seq_tokens + n_chunks - 1)/n_chunks, 64)); + } + auto rows = [&](ggml_tensor * t, int d, int64_t r0, int64_t nr) { + int64_t ne[4] = { t->ne[0], t->ne[1], t->ne[2], t->ne[3] }; + ne[d] = nr; + return ggml_cont(ctx0, ggml_view_4d(ctx0, t, ne[0], ne[1], ne[2], ne[3], t->nb[1], t->nb[2], t->nb[3], r0*t->nb[d])); + }; + + const bool chunk_table = fuse_rel && (n_rows_max < n_seq_tokens) && + (eff_rows * n_head * n_tokens * (int64_t)sizeof(float) > (256LL << 20)); + if (fuse_rel) { + if (!chunk_table) { + table = mul_rel_bias(rel_bias_v, Rcur); + } + } else { + table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); + table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks_raw, 1, n_head, n_tokens)); + table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); + } + + // one zero tensor per head count for the whole graph + ggml_tensor *& zero = zero_sinks[n_head]; + if (!zero) { + zero = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + } + sinks = zero; + + std::vector outs; + for (int64_t r0 = 0; r0 < n_seq_tokens; r0 += n_rows_max) { + const int64_t nr = std::min(n_rows_max, n_seq_tokens - r0); + const bool all = nr == n_seq_tokens; + ggml_tensor * q_c = Qcur; + ggml_tensor * kq_b = nullptr; + if (fuse_rel) { + ggml_tensor *& rel_pos_dev = inp->self_rel_pos_dev[is_swa]; + if (!rel_pos_dev) { + rel_pos_dev = ggml_cont(ctx0, rel_pos); + } + if (!all) { + q_c = ggml_reshape_3d(ctx0, rows(ggml_reshape_4d(ctx0, Qcur, n_embd_head, n_head, n_seq_tokens, n_stream), 2, r0, nr), + n_embd_head, n_head, nr*n_stream); + } + if (chunk_table) { + ggml_tensor * Rcur_c = n_stream == 1 + ? ggml_view_3d(ctx0, Rcur, hparams.n_relative, n_head, nr, Rcur->nb[1], Rcur->nb[2], r0 * Rcur->nb[2]) + : ggml_reshape_3d(ctx0, rows(ggml_reshape_4d(ctx0, Rcur, hparams.n_relative, n_head, n_seq_tokens, n_stream), 2, r0, nr), + hparams.n_relative, n_head, nr*n_stream); + ggml_tensor * table_c = ggml_mul_mat(ctx0, rel_bias_v, Rcur_c); + ggml_tensor * sinks_c = n_stream == 1 + ? ggml_view_2d(ctx0, sinks_raw, n_head, nr, sinks_raw->nb[1], r0 * sinks_raw->nb[1]) + : ggml_reshape_2d(ctx0, rows(ggml_reshape_4d(ctx0, sinks_raw, n_head, 1, n_seq_tokens, n_stream), 2, r0, nr), + n_head, nr*n_stream); + ggml_tensor * rel_pos_c = n_stream == 1 + ? ggml_view_2d(ctx0, rel_pos_dev, n_kv, nr, rel_pos_dev->nb[1], r0 * rel_pos_dev->nb[1]) + : ggml_reshape_2d(ctx0, rows(ggml_reshape_4d(ctx0, rel_pos_dev, n_kv, 1, n_seq_tokens, n_stream), 2, r0, nr), + n_kv, nr*n_stream); + kq_b = ggml_inkling_rel_gather(ctx0, table_c, sinks_c, rel_pos_c, n_kv, nr, n_head, n_stream, + (int32_t)nr, 0, (int32_t)n_extent); + } else { + kq_b = ggml_inkling_rel_gather(ctx0, table, sinks_raw, rel_pos_dev, n_kv, nr, n_head, n_stream, + (int32_t)n_seq_tokens, (int32_t)r0, (int32_t)n_extent); + } + } else if (all) { + kq_b = ggml_get_rows(ctx0, table, rel_pos); + kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, nr, n_stream); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + } else { + q_c = ggml_reshape_3d(ctx0, rows(ggml_reshape_4d(ctx0, Qcur, n_embd_head, n_head, n_seq_tokens, n_stream), 2, r0, nr), + n_embd_head, n_head, nr*n_stream); + ggml_tensor * table_c = ggml_reshape_4d(ctx0, table, table->ne[0], table->ne[1], n_seq_tokens, n_stream); + table_c = ggml_view_4d(ctx0, table_c, table_c->ne[0], table_c->ne[1], nr, n_stream, + table_c->nb[1], table_c->nb[2], table_c->nb[3], r0*table_c->nb[2]); + ggml_tensor *& rel_pos_dev = inp->self_rel_pos_dev[is_swa]; + if (!rel_pos_dev) { + rel_pos_dev = ggml_cont(ctx0, rel_pos); + } + ggml_tensor * rel_pos_c = ggml_view_3d(ctx0, rel_pos_dev, n_kv, nr, n_stream, + rel_pos_dev->nb[1], n_seq_tokens*rel_pos_dev->nb[1], r0*rel_pos_dev->nb[1]); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, ggml_get_rows(ctx0, table_c, rel_pos_c), 2, 0, 1, 3)); + } + cb(kq_b, "kq_b", il); + + // only the first chunk stores K and V + ggml_tensor * out = build_attn(inp, + nullptr, nullptr, nullptr, + q_c, r0 == 0 ? Kcur : nullptr, r0 == 0 ? Vcur : nullptr, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il, r0); + outs.push_back(all ? out : ggml_reshape_3d(ctx0, out, out->ne[0], nr, n_stream)); + } + while (outs.size() > 1) { + std::vector next; + for (size_t c = 0; c + 1 < outs.size(); c += 2) { + next.push_back(ggml_concat(ctx0, outs[c], outs[c + 1], 1)); + } + if (outs.size() % 2) { + next.push_back(outs.back()); + } + outs = std::move(next); + } + cur = n_rows_max >= n_seq_tokens ? outs[0] : ggml_reshape_2d(ctx0, outs[0], outs[0]->ne[0], n_tokens); } - sinks = zero; - - cur = build_attn(inp, - nullptr, nullptr, nullptr, - Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); - cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); + if (Qgate_raw_2d) { + Qgate = ggml_sigmoid(ctx0, Qgate_raw_2d); + } + cur = ggml_mul(ctx0, cur, Qgate); cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); cb(cur, "attn_out", il); } @@ -401,6 +956,9 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens // the first layer of each block starts a new residual stream, the earlier one joins the mixed blocks if (ip % hparams.attn_res_block_size == 0) { blocks.push_back(inpSA); + } else if (cur->op == GGML_OP_INKLING_FUSED && cur->op_params[0] == 1 && + cur->src[5] == nullptr && !getenv("GGML_INKLING_NO_RES_FUSE")) { + cur->src[5] = inpSA; } else { cur = ggml_add(ctx0, inpSA, cur); } @@ -409,11 +967,24 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cb(ffn_inp, "ffn_inp", il); // MoE - cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query), n_embd, n_tokens); - if (messages) { - cur = control(cur, message(LOOP_CTRL_FFN), *loop, LOOP_CTRL_FFN); + if (!messages && fuse_mix_rms && layer.ffn_norm) { + cur = ggml_reshape_2d(ctx0, s19_inkling_mix_rms(ctx0, blocks, cur, layer.ffn_res_query, layer.ffn_norm, hparams.f_norm_rms_eps), n_embd, n_tokens); + } else if (has_s19_loop && layer.ffn_norm && model.s19_loop_layers[ip].ctrl_up_ffn) { + const auto & s19_l = model.s19_loop_layers[ip]; + cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query), n_embd, n_tokens); + ggml_tensor * msg_ffn = message(LOOP_CTRL_FFN); + ggml_tensor * gate_in = ggml_inkling_rms2_concat(ctx0, cur, msg_ffn, 1e-6f); + ggml_tensor * w_down = s19_l.ctrl_down_ffn ? s19_l.ctrl_down_ffn : loop->ctrl_down[LOOP_CTRL_FFN]; + ggml_tensor * gate = ggml_mul_mat(ctx0, w_down, gate_in); + ggml_tensor * up_gf = ggml_mul_mat(ctx0, s19_l.ctrl_up_ffn, gate); + cur = ggml_inkling_ctrl_apply_rms_mul(ctx0, cur, msg_ffn, up_gf, layer.ffn_norm, hparams.f_norm_rms_eps); + } else { + cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query), n_embd, n_tokens); + if (messages) { + cur = control(cur, message(LOOP_CTRL_FFN), *loop, LOOP_CTRL_FFN); + } + cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); } - cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); cur = build_moe_ffn(cur, layer.ffn_gate_inp, @@ -431,9 +1002,13 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens layer.ffn_gate_up_exps); cur = convolve(cur, layer.ffn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa + n_embd); - cb(cur, "ffn_out", il); - - cur = ggml_add(ctx0, ffn_inp, cur); + if (cur->op == GGML_OP_INKLING_FUSED && cur->op_params[0] == 1 && + cur->src[5] == nullptr && !getenv("GGML_INKLING_NO_RES_FUSE")) { + cur->src[5] = ffn_inp; + } else { + cb(cur, "ffn_out", il); + cur = ggml_add(ctx0, ffn_inp, cur); + } cb(cur, "l_out", il); return cur; @@ -453,17 +1028,52 @@ void llama_model_inkling2::graph::build_output(ggml_tensor * cur, const std::vec cb(cur, "result_norm", -1); res->t_embd = cur; - // lm_head - cur = build_lora_mm(model.output, cur); + // Series 19 (W1.1): Slice model.output to n_vocab_unpadded before build_lora_mm (0-ULP, eliminates trailing CPY) + ggml_tensor * w_out = model.output; + ggml_tensor * w_out_s = model.output_s; + if (w_out->ne[1] != hparams.n_vocab_unpadded && + (!hdmd || hdmd->rot.find(w_out) == hdmd->rot.end()) && + (!loras || loras->empty())) { + w_out = ggml_view_2d(ctx0, w_out, w_out->ne[0], hparams.n_vocab_unpadded, w_out->nb[1], 0); + if (w_out_s) { + w_out_s = ggml_view_1d(ctx0, w_out_s, hparams.n_vocab_unpadded, 0); + } + } + cur = build_lora_mm(w_out, cur, w_out_s); + ggml_prec_set_acc(cur, GGML_PREC_F32); + + extern bool llama_s19_is_building_greedy_argmax(void); + const bool greedy_argmax_only = llama_s19_is_building_greedy_argmax() && + n_outputs > 0 && samplers.empty() && !getenv("GGML_INKLING_NO_FUSE") && !getenv("S19_NO_INK_W3"); + + if (greedy_argmax_only) { + if (cur->ne[0] != hparams.n_vocab_unpadded) { + cur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, hparams.n_vocab_unpadded, cur->ne[1], cur->nb[1], 0)); + } + if (hparams.f_final_logit_softcapping != 0.0f) { + const float cap = hparams.f_final_logit_softcapping; + cur = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/cap)), cap); + } + ggml_tensor * tok_ids = ggml_argmax(ctx0, cur); + ggml_set_output(tok_ids); + res->t_sampled = { tok_ids }; + res->t_logits = nullptr; + ggml_build_forward_expand(gf, tok_ids); + return; + } if (hparams.f_final_logit_softcapping != 0.0f) { const float cap = hparams.f_final_logit_softcapping; - - cur = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/cap)), cap); + if (!getenv("GGML_INKLING_NO_FUSE") && ggml_is_contiguous(cur)) { + cur = ggml_inkling_softcap(ctx0, cur, 1.0f/cap, cap); + } else { + cur = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/cap)), cap); + } } - // drop the padded vocabulary - cur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, hparams.n_vocab_unpadded, cur->ne[1], cur->nb[1], 0)); + if (cur->ne[0] != hparams.n_vocab_unpadded) { + cur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, hparams.n_vocab_unpadded, cur->ne[1], cur->nb[1], 0)); + } cb(cur, "result_output", -1); res->t_logits = cur; diff --git a/src/models/models.h b/src/models/models.h index d61469120f42..8241acadfd68 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2532,7 +2532,7 @@ struct llama_model_inkling2 : public llama_model_base { llama_model_inkling2(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; - uint32_t graph_nodes_per_tensor() const override { return 32; } + uint32_t graph_nodes_per_tensor() const override { return 64; } // the layers stored in the file virtual int n_layer_phys() const { return hparams.n_layer(); } @@ -2550,7 +2550,7 @@ struct llama_model_inkling2 : public llama_model_base { struct graph : public llm_graph_context { graph(const llm_graph_params & params); ggml_tensor * mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query); - ggml_tensor * clip(ggml_tensor * cur, ggml_tensor * scale, float threshold); + ggml_tensor * clip(ggml_tensor * cur, ggml_tensor * scale, float threshold, ggml_tensor * mul_tau = nullptr); ggml_tensor * convolve( ggml_tensor * cur, ggml_tensor * weight, diff --git a/tests/test-json-schema-to-grammar.cpp b/tests/test-json-schema-to-grammar.cpp index ea10ad7e7eb8..48c910cfbf63 100755 --- a/tests/test-json-schema-to-grammar.cpp +++ b/tests/test-json-schema-to-grammar.cpp @@ -1526,7 +1526,7 @@ static void test_all(const std::string & title, std::function(1, result.total); result.per_seq = std::max(1, result.per_seq); + if (params.n_parallel == 1 && params.speculative.has_dft() && !getenv("LLAMA_DSPARK_NO_TREE")) { + result.total = std::max(result.total, 2 * result.per_seq); + } return result; } @@ -147,6 +150,8 @@ enum slot_state { SLOT_STATE_GENERATING, }; +extern "C" void llama_s19_set_greedy_argmax_only(llama_context * ctx, bool enabled); + struct server_slot; // forward declaration struct server_batch { @@ -301,11 +306,16 @@ struct server_slot { common_speculative * spec; llama_tokens spec_draft; + llama_tokens spec_draft_alt; // draft candidates per token in spec_draft; only draft-simple and draft-mtp fill it std::vector> spec_draft_q; + std::vector> spec_draft_alt_q; llama_tokens spec_prompt; std::vector spec_i_batch; + std::vector spec_i_batch_alt; + int32_t spec_branch_pos = -1; + llama_seq_id spec_seq_alt = -1; common_prompt_checkpoint spec_ckpt; bool spec_is_replay = false; std::mt19937 spec_synth_rng; @@ -449,7 +459,16 @@ struct server_slot { if (can_speculate()) { spec_draft.clear(); + spec_draft_alt.clear(); + spec_draft_q.clear(); + spec_draft_alt_q.clear(); spec_i_batch.clear(); + spec_i_batch_alt.clear(); + spec_branch_pos = -1; + if (spec_seq_alt >= 0 && ctx_tgt) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), spec_seq_alt, -1, -1); + spec_seq_alt = -1; + } spec_ckpt.clear(); } generated_tokens.clear(); @@ -660,6 +679,19 @@ struct server_slot { for (auto token : spec_draft) { add_ok &= batch.add(this->id, token, pos0++, true, false); } + + if (!spec_draft_alt.empty() && spec_draft_alt.size() == spec_draft.size() && spec_seq_alt >= 0) { + GGML_ASSERT(spec_i_batch_alt.empty()); + const int32_t base_alt = batch.size(); + for (size_t i = 0; i <= spec_draft_alt.size(); ++i) { + spec_i_batch_alt.push_back(base_alt + (int32_t) i); + } + auto pos_alt = prompt.tokens.pos_next(); + add_ok &= batch.add(spec_seq_alt, sampled, pos_alt++, true, false); + for (auto token : spec_draft_alt) { + add_ok &= batch.add(spec_seq_alt, token, pos_alt++, true, false); + } + } } GGML_ASSERT(add_ok && "batch must be large enough to hold the sampled and draft tokens"); @@ -2056,6 +2088,14 @@ struct server_context_impl { // TODO: check verify if this actually works with TTS use_backend_sampling &= task.type != SERVER_TASK_TYPE_TTS; + // Series 23 (B3): Keep pure-greedy slots off per-seq backend sampler chains so ctx_tgt + // executes batched greedy_argmax_only (1 softcap + 1 batched argmax, eliding ggml_pad). + if (task.params.sampling.n_probs == 0 && + common_sampler_is_pure_argmax(slot.smpl.get()) && + !getenv("LLAMA_FORCE_BACKEND_ARGMAX_CHAIN")) { + use_backend_sampling = false; + } + // TODO: tmp until backend sampling is fully implemented if (use_backend_sampling) { llama_set_sampler(ctx_tgt, slot.id, common_sampler_get(slot.smpl.get())); @@ -3849,6 +3889,11 @@ struct server_context_impl { // stale candidates: a replay never reads them, a new draft refills them slot.spec_draft_q.clear(); + slot.spec_draft_alt.clear(); + slot.spec_draft_alt_q.clear(); + slot.spec_i_batch_alt.clear(); + slot.spec_branch_pos = -1; + slot.spec_seq_alt = -1; if (!slot.spec_draft.empty()) { // we have a previous (partial) draft to reuse @@ -3870,17 +3915,28 @@ struct server_context_impl { slot.spec_prompt = slot.prompt.tokens.get_text_tokens(); const bool spec_reject = slot.use_spec_rejection(); + const bool allow_tree = + params_base.n_parallel == 1 && + llama_n_seq_max(ctx_tgt) >= 2 && + !use_ckpt_tgt && + !use_ckpt_dft && + !slot.spec_is_replay && + common_speculative_get_synth_probs(spec.get()).empty() && + !getenv("LLAMA_DSPARK_NO_TREE"); common_speculative_get_draft_params(spec.get(), slot.id) = { - /* .drafting = */ true, - /* .n_max = */ n_draft_max, - /* .pos0 = */ slot.prompt.tokens.pos_next(), - /* .id_last = */ slot.sampled, - /* .prompt = */ &slot.spec_prompt, - /* .result = */ &slot.spec_draft, - /* .result_q = */ spec_reject ? &slot.spec_draft_q : nullptr, - /* .temp = */ slot.task->params.sampling.temp, - /* .seed = */ slot.task->params.sampling.seed, + /* .drafting = */ true, + /* .n_max = */ n_draft_max, + /* .pos0 = */ slot.prompt.tokens.pos_next(), + /* .id_last = */ slot.sampled, + /* .prompt = */ &slot.spec_prompt, + /* .result = */ &slot.spec_draft, + /* .result_alt = */ allow_tree ? &slot.spec_draft_alt : nullptr, + /* .result_branch_pos = */ allow_tree ? &slot.spec_branch_pos : nullptr, + /* .result_q = */ spec_reject ? &slot.spec_draft_q : nullptr, + /* .result_alt_q = */ (allow_tree && spec_reject) ? &slot.spec_draft_alt_q : nullptr, + /* .temp = */ slot.task->params.sampling.temp, + /* .seed = */ slot.task->params.sampling.seed, }; drafting.push_back(&slot); @@ -3941,6 +3997,27 @@ struct server_context_impl { if (use_ckpt_dft) { ckpt.update_dft(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); } + + if (!slot.spec_draft_alt.empty()) { + if (use_ckpt_tgt || use_ckpt_dft || + slot.spec_draft_alt.size() != draft.size() || + slot.spec_branch_pos < 0 || slot.spec_branch_pos >= (int32_t) draft.size() || + (uint32_t) (2 * (draft.size() + 1)) > llama_n_batch(ctx_tgt)) { + slot.spec_draft_alt.clear(); + slot.spec_draft_alt_q.clear(); + slot.spec_branch_pos = -1; + slot.spec_seq_alt = -1; + } else { + slot.spec_seq_alt = params_base.n_parallel; + llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.spec_seq_alt, -1, -1); + llama_memory_seq_cp(llama_get_memory(ctx_tgt), slot.id, slot.spec_seq_alt, -1, -1); + } + } + } else if (!slot.spec_draft_alt.empty()) { + slot.spec_draft_alt.clear(); + slot.spec_draft_alt_q.clear(); + slot.spec_branch_pos = -1; + slot.spec_seq_alt = -1; } }); @@ -4652,9 +4729,28 @@ struct server_context_impl { } bool has_output = false; + bool all_outputs_pure_greedy = true; for (int i = off; i < off + batch.view.size(); ++i) { - has_output |= batch.tokens[i].output; + if (batch.tokens[i].output) { + has_output = true; + const int32_t raw_sid = batch.tokens[i].id_slot; + const int32_t sid = (raw_sid == params_base.n_parallel && params_base.n_parallel == 1 && !slots.empty()) ? 0 : raw_sid; + if (sid >= 0 && sid < (int32_t) slots.size()) { + const auto & sl = slots[sid]; + const bool slot_greedy = + sl.task != nullptr && + sl.task->need_sampling() && + sl.task->params.sampling.n_probs == 0 && + common_sampler_is_pure_argmax(sl.smpl.get()); + if (!slot_greedy) { + all_outputs_pure_greedy = false; + } + } else { + all_outputs_pure_greedy = false; + } + } } + llama_s19_set_greedy_argmax_only(ctx_tgt, has_output && all_outputs_pure_greedy); // yield to the queue, so we can still handle metrics tasks while decoding // note: the sync is done here too, so that the wait is also covered by the yield @@ -4722,18 +4818,82 @@ struct server_context_impl { // TODO: avoid restoring the draft context and re-evaluating the drafted tokens when not needed [TAG_SPEC_AVOID_DRAFT_REEVAL] // for now, always re-evaluate for simplicity // ref: https://github.com/ggml-org/llama.cpp/pull/22728#issuecomment-4400925384 - if (spec) { + // Series 19 (W1.2): Defer speculative injection of draft-verification slots into post_decode() + // so ONLY the k + 1 accepted committed rows are injected (eliminating rejected-token ctx_dft work). + const bool s19_defer_dft = !getenv("S19_NO_DEFER_DFT"); + if (spec && !s19_defer_dft) { bool ok = true; queue_tasks.yield_to_queue([&]() { ok = common_speculative_process(spec.get(), batch.view); }); - if (!ok) { SRV_ERR("%s", "failed to process speculative batch\n"); - - // TODO: handle error throw std::runtime_error("failed to process speculative batch"); } + } else if (spec) { + const int32_t spec_win = !getenv("LLAMA_DSPARK_FULL_PREFILL") ? common_speculative_ctx_window(spec.get()) : 0; + bool any_spec_verify = false; + bool any_skipped = false; + std::vector keep_rows; + keep_rows.reserve(batch.view.size()); + for (int32_t vr = 0; vr < batch.view.size(); ++vr) { + const int32_t sid = batch.tokens[off + vr].id_slot; + const bool is_spec_alt = (sid == params_base.n_parallel && params_base.n_parallel == 1 && + !slots.empty() && !slots[0].spec_i_batch_alt.empty()); + const bool valid_slot = sid >= 0 && sid < (int32_t) slots.size(); + const bool is_spec_slot = is_spec_alt || (valid_slot && + slots[sid].state == SLOT_STATE_GENERATING && + slots[sid].can_speculate() && + !slots[sid].spec_draft.empty() && + !slots[sid].spec_i_batch.empty() && + ctx_dft_seq_rm_type != COMMON_CONTEXT_SEQ_RM_TYPE_FULL); + if (is_spec_slot) { + any_spec_verify = true; + any_skipped = true; + continue; + } + if (valid_slot && slots[sid].task && + (slots[sid].state == SLOT_STATE_PROCESSING_PROMPT || slots[sid].state == SLOT_STATE_DONE_PROMPT)) { + if (spec_win > 0) { + const llama_pos min_pos = (llama_pos) slots[sid].task->n_tokens() - spec_win; + if (batch.view.tokens[vr].pos[0] < min_pos) { + any_skipped = true; + continue; + } + } + if (ctx_dft && (keep_rows.empty() || batch.tokens[off + keep_rows.back()].id_slot != sid)) { + const llama_pos cur_max = llama_memory_seq_pos_max(llama_get_memory(ctx_dft), slots[sid].id); + const llama_pos row_pos = batch.view.tokens[vr].pos[0]; + if (cur_max >= row_pos) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), slots[sid].id, row_pos, -1); + } else if (cur_max >= 0 && row_pos != cur_max + 1) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), slots[sid].id, -1, -1); + } + } + } + keep_rows.push_back(vr); + } + + if (!any_skipped && !any_spec_verify) { + bool ok = true; + queue_tasks.yield_to_queue([&]() { + ok = common_speculative_process(spec.get(), batch.view); + }); + if (!ok) { + SRV_ERR("%s", "failed to process speculative batch\n"); + throw std::runtime_error("failed to process speculative batch"); + } + } else if (!keep_rows.empty()) { + bool ok = true; + queue_tasks.yield_to_queue([&]() { + ok = common_speculative_process_rows( + spec.get(), batch.view, keep_rows.data(), (int32_t) keep_rows.size()); + }); + if (!ok) { + SRV_ERR("%s", "failed to process non-speculative rows\n"); + throw std::runtime_error("failed to process non-speculative rows"); + } + } } // handle `n_cmpl > 1` tasks - when the main prompt is processed, activate all child tasks too @@ -4778,6 +4938,11 @@ struct server_context_impl { throw std::runtime_error(string_format("speculative batch index %d is not inside the current sub-batch [%d, %d)", i, off, off + n_batch_tokens)); } } + for (auto & i : slot.spec_i_batch_alt) { + if (!is_inside_view(i)) { + throw std::runtime_error(string_format("speculative alt batch index %d is not inside the current sub-batch [%d, %d)", i, off, off + n_batch_tokens)); + } + } }); auto accept_special_token = [&](server_slot & slot, llama_token token) { @@ -4897,11 +5062,24 @@ struct server_context_impl { GGML_ASSERT(n_draft > 0); // batch indices of the draft tokens, used to get the token probabilities below - auto spec_i_batch = std::move(slot.spec_i_batch); + auto spec_i_batch = std::move(slot.spec_i_batch); + auto spec_i_batch_alt = std::move(slot.spec_i_batch_alt); + auto spec_draft_alt = std::move(slot.spec_draft_alt); + auto spec_draft_alt_q = std::move(slot.spec_draft_alt_q); + const int32_t branch_pos = slot.spec_branch_pos; + const llama_seq_id seq_alt = slot.spec_seq_alt; + slot.spec_branch_pos = -1; + slot.spec_seq_alt = -1; + const bool has_tree = !spec_draft_alt.empty() && spec_i_batch_alt.size() == n_draft + 1 && + seq_alt >= 0 && branch_pos >= 0 && branch_pos < (int32_t) n_draft; + int won_branch = 0; // verify and try to accept the draft { - common_sampler_ptr smpl_save(common_sampler_clone(slot.smpl.get())); + const bool s19_need_smpl_ckpt = + ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_FULL || + (ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_RS && n_draft > llama_n_rs_seq(ctx_tgt)); + common_sampler_ptr smpl_save(s19_need_smpl_ckpt ? common_sampler_clone(slot.smpl.get()) : nullptr); GGML_ASSERT(spec_i_batch.size() == n_draft + 1); GGML_ASSERT(slot.spec_draft_q.empty() || (slot.spec_draft_q.size() == slot.spec_draft.size())); @@ -4918,6 +5096,18 @@ struct server_context_impl { synth_probs, slot.spec_synth_rng, slot.spec_is_replay); } else if (slot.spec_is_replay && slot.use_spec_rejection()) { accepted = server_accept_replay(slot.smpl.get(), slot.ctx_tgt, spec_i_batch, slot.spec_draft); + } else if (has_tree && use_rejection && spec_draft_alt_q.size() == n_draft) { + accepted = common_sampler_sample_and_accept_n_tree_rejection( + slot.smpl.get(), slot.ctx_tgt, + spec_i_batch, slot.spec_draft, slot.spec_draft_q, + spec_i_batch_alt, spec_draft_alt, spec_draft_alt_q, + branch_pos, &won_branch); + } else if (has_tree && !use_rejection) { + accepted = common_sampler_sample_and_accept_n_tree( + slot.smpl.get(), slot.ctx_tgt, + spec_i_batch, slot.spec_draft, + spec_i_batch_alt, spec_draft_alt, + branch_pos, &won_branch); } else if (use_rejection) { accepted = common_sampler_sample_and_accept_n_rejection(slot.smpl.get(), slot.ctx_tgt, spec_i_batch, slot.spec_draft, slot.spec_draft_q); } else { @@ -4995,13 +5185,53 @@ struct server_context_impl { } // add accepted tokens to the prompt - slot.prompt.tokens.keep_first(slot.prompt.n_tokens() - n_draft); + const size_t n_prompt_base = slot.prompt.n_tokens() - n_draft; + slot.prompt.tokens.keep_first(n_prompt_base); slot.prompt.tokens.insert({ids.begin(), ids.end() - 1}); slot.sampled = ids.back(); // last accepted token SLT_DBG(slot, "add accepted tokens: sampled=%d, ids.size=%zu, n_draft=%zu\n", slot.sampled, ids.size(), n_draft); - slot.mem.seq_rm(slot.id, slot.prompt.tokens.pos_next(), -1); + const auto & active_i_batch = (has_tree && won_branch == 1) ? spec_i_batch_alt : spec_i_batch; + if (has_tree && won_branch == 1) { + const llama_pos pos_round_start = batch.view.tokens[spec_i_batch[0] - off].pos[0]; + const llama_pos pos_keep = slot.prompt.tokens.pos_next(); + llama_memory_seq_rm(llama_get_memory(slot.ctx_tgt), seq_alt, pos_keep, -1); + llama_memory_seq_cp(llama_get_memory(slot.ctx_tgt), seq_alt, slot.id, pos_round_start, pos_keep); + llama_memory_seq_rm(llama_get_memory(slot.ctx_tgt), seq_alt, -1, -1); + if (slot.ctx_dft) { + llama_memory_seq_rm(llama_get_memory(slot.ctx_dft), slot.id, pos_keep, -1); + } + } else { + if (has_tree && seq_alt >= 0) { + llama_memory_seq_rm(llama_get_memory(slot.ctx_tgt), seq_alt, -1, -1); + } + slot.mem.seq_rm(slot.id, slot.prompt.tokens.pos_next(), -1); + } + + auto flush_deferred_dft_rows = [&](size_t n_rows) { + if (n_rows == 0 || !spec || getenv("S19_NO_DEFER_DFT") || + ctx_dft_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_FULL) { + return; + } + std::vector acc_view_rows(n_rows); + for (size_t r = 0; r < n_rows; ++r) { + const int32_t vr = active_i_batch[r] - off; + acc_view_rows[r] = vr; + if (has_tree && won_branch == 1) { + batch.view.tokens[vr].seq_id = { slot.id }; + } + } + bool ok = true; + queue_tasks.yield_to_queue([&]() { + ok = common_speculative_process_rows( + spec.get(), batch.view, acc_view_rows.data(), (int32_t) acc_view_rows.size()); + }); + if (!ok) { + SRV_ERR("%s", "failed to process accepted speculative rows\n"); + throw std::runtime_error("failed to process accepted speculative rows"); + } + }; for (size_t i = 0; i < ids.size(); ++i) { completion_token_output result; @@ -5012,12 +5242,24 @@ struct server_context_impl { // post_sampling_probs is not supported with speculative decoding if (slot.task->params.sampling.n_probs > 0 && !slot.task->params.post_sampling_probs) { - populate_token_probs(slot, result, false, params_base.special, spec_i_batch[i]); + populate_token_probs(slot, result, false, params_base.special, active_i_batch[i]); } slot.stats.n_gen += 1; if (!process_token(result, slot)) { + if (i + 1 < ids.size()) { + slot.prompt.tokens.keep_first(n_prompt_base + i); + slot.mem.seq_rm(slot.id, slot.prompt.tokens.pos_next(), -1); + } + const bool will_clear_prompt = + slot.task->is_child() || slot.task->is_stateless() || + slot.audio_stream || slot.task->type == SERVER_TASK_TYPE_REALTIME || + slot.task->type == SERVER_TASK_TYPE_TTS; + if (!will_clear_prompt) { + flush_deferred_dft_rows(i + 1); + } + slot.print_timings(); send_final_response(slot); slot.release(); @@ -5026,6 +5268,8 @@ struct server_context_impl { } } + flush_deferred_dft_rows(ids.size()); + slot.print_timings_tg(); SLT_DBG(slot, "accepted %d/%d draft tokens, new n_tokens = %d\n", (int) n_accepted, (int) n_draft, slot.prompt.n_tokens()); @@ -5094,7 +5338,7 @@ struct server_context_impl { for (int i = off; i < off + n_tokens; ++i) { const auto & t = batch.tokens[i]; - if (!t.is_prompt) { + if (!t.is_prompt || t.id_slot < 0 || t.id_slot >= (int32_t) slots.size()) { continue; // generated tokens are handled after sampling } @@ -5118,8 +5362,11 @@ struct server_context_impl { const int64_t t_now = ggml_time_us(); for (int i = off; i < off + n_tokens; ++i) { const auto & t = batch.tokens[i]; + if (!t.is_prompt || t.id_slot < 0 || t.id_slot >= (int32_t) slots.size()) { + continue; + } auto & slot = slots[t.id_slot]; - if (t.is_prompt && slot.stats.is_set()) { + if (slot.stats.is_set()) { slot.stats.set_prompt_last(t_now); } } @@ -5167,7 +5414,9 @@ server_context::server_context() : impl(new server_context_impl()) {} server_context::~server_context() = default; bool server_context::load_model(common_params & params) { - return impl->load_model(params); + const bool ok = impl->load_model(params); + server_restore_init_thread_affinity(); + return ok; } void server_context::start_loop() { diff --git a/tools/server/server-models.cpp b/tools/server/server-models.cpp index a8077bd710cb..51a0eebfe176 100644 --- a/tools/server/server-models.cpp +++ b/tools/server/server-models.cpp @@ -1247,6 +1247,21 @@ void server_models::load(const std::string & name, const load_options & opts) { std::vector child_env = base_env; // copy child_env.push_back(std::string(SERVER_ENV_ROUTER_PORT) + "=" + std::to_string(base_params.port)); + // Scope GGML_VK_BATCH_INVARIANT to child instances that actually enable speculative decoding, + // so non-speculative models (--spec-type none) keep full 8x8x8 Flash-Attention and Q8_0 decode speed. + if (std::getenv("GGML_VK_FORCE_BATCH_INVARIANT") == nullptr) { + bool uses_spec = false; + for (size_t ai = 0; ai + 1 < child_args.size(); ++ai) { + if (child_args[ai] == "--spec-type" && child_args[ai + 1] == "draft-mtp") { + uses_spec = true; + break; + } + } + if (!uses_spec) { + set_child_env(child_env, "GGML_VK_BATCH_INVARIANT", "0"); + } + } + if (opts.role == SERVER_ROLE_DOWNLOAD) { inst.meta.status = SERVER_MODEL_STATUS_DOWNLOADING; child_env.push_back(std::string(SERVER_ENV_CHILD_ROLE) + "=" + server_role_type_to_str(SERVER_ROLE_DOWNLOAD)); diff --git a/tools/server/server-queue.cpp b/tools/server/server-queue.cpp index 75daebb0d299..e8113a33d7fc 100644 --- a/tools/server/server-queue.cpp +++ b/tools/server/server-queue.cpp @@ -21,6 +21,28 @@ // server_queue // +#if defined(__linux__) +#include +static cpu_set_t g_s21_srv_init_cpuset; +static bool g_s21_srv_has_init_cpuset = false; + +__attribute__((constructor)) static void s21_srv_capture_init_cpuset() { + CPU_ZERO(&g_s21_srv_init_cpuset); + if (sched_getaffinity(0, sizeof(g_s21_srv_init_cpuset), &g_s21_srv_init_cpuset) == 0 && + CPU_COUNT(&g_s21_srv_init_cpuset) > 1) { + g_s21_srv_has_init_cpuset = true; + } +} + +void server_restore_init_thread_affinity() { + if (g_s21_srv_has_init_cpuset) { + (void) sched_setaffinity(0, sizeof(g_s21_srv_init_cpuset), &g_s21_srv_init_cpuset); + } +} +#else +void server_restore_init_thread_affinity() {} +#endif + static bool task_resets_idle_timer(server_task_type type) { return type != SERVER_TASK_TYPE_METRICS; } @@ -43,6 +65,7 @@ int server_queue::post(server_task && task, bool front) { if (reset_timer) { time_last_task = ggml_time_ms(); } + wake_worker_if_yielding_locked(); condition_tasks.notify_one(); return task_id; } @@ -69,6 +92,7 @@ int server_queue::post(std::vector && tasks, bool front) { if (reset_timer) { time_last_task = ggml_time_ms(); } + wake_worker_if_yielding_locked(); condition_tasks.notify_one(); return 0; } @@ -109,9 +133,17 @@ void server_queue::pop_deferred_task(int id_slot) { } } time_last_task = ggml_time_ms(); + wake_worker_if_yielding_locked(); condition_tasks.notify_one(); } +void server_queue::wake_worker_if_yielding_locked() { + if (worker.yielding && !worker.busy && !queue_tasks.empty()) { + worker.busy = true; + worker.cv.notify_one(); + } +} + void server_queue::wait_until_no_sleep() { std::unique_lock lock(mutex_tasks); if (sleeping) { @@ -166,6 +198,7 @@ bool server_queue::process_new_tasks(bool is_yielding) { } void server_queue::worker_loop() { + server_restore_init_thread_affinity(); while (true) { { std::unique_lock lock(mutex_tasks); @@ -229,13 +262,23 @@ void server_queue::yield_to_queue(std::function && work) { QUE_DBG("%s", "yielding to queue\n"); + // Series 20 (Pillar S20.4): Race-free mutex_tasks-guarded lazy worker wakeup. + // Eliminates 112.3 vcsw/s on worker.thread and 56.2 vcsw/s + 12-P-core wake_affine + // bounce on main loop when queue_tasks is empty during decode/verify! + bool notify_worker = false; { std::unique_lock lock(mutex_tasks); - GGML_ASSERT(!worker.busy && "yield_to_queue() cannot be nested"); - worker.busy = true; + GGML_ASSERT(!worker.busy && !worker.yielding && "yield_to_queue() cannot be nested"); worker.yielding = true; + time_last_task = ggml_time_ms(); + if (!queue_tasks.empty()) { + worker.busy = true; + notify_worker = true; + } + } + if (notify_worker) { + worker.cv.notify_one(); } - worker.cv.notify_one(); // run the work on the current thread, so that all ggml compute stays on the same thread std::exception_ptr exception; @@ -248,12 +291,14 @@ void server_queue::yield_to_queue(std::function && work) { { std::unique_lock lock(mutex_tasks); - // the yield is over, wait for the worker to finish its current task + // the yield is over; only wait if the worker actually woke to process a task worker.yielding = false; - condition_tasks.notify_all(); - condition_tasks.wait(lock, [&]{ - return !worker.busy; - }); + if (worker.busy) { + condition_tasks.notify_all(); + condition_tasks.wait(lock, [&]{ + return !worker.busy; + }); + } // put the declined tasks back, keeping their order while (!queue_tasks_unhandled.empty()) { @@ -281,6 +326,7 @@ void server_queue::yield_to_queue(std::function && work) { } void server_queue::start_loop(int64_t idle_sleep_ms) { + server_restore_init_thread_affinity(); running = true; time_last_task = ggml_time_ms(); @@ -331,6 +377,7 @@ void server_queue::start_loop(int64_t idle_sleep_ms) { // no tasks, check for sleeping state if (should_sleep()) { QUE_INF("%s", "entering sleeping state\n"); + server_restore_init_thread_affinity(); sleeping = true; // Call order cb0 -> cb1 -> cb{N} for (auto & cb : callback_sleeping_state) { diff --git a/tools/server/server-queue.h b/tools/server/server-queue.h index f9d66be64064..89f59408c925 100644 --- a/tools/server/server-queue.h +++ b/tools/server/server-queue.h @@ -150,10 +150,13 @@ struct server_queue { bool process_new_tasks(bool is_yielding); // for worker_t + void wake_worker_if_yielding_locked(); void worker_loop(); void worker_stop(); }; +void server_restore_init_thread_affinity(); + // struct for managing server responses // in most cases, use server_response_reader to retrieve results struct server_response {