diff --git a/common/arg.cpp b/common/arg.cpp index 6bf9355fb0ff..5b2b64476434 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -4206,6 +4206,22 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.speculative.draft.n_ubatch = value; } ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_N_UBATCH")); + add_opt(common_arg( + {"--spec-draft-qsa"}, "{auto,on,off}", + "sparse attention (QSA) of an MTP block whose GGUF stores dense attention (qwen4exp only): auto uses dense attention " + "while the context is short and QSA beyond a model specific length (default: auto)", + [](common_params & params, const std::string & value) { + if (value == "auto") { + params.speculative.draft.mtp_qsa = LLAMA_MTP_QSA_AUTO; + } else if (value == "on") { + params.speculative.draft.mtp_qsa = LLAMA_MTP_QSA_ON; + } else if (value == "off") { + params.speculative.draft.mtp_qsa = LLAMA_MTP_QSA_OFF; + } else { + throw std::invalid_argument("invalid value, must be one of: auto, on, off"); + } + } + ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_QSA")); add_opt(common_arg( {"--spec-synth-len"}, "L", "target mean synthetic acceptance length, including the target token (benchmarking only)", diff --git a/common/common.cpp b/common/common.cpp index c971c3cc579d..04b02c79c157 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1779,6 +1779,8 @@ struct llama_context_params common_context_params_to_llama(const common_params & cparams.type_k = params.cache_type_k; cparams.type_v = params.cache_type_v; + cparams.mtp_qsa = params.speculative.draft.mtp_qsa; + cparams.moe_cache_size = params.moe_cache_size; cparams.moe_cache_cpu_share = params.moe_cache_cpu_share; diff --git a/common/common.h b/common/common.h index efab6c5fc2d2..1a58841cbbd3 100644 --- a/common/common.h +++ b/common/common.h @@ -359,6 +359,9 @@ struct common_params_speculative_draft { int32_t n_ubatch = 0; // physical batch size of the draft context (0 - use the target's n_ubatch) + // MTP draft head options (qwen4exp), see llama_context_params + enum llama_mtp_qsa_type mtp_qsa = LLAMA_MTP_QSA_AUTO; // sparse attention of a dense MTP block + ggml_type cache_type_k = GGML_TYPE_F16; // KV cache data type for the K ggml_type cache_type_v = GGML_TYPE_F16; // KV cache data type for the V diff --git a/common/speculative.cpp b/common/speculative.cpp index 5ca435e1b99c..dfa1f68adc08 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -1601,6 +1601,16 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { int32_t n_batch_tgt = 0; std::vector verify_row0; // [n_seq] device row of the first verify row, see verify_h_rows + // Generation verify batches (every row wants logits, 2 .. n_max+1 tokens) skip the catch-up + // decode. The next draft() replays only the accepted rows plus the new token, and asks for + // logits on the new token alone, so the draft weights are read once. + // defer_h0 is pending_h as process() saw it: the state paired with the first verify token. + std::vector defer_on; + std::vector defer_n_acc; // -1 until accept(); draft tokens accepted, not counting the first verify token + std::vector> defer_id; + std::vector> defer_pos; + std::vector> defer_h0; + common_speculative_impl_draft_mtp(const common_params_speculative & params, uint32_t n_seq) : common_speculative_impl(COMMON_SPECULATIVE_TYPE_DRAFT_MTP, n_seq, params.draft.n_max) , params(params.draft) @@ -1651,7 +1661,11 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { } } - is_mem_shared = llama_get_ctx_other(ctx_dft) == ctx_tgt; + // ctx_other is also set when a draft head borrows token_embd/output from its target (qwen4exp), that + // shares no memory: only the gemma4 assistant runs on the KV cache of its target + char arch_dft[64] = {0}; + llama_model_meta_val_str(llama_get_model(ctx_dft), "general.architecture", arch_dft, sizeof(arch_dft)); + is_mem_shared = llama_get_ctx_other(ctx_dft) == ctx_tgt && std::strcmp(arch_dft, "gemma4-assistant") == 0; chain_heads = n_mtp_layers > 1 && !is_mem_shared; llama_set_embeddings_nextn(ctx_tgt, true, /*masked*/ is_mem_shared); @@ -1679,6 +1693,12 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { n_batch_tgt = (int32_t) llama_n_batch(ctx_tgt); verify_row0.assign(n_seq, -1); + defer_on.assign(n_seq, 0); + defer_n_acc.assign(n_seq, -1); + defer_id.assign(n_seq, {}); + defer_pos.assign(n_seq, {}); + defer_h0.assign(n_seq, std::vector(n_embd, 0.0f)); + // shared memory and chained heads keep the host rows if (!is_mem_shared && !chain_heads) { dev_rows = llama_set_embeddings_nextn_dev(ctx_tgt, true) && llama_set_ctx_state_src(ctx_dft, ctx_tgt); @@ -1708,9 +1728,80 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { backend_chains.clear(); } + // A verify batch is short and every row asks for logits. Prompt rows do not, except the last one. + bool seq_defer_catchup(const common_batch & batch_in, llama_seq_id seq_id) const { + static const bool off = getenv("LLAMA_MTP_NO_FUSE") != nullptr; + if (off || is_mem_shared || chain_heads) { + return false; + } + const int32_t beg = i_batch_beg[seq_id]; + const int32_t end = i_batch_end[seq_id]; + if (beg < 0) { + return false; + } + const int32_t n_rows = end - beg + 1; + if (n_rows < 2 || n_rows > this->params.n_max + 1) { + return false; + } + for (int32_t k = beg; k <= end; ++k) { + const auto & tok = batch_in.tokens[k]; + if (!tok.output || tok.id == LLAMA_TOKEN_NULL) { + return false; + } + } + return true; + } + + // Write a catch-up that draft() did not consume (no draft call after accept). + bool flush_deferred() { + if (is_mem_shared || chain_heads) { + return true; + } + + auto * mem_dft = llama_get_memory(params.ctx_dft); + + batch.clear(); + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (!defer_on[seq_id] || defer_n_acc[seq_id] < 0) { + continue; + } + // the rows continue the draft cache, which ends right before them, unless the sequence was removed or + // rewound since (the next task of a server slot starts with its prompt): then they are stale + if (defer_pos[seq_id].empty() || llama_memory_seq_pos_max(mem_dft, seq_id) + 1 != defer_pos[seq_id][0]) { + SPC_DBG("dropping a stale deferred catch-up (seq_id=%d, pos=%d, draft pos_max=%d)\n", (int) seq_id, + defer_pos[seq_id].empty() ? -1 : (int) defer_pos[seq_id][0], (int) llama_memory_seq_pos_max(mem_dft, seq_id)); + defer_on[seq_id] = 0; + defer_n_acc[seq_id] = -1; + continue; + } + const int32_t n_have = (int32_t) defer_id[seq_id].size(); + const int32_t n_keep = std::min(defer_n_acc[seq_id] + 1, n_have); + for (int32_t t = 0; t < n_keep; ++t) { + const int32_t idx = batch.add(defer_id[seq_id][t], defer_pos[seq_id][t], seq_id, false); + const float * h_row = t == 0 + ? defer_h0[seq_id].data() + : verify_h[seq_id].data() + (size_t) (t - 1) * n_embd; + batch.set_embd_state(idx, { h_row, 1, (size_t) n_embd }); + } + defer_on[seq_id] = 0; + defer_n_acc[seq_id] = -1; + } + if (batch.size() == 0) { + return true; + } + const int32_t rc = llama_process(params.ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + if (rc != 0) { + SPC_ERR("deferred catch-up flush failed rc=%d\n", (int) rc); + return false; + } + return true; + } + void begin(llama_seq_id seq_id, const llama_tokens & prompt) override { // reset here rather than per round, or two identical requests differ common_sampler_reset(smpls[seq_id].get()); + defer_on[seq_id] = 0; + defer_n_acc[seq_id] = -1; const int32_t N = (int32_t) prompt.size(); if (N <= 0) { @@ -1740,6 +1831,10 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { const int32_t n_tokens = batch_in.size(); + if (!flush_deferred()) { + return false; + } + // remember the first and last batch index for each sequence std::fill(i_batch_beg.begin(), i_batch_beg.end(), -1); std::fill(i_batch_end.begin(), i_batch_end.end(), -1); @@ -1760,8 +1855,25 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { const size_t row_bytes = (size_t) n_embd * sizeof(float); - // if kv is shared with target (e.g Gemma4), then we can skip this catch-up decode - if (!is_mem_shared) { + std::vector defer_now(n_seq, 0); + bool any_catchup = false; + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_batch_beg[seq_id] < 0) { + continue; + } + if (seq_defer_catchup(batch_in, seq_id)) { + defer_now[seq_id] = 1; + std::memcpy(defer_h0[seq_id].data(), pending_h[seq_id].data(), row_bytes); + } else { + defer_on[seq_id] = 0; + defer_n_acc[seq_id] = -1; + any_catchup = true; + } + } + + // if kv is shared with target (e.g Gemma4), then we can skip this catch-up decode. + // a deferred verify batch is caught up later, inside draft(), together with the new token. + if (!is_mem_shared && any_catchup) { batch.clear(); // pair each token with the tgt embedding shifted right by one position, and @@ -1773,7 +1885,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { if (dev_rows) { GGML_ASSERT(n_tokens <= n_batch_tgt && "the target batch exceeds the h_nextn device buffer"); for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { - if (i_batch_beg[seq_id] >= 0) { + if (i_batch_beg[seq_id] >= 0 && !defer_now[seq_id]) { llama_set_embeddings_nextn_rows(ctx_tgt, n_batch_tgt + seq_id, 1, pending_h[seq_id].data()); } } @@ -1785,6 +1897,9 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { const auto & t = batch_in.tokens[k]; const llama_seq_id seq_id = t.seq_id; + if (defer_now[seq_id]) { + continue; + } // vision tokens carry an embedding instead of an id const int32_t idx = t.id != LLAMA_TOKEN_NULL @@ -1855,10 +1970,32 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { verify_h_rows[seq_id] = h_rows; + if (defer_now[seq_id]) { + defer_on[seq_id] = 1; + defer_n_acc[seq_id] = -1; + defer_id[seq_id].resize(h_rows); + defer_pos[seq_id].resize(h_rows); + for (int32_t i = 0; i < h_rows; ++i) { + defer_id[seq_id][i] = batch_in.tokens[h_offset + i].id; + defer_pos[seq_id][i] = batch_in.tokens[h_offset + i].pos[0]; + } + } + if (dev_rows) { - // the rows stay on the device until the next target decode, only the pending row comes to the host + // the rows stay on the device until the next target decode, only the pending row comes to the host. + // a deferred catch-up runs on the next draft(), after that decode, so those rows are copied now. verify_row0[seq_id] = h_offset; - llama_get_embeddings_nextn_rows(ctx_tgt, h_offset + h_rows - 1, 1, pending_h[seq_id].data()); + if (defer_now[seq_id]) { + verify_h[seq_id].resize((size_t) h_rows * n_embd); + if (!llama_get_embeddings_nextn_rows(ctx_tgt, h_offset, h_rows, verify_h[seq_id].data())) { + SPC_ERR("failed to copy h_nextn rows for the deferred catch-up (seq_id=%d)\n", (int) seq_id); + return false; + } + std::memcpy(pending_h[seq_id].data(), + verify_h[seq_id].data() + (size_t) (h_rows - 1) * n_embd, row_bytes); + } else { + llama_get_embeddings_nextn_rows(ctx_tgt, h_offset + h_rows - 1, 1, pending_h[seq_id].data()); + } continue; } @@ -1909,6 +2046,26 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { common_sampler_reset(smpls[seq_id].get()); } + const bool fuse = defer_on[seq_id] && defer_n_acc[seq_id] >= 0 && !chain_heads && !is_mem_shared; + if (fuse) { + const int32_t n_have = (int32_t) defer_id[seq_id].size(); + const int32_t n_keep = std::min(defer_n_acc[seq_id] + 1, n_have); + if (n_keep <= 0 || defer_pos[seq_id][n_keep - 1] + 1 != dp.pos0) { + SPC_ERR("deferred catch-up does not meet the new token (seq_id=%d, n_keep=%d, pos0=%d) - drafting the new token only\n", + (int) seq_id, (int) n_keep, (int) dp.pos0); + } else { + for (int32_t t = 0; t < n_keep; ++t) { + const int32_t idx = batch.add(defer_id[seq_id][t], defer_pos[seq_id][t], seq_id, false); + const float * h_row = t == 0 + ? defer_h0[seq_id].data() + : verify_h[seq_id].data() + (size_t) (t - 1) * n_embd; + batch.set_embd_state(idx, { h_row, 1, (size_t) n_embd }); + } + } + } + defer_on[seq_id] = 0; + defer_n_acc[seq_id] = -1; + const int32_t idx = batch.add(dp.id_last, dp.pos0, seq_id, true); batch.set_embd_state(idx, { pending_h[seq_id].data(), 1, (size_t) n_embd }); @@ -2052,6 +2209,10 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { return; } + if (defer_on[seq_id]) { + defer_n_acc[seq_id] = (int32_t) n_accepted; + } + const int32_t i_h = std::min(n_accepted, n_rows - 1); if (dev_rows) { // process() already fetched the last row @@ -2085,6 +2246,8 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { return; } std::memcpy(pending_h[seq_id].data(), data.data(), row_bytes); + defer_on[seq_id] = 0; + defer_n_acc[seq_id] = -1; } }; diff --git a/docs/speculative.md b/docs/speculative.md index d8f3bcb3922a..9d17574843ea 100644 --- a/docs/speculative.md +++ b/docs/speculative.md @@ -251,6 +251,9 @@ Use exactly one of these options: --spec-draft-n-ubatch N physical maximum batch size of the draft context, use a smaller value to spare VRAM (default: 0 - same as --n-ubatch) (env: LLAMA_ARG_SPEC_DRAFT_N_UBATCH) +--spec-draft-qsa {auto,on,off} + sparse attention (QSA) of an MTP block whose GGUF stores dense attention (qwen4exp only): auto uses dense attention while the context is short and QSA beyond a model specific length (default: auto) + (env: LLAMA_ARG_SPEC_DRAFT_QSA) --spec-draft-p-split, --draft-p-split P speculative decoding split probability (default: 0.10) (env: LLAMA_ARG_SPEC_DRAFT_P_SPLIT) diff --git a/examples/speculative-simple/speculative-simple.cpp b/examples/speculative-simple/speculative-simple.cpp index e4a878b82842..875ff3550c3d 100644 --- a/examples/speculative-simple/speculative-simple.cpp +++ b/examples/speculative-simple/speculative-simple.cpp @@ -203,13 +203,13 @@ int main(int argc, char ** argv) { } } - // reset the draft context to the checkpoint before verification + // Drop the speculative tail and keep a catch-up that draft() fused in below n_past. if (ctx_dft) { if (use_ckpt_dft) { GGML_ASSERT(ckpt.load_dft(ctx_dft, seq_id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); } - llama_memory_seq_rm(llama_get_memory(ctx_dft), seq_id, ckpt.pos_max + 1, -1); + llama_memory_seq_rm(llama_get_memory(ctx_dft), seq_id, n_past, -1); } } else { // we have a previous (partial) draft to reuse from checkpoint restoration diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index 12c27423179a..c28ac31acebe 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -1268,6 +1268,9 @@ struct ggml_backend_sched { int n_prefetched; int prefetch_split; // the split that reads the prefetched inputs int prefetch_backend_id; // the backend that copies them + + // a split input in a host buffer was copied asynchronously during this graph, so its copy may still read it + bool host_copy_async; }; #define hash_id(tensor) ggml_hash_find_or_insert(&sched->hash_set, tensor) @@ -2107,6 +2110,66 @@ static bool ggml_backend_sched_is_host_weight(const struct ggml_tensor * t) { ggml_backend_buffer_is_host(t->buffer); } +// inputs from the user must be copied immediately to prevent the user overwriting the data before the copy is done +// wait for the split backend once, and copy the host inputs in batches if the destination buffer supports it +static void ggml_backend_sched_copy_user_inputs(ggml_backend_sched_t sched, struct ggml_backend_sched_split * split) { + const int split_backend_id = split->backend_id; + ggml_backend_t split_backend = sched->backends[split_backend_id]; + + struct ggml_tensor * dsts [GGML_SCHED_MAX_SPLIT_INPUTS]; + const void * srcs [GGML_SCHED_MAX_SPLIT_INPUTS]; + size_t offs [GGML_SCHED_MAX_SPLIT_INPUTS]; + size_t sizes[GGML_SCHED_MAX_SPLIT_INPUTS]; + int n = 0; + ggml_backend_buffer_t batch_buf = NULL; + + auto flush = [&]() { + if (n > 0) { + batch_buf->iface.set_tensor_n(batch_buf, dsts, srcs, offs, sizes, n); + } + n = 0; + batch_buf = NULL; + }; + + bool synced = false; + for (int input_id = 0; input_id < split->n_inputs; input_id++) { + struct ggml_tensor * input = split->inputs[input_id]; + if (!(input->flags & GGML_TENSOR_FLAG_INPUT) || ggml_backend_sched_is_host_weight(input) || !sched->hv_tensor_requires_copy[hash_id(input)]) { + continue; + } + + if (!synced) { + if (sched->events[split_backend_id][sched->cur_copy] != NULL) { + ggml_backend_event_synchronize(sched->events[split_backend_id][sched->cur_copy]); + } else { + ggml_backend_synchronize(split_backend); + } + synced = true; + } + + struct ggml_tensor * input_cpy = tensor_copy(input, split_backend_id, sched->cur_copy); + ggml_backend_buffer_t buf = input_cpy->view_src ? input_cpy->view_src->buffer : input_cpy->buffer; + + if (buf->iface.set_tensor_n == NULL || !ggml_backend_buffer_is_host(input->buffer) || ggml_nbytes(input) == 0) { + ggml_backend_tensor_copy(input, input_cpy); + continue; + } + + if (n == GGML_SCHED_MAX_SPLIT_INPUTS || (batch_buf != NULL && batch_buf != buf)) { + flush(); + } + + batch_buf = buf; + dsts [n] = input_cpy; + srcs [n] = input->data; + offs [n] = 0; + sizes[n] = ggml_nbytes(input); + n++; + } + + flush(); +} + static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggml_backend_sched_split * split, struct ggml_tensor * input) { const int split_backend_id = split->backend_id; ggml_backend_t split_backend = sched->backends[split_backend_id]; @@ -2148,7 +2211,11 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm // try async copy, but if not possible, we can still use a sync copy without synchronizing the dst backend, since we handle the synchronization here with multiple copies and events // TODO: add public function to facilitate this, since applications do not have direct access to the backend interface - if (!split_backend->iface.cpy_tensor_async || !split_backend->iface.cpy_tensor_async(input_backend, split_backend, input, input_cpy)) { + if (split_backend->iface.cpy_tensor_async && split_backend->iface.cpy_tensor_async(input_backend, split_backend, input, input_cpy)) { + if (input->buffer && ggml_backend_buffer_is_host(input->buffer)) { + sched->host_copy_async = true; + } + } else { ggml_backend_synchronize(input_backend); if (sched->events[split_backend_id][sched->cur_copy] != NULL) { ggml_backend_event_synchronize(sched->events[split_backend_id][sched->cur_copy]); @@ -2220,11 +2287,69 @@ static void ggml_backend_sched_prefetch_inputs(ggml_backend_sched_t sched, int s } } +// a small CPU split without inputs, whose results overlap no memory that the earlier splits read or write, +// can run while those splits are still computing on another backend +// (an integrated GPU reads host buffers in place, so a freed input can be what the allocator hands to this split) +static bool ggml_backend_sched_split_is_disjoint(ggml_backend_sched_t sched, int split_id) { + const struct ggml_backend_sched_split * split = &sched->splits[split_id]; + if (sched->n_copies > 1 || split->backend_id != sched->n_backends - 1 || split->graph.n_nodes > 16) { + return false; + } + + auto overlaps = [](const struct ggml_tensor * a, const struct ggml_tensor * b) { + if (a == NULL || b == NULL || a->data == NULL || b->data == NULL) { + return false; + } + const char * a0 = (const char *) a->data; + const char * b0 = (const char *) b->data; + return a0 < b0 + ggml_nbytes(b) && b0 < a0 + ggml_nbytes(a); + }; + + for (int i = 0; i < split->graph.n_nodes; i++) { + const struct ggml_tensor * node = split->graph.nodes[i]; + if (ggml_is_view_op(node->op)) { + continue; + } + for (int s = 0; s < split_id; s++) { + const struct ggml_backend_sched_split * prev = &sched->splits[s]; + // the CPU backend computes synchronously, so its earlier splits are done + if (prev->backend_id == split->backend_id) { + continue; + } + // the inputs copied synchronously are already read; those used in place are srcs of the nodes below + if (sched->host_copy_async) { + for (int j = 0; j < prev->n_inputs; j++) { + if (overlaps(node, prev->inputs[j])) { + return false; + } + } + } + for (int j = 0; j < prev->graph.n_nodes; j++) { + const struct ggml_tensor * pn = prev->graph.nodes[j]; + // a node that is not computed reads and writes nothing + if ((pn->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) { + continue; + } + if (overlaps(node, pn)) { + return false; + } + for (int k = 0; k < GGML_MAX_SRC; k++) { + if (overlaps(node, pn->src[k])) { + return false; + } + } + } + } + } + return true; +} + static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t sched) { GGML_ASSERT(sched); struct ggml_backend_sched_split * splits = sched->splits; int prev_backend_id = -1; + sched->host_copy_async = false; for (int split_id = 0; split_id < sched->n_splits; split_id++) { struct ggml_backend_sched_split * split = &splits[split_id]; @@ -2233,7 +2358,8 @@ static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t s // ensure the previous split's async work has completed before we start // this split, the allocator may have reused buffer regions across splits - if (split->n_inputs == 0 && prev_backend_id >= 0 && prev_backend_id != split_backend_id) { + if (split->n_inputs == 0 && prev_backend_id >= 0 && prev_backend_id != split_backend_id && + !ggml_backend_sched_split_is_disjoint(sched, split_id)) { if (sched->events[prev_backend_id][sched->cur_copy] != NULL) { ggml_backend_event_synchronize(sched->events[prev_backend_id][sched->cur_copy]); } else { @@ -2243,9 +2369,10 @@ static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t s // copy the input tensors to the split backend // the weights in host memory are copied last, so that the copy callback can read the other inputs of the split + ggml_backend_sched_copy_user_inputs(sched, split); for (int input_id = 0; input_id < split->n_inputs; input_id++) { struct ggml_tensor * input = split->inputs[input_id]; - if (!ggml_backend_sched_is_host_weight(input) && sched->hv_tensor_requires_copy[hash_id(input)]) { + if (!(input->flags & GGML_TENSOR_FLAG_INPUT) && !ggml_backend_sched_is_host_weight(input) && sched->hv_tensor_requires_copy[hash_id(input)]) { ggml_backend_sched_copy_input(sched, split, input); } } diff --git a/ggml/src/ggml-cuda/argsort.cu b/ggml/src/ggml-cuda/argsort.cu index 101afeba2861..cf7fdbe0c6f7 100644 --- a/ggml/src/ggml-cuda/argsort.cu +++ b/ggml/src/ggml-cuda/argsort.cu @@ -198,13 +198,22 @@ static inline __device__ void bitonic_step(const float * x_row, int * dst_row, c // shared memory limit) sort with several columns per thread. Every // (k, j) stage runs all owned columns before the barrier; a pair // (col, col ^ j) is exchanged by the owner of its lower index only. -template -static __global__ void k_argsort_f32_i32(const float * x, int * dst, const int ncols, int ncols_pad) { +template +static __global__ void k_argsort_f32_i32(const float * x, int * dst, const int ncols, int ncols_pad, const int ncols_out) { const int row = blockIdx.x; - const float * x_row = x + row * ncols; extern __shared__ int dst_row[]; + // the keys from shared memory when keys_in_smem: the network reads two of them per compare-exchange + const float * x_row = x + row * ncols; + if constexpr (keys_in_smem) { + float * x_smem = (float *) (dst_row + ncols_pad); + for (int col = threadIdx.x; col < ncols; col += blockDim.x) { + x_smem[col] = x_row[col]; + } + x_row = x_smem; + } + // initialize indices for (int col = threadIdx.x; col < ncols_pad; col += blockDim.x) { dst_row[col] = col; @@ -221,9 +230,9 @@ static __global__ void k_argsort_f32_i32(const float * x, int * dst, const int n } } - // copy the result to dst without the padding - for (int col = threadIdx.x; col < ncols; col += blockDim.x) { - dst[row * ncols + col] = dst_row[col]; + // copy the first ncols_out of the result to dst + for (int col = threadIdx.x; col < ncols_out; col += blockDim.x) { + dst[row * ncols_out + col] = dst_row[col]; } } @@ -240,7 +249,11 @@ void argsort_f32_i32_cuda_bitonic(const float * x, const int ncols, const int nrows, ggml_sort_order order, - cudaStream_t stream) { + cudaStream_t stream, + int ncols_out) { + if (ncols_out < 0) { + ncols_out = ncols; + } // bitonic sort requires ncols to be power of 2 const int ncols_pad = next_power_of_2(ncols); @@ -249,16 +262,32 @@ void argsort_f32_i32_cuda_bitonic(const float * x, const dim3 block_dims(ncols_pad < CUDA_ARGSORT_BLOCK_SIZE ? ncols_pad : CUDA_ARGSORT_BLOCK_SIZE, 1, 1); const dim3 block_nums(nrows, 1, 1); const size_t shared_mem = ncols_pad * sizeof(int); + const size_t smpb = ggml_cuda_info().devices[ggml_cuda_get_device()].smpb; // FIXME: this limit could be raised by ~2-4x on Ampere or newer - GGML_ASSERT(shared_mem <= ggml_cuda_info().devices[ggml_cuda_get_device()].smpb); + GGML_ASSERT(shared_mem <= smpb); + + // the keys in shared memory too where they fit, see k_argsort_f32_i32 + const size_t shared_mem_keys = shared_mem + ncols * sizeof(float); + if (shared_mem_keys <= smpb) { + if (order == GGML_SORT_ORDER_ASC) { + k_argsort_f32_i32 + <<>>(x, dst, ncols, ncols_pad, ncols_out); + } else if (order == GGML_SORT_ORDER_DESC) { + k_argsort_f32_i32 + <<>>(x, dst, ncols, ncols_pad, ncols_out); + } else { + GGML_ABORT("fatal error"); + } + return; + } if (order == GGML_SORT_ORDER_ASC) { k_argsort_f32_i32 - <<>>(x, dst, ncols, ncols_pad); + <<>>(x, dst, ncols, ncols_pad, ncols_out); } else if (order == GGML_SORT_ORDER_DESC) { k_argsort_f32_i32 - <<>>(x, dst, ncols, ncols_pad); + <<>>(x, dst, ncols, ncols_pad, ncols_out); } else { GGML_ABORT("fatal error"); } diff --git a/ggml/src/ggml-cuda/argsort.cuh b/ggml/src/ggml-cuda/argsort.cuh index 86df5fda2017..8d1049532547 100644 --- a/ggml/src/ggml-cuda/argsort.cuh +++ b/ggml/src/ggml-cuda/argsort.cuh @@ -20,4 +20,5 @@ void argsort_f32_i32_cuda_bitonic(const float * x, const int ncols, const int nrows, ggml_sort_order order, - cudaStream_t stream); + cudaStream_t stream, + int ncols_out = -1); diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index c89397fd1619..286dcbf32967 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -1384,7 +1385,8 @@ struct ggml_cuda_q8_1_cache { void reset(bool enable); // node writes its output: drop the copies of tensors it overlaps void invalidate(const ggml_tensor * node); - // the copy of t, nullptr if there is none + // the copy of t, nullptr if there is none; a reshape or view of a cached tensor that MMVQ quantizes to the same + // q8_1 blocks shares its copy, see ggml_cuda_q8_1_shares_copy const char * find(const ggml_tensor * t) const; // the buffer for the next copy (size bytes), nullptr if it cannot be cached; commit() makes it t's copy char * reserve(size_t size); @@ -1411,8 +1413,71 @@ struct ggml_backend_cuda_context { ggml_cuda_q8_1_cache q8_1_cache; // where a flash attention whose result MMVQ reads writes the q8_1 copy, and whether it did - block_q8_1 * fa_q8_1 = nullptr; - bool fa_q8_1_written = false; + // the q8_1 copy the node being computed may also write for an MMVQ product that reads it (see q8_1_cache) + block_q8_1 * out_q8_1 = nullptr; + bool out_q8_1_written = false; + + // the activation whose values the fused MMVQ + SCALE + SILU also wrote into the buffer of the hyper-connection gate + // product right after it, for ggml_cuda_mul_mat_vec_q_hc_pre + const ggml_tensor * hc_lo_copy = nullptr; + + // the hyper-connection injection product a fused pre-mix computed ahead into hc_inject_buf, for the combine that + // reads it (see ggml_cuda_hc_inject_ahead) + const ggml_tensor * hc_inject_node = nullptr; + float * hc_inject_buf = nullptr; + + // the pre-mix of a prompt batch whose values the fused hyper-connection kernel also wrote as BF16 (rounded to nearest + // even, as the BF16 conversions of the products) into hc_bf16_buf, K per token, for the products that read it + const ggml_tensor * hc_bf16_src = nullptr; + uint16_t * hc_bf16_buf = nullptr; + size_t hc_bf16_size = 0; + + // the GLU result of a prompt batch that the fused MoE gate/up kernel wrote as BF16 for the down MUL_MAT_ID (see + // ggml_cuda_moe_wmma_glu) + const ggml_tensor * moe_bf16_src = nullptr; + // the experts' rows of a prompt batch that the down MUL_MAT_ID writes as BF16 for the weighted reduction that reads them + const ggml_tensor * moe_down_bf16 = nullptr; + + + // the routed experts' down product whose stage the fused routed + shared expert gate/up prepared in moe_scratch: + // the shared expert's gate, the routing weights from 1 and the ids from QK8_1 (see ggml_cuda_moe_down_fusion) + const ggml_tensor * moe_down_node = nullptr; + float * moe_scratch = nullptr; + + // the SSM_CONV whose result a fused convolution step already wrote (see ggml_cuda_conv_step_fusion), and the + // RMS_NORM + SCALE of its rows it also wrote (see ggml_cuda_conv_step_norms) + const ggml_tensor * conv_done_node = nullptr; + const ggml_tensor * conv_norm_done[2] = { nullptr, nullptr }; + + // the counter of the fused router + top-k MoE selection, zero between its launches + int * router_topk_counter = nullptr; + + // BF16 copies of F32 MoE router weights by their data, see ggml_cuda_prepare_router_bf16 + std::unordered_map router_bf16; + // tiled BF16 copies of weights by their data, see ggml_cuda_prepare_dense_bf16 + std::unordered_map dense_bf16; + // whether F32 weights (by their data) hold BF16 values only, see ggml_cuda_dense_wmma_prepare_f32 + std::unordered_map dense_f32_bf16; + + // QSA attention of this graph, see ggml_cuda_qsa_attn_plan: FLASH_ATTN_EXT -> its TOP_K_MASK, and the masks that + // write cell lists instead + std::unordered_map qsa_fa; + std::unordered_set qsa_masks; + + // the activations that ggml_cuda_dense_wmma rounded to BF16 into dense_x_buf last, on dense_x_stream + const ggml_tensor * dense_x_src = nullptr; + cudaStream_t dense_x_stream = nullptr; + void * dense_x_buf = nullptr; + size_t dense_x_size = 0; + // later MUL_MATs that ggml_cuda_try_dense_wmma_group computed with an earlier one of the same activations + const ggml_tensor * dense_done[4] = {}; + + // the MMQ q8_1 copy (D4 layout) of the src1 at mmq_q8_1_data that a fused HC norm wrote for the MUL_MAT + // mmq_q8_1_dst, until that MUL_MAT reads it or the next graph + const ggml_tensor * mmq_q8_1_dst = nullptr; + const void * mmq_q8_1_data = nullptr; + void * mmq_q8_1_buf = nullptr; + size_t mmq_q8_1_size = 0; #ifdef USE_CUDA_GRAPH // Map from first_node_ptr to cuda_graph - allows multiple graphs per context diff --git a/ggml/src/ggml-cuda/concat.cu b/ggml/src/ggml-cuda/concat.cu index f8dcd95ab008..9e0544ebe420 100644 --- a/ggml/src/ggml-cuda/concat.cu +++ b/ggml/src/ggml-cuda/concat.cu @@ -2,6 +2,10 @@ #include +static constexpr int CUDA_CONCAT_TRANSPOSE_TILE = 64; +static constexpr int CUDA_CONCAT_TRANSPOSE_COLS = 32; +static constexpr int CUDA_CONCAT_TRANSPOSE_ROWS = 8; + // contiguous kernels template static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE) concat_cont(const T * x, @@ -79,6 +83,60 @@ static void concat_cont_cuda(const T * x, concat_cont<<>>(x, y, dst, ne00, ne01, ne02, ne0, ne1, ne2); } +static __global__ void concat_transpose_dim0_f32( + const uint32_t * src0, + const uint32_t * src1, + uint32_t * dst, + int64_t ne00, + int64_t ne10, + int64_t ne1, + int64_t ne0) { + __shared__ uint32_t tile[CUDA_CONCAT_TRANSPOSE_TILE][CUDA_CONCAT_TRANSPOSE_TILE + 1]; + + const int64_t token_load = (int64_t) blockIdx.x * CUDA_CONCAT_TRANSPOSE_TILE + threadIdx.y; + const int64_t channel_load = (int64_t) blockIdx.y * CUDA_CONCAT_TRANSPOSE_TILE + threadIdx.x; + + ggml_cuda_pdl_sync(); +#pragma unroll + for (int j = 0; j < CUDA_CONCAT_TRANSPOSE_TILE; j += CUDA_CONCAT_TRANSPOSE_ROWS) { + if (token_load + j < ne10) { +#pragma unroll + for (int k = 0; k < CUDA_CONCAT_TRANSPOSE_TILE; k += CUDA_CONCAT_TRANSPOSE_COLS) { + if (channel_load + k < ne1) { + tile[threadIdx.y + j][threadIdx.x + k] = src1[(token_load + j) * ne1 + channel_load + k]; + } + } + } + } + + __syncthreads(); + + const int64_t token_store = (int64_t) blockIdx.x * CUDA_CONCAT_TRANSPOSE_TILE + threadIdx.x; + const int64_t channel_store = (int64_t) blockIdx.y * CUDA_CONCAT_TRANSPOSE_TILE + threadIdx.y; +#pragma unroll + for (int j = 0; j < CUDA_CONCAT_TRANSPOSE_TILE; j += CUDA_CONCAT_TRANSPOSE_ROWS) { + if (channel_store + j < ne1) { +#pragma unroll + for (int k = 0; k < CUDA_CONCAT_TRANSPOSE_TILE; k += CUDA_CONCAT_TRANSPOSE_COLS) { + if (token_store + k < ne10) { + dst[(channel_store + j) * ne0 + ne00 + token_store + k] = tile[threadIdx.x + k][threadIdx.y + j]; + } + } + } + } + + if (blockIdx.x == 0) { + for (int64_t i = threadIdx.y * blockDim.x + threadIdx.x; + i < CUDA_CONCAT_TRANSPOSE_TILE * ne00; i += blockDim.x * blockDim.y) { + const int64_t channel = (int64_t) blockIdx.y * CUDA_CONCAT_TRANSPOSE_TILE + i / ne00; + const int64_t i0 = i % ne00; + if (channel < ne1) { + dst[channel * ne0 + i0] = src0[channel * ne00 + i0]; + } + } + } +} + // non-contiguous kernel (slow) template static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE) @@ -139,8 +197,79 @@ static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE) } } +// non-contiguous kernel for short rows: one thread per element, so a block is not left mostly idle on a row +template +static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE) + concat_non_cont_flat( + const char * src0, + const char * src1, + char * dst, + int64_t ne00, + int64_t ne01, + int64_t ne02, + int64_t ne03, + uint64_t nb00, + uint64_t nb01, + uint64_t nb02, + uint64_t nb03, + uint64_t nb10, + uint64_t nb11, + uint64_t nb12, + uint64_t nb13, + int64_t ne0, + int64_t ne1, + int64_t ne2, + int64_t ne3, + uint64_t nb0, + uint64_t nb1, + uint64_t nb2, + uint64_t nb3) { + static_assert(dim >= 0 && dim <= 3, "dim must be in [0, 3]"); + + const int64_t n = ne0*ne1*ne2*ne3; + + for (int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x; i < n; i += (int64_t) blockDim.x*gridDim.x) { + const int64_t i0 = i % ne0; + const int64_t i1 = (i / ne0) % ne1; + const int64_t i2 = (i / (ne0*ne1)) % ne2; + const int64_t i3 = i / (ne0*ne1*ne2); + + const T * x; + if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) { + x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00); + } else { + if constexpr (dim == 0) { + x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10); + } else if constexpr (dim == 1) { + x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10); + } else if constexpr (dim == 2) { + x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10); + } else { + x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10); + } + } + + *(T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0) = *x; + } +} + template -static void concat_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, int dim, cudaStream_t stream) { +static void concat_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, int dim, cudaStream_t stream, int cc) { + if (GGML_CUDA_CC_IS_RDNA3_5(cc) && src0->type == GGML_TYPE_F32 && dim == 0 && src0->ne[0] <= CUDA_CONCAT_TRANSPOSE_TILE && + src1->ne[0] >= CUDA_CONCAT_TRANSPOSE_TILE && src1->ne[1] >= CUDA_CONCAT_TRANSPOSE_TILE && + src0->ne[2] == 1 && src0->ne[3] == 1 && src1->ne[2] == 1 && src1->ne[3] == 1 && + ggml_is_contiguous(src0) && ggml_is_contiguous(dst) && + src1->nb[0] == src1->ne[1] * sizeof(uint32_t) && src1->nb[1] == sizeof(uint32_t)) { + const dim3 block_dim(CUDA_CONCAT_TRANSPOSE_COLS, CUDA_CONCAT_TRANSPOSE_ROWS); + const dim3 grid_dim( + (src1->ne[0] + CUDA_CONCAT_TRANSPOSE_TILE - 1) / CUDA_CONCAT_TRANSPOSE_TILE, + (src1->ne[1] + CUDA_CONCAT_TRANSPOSE_TILE - 1) / CUDA_CONCAT_TRANSPOSE_TILE); + concat_transpose_dim0_f32<<>>( + (const uint32_t *) src0->data, (const uint32_t *) src1->data, (uint32_t *) dst->data, + src0->ne[0], src1->ne[0], dst->ne[1], dst->ne[0]); + return; + } + if (dim != 3 && ggml_is_contiguous_to_3(src0) && ggml_is_contiguous_to_3(src1)) { const T * src0_d = (const T *) src0->data; const T * src1_d = (const T *) src1->data; @@ -165,6 +294,18 @@ static void concat_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml dim3 grid_dim(dst->ne[1], dst->ne[2], dst->ne[3]); auto launch_kernel = [&](auto dim) { + if (dst->ne[0] < CUDA_CONCAT_BLOCK_SIZE) { + const int64_t n = ggml_nelements(dst); + const int num_blocks = (int) std::min((n + CUDA_CONCAT_BLOCK_SIZE - 1) / CUDA_CONCAT_BLOCK_SIZE, 65535); + concat_non_cont_flat<<>>( + (const char *) src0->data, (const char *) src1->data, (char *) dst->data, + src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], + src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3], + src1->nb[0], src1->nb[1], src1->nb[2], src1->nb[3], + dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], + dst->nb[0], dst->nb[1], dst->nb[2], dst->nb[3]); + return; + } concat_non_cont<<>>( (const char *) src0->data, (const char *) src1->data, (char *) dst->data, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], @@ -198,6 +339,7 @@ void ggml_cuda_op_concat(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * src1 = dst->src[1]; cudaStream_t stream = ctx.stream(); + const int cc = ggml_cuda_info().devices[ctx.device].cc; const int32_t dim = ((int32_t *) dst->op_params)[0]; @@ -216,22 +358,22 @@ void ggml_cuda_op_concat(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { GGML_ASSERT(src1->ne[0] % ggml_blck_size(src1->type) == 0); // if first 3 dimensions are contiguous and ne[0] is multiple of the block size we can concat both tensors as byte tensors - concat_cuda(src0, src1, dst, dim, stream); + concat_cuda(src0, src1, dst, dim, stream, cc); } else { GGML_ASSERT(ggml_blck_size(src0->type) == 1); switch (ggml_type_size(src0->type)) { case 1: - concat_cuda(src0, src1, dst, dim, stream); + concat_cuda(src0, src1, dst, dim, stream, cc); break; case 2: - concat_cuda(src0, src1, dst, dim, stream); + concat_cuda(src0, src1, dst, dim, stream, cc); break; case 4: - concat_cuda(src0, src1, dst, dim, stream); + concat_cuda(src0, src1, dst, dim, stream, cc); break; case 8: - concat_cuda(src0, src1, dst, dim, stream); + concat_cuda(src0, src1, dst, dim, stream, cc); break; default: GGML_ABORT("Unsupported type size: %zu", ggml_type_size(src0->type)); diff --git a/ggml/src/ggml-cuda/dense-wmma.cu b/ggml/src/ggml-cuda/dense-wmma.cu new file mode 100644 index 000000000000..e65dd327f07d --- /dev/null +++ b/ggml/src/ggml-cuda/dense-wmma.cu @@ -0,0 +1,636 @@ +// Dense matrix multiplication of a prompt batch with BF16 WMMA on RDNA3: dst[r, t] = w[r, :] . x[t, :] for BF16 copies +// of the weights, made once before the first graph, and F32 activations, which are rounded to BF16 first (once for the +// products that read the same activations one after another). A copy is tiled: per tile of 128 rows, the 128 x 64 +// values of each K step follow one another (16 KB, row-major within), so that the weights of a step are one +// contiguous read. +// +// A block computes 128 tokens x BR rows (128, or 256 when all row counts allow it, which reads a quarter fewer bytes per +// product) with BR / 16 waves of 64 tokens x 32 rows (2 waves over the tokens). K goes in steps of 64 through one LDS +// buffer, the next step loaded into registers during the products: a row of a step is a whole 128 byte cache line, which +// steps of 32 read in halves at different times, so that most halves became a line request of their own to L2. The 16 +// byte chunks of an LDS row are swizzled against bank conflicts instead of padded. The activations are the A operand +// and the weights the B operand of v_wmma_f32_16x16x16_bf16, so a lane of the D fragment holds one row of 8 tokens, and +// 16 lanes store 16 consecutive rows of a token. The row tiles of up to GGML_CUDA_DENSE_GROUP_MAX products of the same +// activations follow one another in the grid. + +#include "dense-wmma.cuh" +#include "convert.cuh" +#include "mmq.cuh" + +#include + +#if defined(GGML_USE_HIP) + +static constexpr int DW_BT = 128; // tokens per block +static constexpr int DW_BR = 128; // rows per block at least +static constexpr int DW_BK = 64; // K per step +static constexpr int DW_SPLIT = 2; // interleaved partitions of the row tiles, see dense_wmma_kernel +static constexpr int DW_TR = 128; // rows of a tile of the weight copies + +// clang vectors: the HIP vector types are structs, which copies from global memory leave on the stack +typedef short dw_short16 __attribute__((ext_vector_type(16))); +typedef uint32_t dw_uint4 __attribute__((ext_vector_type(4))); +typedef uint32_t dw_uint8 __attribute__((ext_vector_type(8))); +typedef float dw_float8 __attribute__((ext_vector_type(8))); + +static __device__ __forceinline__ uint32_t dw_pack_bf16(const float lo, const float hi) { + const uint32_t ul = __float_as_uint(lo), uh = __float_as_uint(hi); + return ((uh + 0x7FFFu + ((uh >> 16) & 1u)) & 0xFFFF0000u) | ((ul + 0x7FFFu + ((ul >> 16) & 1u)) >> 16); +} + +// barrier for the LDS only: __syncthreads also waits for the prefetched global loads +static __device__ __forceinline__ void dw_lds_sync() { + asm volatile("s_waitcnt lgkmcnt(0)\n\ts_barrier" ::: "memory"); +} + +// the offset of chunk c (8 BF16 values) of LDS row r: the 8 chunks of a 128 byte row are permuted with bits 0..3 of r, +// so that 8 consecutive rows read with 128 bit loads hit distinct banks of 128 bytes, and 16 rows those of 256 bytes +static __device__ __forceinline__ int dw_off(const int r, const int c) { + return r * DW_BK + 8 * (c ^ ((r ^ (r >> 3)) & 7)); +} + +// the 16 K values of chunks c0, c0 + 1 of LDS row r as a WMMA fragment +static __device__ __forceinline__ dw_short16 dw_frag(const uint16_t * t, const int r, const int c0) { + const dw_uint4 lo = *(const dw_uint4 *) (t + dw_off(r, c0)); + const dw_uint4 hi = *(const dw_uint4 *) (t + dw_off(r, c0 + 1)); + return __builtin_bit_cast(dw_short16, dw_uint8{lo.x, lo.y, lo.z, lo.w, hi.x, hi.y, hi.z, hi.w}); +} + +// 4 values per thread, rows of K values +static __global__ void dense_wmma_to_bf16(const float * __restrict__ x, const int64_t sx, uint32_t * __restrict__ y, + const int K, const int N) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + const int k4 = K / 4; + if (i >= (int64_t) N * k4) { + return; + } + const int64_t t = i / k4; + const int k = 4 * (i % k4); + const float4 v = *(const float4 *) (x + t * sx + k); + *(uint2 *) (y + (t * K + k) / 2) = make_uint2(dw_pack_bf16(v.x, v.y), dw_pack_bf16(v.z, v.w)); +} + +// the tiled copy of rows x K BF16 values with a row stride of s values: 8 values per thread +static __global__ void dense_wmma_retile_kernel(const uint16_t * __restrict__ src, const int64_t s, uint16_t * __restrict__ dst, + const int K, const int64_t rows) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * (K / 8)) { + return; + } + const int64_t r = i / (K / 8); + const int k = 8 * (int) (i % (K / 8)); + const int64_t o = ((r / DW_TR * (K / DW_BK) + k / DW_BK) * DW_TR + r % DW_TR) * DW_BK + k % DW_BK; + *(uint4 *) (dst + o) = *(const uint4 *) (src + r * s + k); +} + +struct dense_wmma_args { + const uint16_t * w[GGML_CUDA_DENSE_GROUP_MAX]; // tiled BF16 weights + float * dst[GGML_CUDA_DENSE_GROUP_MAX]; + int64_t sd[GGML_CUDA_DENSE_GROUP_MAX]; // dst column strides in values + int tile0[GGML_CUDA_DENSE_GROUP_MAX + 1]; // the first row tile of each product in the grid, then the total + const uint16_t * x; // BF16 activations, K per token + int K, N; + int tiles_t; // token tiles +}; + +template +static __global__ void __launch_bounds__(2 * BR) dense_wmma_kernel(const dense_wmma_args a) { +#if defined(AMD_WMMA_256B_AVAILABLE) + constexpr int NT = 2 * BR; + constexpr int CR = DW_BK / 8; // 16 byte chunks of a row + constexpr int CX = DW_BT * CR / NT; // chunks of activations per thread and step + constexpr int CW = BR * CR / NT; // of weights + __shared__ __attribute__((aligned(16))) uint16_t xs[DW_BT * DW_BK]; + __shared__ __attribute__((aligned(16))) uint16_t ws[BR * DW_BK]; + + // block bid of the 1D grid: the even blocks take the even row tiles and the odd blocks the odd ones, the token tile + // varying fastest. The two halves of the blocks run on different parts of the GPU, so the blocks running at the same + // time on each read the same weights (measured: L2 hit rate 60 -> 67%, 8% faster; groups of 4 or 8 parts, or fewer + // token tiles per group of consecutive blocks, were slower or within 0.3% overall, also with 128 row tiles). + const int bid = blockIdx.x; + const int kb = bid / DW_SPLIT; + const int tt = kb % a.tiles_t; + const int rt = (kb / a.tiles_t) * DW_SPLIT + bid % DW_SPLIT; + if (rt >= a.tile0[GGML_CUDA_DENSE_GROUP_MAX]) { + return; // the row tiles rounded up to a multiple of DW_SPLIT + } + + int g = 0; +#pragma unroll + for (int k = 1; k < GGML_CUDA_DENSE_GROUP_MAX; ++k) { + g += rt >= a.tile0[k]; + } + const uint16_t * w = a.w[g]; + float * dst = a.dst[g]; + const int64_t sd = a.sd[g]; + const uint16_t * x = a.x; + const int K = a.K, N = a.N; + + const int tid = threadIdx.x; + const int t0 = tt * DW_BT; + const int r0 = (rt - a.tile0[g]) * BR; + + // loads of a step: chunk tid + j * NT is chunk % CR of row / token chunk / CR, 8 lanes read a whole row; a token past + // N reads token 0 instead, its products are not stored + const uint16_t * xp[CX]; + const uint16_t * wp[CW]; + int xo[CX], wo[CW]; +#pragma unroll + for (int j = 0; j < CX; ++j) { + const int ci = tid + j * NT, t = ci / CR, c = ci % CR; + xp[j] = x + (int64_t) (t0 + t < N ? t0 + t : 0) * K + 8 * c; + xo[j] = dw_off(t, c); + } + // the weights of row R of step s: tile R / DW_TR, then step s of it, then row R % DW_TR +#pragma unroll + for (int j = 0; j < CW; ++j) { + const int ci = tid + j * NT, r = ci / CR, c = ci % CR, R = r0 + r; + wp[j] = w + ((int64_t) (R / DW_TR) * (K / DW_BK) * DW_TR + R % DW_TR) * DW_BK + 8 * c; + wo[j] = dw_off(r, c); + } + + dw_uint4 xv[CX], wv[CW]; +#define DW_LOAD(s) \ + _Pragma("unroll") for (int j = 0; j < CX; ++j) { xv[j] = *(const dw_uint4 *) (xp[j] + (s) * DW_BK); } \ + _Pragma("unroll") for (int j = 0; j < CW; ++j) { wv[j] = *(const dw_uint4 *) (wp[j] + (int64_t) (s) * DW_TR * DW_BK); } +#define DW_STORE() \ + _Pragma("unroll") for (int j = 0; j < CX; ++j) { *(dw_uint4 *) (xs + xo[j]) = xv[j]; } \ + _Pragma("unroll") for (int j = 0; j < CW; ++j) { *(dw_uint4 *) (ws + wo[j]) = wv[j]; } + + const int lane = threadIdx.x % 32, wave = threadIdx.x / 32, hw = lane / 16, r16 = lane % 16; + const int wt = 64 * (wave % 2); // tokens of this wave in the block + const int wr = 32 * (wave / 2); // rows of this wave in the block (BR / 32 waves) + + dw_float8 acc[4][2] = {}; + + // the weight fragments of a 16 K step, then an activation fragment at a time. The scheduler groups (0x100 LDS + // reads, 0x008 WMMA) load the next activation fragment during the products of the previous one: 6 reads (both + // weight fragments and the first activation fragment), then 3 times 2 reads and 2 products, then 2 products. The + // scheduler barrier keeps the loads of the second step after the products of the first, which would otherwise + // hold twice the fragments. +#define DW_COMPUTE() \ + _Pragma("unroll") for (int kk = 0; kk < DW_BK / 16; ++kk) { \ + dw_short16 bv[2]; \ + _Pragma("unroll") for (int j = 0; j < 2; ++j) { \ + bv[j] = dw_frag(ws, wr + 16 * j + r16, 2 * kk); \ + } \ + _Pragma("unroll") for (int i = 0; i < 4; ++i) { \ + const dw_short16 av = dw_frag(xs, wt + 16 * i + r16, 2 * kk); \ + _Pragma("unroll") for (int j = 0; j < 2; ++j) { \ + acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(av, bv[j], acc[i][j]); \ + } \ + } \ + __builtin_amdgcn_sched_group_barrier(0x100, 6, 0); \ + _Pragma("unroll") for (int i = 0; i < 3; ++i) { \ + __builtin_amdgcn_sched_group_barrier(0x100, 2, 0); \ + __builtin_amdgcn_sched_group_barrier(0x008, 2, 0); \ + } \ + __builtin_amdgcn_sched_group_barrier(0x008, 2, 0); \ + __builtin_amdgcn_sched_barrier(0); \ + } + + // step s from the LDS while the registers receive step s + 1, which goes to the LDS between two barriers + const int steps = K / DW_BK; + DW_LOAD(0); + DW_STORE(); + if (steps > 1) { + DW_LOAD(1); + } + dw_lds_sync(); + + for (int s = 0; s < steps; ++s) { + DW_COMPUTE(); + if (s + 1 < steps) { + dw_lds_sync(); + DW_STORE(); + if (s + 2 < steps) { + DW_LOAD(s + 2); + } + dw_lds_sync(); + } + } +#undef DW_COMPUTE +#undef DW_LOAD +#undef DW_STORE + + // D: lane holds column (row of dst) r16 and A rows (tokens) 2*v + hw +#pragma unroll + for (int i = 0; i < 4; ++i) { +#pragma unroll + for (int v = 0; v < 8; ++v) { + const int t = t0 + wt + 16 * i + 2 * v + hw; + if (t < N) { +#pragma unroll + for (int j = 0; j < 2; ++j) { + dst[(int64_t) t * sd + r0 + wr + 16 * j + r16] = acc[i][j][v]; + } + } + } + } +#else + GGML_UNUSED(a); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + +// x = h + l with h and l rounded to BF16 (to about 2^-16 relative), pairs packed with the first value in the low halves +static __device__ __forceinline__ void dw_split(const float a, const float b, uint32_t & h, uint32_t & l) { + h = dw_pack_bf16(a, b); + l = dw_pack_bf16(a - __uint_as_float(h << 16), b - __uint_as_float(h & 0xFFFF0000u)); +} + +struct dense_wmma_f32_args { + const float * w[GGML_CUDA_DENSE_GROUP_MAX]; // F32 weights, rows of K values + int64_t sw[GGML_CUDA_DENSE_GROUP_MAX]; // their row strides in values + float * dst[GGML_CUDA_DENSE_GROUP_MAX]; + int64_t sd[GGML_CUDA_DENSE_GROUP_MAX]; + int rows[GGML_CUDA_DENSE_GROUP_MAX]; + int tile0[GGML_CUDA_DENSE_GROUP_MAX + 1]; + const float * x; // F32 activations, K per token at stride sx + int64_t sx; + int K, N; + int tiles_t; +}; + +// The F32 variant for F32 weights (routers and gates of a few dozen rows, a small part of the time): both operands are +// read in place as F32 and split into BF16 high and residual parts on the way to the LDS, each product as +// lo*hi + hi*lo + hi*hi, so that the results are within about FP32 rounding of an F32 GEMM (BF16 activations cost the +// routing and the decays of the linear attention measurable quality). With W_BF16 the weights are BF16 values (as +// those of the Qwen routers and gates), whose residual parts are zero: lo*hi + hi*hi. Blocks of 128 tokens x 128 rows as +// in dense_wmma_kernel, the last row tile of a product may be partial. +template +static __global__ void __launch_bounds__(2 * DW_BR) dense_wmma_f32_kernel(const dense_wmma_f32_args a) { +#if defined(AMD_WMMA_256B_AVAILABLE) + constexpr int BR = DW_BR; + constexpr int NT = 2 * BR; + constexpr int CR = DW_BK / 8; + constexpr int CX = DW_BT * CR / NT; + constexpr int CW = BR * CR / NT; + __shared__ __attribute__((aligned(16))) uint16_t xs[2][DW_BT * DW_BK]; // high, residual + __shared__ __attribute__((aligned(16))) uint16_t ws[W_BF16 ? 1 : 2][BR * DW_BK]; + + const int bid = blockIdx.x; + const int kb = bid / DW_SPLIT; + const int tt = kb % a.tiles_t; + const int rt = (kb / a.tiles_t) * DW_SPLIT + bid % DW_SPLIT; + if (rt >= a.tile0[GGML_CUDA_DENSE_GROUP_MAX]) { + return; + } + + int g = 0; +#pragma unroll + for (int k = 1; k < GGML_CUDA_DENSE_GROUP_MAX; ++k) { + g += rt >= a.tile0[k]; + } + const float * w = a.w[g]; + float * dst = a.dst[g]; + const int64_t sd = a.sd[g]; + const int nr = a.rows[g]; + const int K = a.K, N = a.N; + + const int tid = threadIdx.x; + const int t0 = tt * DW_BT; + const int r0 = (rt - a.tile0[g]) * BR; + + // as in dense_wmma_kernel, chunks of 8 values; a token past N and a row past nr read token / row 0 instead + const float * xp[CX]; + const float * wp[CW]; + int xo[CX], wo[CW]; +#pragma unroll + for (int j = 0; j < CX; ++j) { + const int ci = tid + j * NT, t = ci / CR, c = ci % CR; + xp[j] = a.x + (int64_t) (t0 + t < N ? t0 + t : 0) * a.sx + 8 * c; + xo[j] = dw_off(t, c); + } +#pragma unroll + for (int j = 0; j < CW; ++j) { + const int ci = tid + j * NT, r = ci / CR, c = ci % CR, R = r0 + r; + wp[j] = w + (int64_t) (R < nr ? R : 0) * a.sw[g] + 8 * c; + wo[j] = dw_off(r, c); + } + + float4 xv[CX][2], wv[CW][2]; +#define DWF_LOAD(s) \ + _Pragma("unroll") for (int j = 0; j < CX; ++j) { \ + xv[j][0] = *(const float4 *) (xp[j] + (s) * DW_BK); xv[j][1] = *(const float4 *) (xp[j] + (s) * DW_BK + 4); \ + } \ + _Pragma("unroll") for (int j = 0; j < CW; ++j) { \ + wv[j][0] = *(const float4 *) (wp[j] + (s) * DW_BK); wv[j][1] = *(const float4 *) (wp[j] + (s) * DW_BK + 4); \ + } +#define DWF_SPLIT_STORE(v, t, o) \ + { \ + uint32_t h0, h1, h2, h3, l0, l1, l2, l3; \ + dw_split((v)[0].x, (v)[0].y, h0, l0); dw_split((v)[0].z, (v)[0].w, h1, l1); \ + dw_split((v)[1].x, (v)[1].y, h2, l2); dw_split((v)[1].z, (v)[1].w, h3, l3); \ + *(dw_uint4 *) ((t)[0] + (o)) = dw_uint4{h0, h1, h2, h3}; \ + *(dw_uint4 *) ((t)[1] + (o)) = dw_uint4{l0, l1, l2, l3}; \ + } +#define DWF_STORE() \ + _Pragma("unroll") for (int j = 0; j < CX; ++j) { DWF_SPLIT_STORE(xv[j], xs, xo[j]) } \ + _Pragma("unroll") for (int j = 0; j < CW; ++j) { \ + if constexpr (W_BF16) { \ + *(dw_uint4 *) (ws[0] + wo[j]) = dw_uint4{dw_pack_bf16(wv[j][0].x, wv[j][0].y), dw_pack_bf16(wv[j][0].z, wv[j][0].w), \ + dw_pack_bf16(wv[j][1].x, wv[j][1].y), dw_pack_bf16(wv[j][1].z, wv[j][1].w)}; \ + } else { \ + DWF_SPLIT_STORE(wv[j], ws, wo[j]) \ + } \ + } + + const int lane = threadIdx.x % 32, wave = threadIdx.x / 32, hw = lane / 16, r16 = lane % 16; + const int wt = 64 * (wave % 2); + const int wr = 32 * (wave / 2); + + dw_float8 acc[4][2] = {}; + + const int steps = K / DW_BK; + DWF_LOAD(0); + DWF_STORE(); + if (steps > 1) { + DWF_LOAD(1); + } + dw_lds_sync(); + + for (int s = 0; s < steps; ++s) { +#pragma unroll + for (int kk = 0; kk < DW_BK / 16; ++kk) { + dw_short16 bh[2], bl[2]; +#pragma unroll + for (int j = 0; j < 2; ++j) { + bh[j] = dw_frag(ws[0], wr + 16 * j + r16, 2 * kk); + if constexpr (!W_BF16) { + bl[j] = dw_frag(ws[W_BF16 ? 0 : 1], wr + 16 * j + r16, 2 * kk); + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + const dw_short16 ah = dw_frag(xs[0], wt + 16 * i + r16, 2 * kk); + const dw_short16 al = dw_frag(xs[1], wt + 16 * i + r16, 2 * kk); +#pragma unroll + for (int j = 0; j < 2; ++j) { + acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(al, bh[j], acc[i][j]); + if constexpr (!W_BF16) { + acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(ah, bl[j], acc[i][j]); + } + acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(ah, bh[j], acc[i][j]); + } + } + } + if (s + 1 < steps) { + dw_lds_sync(); + DWF_STORE(); + if (s + 2 < steps) { + DWF_LOAD(s + 2); + } + dw_lds_sync(); + } + } +#undef DWF_LOAD +#undef DWF_SPLIT_STORE +#undef DWF_STORE + +#pragma unroll + for (int i = 0; i < 4; ++i) { +#pragma unroll + for (int v = 0; v < 8; ++v) { + const int t = t0 + wt + 16 * i + 2 * v + hw; + if (t < N) { +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int r = r0 + wr + 16 * j + r16; + if (r < nr) { + dst[(int64_t) t * sd + r] = acc[i][j][v]; + } + } + } + } + } +#else + GGML_UNUSED(a); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + +static bool dense_wmma_enabled(const int cc) { + static const bool disabled = getenv("GGML_CUDA_NO_DENSE_WMMA") != nullptr; + return !disabled && GGML_CUDA_CC_IS_RDNA3(cc); +} + +// the shape of a weight that the kernel takes: whole row tiles and K steps +static bool dense_wmma_weight_shape(const ggml_tensor * w) { + return w->ne[1] % DW_BR == 0 && w->ne[0] % DW_BK == 0 && w->ne[2] == 1 && w->ne[3] == 1; +} + +// an F32 weight that the F32 variant reads in place: routers and gates of a few dozen rows or more, whole K steps +static bool dense_wmma_f32_weight(const ggml_tensor * w) { + static const bool off = getenv("GGML_CUDA_NO_DENSE_F32") != nullptr; + return !off && w->type == GGML_TYPE_F32 && w->ne[1] > 8 && w->ne[0] % DW_BK == 0 && w->ne[2] == 1 && w->ne[3] == 1 && + w->nb[0] == sizeof(float) && w->nb[1] % 16 == 0 && (uintptr_t) w->data % 16 == 0 && w->buffer != nullptr && + ggml_backend_buffer_get_usage(w->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS; +} + +// a weight that gets a tiled BF16 copy: BF16, or a K-quant one that a prompt batch would multiply with hipBLAS (no MMQ +// for many columns) +static bool dense_wmma_copies(const ggml_tensor * w, const int cc) { + const bool quant = ggml_is_quantized(w->type) && ggml_get_to_bf16_cuda(w->type) != nullptr && + !ggml_cuda_should_use_mmq(w->type, cc, 4096, /*n_experts =*/ 0); + return (quant || w->type == GGML_TYPE_BF16) && w->buffer != nullptr && + ggml_backend_buffer_get_usage(w->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && ggml_is_contiguous(w) && + (uintptr_t) w->data % 16 == 0 && dense_wmma_weight_shape(w); +} + +void ggml_cuda_dense_wmma_retile(const void * src, const int64_t s, void * dst, const int64_t rows, const int K, cudaStream_t stream) { + const int64_t n = rows * (K / 8); + dense_wmma_retile_kernel<<<(n + 255) / 256, 256, 0, stream>>>((const uint16_t *) src, s, (uint16_t *) dst, K, rows); + CUDA_CHECK(cudaGetLastError()); +} + + +bool ggml_cuda_dense_wmma_wants_copy(const ggml_backend_cuda_context & ctx, const ggml_tensor * w) { + const int cc = ggml_cuda_info().devices[ctx.device].cc; + return dense_wmma_enabled(cc) && dense_wmma_copies(w, cc) && ctx.dense_bf16.count(w->data) == 0; +} + +// the tiled BF16 copy of a weight, or nullptr +static const uint16_t * dense_wmma_weight(const ggml_backend_cuda_context & ctx, const ggml_tensor * w) { + if (!dense_wmma_weight_shape(w)) { + return nullptr; + } + const auto it = ctx.dense_bf16.find(w->data); + return it == ctx.dense_bf16.end() ? nullptr : (const uint16_t *) it->second; +} + +bool ggml_cuda_dense_wmma_supported(const ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, + const ggml_tensor * dst) { + if (!dense_wmma_enabled(ggml_cuda_info().devices[ctx.device].cc)) { + return false; + } + return (dense_wmma_weight(ctx, src0) != nullptr || dense_wmma_f32_weight(src0)) && src1->type == GGML_TYPE_F32 && + dst->type == GGML_TYPE_F32 && src1->ne[2] == 1 && src1->ne[3] == 1 && src1->nb[0] == sizeof(float) && + src1->nb[1] % 16 == 0 && (uintptr_t) src1->data % 16 == 0 && dst->nb[0] == sizeof(float) && + dst->nb[1] % sizeof(float) == 0; +} + +bool ggml_cuda_dense_wmma_is_f32(const ggml_tensor * w) { + return dense_wmma_f32_weight(w); +} + +// ORs the low halves of n F32 values into *bits +static __global__ void dense_wmma_low_bits(const uint32_t * __restrict__ x, const int64_t n, uint32_t * __restrict__ bits) { + uint32_t b = 0; + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { + b |= x[i] & 0xFFFFu; + } + if (b != 0) { + atomicOr(bits, b); + } +} + +void ggml_cuda_dense_wmma_prepare_f32(ggml_backend_cuda_context & ctx, const ggml_tensor * w) { + if (!dense_wmma_enabled(ggml_cuda_info().devices[ctx.device].cc) || !dense_wmma_f32_weight(w) || + ctx.dense_f32_bf16.count(w->data) != 0 || !ggml_is_contiguous(w)) { + return; + } + ggml_cuda_pool_alloc bits(ctx.pool(), 1); + CUDA_CHECK(cudaMemsetAsync(bits.get(), 0, sizeof(uint32_t), ctx.stream())); + dense_wmma_low_bits<<<64, 256, 0, ctx.stream()>>>((const uint32_t *) w->data, ggml_nelements(w), bits.get()); + CUDA_CHECK(cudaGetLastError()); + uint32_t h = 1; + CUDA_CHECK(cudaMemcpyAsync(&h, bits.get(), sizeof(uint32_t), cudaMemcpyDeviceToHost, ctx.stream())); + CUDA_CHECK(cudaStreamSynchronize(ctx.stream())); + ctx.dense_f32_bf16[w->data] = h == 0; +} + +static void dense_wmma_f32(ggml_backend_cuda_context & ctx, const ggml_tensor * const * dsts, const int n) { + const ggml_tensor * src1 = dsts[0]->src[1]; + dense_wmma_f32_args a = {}; + bool w_bf16 = true; + int tiles = 0; + for (int g = 0; g < GGML_CUDA_DENSE_GROUP_MAX; ++g) { + a.tile0[g] = tiles; + if (g >= n) { + a.tile0[g] = INT_MAX; + continue; + } + const ggml_tensor * dst = dsts[g]; + const ggml_tensor * w = dst->src[0]; + GGML_ASSERT(dst->src[1] == src1 && dense_wmma_f32_weight(w)); + const auto it = ctx.dense_f32_bf16.find(w->data); + w_bf16 = w_bf16 && it != ctx.dense_f32_bf16.end() && it->second; + a.w[g] = (const float *) w->data; + a.sw[g] = w->nb[1] / sizeof(float); + a.dst[g] = (float *) dst->data; + a.sd[g] = dst->nb[1] / sizeof(float); + a.rows[g] = w->ne[1]; + tiles += (w->ne[1] + DW_BR - 1) / DW_BR; + } + a.x = (const float *) src1->data; + a.sx = src1->nb[1] / sizeof(float); + a.K = src1->ne[0]; + a.N = src1->ne[1]; + a.tiles_t = (a.N + DW_BT - 1) / DW_BT; + a.tile0[GGML_CUDA_DENSE_GROUP_MAX] = tiles; + + const dim3 grid(a.tiles_t * ((tiles + DW_SPLIT - 1) / DW_SPLIT) * DW_SPLIT); + if (w_bf16) { + dense_wmma_f32_kernel<<>>(a); + } else { + dense_wmma_f32_kernel<<>>(a); + } + CUDA_CHECK(cudaGetLastError()); +} + +static const uint16_t * dense_wmma_x(ggml_backend_cuda_context & ctx, const ggml_tensor * src1, int K, int N); + +void ggml_cuda_dense_wmma(ggml_backend_cuda_context & ctx, const ggml_tensor * const * dsts, const int n) { + GGML_ASSERT(n >= 1 && n <= GGML_CUDA_DENSE_GROUP_MAX); + if (dense_wmma_f32_weight(dsts[0]->src[0])) { + dense_wmma_f32(ctx, dsts, n); + return; + } + const ggml_tensor * src1 = dsts[0]->src[1]; + const int K = src1->ne[0]; + const int N = src1->ne[1]; + cudaStream_t stream = ctx.stream(); + + // the hyper-connection pre-mix wrote it as BF16 already + const uint16_t * x = src1 == ctx.hc_bf16_src && src1->nb[1] == K * sizeof(float) ? ctx.hc_bf16_buf : dense_wmma_x(ctx, src1, K, N); + + // the larger row tile if every product has whole tiles of 256 rows + bool br256 = true; + for (int g = 0; g < n; ++g) { + br256 = br256 && dsts[g]->src[0]->ne[1] % 256 == 0; + } + const int BR = br256 ? 256 : DW_BR; + + dense_wmma_args a = {}; + int tiles = 0; + for (int g = 0; g < GGML_CUDA_DENSE_GROUP_MAX; ++g) { + a.tile0[g] = tiles; + if (g >= n) { + a.tile0[g] = INT_MAX; + continue; + } + const ggml_tensor * dst = dsts[g]; + GGML_ASSERT(dst->src[1] == src1); + a.w[g] = dense_wmma_weight(ctx, dst->src[0]); + GGML_ASSERT(a.w[g] != nullptr); + a.dst[g] = (float *) dst->data; + a.sd[g] = dst->nb[1] / sizeof(float); + tiles += dst->src[0]->ne[1] / BR; + } + a.x = x; + a.K = K; + a.N = N; + a.tiles_t = (N + DW_BT - 1) / DW_BT; + a.tile0[GGML_CUDA_DENSE_GROUP_MAX] = tiles; + + const dim3 grid(a.tiles_t * ((tiles + DW_SPLIT - 1) / DW_SPLIT) * DW_SPLIT); + if (br256) { + dense_wmma_kernel<256><<>>(a); + } else { + dense_wmma_kernel<<>>(a); + } + CUDA_CHECK(cudaGetLastError()); +} + +// the BF16 activations of src1 (F32, K per token at stride nb1): converted once per tensor and stream +static const uint16_t * dense_wmma_x(ggml_backend_cuda_context & ctx, const ggml_tensor * src1, const int K, const int N) { + cudaStream_t stream = ctx.stream(); + if (ctx.dense_x_src != src1 || ctx.dense_x_stream != stream) { + uint16_t * xb = (uint16_t *) ggml_cuda_dense_x_reserve(ctx, (size_t) N * K * sizeof(uint16_t)); + const int64_t n4 = (int64_t) N * (K / 4); + dense_wmma_to_bf16<<<(n4 + 255) / 256, 256, 0, stream>>>((const float *) src1->data, src1->nb[1] / sizeof(float), + (uint32_t *) xb, K, N); + CUDA_CHECK(cudaGetLastError()); + ctx.dense_x_src = src1; + ctx.dense_x_stream = stream; + } + return (const uint16_t *) ctx.dense_x_buf; +} + +#else + +bool ggml_cuda_dense_wmma_supported(const ggml_backend_cuda_context &, const ggml_tensor *, const ggml_tensor *, const ggml_tensor *) { + return false; +} + +void ggml_cuda_dense_wmma(ggml_backend_cuda_context &, const ggml_tensor * const *, int) { + GGML_ABORT("not supported"); +} + +bool ggml_cuda_dense_wmma_wants_copy(const ggml_backend_cuda_context &, const ggml_tensor *) { + return false; +} + +bool ggml_cuda_dense_wmma_is_f32(const ggml_tensor *) { + return false; +} + +void ggml_cuda_dense_wmma_prepare_f32(ggml_backend_cuda_context &, const ggml_tensor *) { +} + +void ggml_cuda_dense_wmma_retile(const void *, int64_t, void *, int64_t, int, cudaStream_t) { + GGML_ABORT("not supported"); +} + +#endif // defined(GGML_USE_HIP) diff --git a/ggml/src/ggml-cuda/dense-wmma.cuh b/ggml/src/ggml-cuda/dense-wmma.cuh new file mode 100644 index 000000000000..98bb57d354f3 --- /dev/null +++ b/ggml/src/ggml-cuda/dense-wmma.cuh @@ -0,0 +1,33 @@ +#pragma once + +#include "common.cuh" + +// the most MUL_MATs of the same activations that one launch of ggml_cuda_dense_wmma computes +#define GGML_CUDA_DENSE_GROUP_MAX 4 + +// dst = src0 * src1 of a prompt batch with BF16 WMMA (RDNA3), with the tiled BF16 copies that ggml_cuda_prepare_dense_bf16 +// makes of BF16 weights and of the K-quant weights that would otherwise go to hipBLAS; F32 weights (routers, gates) are +// read in place and split into BF16 high and residual parts +bool ggml_cuda_dense_wmma_supported(const ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, + const ggml_tensor * dst); + +// the MUL_MATs dsts[0..n-1] of the same src1 in one launch +void ggml_cuda_dense_wmma(ggml_backend_cuda_context & ctx, const ggml_tensor * const * dsts, int n); + +// a weight of a MUL_MAT that is to get a tiled BF16 copy in ctx.dense_bf16 (not yet made); GGML_CUDA_NO_DENSE_WMMA +// disables the copies and the kernel +bool ggml_cuda_dense_wmma_wants_copy(const ggml_backend_cuda_context & ctx, const ggml_tensor * w); + +// whether the product of w goes to the F32 variant (no copy, products to about FP32 precision); the MUL_MATs of one +// launch are all of one variant +bool ggml_cuda_dense_wmma_is_f32(const ggml_tensor * w); + +// records in ctx.dense_f32_bf16 whether the F32 weight w holds BF16 values only (once per weight, synchronizes), which +// lets the F32 variant skip their residual parts +void ggml_cuda_dense_wmma_prepare_f32(ggml_backend_cuda_context & ctx, const ggml_tensor * w); + +// the tiled copy (see dense-wmma.cu) of rows x K BF16 values with a row stride of s values +void ggml_cuda_dense_wmma_retile(const void * src, int64_t s, void * dst, int64_t rows, int K, cudaStream_t stream); + +// ctx.dense_x_buf with at least the given bytes, for the BF16 activations +void * ggml_cuda_dense_x_reserve(ggml_backend_cuda_context & ctx, size_t size); diff --git a/ggml/src/ggml-cuda/dsv4-hc.cu b/ggml/src/ggml-cuda/dsv4-hc.cu index 2d0b3cfeaed7..c3606fc42627 100644 --- a/ggml/src/ggml-cuda/dsv4-hc.cu +++ b/ggml/src/ggml-cuda/dsv4-hc.cu @@ -116,7 +116,8 @@ static __global__ void dsv4_hc_pre_f32( int64_t sw2, int64_t sd0, int64_t sd1, - float scale) { + float scale, + block_q8_1 * q8_1) { ggml_cuda_pdl_lc(); const int64_t ir = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; const int64_t nr = n_embd * n_tokens; @@ -142,7 +143,22 @@ static __global__ void dsv4_hc_pre_f32( sum += xv * wv; } - dst[i0*sd0 + it*sd1] = scale * sum; + const float v = scale * sum; + dst[i0*sd0 + it*sd1] = v; + + if (q8_1 != nullptr) { + // MMVQ's q8_1 copy as quantize_q8_1 makes it: the 32 lanes of a warp hold one block, all of them active + // since n_embd is a multiple of MATRIX_ROW_PADDING + float amax = warp_reduce_max(fabsf(v)); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(v / d); + const int sum_q = warp_reduce_sum((int) q); + block_q8_1 & y = q8_1[ir / QK8_1]; + y.qs[ir % QK8_1] = q; + if (ir % QK8_1 == 0) { + y.ds = make_half2(d, d * sum_q); + } + } } // gated: post = gate_scale_out*sigmoid(gate_scale_in*post), the fused SCALE -> SIGMOID -> SCALE chain of qwen4exp @@ -270,6 +286,14 @@ void ggml_cuda_op_dsv4_hc_pre(ggml_backend_cuda_context & ctx, ggml_tensor * dst const dim3 grid_dims((nr + block_size - 1) / block_size, 1, 1); const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(grid_dims, block_dims, 0, ctx.stream()); + // the q8_1 copy for MMVQ (see ggml_cuda_q8_1_cache), one 32-lane warp per q8_1 block + block_q8_1 * q8_1 = nullptr; + if (ctx.out_q8_1 && ggml_cuda_info().devices[ctx.device].warp_size == QK8_1 && ggml_is_contiguous(dst) && + n_embd % MATRIX_ROW_PADDING == 0) { + q8_1 = ctx.out_q8_1; + ctx.out_q8_1_written = true; + } + auto kernel = gated ? dsv4_hc_pre_f32 : dsv4_hc_pre_f32; ggml_cuda_kernel_launch(kernel, launch_params, (const float *) x->data, (const float *) weights->data, (float *) dst->data, @@ -277,11 +301,11 @@ void ggml_cuda_op_dsv4_hc_pre(ggml_backend_cuda_context & ctx, ggml_tensor * dst nbx0 / sizeof(float), nbx1 / sizeof(float), nbx2 / sizeof(float), nbw0 / sizeof(float), nbw1 / sizeof(float), nbw2 / sizeof(float), nbd0 / sizeof(float), nbd1 / sizeof(float), - scale); + scale, q8_1); } void ggml_cuda_op_dsv4_hc_post(ggml_backend_cuda_context & ctx, ggml_tensor * dst, - const ggml_tensor * gate_scale_in, const ggml_tensor * gate_scale_out) { + const ggml_tensor * gate_scale_in, const ggml_tensor * gate_scale_out, const float * post_data) { const ggml_tensor * x = dst->src[0]; const ggml_tensor * residual = dst->src[1]; const ggml_tensor * comb = dst->src[3]; @@ -322,7 +346,7 @@ void ggml_cuda_op_dsv4_hc_post(ggml_backend_cuda_context & ctx, ggml_tensor * ds : (gated ? dsv4_hc_post_f32 : dsv4_hc_post_f32); ggml_cuda_kernel_launch(kernel, launch_params, (const float *) x->data, (const float *) residual->data, - (const float *) post->data, comb ? (const float *) comb->data : nullptr, (float *) dst->data, + post_data ? post_data : (const float *) post->data, comb ? (const float *) comb->data : nullptr, (float *) dst->data, n_embd, hc, n_tokens, nbx0 / sizeof(float), nbx1 / sizeof(float), nbr0 / sizeof(float), nbr1 / sizeof(float), nbr2 / sizeof(float), @@ -331,3 +355,4 @@ void ggml_cuda_op_dsv4_hc_post(ggml_backend_cuda_context & ctx, ggml_tensor * ds nbd0 / sizeof(float), nbd1 / sizeof(float), nbd2 / sizeof(float), gate_in, gate_out); } + diff --git a/ggml/src/ggml-cuda/dsv4-hc.cuh b/ggml/src/ggml-cuda/dsv4-hc.cuh index 1885e76659d5..4accc467fc58 100644 --- a/ggml/src/ggml-cuda/dsv4-hc.cuh +++ b/ggml/src/ggml-cuda/dsv4-hc.cuh @@ -3,6 +3,8 @@ void ggml_cuda_op_dsv4_hc_comb(ggml_backend_cuda_context & ctx, ggml_tensor * dst); void ggml_cuda_op_dsv4_hc_pre(ggml_backend_cuda_context & ctx, ggml_tensor * dst); -// gate_scale_in/gate_scale_out: the SCALE nodes of a fused SCALE -> SIGMOID -> SCALE chain feeding src[2] +// gate_scale_in/gate_scale_out: the SCALE nodes of a fused SCALE -> SIGMOID -> SCALE chain feeding src[2]; +// post_data: where to read the post weights instead of their tensor, when they were computed ahead void ggml_cuda_op_dsv4_hc_post(ggml_backend_cuda_context & ctx, ggml_tensor * dst, - const ggml_tensor * gate_scale_in = nullptr, const ggml_tensor * gate_scale_out = nullptr); + const ggml_tensor * gate_scale_in = nullptr, const ggml_tensor * gate_scale_out = nullptr, + const float * post_data = nullptr); diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index 9b75a04c662c..a564f279392c 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -1051,7 +1051,8 @@ template void launch_fattn( ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel, const int nwarps, const size_t nbytes_shared, const int nbatch_fa, const bool need_f16_K, const bool need_f16_V, const bool stream_k, const bool use_sparse, - const int warp_size = WARP_SIZE, const bool async_kv_preload = false + const int warp_size = WARP_SIZE, const bool async_kv_preload = false, + const int max_blocks_per_sm_override = 0 ) { constexpr int ncols = ncols1 * ncols2; @@ -1178,7 +1179,8 @@ void launch_fattn( GGML_ASSERT(mask != nullptr); const int32_t n_kv_max_query = ggml_get_op_params_i32(KQV, 4); GGML_ASSERT(n_kv_max_query > 0); - n_kv_max = std::min(K->ne[1], int64_t(ncols1)*n_kv_max_query); + // a tile holds at most Q->ne[1] queries, e.g. a single one when decoding with a wide tile + n_kv_max = std::min(K->ne[1], std::min(ncols1, Q->ne[1])*n_kv_max_query); const size_t n_lists = size_t(ntiles_x) * mask->ne[3]; @@ -1217,6 +1219,9 @@ void launch_fattn( int max_blocks_per_sm = 1; // Max. number of active blocks limited by occupancy. CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&max_blocks_per_sm, fattn_kernel, block_dim.x * block_dim.y * block_dim.z, nbytes_shared)); GGML_ASSERT(max_blocks_per_sm > 0); + if (max_blocks_per_sm_override > 0) { + max_blocks_per_sm = max_blocks_per_sm_override; + } int parallel_blocks = max_blocks_per_sm; const int64_t n_kv = use_sparse ? n_kv_max : n_kv_cols; @@ -1390,10 +1395,10 @@ void launch_fattn( // the graph evaluation may ask for MMVQ's q8_1 copy of the result (rows of whole, unpadded 32-value blocks) block_q8_1 * q8_1 = nullptr; - if (ctx.fa_q8_1 && DV % QK8_1 == 0 && warp_size == QK8_1 && ggml_is_contiguous(KQV) && + if (ctx.out_q8_1 && DV % QK8_1 == 0 && warp_size == QK8_1 && ggml_is_contiguous(KQV) && (KQV->ne[0]*KQV->ne[1]) % MATRIX_ROW_PADDING == 0) { - q8_1 = ctx.fa_q8_1; - ctx.fa_q8_1_written = true; + q8_1 = ctx.out_q8_1; + ctx.out_q8_1_written = true; } const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_combine, block_dim_combine, nbytes_shared_combine, main_stream); diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 0821644e7f6a..2c194b856f76 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -623,7 +623,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_mask( } } -template static __device__ __forceinline__ void flash_attn_ext_f16_iter( @@ -656,9 +656,14 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( #if defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int ncols = ncols1 * ncols2; + constexpr int DVp_split = GGML_PAD(DV, 16); constexpr int cols_per_warp = T_B_KQ::I; constexpr int cols_per_thread = get_cols_per_thread(); - constexpr int np = cols_per_warp > ncols ? nwarps : nwarps * cols_per_warp/ncols; // Number of parallel CUDA warps per Q column. + constexpr int nwb = nwarps / nsv; // Number of warps per group of the DV split. + constexpr int np = cols_per_warp > ncols ? nwb : nwb * cols_per_warp/ncols; // Number of parallel CUDA warps per Q column. + // Group sv of the DV split computes KQ like the others and VKQ for the output rows [sv_off, sv_off + DVp/nsv). + const int wy = threadIdx.y % nwb; + const int sv_off = nsv == 1 ? 0 : (threadIdx.y / nwb) * (DVp_split/nsv); constexpr int nbatch_fa = ggml_cuda_fattn_mma_get_nbatch_fa(DKQ, DV, ncols); constexpr int nbatch_K2 = ggml_cuda_fattn_mma_get_nbatch_K2(DKQ, DV, ncols); constexpr int nbatch_V2 = ggml_cuda_fattn_mma_get_nbatch_V2(DKQ, DV, ncols); @@ -720,7 +725,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( if constexpr (Q_in_reg) { #pragma unroll for (int i_KQ_00 = 0; i_KQ_00 < nbatch_fa; i_KQ_00 += np*T_A_KQ::I) { - const int i_KQ_0 = i_KQ_00 + (threadIdx.y % np)*T_A_KQ::I; + const int i_KQ_0 = i_KQ_00 + (wy % np)*T_A_KQ::I; #pragma unroll for (int k_KQ_0 = k0_start; k_KQ_0 < k0_stop; k_KQ_0 += T_A_KQ::J) { T_A_KQ K_A; @@ -743,11 +748,11 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( constexpr int stride_tile_Q = DKQp/2 + 4; #pragma unroll for (int k_KQ_0 = k0_start; k_KQ_0 < k0_stop; k_KQ_0 += T_A_KQ::J) { - load_ldmatrix(Q_B[0], tile_Q + (threadIdx.y / np)*(T_B_KQ::I*stride_tile_Q) + k_KQ_0, stride_tile_Q); + load_ldmatrix(Q_B[0], tile_Q + (wy / np)*(T_B_KQ::I*stride_tile_Q) + k_KQ_0, stride_tile_Q); #pragma unroll for (int i_KQ_00 = 0; i_KQ_00 < nbatch_fa; i_KQ_00 += np*T_A_KQ::I) { - const int i_KQ_0 = i_KQ_00 + (threadIdx.y % np)*T_A_KQ::I; + const int i_KQ_0 = i_KQ_00 + (wy % np)*T_A_KQ::I; T_A_KQ K_A; load_ldmatrix_swizzled(K_A, tile_K, i_KQ_0*stride_tile_K + k_KQ_0-k0_start); @@ -796,11 +801,11 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( if (ncols2 > 1 || mask_h) { #pragma unroll for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::I) { - const int i0 = i00 + (threadIdx.y % np)*T_C_KQ::I; + const int i0 = i00 + (wy % np)*T_C_KQ::I; #pragma unroll for (int l = 0; l < T_C_KQ::ne; ++l) { const int i = i0 + T_C_KQ::get_i(l); - const int j = ((threadIdx.y / np)*T_C_KQ::J + T_C_KQ::get_j(l)) / ncols2; + const int j = ((wy / np)*T_C_KQ::J + T_C_KQ::get_j(l)) / ncols2; KQ_C[i00/(np*T_C_KQ::I)].x[l] += slope * __half2float(tile_mask[j*(nbatch_fa + 8) + i]); } @@ -814,7 +819,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( for (int k0 = 0; k0 < nbatch_fa; k0 += np*T_C_KQ::I) { #pragma unroll for (int l = 0; l < T_C_KQ::ne; ++l) { - if (!oob_check || k0 + (threadIdx.y % np)*T_C_KQ::I + T_C_KQ::get_i(l) < k_VKQ_sup) { + if (!oob_check || k0 + (wy % np)*T_C_KQ::I + T_C_KQ::get_i(l) < k_VKQ_sup) { #if defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) constexpr int KQ_idx = 0; #else @@ -840,7 +845,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( for (int k0 = 0; k0 < nbatch_fa; k0 += np*T_C_KQ::I) { #pragma unroll for (int l = 0; l < T_C_KQ::ne; ++l) { - if (!oob_check || k0 + (threadIdx.y % np)*T_C_KQ::I + T_C_KQ::get_i(l) < k_VKQ_sup) { + if (!oob_check || k0 + (wy % np)*T_C_KQ::I + T_C_KQ::get_i(l) < k_VKQ_sup) { #if defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) constexpr int KQ_idx = 0; #else @@ -858,7 +863,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( if (ncols2 > 1 || mask_h) { #pragma unroll for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::J) { - const int i0 = i00 + (threadIdx.y % np)*T_C_KQ::J; + const int i0 = i00 + (wy % np)*T_C_KQ::J; // The mask is stored as 16 bit half values, loading them as 32 bit half2 values is preferred in terms of speed. // However, this is not possible for RDNA3 where 2 consecutive l indices are not consecutive in the mask memory layout. @@ -866,7 +871,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( #pragma unroll for (int l = 0; l < T_C_KQ::ne; ++l) { const int i = i0 + T_C_KQ::get_j(l); - const int j = ((threadIdx.y / np)*cols_per_warp + T_C_KQ::get_i(l)) / ncols2; + const int j = ((wy / np)*cols_per_warp + T_C_KQ::get_i(l)) / ncols2; KQ_C[i00/(np*T_C_KQ::J)].x[l] += __half2float(tile_mask[j*(nbatch_fa + 8) + i]); } @@ -874,7 +879,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( #pragma unroll for (int l0 = 0; l0 < T_C_KQ::ne; l0 += 2) { const int i = (i0 + T_C_KQ::get_j(l0)) / 2; - const int j = ((threadIdx.y / np)*cols_per_warp + T_C_KQ::get_i(l0)) / ncols2; + const int j = ((wy / np)*cols_per_warp + T_C_KQ::get_i(l0)) / ncols2; const float2 tmp = __half22float2(((const half2 *)tile_mask)[j*(nbatch_fa/2 + 4) + i]); KQ_C[i00/(np*T_C_KQ::J)].x[l0 + 0] += slope*tmp.x; @@ -891,7 +896,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( for (int k0 = 0; k0 < nbatch_fa; k0 += np*T_C_KQ::J) { #pragma unroll for (int l = 0; l < T_C_KQ::ne; ++l) { - if (!oob_check || k0 + (threadIdx.y % np)*T_C_KQ::J + T_C_KQ::get_j(l) < k_VKQ_sup) { + if (!oob_check || k0 + (wy % np)*T_C_KQ::J + T_C_KQ::get_j(l) < k_VKQ_sup) { #if defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) constexpr int KQ_idx = 0; #else @@ -933,7 +938,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( for (int k0 = 0; k0 < nbatch_fa; k0 += np*T_C_KQ::J) { #pragma unroll for (int l = 0; l < T_C_KQ::ne; ++l) { - if (!oob_check || k0 + (threadIdx.y % np)*T_C_KQ::J + T_C_KQ::get_j(l) < k_VKQ_sup) { + if (!oob_check || k0 + (wy % np)*T_C_KQ::J + T_C_KQ::get_j(l) < k_VKQ_sup) { #if defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) constexpr int KQ_idx = 0; #else @@ -990,7 +995,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( if constexpr (std::is_same_v) { const half2 KQ_max_scale_h2 = make_half2(KQ_max_scale[0], KQ_max_scale[0]); #pragma unroll - for (int i = 0; i < (DVp/2)/T_C_VKQ::J; ++i) { + for (int i = 0; i < (DVp/2)/(T_C_VKQ::J*nsv); ++i) { #pragma unroll for (int l = 0; l < T_C_VKQ::ne; ++l) { VKQ_C[i].x[l] *= KQ_max_scale_h2; @@ -1073,24 +1078,28 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( #if defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) #pragma unroll - for (int i_VKQ_0 = i0_start; i_VKQ_0 < i0_stop; i_VKQ_0 += T_A_VKQ::I) { + for (int i_VKQ_l = 0; i_VKQ_l < DVp/nsv; i_VKQ_l += T_A_VKQ::I) { + const int i_VKQ_0 = sv_off + i_VKQ_l; + if (i_VKQ_0 < i0_start || i_VKQ_0 >= i0_stop) { + continue; + } static_assert((nbatch_fa/2) % (np*T_A_VKQ::J) == 0, "bad loop size"); #pragma unroll for (int k00 = 0; k00 < nbatch_fa/2; k00 += np*T_A_VKQ::J) { - const int k0 = k00 + (threadIdx.y % np)*T_A_VKQ::J; + const int k0 = k00 + (wy % np)*T_A_VKQ::J; T_A_VKQ A; // Transposed in SRAM but not in registers, gets transposed on load. load_ldmatrix_trans_swizzled(A, tile_V, tile_V_offset_i + 2*k0*stride_tile_V + (i_VKQ_0 - i0_start)/2); if constexpr (T_B_KQ::I == 8) { - mma(VKQ_C[i_VKQ_0/T_A_VKQ::I], A, B[k00/(np*T_A_VKQ::J)]); + mma(VKQ_C[i_VKQ_l/T_A_VKQ::I], A, B[k00/(np*T_A_VKQ::J)]); } else { // Wide version of VKQ_C is column-major. #if defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) // AMD matrix C is column-major. - mma(VKQ_C[i_VKQ_0/T_A_VKQ::I], A, B[k00/(np*T_A_VKQ::J)]); + mma(VKQ_C[i_VKQ_l/T_A_VKQ::I], A, B[k00/(np*T_A_VKQ::J)]); #else // swap A and B for CUDA. - mma(VKQ_C[i_VKQ_0/T_A_VKQ::I], B[k00/(np*T_A_VKQ::J)], A); + mma(VKQ_C[i_VKQ_l/T_A_VKQ::I], B[k00/(np*T_A_VKQ::J)], A); #endif // defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) } } @@ -1103,7 +1112,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( static_assert(2*T_B_VKQ::J == T_A_VKQ::I, "bad tile sizes"); #pragma unroll for (int k00 = 0; k00 < nbatch_fa; k00 += np*T_A_VKQ::I) { - const int k0 = k00 + (threadIdx.y % np)*T_A_VKQ::I; + const int k0 = k00 + (wy % np)*T_A_VKQ::I; T_A_VKQ A; // Transposed in both SRAM and registers, load normally. load_ldmatrix_swizzled(A, tile_V, tile_V_offset_i + k0*stride_tile_V + (i_VKQ_0 - i0_start)/2); @@ -1273,7 +1282,7 @@ template struct mma_tile_sizes { }; #endif // defined(TURING_MMA_AVAILABLE) -template +template static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( const float2 * const __restrict__ Q_f2, const half2 * const __restrict__ K_h2, @@ -1311,9 +1320,14 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( using T_B_VKQ = typename mma_tile_sizes::T_B_VKQ; using T_C_VKQ = typename mma_tile_sizes::T_C_VKQ; + constexpr int DVp_split = GGML_PAD(DV, 16); constexpr int cols_per_warp = T_B_KQ::I; constexpr int cols_per_thread = get_cols_per_thread(); - constexpr int np = cols_per_warp > ncols ? nwarps : nwarps * cols_per_warp/ncols; // Number of parallel CUDA warps per Q column. + constexpr int nwb = nwarps / nsv; // Number of warps per group of the DV split. + constexpr int np = cols_per_warp > ncols ? nwb : nwb * cols_per_warp/ncols; // Number of parallel CUDA warps per Q column. + // Group sv of the DV split computes KQ like the others and VKQ for the output rows [sv_off, sv_off + DVp/nsv). + const int wy = threadIdx.y % nwb; + const int sv_off = nsv == 1 ? 0 : (threadIdx.y / nwb) * (DVp_split/nsv); constexpr int nbatch_fa = ggml_cuda_fattn_mma_get_nbatch_fa (DKQ, DV, ncols); constexpr int nbatch_K2 = ggml_cuda_fattn_mma_get_nbatch_K2 (DKQ, DV, ncols); constexpr int nbatch_V2 = ggml_cuda_fattn_mma_get_nbatch_V2 (DKQ, DV, ncols); @@ -1329,7 +1343,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( return; } - static_assert(nwarps * (cols_per_warp/ncols2) % ncols1 == 0, "bad nwarps"); + static_assert(nwb * (cols_per_warp/ncols2) % ncols1 == 0, "bad nwarps"); constexpr bool swz = ggml_cuda_fattn_mma_get_swizzled(DKQ, DV, ncols); constexpr int stride_tile_Q = DKQp/2 + 4; @@ -1350,7 +1364,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( #elif defined(AMD_MFMA_AVAILABLE) T_C_VKQ VKQ_C[ DVp/T_C_VKQ::J]; #elif defined(AMD_WMMA_AVAILABLE) - T_C_VKQ VKQ_C[ DVp/(2*T_C_VKQ::J)]; + T_C_VKQ VKQ_C[ DVp/(2*T_C_VKQ::J*nsv)]; #else // Volta T_C_VKQ VKQ_C[ DVp/(2*T_C_VKQ::J)]; #endif // defined(TURING_MMA_AVAILABLE) @@ -1410,7 +1424,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( __syncthreads(); if (Q_in_reg) { - const int j0 = (threadIdx.y / np) * cols_per_warp; + const int j0 = (wy / np) * cols_per_warp; #pragma unroll for (int k0 = 0; k0 < DKQp/2; k0 += T_B_KQ::J) { @@ -1475,7 +1489,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr bool last_iter = false; constexpr int k_VKQ_sup = nbatch_fa; flash_attn_ext_f16_iter - (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, @@ -1484,7 +1498,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr bool last_iter = true; const int k_VKQ_sup = ne11 - kb0*nbatch_fa; flash_attn_ext_f16_iter - (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, @@ -1495,7 +1509,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr bool last_iter = false; constexpr int k_VKQ_sup = nbatch_fa; flash_attn_ext_f16_iter - (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, @@ -1504,7 +1518,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr bool last_iter = true; constexpr int k_VKQ_sup = nbatch_fa; flash_attn_ext_f16_iter - (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, @@ -1513,7 +1527,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( // With multi-stage loading there is no __syncthreads at the end of the iter, // there can be a race condition on shared memory access for combining/writing back results. - if constexpr (nstages > 1 && nwarps*cols_per_warp > nbatch_fa) { + if constexpr (nstages > 1 && nwb*cols_per_warp > nbatch_fa) { __syncthreads(); } @@ -1548,11 +1562,11 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( // If attention sinks are used, potentially re-scale if KQ_max is small. // Also add the sink as a value to KQ_rowsum, this is done after synchronization of KQ_rowsum // so it's being done unconditionally for every thread. - if (!is_fixup && (np == 1 || threadIdx.y % np == 0) && sinks_f) { + if (!is_fixup && (np == 1 || wy % np == 0) && sinks_f) { float KQ_max_scale[cols_per_thread]; #pragma unroll for (int col = 0; col < cols_per_thread; ++col) { - const int jc = (threadIdx.y/np)*cols_per_warp + (cols_per_warp == 8 ? T_C_KQ::get_j(col) : T_C_KQ::get_i(2*col)); + const int jc = (wy/np)*cols_per_warp + (cols_per_warp == 8 ? T_C_KQ::get_j(col) : T_C_KQ::get_i(2*col)); if (zt_gqa*ncols2 + jc % ncols2 >= gqa_ratio) { KQ_max_scale[col] = 1.0f; continue; @@ -1597,7 +1611,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( if constexpr (std::is_same_v) { const half2 KQ_max_scale_h2 = make_half2(KQ_max_scale[0], KQ_max_scale[0]); #pragma unroll - for (int i = 0; i < (DVp/2)/T_C_VKQ::J; ++i) { + for (int i = 0; i < (DVp/2)/(T_C_VKQ::J*nsv); ++i) { #pragma unroll for (int l = 0; l < T_C_VKQ::ne; ++l) { VKQ_C[i].x[l] *= KQ_max_scale_h2; @@ -1635,7 +1649,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( if constexpr (cols_per_warp == 8) { const int jc_cwmo = (threadIdx.x % (2*T_C_VKQ::J)) / T_C_VKQ::J; // jc combine write meta offset - const int jc_cwm = threadIdx.y*(2*T_C_VKQ::J) + 2*T_C_VKQ::get_j(-1) + jc_cwmo; // jc combine write meta + const int jc_cwm = wy*(2*T_C_VKQ::J) + 2*T_C_VKQ::get_j(-1) + jc_cwmo; // jc combine write meta const float2 KQ_cmr = make_float2(KQ_max[jc_cwmo], KQ_rowsum[jc_cwmo]); // KQ combine max rowsum if constexpr (swz) { @@ -1665,15 +1679,15 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( // KQ_cmr = KQ combine max rowsum // Use the 16 bytes of padding in each Q column to store the meta data: KQ max, KQ rowsum, KQ max scale. #if defined(TURING_MMA_AVAILABLE) - const int jc_cwm = threadIdx.y*cols_per_warp + T_C_VKQ::get_i(threadIdx.x % 4); + const int jc_cwm = wy*cols_per_warp + T_C_VKQ::get_i(threadIdx.x % 4); const float2 KQ_cmr = make_float2(KQ_max[threadIdx.x % cols_per_thread], KQ_rowsum[threadIdx.x % cols_per_thread]); const bool thread_should_write = threadIdx.x % 4 < cols_per_thread; #elif defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) - const int jc_cwm = threadIdx.y*cols_per_warp + T_C_VKQ::get_i(0); + const int jc_cwm = wy*cols_per_warp + T_C_VKQ::get_i(0); const float2 KQ_cmr = make_float2(KQ_max[0], KQ_rowsum[0]); const bool thread_should_write = threadIdx.x / 16 < cols_per_thread; #else // Volta - const int jc_cwm = threadIdx.y*cols_per_warp + T_C_KQ::get_i(threadIdx.x & 2); + const int jc_cwm = wy*cols_per_warp + T_C_KQ::get_i(threadIdx.x & 2); const float2 KQ_cmr = make_float2(KQ_max[(threadIdx.x & 2) / 2], KQ_rowsum[(threadIdx.x & 2) / 2]); const bool thread_should_write = T_C_KQ::J == 8 || T_C_KQ::get_j(threadIdx.x & 2) < 8; #endif // defined(TURING_MMA_AVAILABLE) @@ -1708,10 +1722,10 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( float KQ_cms[nmeta]; float KQ_crs; - const int jc_meta = threadIdx.y*cols_per_warp + (np*cols_per_warp < warp_size ? threadIdx.x % (np*cols_per_warp) : threadIdx.x); + const int jc_meta = wy*cols_per_warp + (np*cols_per_warp < warp_size ? threadIdx.x % (np*cols_per_warp) : threadIdx.x); float2 * const meta_ptr = ((float2 *) tile_Q) + jc_meta*(tile_stride/2) + nbatch_combine/2; - if (threadIdx.y % np == 0) { + if (wy % np == 0) { // Combine the meta data for parallel warps via shared memory. float2 meta[nmeta]; #pragma unroll @@ -1751,7 +1765,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( __syncthreads(); - if (threadIdx.y % np == 0) { + if (wy % np == 0) { // Write back combined meta data: #pragma unroll for (int imeta = 0; imeta < nmeta; ++imeta) { @@ -1765,11 +1779,11 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( static_assert(cols_per_warp <= warp_size); if (needs_fixup && (cols_per_warp == warp_size || threadIdx.x < cols_per_warp)) { float2 * dstk_fixup_meta = dstk_fixup + blockIdx.x*ncols; - dstk_fixup_meta[(threadIdx.y/np)*cols_per_warp + threadIdx.x] = make_float2(KQ_cmn, KQ_crs); + dstk_fixup_meta[(wy/np)*cols_per_warp + threadIdx.x] = make_float2(KQ_cmn, KQ_crs); } if (is_fixup && (cols_per_warp == warp_size || threadIdx.x < cols_per_warp)) { float2 * dstk_fixup_meta = dstk_fixup + (gridDim.x + blockIdx.x)*ncols; - dstk_fixup_meta[(threadIdx.y/np)*cols_per_warp + threadIdx.x] = make_float2(KQ_cmn, KQ_crs); + dstk_fixup_meta[(wy/np)*cols_per_warp + threadIdx.x] = make_float2(KQ_cmn, KQ_crs); } } } @@ -1778,7 +1792,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( for (int k00 = 0; k00 < DVp/2; k00 += nbatch_combine) { if constexpr (cols_per_warp == 8) { static_assert(std::is_same_v, "bad VKQ type"); - const int jc_cwd = threadIdx.y*T_B_KQ::I + T_B_KQ::get_i(-1); // jc combine write data + const int jc_cwd = wy*T_B_KQ::I + T_B_KQ::get_i(-1); // jc combine write data #pragma unroll for (int k1 = 0; k1 < nbatch_combine; k1 += T_B_KQ::J) { const T_B_KQ B = get_transposed(VKQ_C[(k00 + k1)/T_B_KQ::J]); // Conversion of C to B matrix puts it in column-major format. @@ -1791,17 +1805,21 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( } } } else { - const int j0 = threadIdx.y*cols_per_warp; + const int j0 = wy*cols_per_warp; if constexpr (std::is_same_v) { if constexpr (T_C_VKQ::dl == DATA_LAYOUT_I_MAJOR) { #pragma unroll - for (int k1 = 0; k1 < nbatch_combine; k1 += T_C_VKQ::J) { + for (int k1_l = 0; k1_l < DVp/(2*nsv); k1_l += T_C_VKQ::J) { + const int k1 = sv_off/2 + k1_l - k00; + if (k1 < 0 || k1 >= nbatch_combine) { + continue; + } #pragma unroll for (int l = 0; l < T_C_VKQ::ne; ++l) { const int j = j0 + T_C_VKQ::get_i(l); const int k = k1 + T_C_VKQ::get_j(l); - tile_Q[j*tile_stride + k] = VKQ_C[(k00 + k1)/T_C_VKQ::J].x[l]; + tile_Q[j*tile_stride + k] = VKQ_C[k1_l/T_C_VKQ::J].x[l]; } } } else { @@ -1837,7 +1855,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( __syncthreads(); - if (np == 1 || threadIdx.y % np == 0) { + if ((np == 1 || wy % np == 0) && sv_off == 0) { // The first 2*2*gridDim.x*ncols floats in dstk_fixup are for storing max. values and row sums. // The values after that are for the partial results of the individual blocks. float2 * dstk_fixup_data = dstk_fixup + gridDim.x*(2*ncols) + blockIdx.x*(ncols*(DV/2)); @@ -1853,10 +1871,10 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( } #pragma unroll - for (int jc0_dst = 0; jc0_dst < ncols; jc0_dst += (nwarps/np)*stride_jc) { - const int jc_dst = jc0_dst + (threadIdx.y/np)*stride_jc + (stride_k == warp_size ? 0 : threadIdx.x / stride_k); + for (int jc0_dst = 0; jc0_dst < ncols; jc0_dst += (nwb/np)*stride_jc) { + const int jc_dst = jc0_dst + (wy/np)*stride_jc + (stride_k == warp_size ? 0 : threadIdx.x / stride_k); - if (jc0_dst + (nwarps/np)*stride_jc > ncols && jc_dst >= ncols) { + if (jc0_dst + (nwb/np)*stride_jc > ncols && jc_dst >= ncols) { break; } @@ -1920,11 +1938,19 @@ static constexpr __host__ __device__ bool ggml_cuda_flash_attn_ext_mma_f16_may_u return (DKQ == 512 && DV == 512 && ncols1 == 1 && ncols2 == 8) || (DKQ == 576 && DV == 512 && ncols1 == 1 && ncols2 == 16) || (DKQ == 256 && DV == 256 && ncols1 == 1 && ncols2 == 8) || +#if defined(GGML_USE_HIP) + // RDNA decode and MTP verify, the WMMA kernel has no 8-column variant + (DKQ == 256 && DV == 256 && (ncols1 == 2 || ncols1 == 4) && ncols2 == 8) || + // RDNA prompt batches with GQA 12: all heads of a KV head in one tile + (DKQ == 256 && DV == 256 && ncols1 == 2 && ncols2 == 16) || +#endif // defined(GGML_USE_HIP) (DKQ == 256 && DV == 256 && ncols1 == 8 && ncols2 == 8); } -template -__launch_bounds__(ggml_cuda_fattn_mma_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_mma_get_occupancy(DKQ, DV, ncols1*ncols2)) +// nsv: the number of warp groups that split DV between them, each computing KQ for its tile and DV/nsv of VKQ, the same +// values per output element as with nsv == 1 (implemented for RDNA3.5) +template +__launch_bounds__(ggml_cuda_fattn_mma_get_nthreads(DKQ, DV, ncols1*ncols2)*nsv, ggml_cuda_fattn_mma_get_occupancy(DKQ, DV, ncols1*ncols2)) static __global__ void flash_attn_ext_f16( const char * Q_ptr, const char * K_ptr, @@ -1996,6 +2022,13 @@ static __global__ void flash_attn_ext_f16( } #endif // defined(AMD_WMMA_AVAILABLE) +#if !defined(RDNA3_5) + if (nsv > 1) { + NO_DEVICE_CODE; + return; + } +#endif // !defined(RDNA3_5) + #if defined(AMD_MFMA_AVAILABLE) if (ncols1*ncols2 < 16 || (DKQ > 256 && ncols1*ncols2 < 32 && !use_sparse)) { NO_DEVICE_CODE; @@ -2006,7 +2039,7 @@ static __global__ void flash_attn_ext_f16( constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int ncols = ncols1 * ncols2; constexpr int nbatch_fa = ggml_cuda_fattn_mma_get_nbatch_fa(DKQ, DV, ncols); - constexpr int nthreads = ggml_cuda_fattn_mma_get_nthreads(DKQ, DV, ncols); + constexpr int nthreads = ggml_cuda_fattn_mma_get_nthreads(DKQ, DV, ncols)*nsv; constexpr int nwarps = nthreads / warp_size; const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. @@ -2068,12 +2101,12 @@ static __global__ void flash_attn_ext_f16( constexpr bool is_fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer. if (kb0_start == 0) { constexpr bool needs_fixup = false; // CUDA block is working on an entire tile. - flash_attn_ext_f16_process_tile + flash_attn_ext_f16_process_tile (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); } else { constexpr bool needs_fixup = true; // CUDA block is missing the beginning of a tile. - flash_attn_ext_f16_process_tile + flash_attn_ext_f16_process_tile (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); } @@ -2118,7 +2151,7 @@ static __global__ void flash_attn_ext_f16( constexpr bool is_fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks. constexpr bool needs_fixup = false; - flash_attn_ext_f16_process_tile + flash_attn_ext_f16_process_tile (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); #else @@ -2155,7 +2188,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml const int cols_per_warp = std::min(ncols, get_cols_per_warp(cc)); const int warp_size_host = ggml_cuda_info().devices[ctx.device].warp_size; - const int nwarps = nthreads / warp_size_host; + const int nwarps = nthreads / warp_size_host; // per group of the DV split constexpr bool V_is_K_view = DKQ == 576; // Guaranteed by the kernel selection logic in fattn.cu constexpr int DKQp = GGML_PAD(DKQ, 16); @@ -2186,13 +2219,14 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml #endif // defined(GGML_USE_HIP) fattn_kernel_t fattn_kernel; bool use_sparse = false; + int nsv = 1; if (logit_softcap == 0.0f) { constexpr bool use_logit_softcap = false; #if !defined(GGML_USE_MUSA) if constexpr (ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, ncols1, ncols2)) { if (ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, ncols1, ncols2)) { constexpr bool use_sparse_kernel = true; - fattn_kernel = flash_attn_ext_f16; + fattn_kernel = flash_attn_ext_f16; use_sparse = true; static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false}; @@ -2202,7 +2236,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml } } else { constexpr bool use_sparse_kernel = false; - fattn_kernel = flash_attn_ext_f16; + fattn_kernel = flash_attn_ext_f16; static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false}; if (!shared_memory_limit_raised[id]) { @@ -2214,7 +2248,16 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml #endif // !defined(GGML_USE_MUSA) { constexpr bool use_sparse_kernel = false; - fattn_kernel = flash_attn_ext_f16; + fattn_kernel = flash_attn_ext_f16; +#if defined(GGML_USE_HIP) + // RDNA3.5 decode with the 256/256 head size: 2 groups of warps split DV + if constexpr (DKQ == 256 && DV == 256 && ncols == 16) { + if (GGML_CUDA_CC_IS_RDNA3_5(cc)) { + fattn_kernel = flash_attn_ext_f16; + nsv = 2; + } + } +#endif // defined(GGML_USE_HIP) static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false}; if (!shared_memory_limit_raised[id]) { @@ -2225,7 +2268,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml } else { constexpr bool use_logit_softcap = true; constexpr bool use_sparse_kernel = false; - fattn_kernel = flash_attn_ext_f16; + fattn_kernel = flash_attn_ext_f16; static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false}; if (!shared_memory_limit_raised[id]) { @@ -2236,7 +2279,9 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml const bool async_kv_preload = nstages == 2 && !use_sparse; launch_fattn - (ctx, dst, fattn_kernel, nwarps, nbytes_shared_total, nbatch_fa, true, true, true, use_sparse, warp_size_host, async_kv_preload); + (ctx, dst, fattn_kernel, nwarps*nsv, nbytes_shared_total, nbatch_fa, true, true, true, use_sparse, warp_size_host, async_kv_preload, + // the stream-k blocks per WGP with the DV split, measured fastest on RDNA3.5 from 2K to 16K of context + nsv > 1 ? 5 : 0); } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 7b8d9e3c38ba..26552ad5be73 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -17,11 +17,17 @@ static bool ggml_cuda_fattn_rdna_kv_rows_enabled(const int cc) { return ggml_cuda_switch_or_rdna3_5(env_switch, cc); } +// gather only the K/V rows that a sparse mask keeps (e.g. Qwen QSA) instead of reading the whole cache +static bool ggml_cuda_fattn_rdna_sparse_enabled(const int cc) { + static const int env_switch = ggml_cuda_env_switch("GGML_HIP_FA_SPARSE"); + return ggml_cuda_switch_or_rdna3_5(env_switch, cc); +} + #if !defined(GGML_USE_MUSA) // one list per group of ncols1 queries: a column is selected if any query of the group can see it -template -__launch_bounds__(256, 1) +template +__launch_bounds__(nthreads, 1) static __global__ void flash_attn_mask_to_sparse_indices( const half * mask_ptr, int32_t * indices_ptr, int32_t * counts_ptr, const int ne30, const int n_queries, const int n_kv_max, const int64_t s31, const int64_t s33) { @@ -50,7 +56,7 @@ static __global__ void flash_attn_mask_to_sparse_indices( const half * mask = mask_ptr + sequence*s33 + q0*s31; int32_t * indices = indices_ptr + (int64_t(sequence)*gridDim.x + group)*n_kv_max; - __shared__ int warp_offsets[256/warp_size]; + __shared__ int warp_offsets[nthreads/warp_size]; __shared__ int row_count; __shared__ int chunk_count; @@ -84,7 +90,7 @@ static __global__ void flash_attn_mask_to_sparse_indices( if (tid == 0) { int offset = 0; #pragma unroll - for (int iw = 0; iw < 256/warp_size; ++iw) { + for (int iw = 0; iw < nthreads/warp_size; ++iw) { const int count = warp_offsets[iw]; warp_offsets[iw] = offset; offset += count; @@ -135,13 +141,25 @@ void ggml_cuda_flash_attn_ext_compact_mask( const int64_t s31 = mask->nb[1] / sizeof(half); const int64_t s33 = mask->nb[3] / sizeof(half); const dim3 blocks_num((n_queries + ncols1 - 1)/ncols1, mask->ne[3], 1); - const dim3 block_dim(256, 1, 1); + // each block scans its whole mask row serially, with few lists (decode) wider blocks shorten the scan + const bool wide = int64_t(blocks_num.x)*blocks_num.y < ggml_cuda_info().devices[ggml_cuda_get_device()].nsm; + const dim3 block_dim(wide ? 1024 : 256, 1, 1); const ggml_cuda_kernel_launch_params launch_params(blocks_num, block_dim, 0, stream); // the last group of queries is partial only if ncols1 does not divide n_queries - GGML_ASSERT(ncols1 == 1 || ncols1 == 8); - const auto kernel = ncols1 == 1 ? flash_attn_mask_to_sparse_indices<1, false> : - n_queries % 8 != 0 ? flash_attn_mask_to_sparse_indices<8, true> : - flash_attn_mask_to_sparse_indices<8, false>; + const bool oob = n_queries % ncols1 != 0; + decltype(&flash_attn_mask_to_sparse_indices<1, false, 256>) kernel = nullptr; + auto select = [&](auto ncols1_c) { + constexpr int nc = decltype(ncols1_c)::value; + if (ncols1 == nc) { + kernel = oob ? (wide ? flash_attn_mask_to_sparse_indices : flash_attn_mask_to_sparse_indices) : + (wide ? flash_attn_mask_to_sparse_indices : flash_attn_mask_to_sparse_indices); + } + }; + select(std::integral_constant{}); + select(std::integral_constant{}); + select(std::integral_constant{}); + select(std::integral_constant{}); + GGML_ASSERT(kernel != nullptr); ggml_cuda_kernel_launch(kernel, launch_params, (const half *) mask->data, indices, counts, int(mask->ne[0]), n_queries, n_kv_max, s31, s33); CUDA_CHECK(cudaGetLastError()); @@ -173,13 +191,40 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_ // the dense kernel handles up to 64/ncols2 queries per K/V pass, the single-query gather has to beat that const int64_t n_gather = (ncols1 == 1 ? std::min(Q->ne[1], 64/ncols2) : ncols1) * (int64_t) n_kv_max; - return ((GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc)) || amd_mfma_available(cc)) && dst->src[5] == nullptr && + // the WMMA kernel has no variant with fewer than 16 columns + const bool rdna_sparse = amd_wmma_available(cc) && ncols1*ncols2 >= 16 && Q->ne[0] <= 256 && ggml_cuda_fattn_rdna_sparse_enabled(cc); + // sparse tiles narrower than the full width but wider than one query are only dispatched on RDNA + if (!rdna_sparse && ncols1 != 1 && ncols1*ncols2 != 64) { + return false; + } + // on RDNA a list holds the union of the queries in a tile and a gathered row costs about 1.5 dense rows, + // for prompt batches the dense kernel is slower per row and neighbouring queries select overlapping rows, + // the 8x8 tile breaks even with the dense kernel at K = 6*n_kv_max, the 2x16 tile (all heads of a KV head in + // one tile) at 4*n_kv_max: it is faster than dense for every batch size and mask type tested at K = 4*n_kv_max + // (8192 for n_kv_max = 2048), but not at 2x n_kv_max and not at 3x with 512 queries + const int64_t n_kv_min_prompt = ncols2 == 16 ? 4LL*n_kv_max : 3*ncols1*n_kv_max/4; + const int64_t n_kv_min = rdna_sparse ? (Q->ne[1] > 8 ? n_kv_min_prompt : 3*std::min(ncols1, Q->ne[1])*n_kv_max/2) : + GGML_CUDA_CC_IS_NVIDIA(cc) ? 2*n_gather : 2LL*n_kv_max; + + return ((GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc)) || amd_mfma_available(cc) || rdna_sparse) && dst->src[5] == nullptr && mask != nullptr && n_kv_max > 0 && max_bias == 0.0f && logit_softcap == 0.0f && mask->ne[0] == K->ne[1] && mask->ne[1] >= Q->ne[1] && mask->ne[2] == 1 && - K->ne[1] >= std::max(4096, GGML_CUDA_CC_IS_NVIDIA(cc) ? 2*n_gather : 2LL*n_kv_max); + K->ne[1] >= std::max(4096, n_kv_min); #endif // !defined(GGML_USE_MUSA) } +template +static bool ggml_cuda_flash_attn_ext_mma_f16_try_sparse(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const int cc) { + if constexpr (ncols1 >= 1 && ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, ncols1, ncols2)) { + if (ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, ncols1, ncols2)) { + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); + return true; + } + } + GGML_UNUSED_VARS(ctx, dst, cc); + return false; +} + template static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; @@ -194,6 +239,18 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con return; } } + // on RDNA small batches take the narrowest sparse tile that holds them + if (amd_wmma_available(cc)) { + if (Q->ne[1] <= 16/ncols2 && ggml_cuda_flash_attn_ext_mma_f16_try_sparse(ctx, dst, cc)) { + return; + } + if (Q->ne[1] <= 32/ncols2 && ggml_cuda_flash_attn_ext_mma_f16_try_sparse(ctx, dst, cc)) { + return; + } + if (ggml_cuda_flash_attn_ext_mma_f16_try_sparse(ctx, dst, cc)) { + return; + } + } #endif // !defined(GGML_USE_MUSA) if constexpr (ncols2 <= 8) { @@ -284,8 +341,23 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con return; } - // small batches are K/V bandwidth bound, large batches fill the tiles without padding - if (use_gqa_opt && gqa_ratio > 4 && Q->ne[1] <= 8 && ggml_cuda_fattn_rdna_gqa_pad_enabled(cc)) { + // GQA 12 prompt batches: one 16-head tile per KV head reads each gathered row once, and the + // tile is limited by WMMA work, which grows with the union of its queries, so 2 queries per tile + // (union about 0.4x that of 8 queries for Qwen QSA) beat wider tiles that read K/V less often + if constexpr (ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, 2, 16)) { + if (use_gqa_opt && gqa_ratio > 8 && gqa_ratio < 16 && Q->ne[1] > 8 && + ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 2, 16)) { + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); + return; + } + } + + // small batches are K/V bandwidth bound, large batches fill the tiles without padding, + // unless the 8x8 sparse tile gathers far fewer rows than the dense kernel reads + const bool sparse_pad = use_gqa_opt && gqa_ratio > 4 && Q->ne[1] > 8 && + ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, 8, 8) && + ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 8, 8); + if (use_gqa_opt && gqa_ratio > 4 && (sparse_pad || (Q->ne[1] <= 8 && ggml_cuda_fattn_rdna_gqa_pad_enabled(cc)))) { ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } diff --git a/ggml/src/ggml-cuda/gated-delta-net-mma.cu b/ggml/src/ggml-cuda/gated-delta-net-mma.cu index 0684adc1ad3d..23574cd61ce6 100644 --- a/ggml/src/ggml-cuda/gated-delta-net-mma.cu +++ b/ggml/src/ggml-cuda/gated-delta-net-mma.cu @@ -391,7 +391,9 @@ static gdn_path select_gdn_mma_path(int device, const ggml_cuda_gdn_mma_args & a } const auto & info = ggml_cuda_info().devices[device]; #ifdef GGML_USE_HIP - if (!GGML_CUDA_CC_IS_RDNA3_5(info.cc) || a.n_tokens < 2048) { + // gated_delta_net_chunk_cuda (gated_delta_net.cu) is faster on RDNA3.5 for prompts + static const bool use_mma = getenv("GGML_CUDA_GDN_MMA") != nullptr; + if (!use_mma || !GGML_CUDA_CC_IS_RDNA3_5(info.cc) || a.n_tokens < 2048) { return gdn_path::ar; } return init<16, 64>(device) ? gdn_path::slice64 : gdn_path::ar; diff --git a/ggml/src/ggml-cuda/gated_delta_net.cu b/ggml/src/ggml-cuda/gated_delta_net.cu index ae2374cbcdd7..24df294606e4 100644 --- a/ggml/src/ggml-cuda/gated_delta_net.cu +++ b/ggml/src/ggml-cuda/gated_delta_net.cu @@ -32,7 +32,9 @@ gated_delta_net_cuda(const float * q, const uint3 rq3_magic, float scale, int64_t state_slot_stride, - int K) { + int K, + const int32_t * state_rows, + int64_t state_row_stride) { const uint32_t h_idx = blockIdx.x; const uint32_t sequence = blockIdx.y; @@ -54,9 +56,11 @@ gated_delta_net_cuda(const float * q, float * attn_data = dst; - // input state holds s0 only: [S_v, S_v, H, n_seqs] — seq stride is D = H * S_v * S_v. + // input state holds s0 only: [S_v, S_v, H, n_seqs] — seq stride is D = H * S_v * S_v, or the cache rows that + // state_rows index when the state is read in place (see ggml_cuda_gdn_state_rows). // output state layout (per-slot D * n_seqs) — same per-(seq,head) offset as before. - const int64_t state_in_offset = sequence * H * S_v * S_v + h_idx * S_v * S_v; + const int64_t seq_in_offset = state_rows ? state_rows[sequence] * state_row_stride : sequence * H * S_v * S_v; + const int64_t state_in_offset = seq_in_offset + h_idx * S_v * S_v; const int64_t state_out_offset = (sequence * H + h_idx) * S_v * S_v; state += state_out_offset; curr_state += state_in_offset + col * S_v; @@ -178,6 +182,344 @@ gated_delta_net_cuda(const float * q, } } +// Prompt batches on RDNA3 (S_v 128, scalar gate, no snapshots), chunks of GDN_CH_C tokens with BF16 WMMA, each product as +// hi*hi + lo*hi + hi*lo of the BF16 high/residual parts of the FP32 operands. Per chunk with prefix log decays gamma: +// A = strict_tril(beta_i k_i.k_j e^(gamma_i - gamma_j)), T = (I + A)^-1, P = tril(q_i.k_j e^(gamma_i - gamma_j)), +// delta = beta (v - e^gamma K S), U = T delta, out = e^gamma Q S + P U, S = e^gamma_last S + K^T (e^(gamma_last - gamma) U). +// A block per half of the value columns of a head (both blocks compute the k and q side), wave w holds 16 value columns +// of the state in WMMA accumulators and turns them (and its delta and U) into B operands in registers; q, k, K^T, P and T +// go through LDS, small enough for all blocks to be resident: each block runs through all chunks. +constexpr int GDN_CH_C = 16; +constexpr int GDN_CH_NW = 8; +constexpr int GDN_CH_SPLIT = 128 / (16 * GDN_CH_NW); + +typedef short gdn_short16 __attribute__((ext_vector_type(16))); +typedef float gdn_float8 __attribute__((ext_vector_type(8))); +typedef uint32_t gdn_uint8 __attribute__((ext_vector_type(8))); + +// after the products with q and k, their memory holds the partial products k.k (first half of the waves) and q.k (second half) +// over a part of the d-tiles each, A, P and T +struct gdn_ch_late { + float part[GDN_CH_NW][GDN_CH_C * GDN_CH_C]; + float lower[GDN_CH_C * GDN_CH_C]; + uint16_t ph[GDN_CH_C * GDN_CH_C], pl[GDN_CH_C * GDN_CH_C], th[GDN_CH_C * GDN_CH_C], tl[GDN_CH_C * GDN_CH_C]; +}; + +struct gdn_ch_smem { + union { + struct { + uint16_t qh[GDN_CH_C * 128], ql[GDN_CH_C * 128]; // [t][d], 16-value groups of row t xor-swizzled by t % 8 + uint16_t kh[GDN_CH_C * 128], kl[GDN_CH_C * 128]; + }; + gdn_ch_late late; + }; + uint16_t kth[128 * GDN_CH_C], ktl[128 * GDN_CH_C]; // [d][t] + float gamma[GDN_CH_C], egamma[GDN_CH_C], beta[GDN_CH_C]; +}; +static_assert(sizeof(gdn_ch_late) <= 4 * GDN_CH_C * 128 * sizeof(uint16_t), "GDN chunk LDS overlap"); + +static __device__ __forceinline__ int gdn_ch_swz(const int t, const int d) { + return t * 128 + (((d >> 4) ^ (t & 7)) << 4) + (d & 15); +} + +// x = h + l to about 2^-15 relative: h rounded to BF16 (the residual is exact in FP32), l the truncated residual +static __device__ __forceinline__ void gdn_ch_split(const float x, uint32_t & h, uint32_t & l) { + const uint32_t hb = (__float_as_uint(x) + 0x8000u) & 0xFFFF0000u; + h = hb >> 16; + l = __float_as_uint(x - __uint_as_float(hb)) >> 16; +} + +// as gdn_ch_split for a pair, packed with a in the low halves +static __device__ __forceinline__ void gdn_ch_split2(const float a, const float b, uint32_t & h, uint32_t & l) { + const uint32_t ha = (__float_as_uint(a) + 0x8000u) & 0xFFFF0000u; + const uint32_t hb = (__float_as_uint(b) + 0x8000u) & 0xFFFF0000u; + h = __builtin_amdgcn_perm(hb, ha, 0x07060302u); + l = __builtin_amdgcn_perm(__float_as_uint(b - __uint_as_float(hb)), __float_as_uint(a - __uint_as_float(ha)), 0x07060302u); +} + +// B operand (k = rows of the tile, n = lane % 16) from an accumulator tile, which holds rows 2*i + lane / 16 +static __device__ __forceinline__ void gdn_ch_frag(const gdn_float8 & x, gdn_short16 & fh, gdn_short16 & fl, const int hw) { + uint32_t h[8], l[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float own = x[i]; + const float oth = __uint_as_float(__builtin_amdgcn_permlanex16(__float_as_uint(own), __float_as_uint(own), 0x76543210u, 0xFEDCBA98u, false, false)); + gdn_ch_split2(hw == 0 ? own : oth, hw == 0 ? oth : own, h[i], l[i]); + } + fh = __builtin_bit_cast(gdn_short16, gdn_uint8{h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]}); + fl = __builtin_bit_cast(gdn_short16, gdn_uint8{l[0], l[1], l[2], l[3], l[4], l[5], l[6], l[7]}); +} + +// barrier for the LDS only: __syncthreads also waits for the global loads in flight, here the prefetched inputs +static __device__ __forceinline__ void gdn_ch_sync() { +#if defined(GGML_USE_HIP) + asm volatile("s_waitcnt lgkmcnt(0)\n\ts_barrier" ::: "memory"); +#else + __syncthreads(); +#endif // defined(GGML_USE_HIP) +} + +static __device__ __forceinline__ gdn_short16 gdn_ch_ld(const uint16_t * p) { + const uint4 a = ((const uint4 *) p)[0], b = ((const uint4 *) p)[1]; + return __builtin_bit_cast(gdn_short16, gdn_uint8{a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}); +} + +static __device__ __forceinline__ void gdn_ch_mma(gdn_float8 & c, const gdn_short16 & ah, const gdn_short16 & al, + const gdn_short16 & bh, const gdn_short16 & bl) { +#if defined(AMD_WMMA_256B_AVAILABLE) + c = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(al, bh, c); + c = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(ah, bl, c); + c = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(ah, bh, c); +#else + GGML_UNUSED_VARS(c, ah, al, bh, bl); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + +static __global__ void __launch_bounds__(32 * GDN_CH_NW, 1) gated_delta_net_chunk_cuda( + const float * __restrict__ q, const float * __restrict__ k, const float * __restrict__ v, + const float * __restrict__ g, const float * __restrict__ beta, const float * __restrict__ curr_state, + float * __restrict__ dst, float * __restrict__ state, const int64_t H, const int64_t n_tokens, + const int64_t sq1, const int64_t sq2, const int64_t sq3, const int64_t sv1, const int64_t sv2, const int64_t sv3, + const int64_t sb1, const int64_t sb2, const int64_t sb3, const uint3 neqk1_magic, const uint3 rq3_magic, const float scale) { +#if defined(AMD_WMMA_256B_AVAILABLE) + constexpr int S = 128, C = GDN_CH_C; + __shared__ gdn_ch_smem sm; + + const int lane = threadIdx.x, w = threadIdx.y, tid = w * 32 + lane, hw = lane / 16, r16 = lane % 16; + const uint32_t h_idx = blockIdx.x / GDN_CH_SPLIT, sequence = blockIdx.y; + const int col = (blockIdx.x % GDN_CH_SPLIT) * 16 * GDN_CH_NW + 16 * w + r16; + const uint32_t iq1 = fastmodulo(h_idx, neqk1_magic); + const uint32_t iq3 = fastdiv(sequence, rq3_magic); + const float * qh_ptr = q + iq3 * sq3 + iq1 * sq1; + const float * kh_ptr = k + iq3 * sq3 + iq1 * sq1; + const float * v_col = v + sequence * sv3 + h_idx * sv1 + col; + const int64_t gb0 = sequence * sb3 + h_idx * sb1; + float * out = dst + (sequence * n_tokens * H + h_idx) * S + col; + + // state tile j: S[d][v] with v = col, d = 16 j + 2 i + lane / 16; the state tensors are [v][d] + gdn_float8 st[S / 16]; + { + const float * s_in = curr_state + (sequence * H + h_idx) * S * S + col * S; +#pragma unroll + for (int j = 0; j < S / 16; ++j) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + st[j][i] = s_in[16 * j + 2 * i + hw]; + } + } + } + + constexpr int NQK = C * (S / 4) / (32 * GDN_CH_NW); // float4 of q and of k per thread + float4 qn[NQK], kn[NQK]; + float vn[8], gbn; + // a macro, not a lambda: the arrays a lambda captures stay in scratch memory +#define GDN_CH_LOAD_CHUNK(t0) \ + _Pragma("unroll") for (int m = 0; m < NQK; ++m) { \ + const int j = tid + 32 * GDN_CH_NW * m, t = j % C, c4 = j / C; \ + qn[m] = kn[m] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); \ + if ((t0) + t < n_tokens) { \ + qn[m] = *(const float4 *) (qh_ptr + ((t0) + t) * sq2 + 4 * c4); \ + kn[m] = *(const float4 *) (kh_ptr + ((t0) + t) * sq2 + 4 * c4); \ + } \ + } \ + _Pragma("unroll") for (int i = 0; i < 8; ++i) { \ + const int64_t t = (t0) + 2 * i + hw; \ + vn[i] = t < n_tokens ? v_col[t * sv2] : 0.0f; \ + } \ + gbn = 0.0f; \ + if (tid < 2 * C && (t0) + tid % C < n_tokens) { \ + gbn = (tid < C ? g : beta)[gb0 + ((t0) + tid % C) * sb2]; \ + } + GDN_CH_LOAD_CHUNK(0); + + for (int64_t t0 = 0; t0 < n_tokens; t0 += C) { + const int valid = (int) min((int64_t) C, n_tokens - t0); + // the chunk's q (scaled), k and K^T as BF16 high/residual parts, the prefix log decays and beta +#pragma unroll + for (int m = 0; m < NQK; ++m) { + const int j = tid + 32 * GDN_CH_NW * m, t = j % C, d = 4 * (j / C); // lanes along t: conflict-free K^T stores + const float qv[4] = { qn[m].x * scale, qn[m].y * scale, qn[m].z * scale, qn[m].w * scale }; + const float kv[4] = { kn[m].x, kn[m].y, kn[m].z, kn[m].w }; + uint32_t qhv[2], qlv[2], khv[2], klv[2]; +#pragma unroll + for (int e = 0; e < 2; ++e) { + gdn_ch_split2(qv[2 * e], qv[2 * e + 1], qhv[e], qlv[e]); + gdn_ch_split2(kv[2 * e], kv[2 * e + 1], khv[e], klv[e]); + sm.kth[(d + 2 * e + 0) * C + t] = khv[e] & 0xFFFFu; + sm.kth[(d + 2 * e + 1) * C + t] = khv[e] >> 16; + sm.ktl[(d + 2 * e + 0) * C + t] = klv[e] & 0xFFFFu; + sm.ktl[(d + 2 * e + 1) * C + t] = klv[e] >> 16; + } + const int o = gdn_ch_swz(t, d); + *(uint2 *) (sm.qh + o) = make_uint2(qhv[0], qhv[1]); + *(uint2 *) (sm.ql + o) = make_uint2(qlv[0], qlv[1]); + *(uint2 *) (sm.kh + o) = make_uint2(khv[0], khv[1]); + *(uint2 *) (sm.kl + o) = make_uint2(klv[0], klv[1]); + } + float v_cur[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + v_cur[i] = vn[i]; + } + if (w == 0) { + // lanes 0-15 the log decays (summed), lanes 16-31 beta + float x = gbn; +#pragma unroll + for (int off = 1; off < C; off *= 2) { + const float y = __shfl_up_sync(0xffffffff, x, off, C); + if (r16 >= off) { + x += y; + } + } + if (hw == 0) { + sm.gamma[r16] = x; + sm.egamma[r16] = expf(x); + } else { + sm.beta[r16] = gbn; + } + } + gdn_ch_sync(); + if (t0 + C < n_tokens) { + GDN_CH_LOAD_CHUNK(t0 + C); + } + + // K S and Q S for this wave's columns + gdn_float8 ks = {}, qs = {}; +#pragma unroll + for (int j = 0; j < S / 16; ++j) { + gdn_short16 sh, sl; + gdn_ch_frag(st[j], sh, sl, hw); + const int o = gdn_ch_swz(r16, 16 * j); + gdn_ch_mma(ks, gdn_ch_ld(sm.kh + o), gdn_ch_ld(sm.kl + o), sh, sl); + gdn_ch_mma(qs, gdn_ch_ld(sm.qh + o), gdn_ch_ld(sm.ql + o), sh, sl); + } + // partial k.k (first half of the waves) and q.k (second half) over a part of the d-tiles each + constexpr int JP = (S / 16) / (GDN_CH_NW / 2); + gdn_float8 x = {}; +#pragma unroll + for (int jj = 0; jj < JP; ++jj) { + const int o = gdn_ch_swz(r16, 16 * (JP * (w % (GDN_CH_NW / 2)) + jj)); + const gdn_short16 bh = gdn_ch_ld(sm.kh + o), bl = gdn_ch_ld(sm.kl + o); + if (w < GDN_CH_NW / 2) { + gdn_ch_mma(x, bh, bl, bh, bl); + } else { + gdn_ch_mma(x, gdn_ch_ld(sm.qh + o), gdn_ch_ld(sm.ql + o), bh, bl); + } + } + gdn_float8 delta; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int t = 2 * i + hw; + delta[i] = sm.beta[t] * (v_cur[i] - sm.egamma[t] * ks[i]); + } + gdn_ch_sync(); // q and k are no longer read +#pragma unroll + for (int i = 0; i < 8; ++i) { + sm.late.part[w][(2 * i + hw) * C + r16] = x[i]; + } + gdn_ch_sync(); + + // A (for the inverse) and P, the partial sums in a fixed order + for (int e = tid; e < C * C; e += 32 * GDN_CH_NW) { + const int i = e / C, j = e % C; + float a = 0.0f, p = 0.0f; +#pragma unroll + for (int ww = 0; ww < GDN_CH_NW / 2; ++ww) { + a += sm.late.part[ww][e]; + p += sm.late.part[GDN_CH_NW / 2 + ww][e]; + } + sm.late.lower[e] = j < i ? a * sm.beta[i] * expf(sm.gamma[i] - sm.gamma[j]) : 0.0f; + uint32_t h, l; + gdn_ch_split(j <= i ? p * expf(sm.gamma[i] - sm.gamma[j]) : 0.0f, h, l); + sm.late.ph[e] = h; + sm.late.pl[e] = l; + } + gdn_ch_sync(); + + // T = (I + A)^-1 by forward substitution, the rows w, w + NW, .. of a wave interleaved + { + constexpr int NR = C / GDN_CH_NW; + float xr[NR]; +#pragma unroll + for (int r = 0; r < NR; ++r) { + const int row = w + r * GDN_CH_NW; + xr[r] = lane == row ? 1.0f : (lane < row ? -sm.late.lower[row * C + lane] : 0.0f); + } + for (int pivot = C - 2; pivot > 0; --pivot) { + const float lp = lane < pivot ? sm.late.lower[pivot * C + lane] : 0.0f; +#pragma unroll + for (int r = 0; r < NR; ++r) { + const float xp = __shfl_sync(0xffffffff, xr[r], pivot, 32); + if (pivot < w + r * GDN_CH_NW) { + xr[r] -= xp * lp; + } + } + } +#pragma unroll + for (int r = 0; r < NR; ++r) { + const int row = w + r * GDN_CH_NW; + if (lane < C) { + uint32_t h, l; + gdn_ch_split(xr[r], h, l); + sm.late.th[row * C + lane] = h; + sm.late.tl[row * C + lane] = l; + } + } + } + gdn_ch_sync(); + + // U = T delta, out = e^gamma Q S + P U + gdn_short16 bh, bl; + gdn_ch_frag(delta, bh, bl, hw); + gdn_float8 u = {}; + gdn_ch_mma(u, gdn_ch_ld(sm.late.th + r16 * C), gdn_ch_ld(sm.late.tl + r16 * C), bh, bl); + gdn_ch_frag(u, bh, bl, hw); + gdn_float8 pu = {}; + gdn_ch_mma(pu, gdn_ch_ld(sm.late.ph + r16 * C), gdn_ch_ld(sm.late.pl + r16 * C), bh, bl); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int t = 2 * i + hw; + if (t < valid) { + out[(t0 + t) * S * H] = sm.egamma[t] * qs[i] + pu[i]; + } + } + + // S = e^gamma_last S + K^T (e^(gamma_last - gamma) U); the tokens past the end have no decay and no update + const float glast = sm.gamma[C - 1]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + u[i] *= expf(glast - sm.gamma[2 * i + hw]); + } + gdn_ch_frag(u, bh, bl, hw); + const float dc = sm.egamma[C - 1]; +#pragma unroll + for (int j = 0; j < S / 16; ++j) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + st[j][i] *= dc; + } + gdn_ch_mma(st[j], gdn_ch_ld(sm.kth + (16 * j + r16) * C), gdn_ch_ld(sm.ktl + (16 * j + r16) * C), bh, bl); + } + gdn_ch_sync(); + } + +#undef GDN_CH_LOAD_CHUNK + float * s_out = state + (sequence * H + h_idx) * S * S + col * S; +#pragma unroll + for (int j = 0; j < S / 16; ++j) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + s_out[16 * j + 2 * i + hw] = st[j][i]; + } + } +#else + GGML_UNUSED_VARS(q, k, v, g, beta, curr_state, dst, state, H, n_tokens, sq1, sq2, sq3, sv1, sv2, sv3, sb1, sb2, sb3, + neqk1_magic, rq3_magic, scale); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + template static void launch_gated_delta_net( const float * q_d, const float * k_d, const float * v_d, @@ -188,7 +530,8 @@ static void launch_gated_delta_net( int64_t sv1, int64_t sv2, int64_t sv3, int64_t sb1, int64_t sb2, int64_t sb3, int64_t neqk1, int64_t rq3, - float scale, int64_t state_slot_stride, int K, cudaStream_t stream) { + float scale, int64_t state_slot_stride, int K, const int32_t * state_rows, int64_t state_row_stride, + cudaStream_t stream) { //TODO: Add chunked kernel for even faster pre-fill const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; // four columns per warp (see the kernel); shrink the CTA when the wider CTA would leave @@ -212,26 +555,26 @@ static void launch_gated_delta_net( ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, state_rows, state_row_stride); break; case 32: ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, state_rows, state_row_stride); break; case 64: { ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, state_rows, state_row_stride); break; } case 128: { ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, state_rows, state_row_stride); break; } default: @@ -277,6 +620,29 @@ static ggml_cuda_gdn_mma_args ggml_cuda_gdn_mma_args_from_tensor(const ggml_tens }; } +const ggml_tensor * ggml_cuda_gdn_state_rows(const ggml_tensor * gdn) { + if (gdn->op != GGML_OP_GATED_DELTA_NET) { + return nullptr; + } + const ggml_tensor * v = gdn->src[2]; + const ggml_tensor * state = gdn->src[5]; + const ggml_tensor * rows = state->view_src ? state->view_src : state; + if (rows->op != GGML_OP_GET_ROWS || state->view_offs != 0 || ggml_nbytes(state) != ggml_nbytes(rows)) { + return nullptr; + } + const ggml_tensor * src = rows->src[0]; + const ggml_tensor * idxs = rows->src[1]; + + // One sequence: with several, a block writing its snapshot into the cache could overwrite the row another block + // still reads. Fewer than 64 tokens keeps out the MMA kernel, which reads the gathered copy (see + // select_gdn_mma_path). + const bool in_place = v->ne[3] == 1 && v->ne[2] < 64 && ggml_nelements(idxs) == 1 && idxs->type == GGML_TYPE_I32 && + rows->type == GGML_TYPE_F32 && src->type == GGML_TYPE_F32 && ggml_nrows(rows) == 1 && + rows->ne[0] == v->ne[0]*v->ne[0]*v->ne[1] && src->ne[0] == rows->ne[0] && src->ne[2] == 1 && src->ne[3] == 1 && + src->nb[0] == sizeof(float) && src->nb[1] % sizeof(float) == 0; + return in_place ? rows : nullptr; +} + static void ggml_cuda_op_gated_delta_net_impl( ggml_backend_cuda_context & ctx, ggml_tensor * dst, const ggml_cuda_gated_delta_net_fused_cache * cache) { ggml_tensor * src_q = dst->src[0]; @@ -317,6 +683,15 @@ static void ggml_cuda_op_gated_delta_net_impl( const float * s_d = (const float *) src_state->data; float * dst_d = (float *) dst->data; + // the state read in place through the row indices of the GET_ROWS that gathers it, see ggml_cuda_gdn_state_rows + const int32_t * state_rows = nullptr; + int64_t state_row_stride = 0; + if (const ggml_tensor * rows = ggml_cuda_gdn_state_rows(dst)) { + s_d = (const float *) rows->src[0]->data; + state_rows = (const int32_t *) rows->src[1]->data; + state_row_stride = rows->src[0]->nb[1] / sizeof(float); + } + GGML_ASSERT(ggml_is_contiguous_rows(src_q)); GGML_ASSERT(ggml_is_contiguous_rows(src_k)); GGML_ASSERT(ggml_is_contiguous_rows(src_v)); @@ -360,25 +735,36 @@ static void ggml_cuda_op_gated_delta_net_impl( return; } } + const int cc = ggml_cuda_info().devices[ctx.device].cc; + const bool aligned = (((uintptr_t) q_d | (uintptr_t) k_d) & 15) == 0 && sq1 % 4 == 0 && sq2 % 4 == 0 && sq3 % 4 == 0; + if (GGML_CUDA_CC_IS_RDNA3_5(cc) && !kda && !keep_rs && S_v == 128 && neq0 == 128 && state_rows == nullptr && n_tokens >= 64 && + aligned) { + const uint3 neqk1_magic = init_fastdiv_values(neqk1); + const uint3 rq3_magic = init_fastdiv_values(rq3); + gated_delta_net_chunk_cuda<<>>(q_d, k_d, v_d, g_d, b_d, s_d, + dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale); + CUDA_CHECK(cudaGetLastError()); + return; + } if (kda) { if (keep_rs) { launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, state_rows, state_row_stride, stream); } else { launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, state_rows, state_row_stride, stream); } } else { if (keep_rs) { launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, state_rows, state_row_stride, stream); } else { launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, state_rows, state_row_stride, stream); } } } diff --git a/ggml/src/ggml-cuda/gated_delta_net.cuh b/ggml/src/ggml-cuda/gated_delta_net.cuh index f9bf43706789..ff0cb26d8e61 100644 --- a/ggml/src/ggml-cuda/gated_delta_net.cuh +++ b/ggml/src/ggml-cuda/gated_delta_net.cuh @@ -9,6 +9,10 @@ struct ggml_cuda_gated_delta_net_fused_cache { void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst); +// the GET_ROWS node that gathers the recurrent state of gdn when the kernel reads that state in place in the cache, +// through the row indices, instead of the gathered copy; nullptr otherwise +const ggml_tensor * ggml_cuda_gdn_state_rows(const ggml_tensor * gdn); + // same op, but writes the snapshot(s) into the cache instead of dst (see ggml_cuda_try_gdn_cache_fusion) void ggml_cuda_op_gated_delta_net_fused_cache(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_cuda_gated_delta_net_fused_cache cache); diff --git a/ggml/src/ggml-cuda/gdn-conv.cu b/ggml/src/ggml-cuda/gdn-conv.cu new file mode 100644 index 000000000000..b7b4f42ad3a7 --- /dev/null +++ b/ggml/src/ggml-cuda/gdn-conv.cu @@ -0,0 +1,139 @@ +#include "gdn-conv.cuh" +#include "unary.cuh" + +static constexpr int GDN_CONV_HEAD = 128; // channels of a head, threads of a block +static constexpr int GDN_CONV_T = 32; // tokens of a block + +// A block per head (a thread per channel) and GDN_CONV_T tokens: the d_conv columns of a token are those of the conv +// state before the first token, the convolution and the SiLU are those of ssm_conv (the zero bias included). For the +// q and k heads the outputs go through the LDS, and each wave normalizes tokens as rms_norm_f32 does a row of 128 +// (32 threads with 4 values each, do_vec) before the scale. +template +static __global__ void __launch_bounds__(GDN_CONV_HEAD) gdn_conv_kernel( + const float * __restrict__ x, const int64_t sx1, const int64_t sx2, + const float * __restrict__ cs, const int64_t cs1, const int64_t cs2, + const float * __restrict__ w, const int64_t w1, + float * __restrict__ silu, const int64_t ss1, const int64_t ss2, + float * __restrict__ q, float * __restrict__ k, const int64_t sn1, const int64_t sn2, + const int q_head0, const int k_head0, const int n_qk_heads, const int n_tokens, const float eps, const float l2_scale) { + __shared__ __attribute__((aligned(16))) float buf[GDN_CONV_T][GDN_CONV_HEAD]; + + // the heads vary fastest, so that the blocks running together read whole rows of the raw input + const int tid = threadIdx.x; + const int head = blockIdx.x; + const int64_t seq = blockIdx.z; + const int t0 = blockIdx.y * GDN_CONV_T; + const int64_t ch = (int64_t) head * GDN_CONV_HEAD + tid; + + constexpr int n_cols = GDN_CONV_T + d_conv - 1; + float xv[n_cols]; +#pragma unroll + for (int j = 0; j < n_cols; ++j) { + const int t = t0 + j - (d_conv - 1); + xv[j] = t < 0 ? cs[seq * cs2 + ch * cs1 + t + d_conv - 1] : + t < n_tokens ? x[seq * sx2 + t * sx1 + ch] : 0.0f; + } + float wv[d_conv]; +#pragma unroll + for (int j = 0; j < d_conv; ++j) { + wv[j] = w[ch * w1 + j]; + } + + const int qk = head >= q_head0 && head < q_head0 + n_qk_heads ? 0 : head >= k_head0 && head < k_head0 + n_qk_heads ? 1 : -1; + const bool norm = qk >= 0; +#pragma unroll + for (int i = 0; i < GDN_CONV_T; ++i) { + float sumf = 0.0f; +#pragma unroll + for (int j = 0; j < d_conv; ++j) { + sumf += xv[i + j] * wv[j]; + } + sumf += 0.0f; + const float y = ggml_cuda_op_silu_single(sumf); + if (norm) { + buf[i][tid] = y; + } else if (t0 + i < n_tokens) { + silu[seq * ss2 + (int64_t) (t0 + i) * ss1 + ch] = y; + } + } + if (!norm) { + return; + } + __syncthreads(); + + const int lane = tid % WARP_SIZE, wave = tid / WARP_SIZE; + float * dst = (qk == 0 ? q : k) + seq * sn2 + (int64_t) (head - (qk == 0 ? q_head0 : k_head0)) * GDN_CONV_HEAD + 4 * lane; + constexpr int ncols = GDN_CONV_HEAD; + for (int i = wave; i < GDN_CONV_T && t0 + i < n_tokens; i += GDN_CONV_HEAD / WARP_SIZE) { + const float4 xs = *(const float4 *) &buf[i][4 * lane]; + float tmp = 0.0f; + tmp += xs.x*xs.x + xs.y*xs.y + xs.z*xs.z + xs.w*xs.w; + tmp = warp_reduce_sum(tmp); + const float scale = rsqrtf(tmp / ncols + eps); + float4 r = make_float4(scale*xs.x, scale*xs.y, scale*xs.z, scale*xs.w); + r.x *= l2_scale; + r.y *= l2_scale; + r.z *= l2_scale; + r.w *= l2_scale; + *(float4 *) (dst + (int64_t) (t0 + i) * sn1) = r; + } +} + +// the head of the channels a view of the silu output starts at, or -1 +static int gdn_conv_head(const ggml_tensor * view, const ggml_tensor * silu) { + if (view->view_src != silu || view->type != GGML_TYPE_F32 || view->ne[0] != GDN_CONV_HEAD || + view->nb[0] != sizeof(float) || view->nb[1] != GDN_CONV_HEAD * sizeof(float) || view->nb[2] != silu->nb[1] || + view->view_offs % (GDN_CONV_HEAD * sizeof(float)) != 0) { + return -1; + } + return view->view_offs / (GDN_CONV_HEAD * sizeof(float)); +} + +bool ggml_cuda_gdn_conv_supported(const ggml_backend_cuda_context & ctx, const ggml_cuda_gdn_conv_nodes & n) { + static const bool off = getenv("GGML_CUDA_NO_GDN_CONV") != nullptr; + GGML_UNUSED(ctx); + if (off) { + return false; + } + const ggml_tensor * a = n.concat->src[0]; // conv state [d_conv - 1, channels, n_seqs] + const ggml_tensor * x = n.concat->src[1]; // transposed raw input [tokens, channels, n_seqs] + const ggml_tensor * w = n.conv->src[1]; // [d_conv, channels] + const int64_t channels = n.silu->ne[0], n_tokens = n.silu->ne[1]; + bool ok = n.concat->op == GGML_OP_CONCAT && ggml_get_op_params_i32(n.concat, 0) == 0 && + a->type == GGML_TYPE_F32 && x->type == GGML_TYPE_F32 && w->type == GGML_TYPE_F32 && n.silu->type == GGML_TYPE_F32 && + w->ne[0] == 4 && a->ne[0] == w->ne[0] - 1 && a->ne[1] == channels && w->ne[1] == channels && x->ne[1] == channels && + x->ne[0] == n_tokens && x->ne[2] == n.silu->ne[2] && a->ne[2] == n.silu->ne[2] && x->ne[3] == 1 && + channels % GDN_CONV_HEAD == 0 && a->nb[0] == sizeof(float) && x->nb[1] == sizeof(float) && w->nb[0] == sizeof(float) && + ggml_is_contiguous(n.silu) && n_tokens >= 64; + for (int s = 0; s < 2 && ok; ++s) { + const ggml_tensor * view = n.rms[s]->src[0]; + const ggml_tensor * sc = n.scale[s]; + ok = gdn_conv_head(view, n.silu) >= 0 && n.scale[s]->src[0] == n.rms[s] && sc->type == GGML_TYPE_F32 && + ggml_is_contiguous(sc) && ggml_are_same_shape(sc, view) && ggml_get_op_params_f32(sc, 1) == 0.0f && + ((uintptr_t) sc->data & 15) == 0 && view->ne[1] == n.rms[0]->src[0]->ne[1] && + ggml_get_op_params_f32(n.rms[s], 0) == ggml_get_op_params_f32(n.rms[0], 0) && + ggml_get_op_params_f32(sc, 0) == ggml_get_op_params_f32(n.scale[0], 0); + } + return ok; +} + +void ggml_cuda_op_gdn_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_gdn_conv_nodes & n) { + const ggml_tensor * a = n.concat->src[0]; + const ggml_tensor * x = n.concat->src[1]; + const ggml_tensor * w = n.conv->src[1]; + const int64_t channels = n.silu->ne[0], n_tokens = n.silu->ne[1], n_seqs = n.silu->ne[2]; + const ggml_tensor * vq = n.rms[0]->src[0]; + const ggml_tensor * vk = n.rms[1]->src[0]; + GGML_ASSERT(n.scale[0]->nb[2] == n.scale[1]->nb[2] && n.scale[0]->nb[3] == n.scale[1]->nb[3]); + + const dim3 grid(channels / GDN_CONV_HEAD, (n_tokens + GDN_CONV_T - 1) / GDN_CONV_T, n_seqs); + gdn_conv_kernel<4><<>>( + (const float *) x->data, x->nb[0] / sizeof(float), x->nb[2] / sizeof(float), + (const float *) a->data, a->nb[1] / sizeof(float), a->nb[2] / sizeof(float), + (const float *) w->data, w->nb[1] / sizeof(float), + (float *) n.silu->data, n.silu->nb[1] / sizeof(float), n.silu->nb[2] / sizeof(float), + (float *) n.scale[0]->data, (float *) n.scale[1]->data, n.scale[0]->nb[2] / sizeof(float), n.scale[0]->nb[3] / sizeof(float), + gdn_conv_head(vq, n.silu), gdn_conv_head(vk, n.silu), (int) vq->ne[1], (int) n_tokens, + ggml_get_op_params_f32(n.rms[0], 0), ggml_get_op_params_f32(n.scale[0], 0)); + CUDA_CHECK(cudaGetLastError()); +} diff --git a/ggml/src/ggml-cuda/gdn-conv.cuh b/ggml/src/ggml-cuda/gdn-conv.cuh new file mode 100644 index 000000000000..2ee531afbb3f --- /dev/null +++ b/ggml/src/ggml-cuda/gdn-conv.cuh @@ -0,0 +1,21 @@ +#pragma once + +#include "common.cuh" + +// The convolution in front of the gated delta net of a prompt batch, as the graph builds it: +// CONCAT(conv state, transposed raw input) -> SSM_CONV -> SILU, whose views are v and, through RMS_NORM -> SCALE (the L2 +// norm of each head and token), q and k. +struct ggml_cuda_gdn_conv_nodes { + const ggml_tensor * concat; + const ggml_tensor * conv; + const ggml_tensor * silu; + const ggml_tensor * rms[2]; // of q, of k + const ggml_tensor * scale[2]; +}; + +// whether ggml_cuda_op_gdn_conv computes those nodes (GGML_CUDA_NO_GDN_CONV turns it off) +bool ggml_cuda_gdn_conv_supported(const ggml_backend_cuda_context & ctx, const ggml_cuda_gdn_conv_nodes & n); + +// all of them in one kernel, reading the raw input and the conv state in place: v in the SILU output, q and k in the +// SCALE outputs (the q and k parts of the SILU output are not written), with the results of the nodes bit for bit +void ggml_cuda_op_gdn_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_gdn_conv_nodes & n); diff --git a/ggml/src/ggml-cuda/getrows.cu b/ggml/src/ggml-cuda/getrows.cu index 09b7f02b8f85..3bc927d2febc 100644 --- a/ggml/src/ggml-cuda/getrows.cu +++ b/ggml/src/ggml-cuda/getrows.cu @@ -490,3 +490,51 @@ void ggml_cuda_op_get_rows_back(ggml_backend_cuda_context & ctx, ggml_tensor * d k_get_rows_back_float<<>>(src0_d, src1_d, dst_d, ne00, ne10, ne1); } + +// The k-pool update of a QSA indexer for one token, in one block: the new row (k_new, then n_fill copies of +// fill_value) is written as F16 to row set_idx[0] of the cache, as SET_ROWS does, then the first n_cols values of the +// cache rows get_idx[rows[0..3]] are summed in that order and scaled, as GET_ROWS, the ADD chain and SCALE do. +static __global__ void qsa_kpool_step_f16( + const float * __restrict__ k_new, const int n_new, const float fill_value, const int n_fill, + char * set_base, const void * set_idx, const bool set_idx_i64, const size_t set_nb1, + const char * get_base, const void * get_idx, const bool get_idx_i64, const size_t get_nb1, const int n_cols, + const int r0, const int r1, const int r2, const int r3, const float scale, const float bias, float * dst) { + const int tid = threadIdx.x; + + const int64_t row_new = set_idx_i64 ? ((const int64_t *) set_idx)[0] : ((const int32_t *) set_idx)[0]; + half * row = (half *) (set_base + row_new*set_nb1); + for (int c = tid; c < n_new + n_fill; c += blockDim.x) { + row[c] = ggml_cuda_cast(c < n_new ? k_new[c] : fill_value); + } + __syncthreads(); + + const int rows[4] = { r0, r1, r2, r3 }; + const half * src[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int64_t r = get_idx_i64 ? ((const int64_t *) get_idx)[rows[j]] : ((const int32_t *) get_idx)[rows[j]]; + src[j] = (const half *) (get_base + r*get_nb1); + } + for (int c = tid; c < n_cols; c += blockDim.x) { + float sum = ggml_cuda_cast(src[0][c]) + ggml_cuda_cast(src[1][c]); + sum = sum + ggml_cuda_cast(src[2][c]); + sum = sum + ggml_cuda_cast(src[3][c]); + dst[c] = scale * sum + bias; + } +} + +void ggml_cuda_op_qsa_kpool_step(ggml_backend_cuda_context & ctx, const ggml_tensor * k_new, const ggml_tensor * fill, + const ggml_tensor * set_rows, const ggml_tensor * get_rows, const int * rows, + const ggml_tensor * scale_node, ggml_tensor * dst) { + float scale; + float bias; + memcpy(&scale, (const float *) scale_node->op_params + 0, sizeof(float)); + memcpy(&bias, (const float *) scale_node->op_params + 1, sizeof(float)); + const ggml_tensor * set_idx = set_rows->src[1]; + const ggml_tensor * get_idx = get_rows->src[1]; + qsa_kpool_step_f16<<<1, 128, 0, ctx.stream()>>>( + (const float *) k_new->data, k_new->ne[0], ggml_get_op_params_f32(fill, 0), fill->ne[0], + (char *) set_rows->data, set_idx->data, set_idx->type == GGML_TYPE_I64, set_rows->nb[1], + (const char *) get_rows->src[0]->data, get_idx->data, get_idx->type == GGML_TYPE_I64, get_rows->src[0]->nb[1], + get_rows->ne[0], rows[0], rows[1], rows[2], rows[3], scale, bias, (float *) dst->data); +} diff --git a/ggml/src/ggml-cuda/getrows.cuh b/ggml/src/ggml-cuda/getrows.cuh index 3c5bea5f48c1..0ca426e29b93 100644 --- a/ggml/src/ggml-cuda/getrows.cuh +++ b/ggml/src/ggml-cuda/getrows.cuh @@ -13,3 +13,9 @@ void get_rows_cuda( void ggml_cuda_op_get_rows(ggml_backend_cuda_context & ctx, ggml_tensor * dst); void ggml_cuda_op_get_rows_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst); + +// dst = scale_node(the sum of rows rows[0..3] of get_rows) for one token, after writing the CONCAT of k_new and fill +// into the cache row of set_rows (F16), as FILL, CONCAT, SET_ROWS, GET_ROWS, the ADD chain and SCALE compute it +void ggml_cuda_op_qsa_kpool_step(ggml_backend_cuda_context & ctx, const ggml_tensor * k_new, const ggml_tensor * fill, + const ggml_tensor * set_rows, const ggml_tensor * get_rows, const int * rows, + const ggml_tensor * scale_node, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index c8dc8e67366d..c00389e9250d 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -2,6 +2,8 @@ #include "ggml-impl.h" #include "ggml-backend-impl.h" +#include + #include "ggml-cuda/allreduce.cuh" #include "ggml-cuda/common.cuh" #include "ggml-cuda/graph.cuh" @@ -30,6 +32,8 @@ #include "ggml-cuda/fp8.cuh" #include "ggml-cuda/fwht.cuh" #include "ggml-cuda/getrows.cuh" +#include "ggml-cuda/dense-wmma.cuh" +#include "ggml-cuda/hc-wmma.cuh" #include "ggml-cuda/im2col.cuh" #include "ggml-cuda/mmf.cuh" #include "ggml-cuda/mmq.cuh" @@ -37,6 +41,8 @@ #include "ggml-cuda/mmvf.cuh" #include "ggml-cuda/mmvq.cuh" #include "ggml-cuda/moe-weighted-reduction.cuh" +#include "ggml-cuda/moe-wmma.cuh" +#include "ggml-cuda/mul-mat-f32-wmma.cuh" #include "ggml-cuda/norm.cuh" #include "ggml-cuda/opt-step-adamw.cuh" #include "ggml-cuda/opt-step-sgd.cuh" @@ -64,6 +70,7 @@ #include "ggml-cuda/wkv.cuh" #include "ggml-cuda/gla.cuh" #include "ggml-cuda/gated_delta_net.cuh" +#include "ggml-cuda/gdn-conv.cuh" #include "ggml-cuda/dsv4-hc.cuh" #include "ggml-cuda/set.cuh" #include "ggml-cuda/set-rows.cuh" @@ -74,6 +81,7 @@ #include "ggml-cuda/fill.cuh" #include "ggml-cuda/lightning-indexer.cuh" #include "ggml-cuda/top-k-mask.cuh" +#include "ggml-cuda/qsa-attn.cuh" #include "ggml.h" #include @@ -1102,12 +1110,29 @@ void ggml_cuda_q8_1_cache::invalidate(const ggml_tensor * node) { } } +// Whether MMVQ quantizes a and b, views of the same tensor over the same contiguous F32 data, to the same q8_1 +// blocks, so that one copy serves both: MMVQ pads every row to MATRIX_ROW_PADDING, so rows that are whole multiples +// of it quantize to the same blocks however the data is split into rows. Requiring the same tensor keeps a copy of +// an earlier tensor at the same address from being taken for a later one. +static bool ggml_cuda_q8_1_shares_copy(const ggml_tensor * a, const ggml_tensor * b) { + const ggml_tensor * root_a = a->view_src ? a->view_src : a; + const ggml_tensor * root_b = b->view_src ? b->view_src : b; + return root_a == root_b && a->type == GGML_TYPE_F32 && b->type == GGML_TYPE_F32 && a->data == b->data && + ggml_nbytes(a) == ggml_nbytes(b) && ggml_is_contiguous(a) && ggml_is_contiguous(b) && + (a->ne[0] == b->ne[0] || (a->ne[0] % MATRIX_ROW_PADDING == 0 && b->ne[0] % MATRIX_ROW_PADDING == 0)); +} + const char * ggml_cuda_q8_1_cache::find(const ggml_tensor * t) const { for (const entry & e : entries) { if (e.tensor == t && e.data == t->data) { return e.buf; } } + for (const entry & e : entries) { + if (e.tensor && e.data == e.tensor->data && ggml_cuda_q8_1_shares_copy(e.tensor, t)) { + return e.buf; + } + } return nullptr; } @@ -1146,6 +1171,31 @@ ggml_backend_cuda_context::~ggml_backend_cuda_context() { if (copy_event != nullptr) { CUDA_CHECK(cudaEventDestroy(copy_event)); } + if (hc_inject_buf != nullptr) { + ggml_cuda_device_free(hc_inject_buf, device); + } + if (hc_bf16_buf != nullptr) { + ggml_cuda_device_free(hc_bf16_buf, device); + } + if (router_topk_counter != nullptr) { + ggml_cuda_device_free(router_topk_counter, device); + } + for (auto & kv : router_bf16) { + ggml_cuda_device_free(kv.second, device); + } + for (auto & kv : dense_bf16) { + ggml_cuda_device_free(kv.second, device); + } + + if (dense_x_buf != nullptr) { + ggml_cuda_device_free(dense_x_buf, device); + } + if (mmq_q8_1_buf != nullptr) { + ggml_cuda_device_free(mmq_q8_1_buf, device); + } + if (moe_scratch != nullptr) { + ggml_cuda_device_free(moe_scratch, device); + } for (int i = 0; i < GGML_CUDA_MAX_DEVICES; ++i) { for (int j = 0; j < GGML_CUDA_MAX_STREAMS; ++j) { if (streams[i][j] != nullptr) { @@ -2139,6 +2189,8 @@ static void ggml_cuda_mul_mat_cublas_impl(ggml_backend_cuda_context & ctx, const if (src1->type == compute_type) { src1_ptr = (const cuda_t *) src1->data; + } else if (compute_type == GGML_TYPE_BF16 && src1 == ctx.hc_bf16_src) { + src1_ptr = (const cuda_t *) (const void *) ctx.hc_bf16_buf; } else { src1_alloc.alloc(ggml_nelements(src1)); @@ -2287,6 +2339,48 @@ static void ggml_cuda_mul_mat_cublas_impl(ggml_backend_cuda_context & ctx, const } } +// one small GEMM of a compute type, with the operands of ggml_cuda_mul_mat_cublas_impl +template +static void ggml_cuda_blas_prewarm_type(ggml_backend_cuda_context & ctx, bool prefer_f32_output) { + using traits = batched_mul_mat_traits; + constexpr int n = 256; + ggml_cuda_pool_alloc buf(ctx.pool(), 3 * n * n * sizeof(float)); + CUDA_CHECK(cudaMemsetAsync(buf.get(), 0, 3 * n * n * sizeof(float), ctx.stream())); + const char * a = buf.get(); + const char * b = a + n * n * sizeof(float); + char * c = buf.get() + 2 * n * n * sizeof(float); + const cublasComputeType_t ct = prefer_f32_output ? CUBLAS_COMPUTE_32F : traits::compute_type; + const cudaDataType_t dt = prefer_f32_output ? CUDA_R_32F : traits::data_type; + const void * alpha = prefer_f32_output ? batched_mul_mat_traits::get_alpha() : traits::get_alpha(); + const void * beta = prefer_f32_output ? batched_mul_mat_traits::get_beta() : traits::get_beta(); + CUBLAS_CHECK(cublasGemmEx(ctx.cublas_handle(), CUBLAS_OP_T, CUBLAS_OP_N, n, n, n, + alpha, a, traits::data_type, n, b, traits::data_type, n, beta, c, dt, n, ct, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); +} + +// hipBLASLt loads the kernels of a GEMM type on its first use (about 40 ms for F16 and 10 ms for BF16 on gfx1151), +// which the first prompt would wait for, as the warmup decode does not reach hipBLAS +static void ggml_cuda_blas_prewarm(ggml_backend_cuda_context & ctx) { +#if defined(GGML_USE_HIP) + static bool done[GGML_CUDA_MAX_DEVICES] = {}; + if (done[ctx.device]) { + return; + } + done[ctx.device] = true; + if (getenv("GGML_CUDA_NO_BLAS_PREWARM") != nullptr) { + return; + } + const int cc = ggml_cuda_info().devices[ctx.device].cc; + if (fast_fp16_hardware_available(cc)) { + ggml_cuda_blas_prewarm_type(ctx, cc == GGML_CUDA_CC_VOLTA || GGML_CUDA_CC_IS_RDNA4(cc) || GGML_CUDA_CC_IS_CDNA(cc)); + } + if (fast_bf16_hardware_available(cc)) { + ggml_cuda_blas_prewarm_type(ctx, !GGML_CUDA_CC_IS_RDNA3(cc) && !GGML_CUDA_CC_IS_RDNA4_M(cc) && !GGML_CUDA_CC_IS_CDNA(cc)); + } +#else + GGML_UNUSED(ctx); +#endif // defined(GGML_USE_HIP) +} + static void ggml_cuda_mul_mat_cublas(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { const int cc = ggml_cuda_info().devices[ctx.device].cc; const ggml_prec prec = ggml_prec_get_acc(dst); @@ -2562,8 +2656,9 @@ static bool ggml_cuda_match_shared_expert(const ggml_cgraph * graph, int routed_ if (input->op != GGML_OP_RESHAPE || input->src[0] != shared_up->src[1] || input->ne[1] != 1 || input->ne[3] != 1 || !ggml_is_contiguous(input) || !ggml_is_contiguous(shared_up->src[1]) || !ggml_is_matrix(shared_up->src[1]) || - weight->type != shared_weight->type || weight->ne[0] != shared_weight->ne[0] || - weight->ne[1] != shared_weight->ne[1] || weight->nb[1] != shared_weight->nb[1] || weight->ne[3] != 1 || + (weight->type == shared_weight->type ? weight->nb[1] != shared_weight->nb[1] : + !ggml_cuda_mmvq_moe_glu_shared_supported(weight->type, shared_weight->type)) || + weight->ne[0] != shared_weight->ne[0] || weight->ne[1] != shared_weight->ne[1] || weight->ne[3] != 1 || !ggml_is_matrix(shared_weight) || !ggml_is_contiguous(shared_weight) || !ggml_is_contiguous(shared_gate->src[0]) || !ggml_is_contiguous(routed) || !ggml_is_contiguous(shared)) { return false; @@ -2689,6 +2784,41 @@ static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_t return ggml_cuda_mmq_fusion_is_efficient(x_up->type, ggml_prec_get_src(up, 1), x_up->ne[1], ncols, nchannels, device); } +// dst[j, t] = sum_k x[j, k] * y[k, t] for the few rows j < NR of an F32 matrix, a block per column t (hipBLAS takes a +// single workgroup for such shapes) +template +static __global__ void mul_mat_f32_few_rows(const float * __restrict__ x, const float * __restrict__ y, float * __restrict__ dst, + const int ne00, const int ne01, const int64_t s01, const int64_t s11, const int64_t s1) { + constexpr int ws = ggml_cuda_get_physical_warp_size(); + const float * yt = y + blockIdx.x * s11; + float sum[NR] = {}; + for (int k = threadIdx.x; k < ne00; k += blockDim.x) { + const float v = yt[k]; +#pragma unroll + for (int j = 0; j < NR; ++j) { + if (j < ne01) { + sum[j] += x[j * s01 + k] * v; + } + } + } + __shared__ float red[NR][256 / ws]; +#pragma unroll + for (int j = 0; j < NR; ++j) { + sum[j] = warp_reduce_sum(sum[j]); + if (threadIdx.x % ws == 0) { + red[j][threadIdx.x / ws] = sum[j]; + } + } + __syncthreads(); + if (threadIdx.x < ne01) { + float a = 0.0f; + for (int w = 0; w < 256 / ws; ++w) { + a += red[threadIdx.x][w]; + } + dst[blockIdx.x * s1 + threadIdx.x] = a; + } +} + static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_TENSOR_BINARY_OP_LOCALS @@ -2750,6 +2880,22 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor if (src0->type == GGML_TYPE_F8_E4M3 && ggml_cuda_mul_mat_fp8(ctx, src0, src1, dst)) { return; } + if (dst->src[0] == src0 && dst->src[1] == src1 && ggml_cuda_dense_wmma_supported(ctx, src0, src1, dst)) { + const ggml_tensor * dsts[1] = { dst }; + ggml_cuda_dense_wmma(ctx, dsts, 1); + return; + } + if (ggml_cuda_should_use_mul_mat_f32_wmma(src0, src1, dst, cc)) { + ggml_cuda_mul_mat_f32_wmma(ctx, src0, src1, dst); + return; + } + if (src0->type == GGML_TYPE_F32 && ne01 <= 8 && ne02 == 1 && ne03 == 1 && ne12 == 1 && ne13 == 1 && + nb00 == sizeof(float) && nb10 == sizeof(float) && nb0 == sizeof(float)) { + mul_mat_f32_few_rows<8><<>>((const float *) src0->data, (const float *) src1->data, + (float *) dst->data, ne00, ne01, nb01 / sizeof(float), nb11 / sizeof(float), nb1 / sizeof(float)); + CUDA_CHECK(cudaGetLastError()); + return; + } ggml_cuda_mul_mat_cublas(ctx, src0, src1, dst); } @@ -2764,6 +2910,10 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c return true; } + if (ggml_cuda_moe_wmma_is_repacked(src0)) { + return false; + } + if (dst->ne[2] <= MMVQ_MAX_BATCH_SIZE) { if (ggml_is_quantized(src0->type)) { if (dst->ne[2] <= get_mmvq_mmid_max_batch(src0->type, cc)) { @@ -2796,6 +2946,12 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * GGML_ASSERT(src1->type == GGML_TYPE_F32); GGML_ASSERT(dst->type == GGML_TYPE_F32); + // the repacked experts are only read by the WMMA kernels + if (ggml_cuda_moe_wmma_is_repacked(src0)) { + ggml_cuda_moe_wmma_mul_mat_id(ctx, dst); + return; + } + GGML_TENSOR_BINARY_OP_LOCALS const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; @@ -3251,7 +3407,11 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg ggml_cuda_op_argsort(ctx, dst); break; case GGML_OP_FLASH_ATTN_EXT: - ggml_cuda_flash_attn_ext(ctx, dst); + if (const auto it = ctx.qsa_fa.find(dst); it != ctx.qsa_fa.end()) { + ggml_cuda_qsa_attn(ctx, dst, it->second); + } else { + ggml_cuda_flash_attn_ext(ctx, dst); + } break; case GGML_OP_CROSS_ENTROPY_LOSS: ggml_cuda_cross_entropy_loss(ctx, dst); @@ -3299,7 +3459,11 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg ggml_cuda_lightning_indexer(ctx, dst); break; case GGML_OP_TOP_K_MASK: - ggml_cuda_op_top_k_mask(ctx, dst); + if (ctx.qsa_masks.count(dst)) { + ggml_cuda_qsa_select(ctx, dst); + } else { + ggml_cuda_op_top_k_mask(ctx, dst); + } break; default: return false; @@ -3720,6 +3884,200 @@ static bool ggml_cuda_should_fuse_rms_norm_mul_rope(const ggml_tensor * rms_norm return true; } +// The SSM_CONV computed by the convolution step starting at the CONCAT node j, -1 otherwise: the CONCAT of the state +// (d_conv - 1 values per channel, a GET_ROWS of one cache row, through views) and the new input x (a contiguous product, +// through a reshape and a transpose); its last d_conv - 1 columns copied back to the cache (VIEW, VIEW, CPY right +// after); and SSM_CONV -> SILU of it a few nodes on, without bias. Nothing else reads the CONCAT, so +// ggml_cuda_op_ssm_conv_step can read the state in place and compute all of them. +static int ggml_cuda_conv_step_fusion(const ggml_cgraph * cgraph, int j) { + const ggml_tensor * cat = cgraph->nodes[j]; + if (cat->op != GGML_OP_CONCAT || j + 3 >= cgraph->n_nodes || ggml_get_op_params_i32(cat, 0) != 0 || + cat->type != GGML_TYPE_F32 || cat->ne[0] != 4 || cat->ne[2] != 1 || cat->ne[3] != 1 || + ggml_node_get_use_count(cgraph, j) != 2) { + return -1; + } + const int64_t n_channels = cat->ne[1]; + const ggml_tensor * st = cat->src[0]; + const ggml_tensor * rows = st->view_src; + const ggml_tensor * xin = cat->src[1]; + const ggml_tensor * x = xin->view_src; + if (rows == nullptr || rows->op != GGML_OP_GET_ROWS || st->data != rows->data || !ggml_is_contiguous(st) || + st->ne[0] != 3 || st->ne[1] != n_channels || ggml_nrows(rows) != 1 || rows->ne[0] != 3*n_channels || + rows->src[0]->type != GGML_TYPE_F32 || rows->src[0]->ne[0] != rows->ne[0] || rows->src[0]->nb[0] != sizeof(float) || + rows->src[1]->type != GGML_TYPE_I32 || ggml_nelements(rows->src[1]) != 1) { + return -1; + } + if (x == nullptr || xin->data != x->data || x->type != GGML_TYPE_F32 || !ggml_is_contiguous(x) || + ggml_nelements(x) != n_channels || ggml_nelements(xin) != n_channels) { + return -1; + } + const ggml_tensor * v_src = cgraph->nodes[j + 1]; + const ggml_tensor * v_dst = cgraph->nodes[j + 2]; + const ggml_tensor * cpy = cgraph->nodes[j + 3]; + if (v_src->op != GGML_OP_VIEW || v_src->src[0] != cat || v_src->view_offs != sizeof(float) || + v_src->nb[1] != 4*sizeof(float) || v_src->ne[0] != 3 || v_src->ne[1] != n_channels || + v_dst->op != GGML_OP_VIEW || cpy->op != GGML_OP_CPY || cpy->src[0] != v_src || cpy->src[1] != v_dst || + v_dst->type != GGML_TYPE_F32 || !ggml_is_contiguous(v_dst) || ggml_nelements(v_dst) != 3*n_channels) { + return -1; + } + for (int k = j + 4; k < std::min(cgraph->n_nodes - 1, j + 24); ++k) { + const ggml_tensor * conv = cgraph->nodes[k]; + if (conv->op != GGML_OP_SSM_CONV || conv->src[0] != cat) { + continue; + } + const ggml_tensor * w = conv->src[1]; + const ggml_tensor * silu = cgraph->nodes[k + 1]; + const bool ok = w->type == GGML_TYPE_F32 && ggml_is_contiguous(w) && w->ne[0] == 4 && w->ne[1] == n_channels && + silu->op == GGML_OP_UNARY && ggml_get_unary_op(silu) == GGML_UNARY_OP_SILU && silu->src[0] == conv && + ggml_node_get_use_count(cgraph, k) == 1 && ggml_is_contiguous(silu) && ggml_nelements(silu) == n_channels; + return ok ? k : -1; + } + return -1; +} + +static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, + int node_idx, + std::initializer_list ops, + std::initializer_list unary_ops); + +// The RMS_NORM + SCALE pairs shortly after the SiLU at silu_idx of a convolution step that normalize rows of 128 of its +// channels of one token (the q and k heads of a gated delta net), which the step can compute too (see +// ggml_cuda_op_ssm_conv_step): up to two, in norm and norm_scale. Returns how many. +static int ggml_cuda_conv_step_norms(const ggml_cgraph * cgraph, int silu_idx, const ggml_tensor ** norm, + const ggml_tensor ** norm_scale) { + const ggml_tensor * silu = cgraph->nodes[silu_idx]; + const int64_t n_channels = ggml_nelements(silu); + int n = 0; + for (int k = silu_idx + 1; k < std::min(cgraph->n_nodes - 1, silu_idx + 12) && n < 2; ++k) { + const ggml_tensor * rms = cgraph->nodes[k]; + if (rms->op != GGML_OP_RMS_NORM) { + // the norms are written early: nothing in between may read memory they reuse + if (rms->op == GGML_OP_VIEW || rms->op == GGML_OP_RESHAPE || rms->op == GGML_OP_PERMUTE || + rms->op == GGML_OP_TRANSPOSE || rms->op == GGML_OP_NONE) { + continue; + } + break; + } + const ggml_tensor * view = rms->src[0]; + const ggml_tensor * scale = cgraph->nodes[k + 1]; + if (view->op != GGML_OP_VIEW || view->view_src != silu || !ggml_cuda_can_fuse(cgraph, k, { GGML_OP_RMS_NORM, GGML_OP_SCALE }, {})) { + break; + } + const bool ok = n_channels % 128 == 0 && view->type == GGML_TYPE_F32 && ggml_is_contiguous(view) && + view->ne[0] == 128 && view->view_offs % (128*sizeof(float)) == 0 && ((uintptr_t) view->data & 15) == 0 && + view->view_offs + ggml_nbytes(view) <= (size_t) n_channels*sizeof(float) && + scale->type == GGML_TYPE_F32 && ggml_is_contiguous(scale) && ggml_are_same_shape(scale, view) && + ggml_get_op_params_f32(scale, 1) == 0.0f && ((uintptr_t) scale->data & 15) == 0; + if (!ok) { + break; + } + norm[n] = rms; + norm_scale[n] = scale; + ++n; + ++k; + } + return n; +} + +// Whether node i gathers the conv state that a convolution step shortly after reads in place instead (see +// ggml_cuda_conv_step_fusion): read through the views on the way to the CONCAT, and an empty view (see build_rs). +static bool ggml_cuda_conv_state_rows_unused(const ggml_cgraph * cgraph, int i) { + const ggml_tensor * rows = cgraph->nodes[i]; + if (rows->op != GGML_OP_GET_ROWS || (rows->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + int cat_idx = -1; + for (int j = i + 1; j < std::min(cgraph->n_nodes, i + 32); ++j) { + const ggml_tensor * cat = cgraph->nodes[j]; + if (cat->op == GGML_OP_CONCAT && cat->src[0]->view_src == rows && ggml_cuda_conv_step_fusion(cgraph, j) > j) { + cat_idx = j; + break; + } + } + if (cat_idx < 0) { + return false; + } + const ggml_tensor * reader = cgraph->nodes[cat_idx]; + for (const ggml_tensor * t = reader->src[0]; t != rows; t = t->src[0]) { + int t_idx = -1; + for (int j = i + 1; j < cat_idx; ++j) { + if (cgraph->nodes[j] == t) { + t_idx = j; + break; + } + } + if (t->view_src != rows || t_idx < 0 || ggml_node_get_use_count(cgraph, t_idx) != 1 || + (t->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + reader = t; + } + int n_reads = 0; + for (int j = i + 1; j <= cat_idx; ++j) { + const ggml_tensor * node = cgraph->nodes[j]; + for (int k = 0; k < GGML_MAX_SRC; ++k) { + if (node->src[k] != rows) { + continue; + } + if (node != reader && ggml_nelements(node) != 0) { + return false; + } + n_reads++; + } + } + return n_reads == ggml_node_get_use_count(cgraph, i); +} + +// Whether node i gathers the recurrent states that a gated delta net shortly after reads in place instead (see +// ggml_cuda_gdn_state_rows), so that nothing reads the gathered copy and the node can be skipped. The copy is read +// through the views on the way to the state input, and an empty view of the states of no other sequence (see build_rs). +static bool ggml_cuda_gdn_state_rows_unused(const ggml_cgraph * cgraph, int i) { + const ggml_tensor * rows = cgraph->nodes[i]; + if (rows->op != GGML_OP_GET_ROWS || (rows->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + int gdn_idx = -1; + for (int j = i + 1; j < std::min(cgraph->n_nodes, i + 64); ++j) { + if (cgraph->nodes[j]->op == GGML_OP_GATED_DELTA_NET && ggml_cuda_gdn_state_rows(cgraph->nodes[j]) == rows) { + gdn_idx = j; + break; + } + } + if (gdn_idx < 0) { + return false; + } + const ggml_tensor * gdn = cgraph->nodes[gdn_idx]; + const ggml_tensor * reader = gdn; + for (const ggml_tensor * t = gdn->src[5]; t != rows; t = t->src[0]) { + int t_idx = -1; + for (int j = i + 1; j < gdn_idx; ++j) { + if (cgraph->nodes[j] == t) { + t_idx = j; + break; + } + } + if (t->view_src != rows || t_idx < 0 || ggml_node_get_use_count(cgraph, t_idx) != 1 || + (t->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + reader = t; + } + int n_reads = 0; + for (int j = i + 1; j <= gdn_idx; ++j) { + const ggml_tensor * node = cgraph->nodes[j]; + for (int k = 0; k < GGML_MAX_SRC; ++k) { + if (node->src[k] != rows) { + continue; + } + if (node != reader && ggml_nelements(node) != 0) { + return false; + } + n_reads++; + } + } + return n_reads == ggml_node_get_use_count(cgraph, i); +} + // match gated_delta_net + the strided cpy that scatters its state snapshots into the cache // (slot i -> rollback group i, slot 0 newest), so the kernel can write them and skip the cpy. static int ggml_cuda_try_gdn_cache_fusion( @@ -4468,6 +4826,44 @@ static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, } } + // the gated residual of a shared expert, a + x*sigmoid(g), whose gate has one value per row of x: the generic + // check below wants the same shape for all nodes + if (ops.size() == 3 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_MUL && ops.begin()[2] == GGML_OP_ADD + && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_SIGMOID) { + if (!ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 2 })) { + return false; + } + const ggml_tensor * unary = cgraph->nodes[node_idx]; + const ggml_tensor * mul = cgraph->nodes[node_idx+1]; + const ggml_tensor * add = cgraph->nodes[node_idx+2]; + if (ggml_get_unary_op(unary) != GGML_UNARY_OP_SIGMOID || (mul->src[0] == unary) == (mul->src[1] == unary) || + (add->src[0] == mul) == (add->src[1] == mul)) { + return false; + } + const ggml_tensor * x = mul->src[0] == unary ? mul->src[1] : mul->src[0]; + const ggml_tensor * a = add->src[0] == mul ? add->src[1] : add->src[0]; + + // the fused kernel reads one gate value per row of x and all of x, a and dst as dense F32 + for (const ggml_tensor * t : { (const ggml_tensor *) unary->src[0], unary, x, mul, a, add }) { + if (t->type != GGML_TYPE_F32 || !ggml_is_contiguous(t)) { + return false; + } + } + if (unary->ne[0] != 1 || ggml_nelements(unary) != ggml_nrows(x) || !ggml_are_same_shape(unary, unary->src[0]) || + unary->ne[1] != x->ne[1] || unary->ne[2] != x->ne[2] || unary->ne[3] != x->ne[3] || + !ggml_are_same_shape(x, mul) || !ggml_are_same_shape(a, add) || !ggml_are_same_shape(mul, add)) { + return false; + } + // each thread reads x and a where it writes, so dst may be either in place, but all threads of a row read its gate + const auto overlap = [](const ggml_tensor * t0, const ggml_tensor * t1) { + const char * b0 = (const char *) t0->data; + const char * b1 = (const char *) t1->data; + return b0 < b1 + ggml_nbytes(t1) && b1 < b0 + ggml_nbytes(t0); + }; + return !overlap(add, unary->src[0]) && (!overlap(add, x) || add->data == x->data) && + (!overlap(add, a) || add->data == a->data); + } + if (!ggml_can_fuse(cgraph, node_idx, ops)) { return false; } @@ -4595,6 +4991,51 @@ static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, return true; } + if (ops.size() == 3 && ops.begin()[0] == GGML_OP_ADD && ops.begin()[1] == GGML_OP_UNARY && ops.begin()[2] == GGML_OP_MUL + && unary_ops.size() == 1 && (unary_ops.begin()[0] == GGML_UNARY_OP_SILU || unary_ops.begin()[0] == GGML_UNARY_OP_SIGMOID || unary_ops.begin()[0] == GGML_UNARY_OP_SOFTPLUS)) { + const ggml_tensor * add = cgraph->nodes[node_idx]; + const ggml_tensor * unary = cgraph->nodes[node_idx+1]; + const ggml_tensor * mul = cgraph->nodes[node_idx+2]; + + if (ggml_get_unary_op(unary) != unary_ops.begin()[0]) { + return false; + } + + // x + b, then * a: b and a hold one value per element of a row of x + const ggml_tensor * x = add->src[0]; + const ggml_tensor * b = add->src[1]; + const ggml_tensor * a = mul->src[0] == unary ? mul->src[1] : mul->src[0]; + + for (const ggml_tensor * t : { x, b, a, add, unary, mul }) { + if (t->type != GGML_TYPE_F32 || !ggml_is_contiguous(t)) { + return false; + } + } + + return ggml_are_same_shape(x, mul) && ggml_nelements(b) == x->ne[0] && ggml_nelements(a) == x->ne[0] && b->ne[0] == x->ne[0] && a->ne[0] == x->ne[0]; + } + + if (ops.size() == 2 && ops.begin()[0] == GGML_OP_SCALE && ops.begin()[1] == GGML_OP_UNARY + && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_SILU) { + const ggml_tensor * scale = cgraph->nodes[node_idx]; + const ggml_tensor * silu = cgraph->nodes[node_idx+1]; + + if (ggml_get_unary_op(silu) != GGML_UNARY_OP_SILU) { + return false; + } + + if (scale->src[0]->type != GGML_TYPE_F32 || scale->type != GGML_TYPE_F32 || silu->type != GGML_TYPE_F32) { + return false; + } + + // the fused kernel reads src and writes dst as dense + if (!ggml_is_contiguous(scale->src[0]) || !ggml_is_contiguous(silu)) { + return false; + } + + return true; + } + if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_SQR && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_RELU) { const ggml_tensor * unary = cgraph->nodes[node_idx]; @@ -4647,6 +5088,17 @@ static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, return true; } + if (ops.size() == 2 && ops.begin()[0] == GGML_OP_SCALE && ops.begin()[1] == GGML_OP_UNARY + && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_SILU) { + const ggml_tensor * scale = cgraph->nodes[node_idx]; + const ggml_tensor * unary = cgraph->nodes[node_idx+1]; + + // the fused scale + unary kernel is F32 only and reads src and writes dst as dense + return ggml_get_unary_op(unary) == GGML_UNARY_OP_SILU && scale->src[0]->type == GGML_TYPE_F32 && + scale->type == GGML_TYPE_F32 && unary->type == GGML_TYPE_F32 && ggml_is_contiguous(scale->src[0]) && + ggml_is_contiguous(unary) && ggml_are_same_shape(scale->src[0], unary); + } + return false; } @@ -4698,90 +5150,1273 @@ static const ggml_tensor * ggml_cuda_mmvq_q8_1_target(const ggml_cgraph * cgraph return nullptr; } -// Whether one of the nodes shortly after node i multiplies a quantized matrix by t through MMVQ. -static bool ggml_cuda_mmvq_reads_soon(const ggml_cgraph * cgraph, int i, const ggml_tensor * t) { +// Whether one of the nodes shortly after node i (fewer than max_distance nodes on) multiplies a quantized matrix by t +// through MMVQ. +static bool ggml_cuda_mmvq_reads_soon(const ggml_cgraph * cgraph, int i, const ggml_tensor * t, int max_distance = 16) { const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; - for (int j = i + 1; j < std::min(cgraph->n_nodes, i + 16); ++j) { + for (int j = i + 1; j < std::min(cgraph->n_nodes, i + max_distance); ++j) { const ggml_tensor * mm = cgraph->nodes[j]; - if ((mm->op != GGML_OP_MUL_MAT && mm->op != GGML_OP_MUL_MAT_ID) || mm->src[1] != t || - !ggml_is_quantized(mm->src[0]->type)) { + if ((mm->op != GGML_OP_MUL_MAT && mm->op != GGML_OP_MUL_MAT_ID) || !ggml_is_quantized(mm->src[0]->type)) { + continue; + } + // MMVQ may read t through a reshape or view, which finds the same q8_1 copy (see ggml_cuda_q8_1_cache::find) + const ggml_tensor * src1 = mm->src[1]; + if (src1 != t && !ggml_cuda_q8_1_shares_copy(t, src1)) { continue; } - if (mm->op == GGML_OP_MUL_MAT ? ggml_cuda_should_use_mmvq(mm->src[0]->type, cc, t->ne[1]) - : t->ne[2] <= get_mmvq_mmid_max_batch(mm->src[0]->type, cc)) { + if (mm->op == GGML_OP_MUL_MAT ? ggml_cuda_should_use_mmvq(mm->src[0]->type, cc, src1->ne[1]) + : src1->ne[2] <= get_mmvq_mmid_max_batch(mm->src[0]->type, cc)) { return true; } } return false; } -// try and fuse nodes and return the number of nodes to skip -static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { - - if (ggml_cuda_fusion_disabled()) { +// A dim 0 CONCAT whose only use is the SSM_CONV right after it: the conv reads both concat inputs in place. +// Returns the number of nodes after the CONCAT that are fused (SSM_CONV, then the optional ADD bias and SILU), or 0. +// Shared by ggml_cuda_try_fuse and graph_optimize, and independent of the batch size. +static int ggml_cuda_ssm_conv_concat_match(const ggml_cgraph * cgraph, int i) { + if (i + 1 >= cgraph->n_nodes) { + return 0; + } + const ggml_tensor * concat = cgraph->nodes[i]; + const ggml_tensor * conv = cgraph->nodes[i + 1]; + if (concat->op != GGML_OP_CONCAT || conv->op != GGML_OP_SSM_CONV || conv->src[0] != concat || + (concat->flags & GGML_TENSOR_FLAG_COMPUTE) == 0 || (conv->flags & GGML_TENSOR_FLAG_COMPUTE) == 0 || + !ggml_node_has_n_uses(cgraph, i, 1) || ggml_get_op_params_i32(concat, 0) != 0) { + return 0; + } + const ggml_tensor * w = conv->src[1]; + if (concat->src[0]->type != GGML_TYPE_F32 || concat->src[1]->type != GGML_TYPE_F32 || conv->type != GGML_TYPE_F32 || + w->type != GGML_TYPE_F32 || w->nb[0] != sizeof(float) || concat->ne[3] != 1) { return 0; } + switch (w->ne[0]) { + case 3: case 4: case 5: case 7: case 9: case 15: break; + default: return 0; + } + if (ggml_cuda_can_fuse(cgraph, i + 1, { GGML_OP_SSM_CONV, GGML_OP_ADD, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { + return 3; + } + if (ggml_cuda_can_fuse(cgraph, i + 1, { GGML_OP_SSM_CONV, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { + return 2; + } + return 1; +} - ggml_tensor * node = cgraph->nodes[i]; +// Qwen HC prefill: the 4-row F32 inject reads the same normalized activation as HC down. +// Returns the last node index covered by the RMS_NORM at i when the matmul sits next to that norm +// (only views in between), or -1. require_adjacent is false while reordering the graph. +static int ggml_cuda_hc_inject_find(const ggml_cgraph * cgraph, int i, bool require_adjacent, int * mul_i_out) { + 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) { + return -1; + } + if (rms->ne[0] != 2560 || rms->ne[1] != 4 || rms->ne[2] < 32 || rms->ne[3] != 1 || !ggml_is_contiguous(rms->src[0])) { + return -1; + } + if (i + 1 >= cgraph->n_nodes) { + return -1; + } + const ggml_tensor * mul = cgraph->nodes[i + 1]; + if (mul->op != GGML_OP_MUL || mul->src[0] != rms || !ggml_is_contiguous(mul)) { + return -1; + } + const ggml_tensor * gamma = mul->src[1]; + if (gamma->type != GGML_TYPE_F32 || gamma->ne[0] != 2560 || gamma->ne[1] != 4 || gamma->ne[2] != 1 || + !ggml_is_contiguous(gamma)) { + return -1; + } - if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() && - ggml_cuda_match_shared_expert(cgraph, i, i + 3) && - ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1])) { - const int outputs[] = { i + 2, i + 5 }; - if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, 6, outputs, 2)) { - ggml_tensor * routed = cgraph->nodes[i + 2]; - ggml_tensor * shared = cgraph->nodes[i + 5]; - const ggml_tensor * up = routed->src[1]; - ggml_cuda_mm_fusion_args_host fusion{}; - fusion.gate = routed->src[0]->src[0]; - fusion.glu_op = ggml_get_glu_op(routed); - fusion.glu_limit = ggml_get_op_params_f32(routed, 3); - fusion.shared_up = shared->src[1]->src[0]; - fusion.shared_gate = shared->src[0]->src[0]; - fusion.shared_dst = shared; - ggml_cuda_mul_mat_vec_q(*cuda_ctx, up->src[0], up->src[1], up->src[2], routed, &fusion); - return 5; + int mm_i = -1; + for (int j = i + 2; j < cgraph->n_nodes; ++j) { + const ggml_tensor * n = cgraph->nodes[j]; + if (n->op != GGML_OP_MUL_MAT || n->src[0]->type != GGML_TYPE_F32) { + continue; + } + const ggml_tensor * w = n->src[0]; + const ggml_tensor * act = n->src[1]; + if (w->ne[0] != 10240 || w->ne[1] != 4 || w->ne[2] != 1 || !ggml_is_contiguous(w) || act->ne[0] != 10240) { + continue; + } + const bool act_ok = act == mul || act->src[0] == mul || act->view_src == mul; + if (!act_ok) { + continue; } + mm_i = j; + break; } + if (mm_i < 0) { + return -1; + } + if (require_adjacent) { + for (int j = i + 2; j < mm_i; ++j) { + if (!ggml_cuda_is_view_or_noop(cgraph->nodes[j])) { + return -1; + } + } + } + int last = mm_i; + if (mm_i + 1 < cgraph->n_nodes) { + const ggml_tensor * sc = cgraph->nodes[mm_i + 1]; + if (sc->op == GGML_OP_SCALE && sc->src[0] == cgraph->nodes[mm_i] && ggml_is_contiguous(sc) && + ggml_node_has_n_uses(cgraph, mm_i, 1)) { + last = mm_i + 1; + } + } + if (mul_i_out) { + *mul_i_out = i + 1; + } + return last; +} - if (node->op == GGML_OP_MUL) { - ggml_cuda_moe_weighted_reduction_match match; - if (ggml_cuda_match_moe_weighted_reduction(cgraph, i, match)) { - const int output_idx = i + match.node_count - 1; - if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, match.node_count, &output_idx, 1)) { - // the reduction also writes the q8_1 copy for the MMVQ product that reads its result - const ggml_tensor * q8_1_tensor = ggml_cuda_mmvq_q8_1_target(cgraph, output_idx, match.dst); - block_q8_1 * q8_1 = q8_1_tensor ? (block_q8_1 *) cuda_ctx->q8_1_cache.reserve( - ggml_nrows(q8_1_tensor) * q8_1_tensor->ne[0]/QK8_1 * sizeof(block_q8_1)) : nullptr; - if (ggml_cuda_op_moe_weighted_reduction( - *cuda_ctx, match.experts, match.expert_scale, match.weights, match.dst, q8_1) && q8_1) { - cuda_ctx->q8_1_cache.commit(q8_1_tensor); +static void ggml_cuda_hc_inject_reorder(ggml_cgraph * cgraph) { + for (int i = 0; i + 2 < cgraph->n_nodes; ++i) { + int mul_i = -1; + const int last = ggml_cuda_hc_inject_find(cgraph, i, /*require_adjacent =*/ false, &mul_i); + if (last < 0) { + continue; + } + int mm_i = last; + if (cgraph->nodes[last]->op == GGML_OP_SCALE) { + mm_i = last - 1; + } + const ggml_tensor * act = cgraph->nodes[mm_i]->src[1]; + int insert_after = mul_i; + for (int j = mul_i + 1; j < mm_i; ++j) { + if (cgraph->nodes[j] == act) { + insert_after = j; + } + } + if (mm_i == insert_after + 1) { + continue; + } + bool used = false; + for (int j = insert_after + 1; j < mm_i && !used; ++j) { + for (int s = 0; s < GGML_MAX_SRC; ++s) { + const ggml_tensor * src = cgraph->nodes[j]->src[s]; + if (src == cgraph->nodes[mm_i] || src == cgraph->nodes[last]) { + used = true; } - return match.node_count - 1; } } + if (used) { + continue; + } + std::rotate(cgraph->nodes + insert_after + 1, cgraph->nodes + mm_i, cgraph->nodes + last + 1); } +} - // gated_delta_net -> cpy: scatter recurrent-state snapshots into the cache - if (node->op == GGML_OP_GATED_DELTA_NET) { - ggml_cuda_gated_delta_net_fused_cache fused_state_cpy; - const int nodes_to_skip = ggml_cuda_try_gdn_cache_fusion(cgraph, i, fused_state_cpy); - if (nodes_to_skip > 0) { -#ifdef GGML_CUDA_DEBUG - GGML_LOG_INFO("%s: fused gated_delta_net snapshot copies for %s (skipped %d nodes)\n", - __func__, node->name, nodes_to_skip); -#endif - ggml_cuda_op_gated_delta_net_fused_cache(*cuda_ctx, node, fused_state_cpy); - return nodes_to_skip; +void * ggml_cuda_dense_x_reserve(ggml_backend_cuda_context & ctx, size_t size) { + if (ctx.dense_x_size < size) { + if (ctx.dense_x_buf != nullptr) { + CUDA_CHECK(cudaStreamSynchronize(ctx.stream())); + ggml_cuda_device_free(ctx.dense_x_buf, ctx.device); } + CUDA_CHECK(ggml_cuda_device_malloc(&ctx.dense_x_buf, size, ctx.device)); + ctx.dense_x_size = size; } + return ctx.dense_x_buf; +} - // ssm_scan -> cpy: scatter recurrent-state snapshots into the cache - if (node->op == GGML_OP_SSM_SCAN) { - ggml_cuda_ssm_scan_fused_cache fused_state_cpy; - const int nodes_to_skip = ggml_cuda_try_ssm_scan_cache_fusion(cgraph, i, fused_state_cpy); - if (nodes_to_skip > 0) { -#ifdef GGML_CUDA_DEBUG +uint16_t * ggml_cuda_hc_bf16_reserve(ggml_backend_cuda_context & ctx, size_t n) { + if (ctx.hc_bf16_size < n) { + if (ctx.hc_bf16_buf != nullptr) { + CUDA_CHECK(cudaStreamSynchronize(ctx.stream())); + ggml_cuda_device_free(ctx.hc_bf16_buf, ctx.device); + } + CUDA_CHECK(ggml_cuda_device_malloc((void **) &ctx.hc_bf16_buf, n * sizeof(uint16_t), ctx.device)); + ctx.hc_bf16_size = n; + } + return ctx.hc_bf16_buf; +} + +static bool ggml_cuda_hc_inject_on(const ggml_backend_cuda_context * cuda_ctx) { + static const int sw = ggml_cuda_env_switch("GGML_HIP_HC_INJECT"); + const int cc = ggml_cuda_info().devices[cuda_ctx->device].cc; + return ggml_cuda_switch_or_rdna3_5(sw, cc); +} + +// try and fuse nodes and return the number of nodes to skip +// Whether mm is an MMVQ product of Q8_0 weights for one token that a fused kernel sums as mul_mat_vec_q does, one warp +// per row and block: the RDNA3.5 parameters for one column. +static bool ggml_cuda_mmvq_one_warp_row(const ggml_tensor * mm) { + if (mm->op != GGML_OP_MUL_MAT || mm->src[0]->type != GGML_TYPE_Q8_0 || mm->src[1]->type != GGML_TYPE_F32 || + mm->type != GGML_TYPE_F32 || ggml_nrows(mm->src[1]) != 1 || !ggml_is_contiguous(mm->src[1]) || + !ggml_is_contiguous(mm) || !ggml_is_contiguous(mm->src[0]) || mm->src[0]->ne[2] != 1 || + mm->src[0]->ne[3] != 1) { + return false; + } + const int device = ggml_cuda_get_device(); + const int cc = ggml_cuda_info().devices[device].cc; + return GGML_CUDA_CC_IS_RDNA3_5(cc) && ggml_cuda_info().devices[device].warp_size == QK8_1 && + ggml_cuda_should_use_mmvq(mm->src[0]->type, cc, 1); +} + +static bool ggml_cuda_node_is_empty_op(const ggml_tensor * t) { + return t->op == GGML_OP_VIEW || t->op == GGML_OP_RESHAPE || t->op == GGML_OP_PERMUTE || t->op == GGML_OP_TRANSPOSE || + t->op == GGML_OP_NONE; +} + +// RMS_NORM (rows of 128) -> MUL at i, the gated delta net's output norm, then the MMVQ product of its gate and +// SIGMOID -> MUL with the norm, which ggml_cuda_mul_mat_vec_q_norm_gate computes with the norm's configuration of +// rms_norm_f32. Only views in between, since the kernel writes the result early. Returns the index of the last MUL, or -1. +static int ggml_cuda_norm_gate_fusion(const ggml_cgraph * cgraph, int i, int & mm_idx, const ggml_tensor *& norm_w) { + const ggml_tensor * rms = cgraph->nodes[i]; + if (rms->op != GGML_OP_RMS_NORM || i + 4 >= cgraph->n_nodes || ggml_node_get_use_count(cgraph, i) != 1) { + return -1; + } + const ggml_tensor * mul_n = cgraph->nodes[i + 1]; + if (mul_n->op != GGML_OP_MUL || (mul_n->src[0] != rms && mul_n->src[1] != rms) || ggml_node_get_use_count(cgraph, i + 1) != 1) { + return -1; + } + const ggml_tensor * x = rms->src[0]; + const ggml_tensor * w = mul_n->src[0] == rms ? mul_n->src[1] : mul_n->src[0]; + // the vector path of rms_norm_f32 with one 32-lane warp per row of 128 + if (x->type != GGML_TYPE_F32 || w->type != GGML_TYPE_F32 || mul_n->type != GGML_TYPE_F32 || x->ne[0] != 128 || + !ggml_is_contiguous(x) || !ggml_is_contiguous(w) || w->ne[0] != 128 || ggml_nrows(w) != 1 || + !ggml_are_same_shape(mul_n, x) || !ggml_is_contiguous(mul_n) || ((uintptr_t) x->data & 15) != 0 || + ((uintptr_t) w->data & 15) != 0 || ((uintptr_t) mul_n->data & 15) != 0 || + ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size != QK8_1) { + return -1; + } + int k = i + 2; + while (k < cgraph->n_nodes && ggml_cuda_node_is_empty_op(cgraph->nodes[k])) { + ++k; + } + if (k >= cgraph->n_nodes) { + return -1; + } + const ggml_tensor * mm = cgraph->nodes[k]; + const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + if (mm->op != GGML_OP_MUL_MAT || !ggml_cuda_mmvq_norm_gate_supported(mm->src[0]->type) || mm->src[1]->type != GGML_TYPE_F32 || + mm->type != GGML_TYPE_F32 || ggml_nrows(mm->src[1]) != 1 || !ggml_is_contiguous(mm->src[1]) || !ggml_is_contiguous(mm) || + !ggml_is_contiguous(mm->src[0]) || mm->src[0]->ne[2] != 1 || mm->src[0]->ne[3] != 1 || + ggml_nelements(mm) != ggml_nelements(mul_n) || mm->ne[0] % QK8_1 != 0 || !GGML_CUDA_CC_IS_RDNA3_5(cc) || + !ggml_cuda_should_use_mmvq(mm->src[0]->type, cc, 1) || ggml_node_get_use_count(cgraph, k) != 1) { + return -1; + } + const int mk = k; + // the gate through a view or reshape of the product, then SIGMOID + const ggml_tensor * gate = mm; + for (++k; k < cgraph->n_nodes && ggml_cuda_node_is_empty_op(cgraph->nodes[k]); ++k) { + const ggml_tensor * v = cgraph->nodes[k]; + if (v->src[0] == gate && ggml_node_get_use_count(cgraph, k) == 1 && v->data == mm->data && ggml_is_contiguous(v)) { + gate = v; + } + } + if (k + 1 >= cgraph->n_nodes) { + return -1; + } + const ggml_tensor * sig = cgraph->nodes[k]; + const ggml_tensor * mul = cgraph->nodes[k + 1]; + if (sig->op != GGML_OP_UNARY || ggml_get_unary_op(sig) != GGML_UNARY_OP_SIGMOID || sig->src[0] != gate || + gate->data != mm->data || !ggml_is_contiguous(gate) || ggml_node_get_use_count(cgraph, k) != 1 || + mul->op != GGML_OP_MUL || !((mul->src[0] == sig && mul->src[1] == mul_n) || (mul->src[0] == mul_n && mul->src[1] == sig)) || + !ggml_are_same_shape(sig, mul_n) || mul->type != GGML_TYPE_F32 || !ggml_is_contiguous(mul)) { + return -1; + } + // the result is written while other blocks still read the norm's input + const char * x0 = (const char *) x->data; + const char * d0 = (const char *) mul->data; + if (d0 < x0 + ggml_nbytes(x) && x0 < d0 + ggml_nbytes(mul)) { + return -1; + } + mm_idx = mk; + norm_w = w; + return k + 1; +} + +// Whether node i, an MMVQ product, is followed by SCALE -> SILU, which ggml_cuda_mul_mat_vec_q_scale_silu computes with it. +static bool ggml_cuda_mmvq_scale_silu_fusion(const ggml_cgraph * cgraph, int i) { + static constexpr ggml_op ops[] = { GGML_OP_MUL_MAT, GGML_OP_SCALE, GGML_OP_UNARY }; + if (!ggml_cuda_mmvq_one_warp_row(cgraph->nodes[i]) || !ggml_can_fuse(cgraph, i, ops, 3)) { + return false; + } + const ggml_tensor * scale = cgraph->nodes[i + 1]; + const ggml_tensor * unary = cgraph->nodes[i + 2]; + return scale->src[0] == cgraph->nodes[i] && unary->src[0] == scale && ggml_get_unary_op(unary) == GGML_UNARY_OP_SILU && + scale->type == GGML_TYPE_F32 && unary->type == GGML_TYPE_F32 && ggml_is_contiguous(unary); +} + +// The gated DSV4_HC_PRE node shortly after node i that mixes the streams with the sigmoid of node i, an MMVQ product +// for one token that only it reads (through a reshape), as ggml_cuda_mul_mat_vec_q_hc_pre computes the two; -1 otherwise. +static int ggml_cuda_hc_pre_gate_fusion(const ggml_cgraph * cgraph, int i) { + const ggml_tensor * mm = cgraph->nodes[i]; + if (!ggml_cuda_mmvq_one_warp_row(mm) || !ggml_node_has_n_uses(cgraph, i, 1)) { + return -1; + } + for (int j = i + 1; j < std::min(cgraph->n_nodes, i + 6); ++j) { + const ggml_tensor * node = cgraph->nodes[j]; + if (node->op == GGML_OP_DSV4_HC_PRE) { + const ggml_tensor * x = node->src[0]; + const ggml_tensor * w = node->src[1]; + const bool ok = ggml_get_op_params_i32(node, 1) != 0 && w->view_src == mm && w->view_offs == 0 && + ggml_nbytes(w) == ggml_nbytes(mm) && ggml_is_contiguous(w) && x->type == GGML_TYPE_F32 && + ggml_is_contiguous(x) && node->type == GGML_TYPE_F32 && ggml_is_contiguous(node) && x->ne[2] == 1 && + x->ne[3] == 1 && ggml_are_same_shape(x, w) && x->ne[0] % QK8_1 == 0 && x->ne[0]*x->ne[1] == mm->ne[0]; + return ok ? j : -1; + } + if (node->op != GGML_OP_RESHAPE && node->op != GGML_OP_VIEW) { + return -1; + } + if (node->view_src == mm && (ggml_node_get_use_count(cgraph, j) != 1 || (node->flags & GGML_TENSOR_FLAG_OUTPUT))) { + return -1; + } + } + return -1; +} + +// The gated DSV4_HC_PRE node shortly after node i that mixes the streams with the sigmoid of node i, the hyper-connection +// up product of a prompt batch that only it reads (through reshapes), as ggml_cuda_hc_up_pre computes the two; -1 otherwise. +static int ggml_cuda_hc_up_pre_fusion(const ggml_cgraph * cgraph, int i) { + const ggml_tensor * mm = cgraph->nodes[i]; + if (mm->op != GGML_OP_MUL_MAT || !ggml_node_has_n_uses(cgraph, i, 1) || (mm->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return -1; + } + for (int j = i + 1; j < std::min(cgraph->n_nodes, i + 6); ++j) { + const ggml_tensor * node = cgraph->nodes[j]; + if (node->op == GGML_OP_DSV4_HC_PRE) { + const ggml_tensor * w = node->src[1]; + const bool ok = w->view_src == mm && w->view_offs == 0 && ggml_nbytes(w) == ggml_nbytes(mm) && + ggml_is_contiguous(w) && ggml_is_contiguous(mm) && ggml_cuda_hc_up_pre_supported(mm, node); + return ok ? j : -1; + } + if (node->op != GGML_OP_RESHAPE && node->op != GGML_OP_VIEW) { + return -1; + } + if (node->view_src == mm && (ggml_node_get_use_count(cgraph, j) != 1 || (node->flags & GGML_TENSOR_FLAG_OUTPUT))) { + return -1; + } + } + return -1; +} + +// The hyper-connection injection product after the fused pre-mix at node hc_idx that reads the same normalized +// streams, and that a block of the pre-mix kernel can compute ahead, -1 otherwise: F32 weights for one token that +// mul_mat_vec_f would sum with 256 threads per row, read only by the fused SCALE -> SIGMOID -> SCALE -> DSV4_HC_POST +// right after it. The streams stay unchanged until the product reads them, as the product keeps them alive. +static int ggml_cuda_hc_inject_ahead(const ggml_cgraph * cgraph, int hc_idx) { + const ggml_tensor * xn = cgraph->nodes[hc_idx]->src[0]; + const ggml_tensor * root = xn->view_src ? xn->view_src : xn; + const int device = ggml_cuda_get_device(); + const int cc = ggml_cuda_info().devices[device].cc; + const int warp_size = ggml_cuda_info().devices[device].warp_size; + if (warp_size != 32 || (cc > GGML_CUDA_CC_OFFSET_AMD && cc < GGML_CUDA_CC_RDNA1)) { + return -1; + } + for (int j = hc_idx + 1; j < std::min(cgraph->n_nodes - 4, hc_idx + 512); ++j) { + const ggml_tensor * mm = cgraph->nodes[j]; + if (mm->op != GGML_OP_MUL_MAT || mm->src[0]->type != GGML_TYPE_F32) { + continue; + } + const ggml_tensor * w = mm->src[0]; + const ggml_tensor * x = mm->src[1]; + if ((x->view_src ? x->view_src : x) != root) { + continue; + } + if (x->type != GGML_TYPE_F32 || x->data != xn->data || ggml_nbytes(x) != ggml_nbytes(xn) || !ggml_is_contiguous(x) || + ggml_nrows(x) != 1 || mm->type != GGML_TYPE_F32 || !ggml_is_contiguous(w) || w->ne[2] != 1 || w->ne[3] != 1 || + w->ne[0] % 2 != 0 || w->ne[1] > 4 || !ggml_node_has_n_uses(cgraph, j, 1) || + !ggml_cuda_should_use_mmvf(w, cc, warp_size, 1)) { + return -1; + } + // the block size mul_mat_vec_f picks, see ggml_cuda_mul_mat_vec_f + int64_t block_size_best = warp_size; + int64_t niter_best = (w->ne[0] + 2*warp_size - 1) / (2*warp_size); + for (int64_t block_size = 2*warp_size; block_size <= 256; block_size += warp_size) { + const int64_t niter = (w->ne[0] + 2*block_size - 1) / (2*block_size); + if (niter < niter_best) { + niter_best = niter; + block_size_best = block_size; + } + } + const bool fused_post = block_size_best == 256 && cgraph->nodes[j + 1]->src[0] == mm && + ggml_cuda_can_fuse(cgraph, j + 1, { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_DSV4_HC_POST }, { GGML_UNARY_OP_SIGMOID }); + return fused_post ? j : -1; + } + return -1; +} + +// The last node of the MoE down stage at node k that ggml_cuda_mul_mat_vec_q_moe_down_shared computes, -1 otherwise: +// the routed experts' down product of routed (MUL_MAT_ID), their routing-weighted sum, the shared expert's down product +// of shared and the gated sum with it, whose gate (gate_idx) reads x, as an F32 product mul_mat_vec_f sums with 256 +// threads. Every node but the last has no other reader. +static int ggml_cuda_moe_down_fusion(const ggml_cgraph * cgraph, int k, const ggml_tensor * routed, const ggml_tensor * shared, + const ggml_tensor * x, int & gate_idx) { + if (k >= cgraph->n_nodes) { + return -1; + } + const ggml_tensor * down = cgraph->nodes[k]; + if (down->op != GGML_OP_MUL_MAT_ID || down->src[1] != routed || down->ne[2] != 1 || !ggml_is_contiguous(down) || + down->ne[1] >= QK8_1 || !ggml_node_has_n_uses(cgraph, k, 1)) { + return -1; + } + ggml_cuda_moe_weighted_reduction_match match; + if (!ggml_cuda_match_moe_weighted_reduction(cgraph, k + 1, match) || match.experts != down || + match.expert_scale != nullptr || !ggml_node_has_n_uses(cgraph, k + match.node_count, 1)) { + return -1; + } + const int j = k + 1 + match.node_count; + if (j + 4 >= cgraph->n_nodes) { + return -1; + } + const ggml_tensor * shexp = cgraph->nodes[j]; + const ggml_tensor * gate = cgraph->nodes[j + 1]; + if (shexp->op != GGML_OP_MUL_MAT || shexp->src[1] != shared || !ggml_is_contiguous(shexp->src[0]) || + shexp->src[0]->ne[2] != 1 || shexp->ne[0] != down->ne[0] || shexp->src[0]->ne[0] != down->src[0]->ne[0] || + !ggml_cuda_mmvq_moe_down_shared_supported(down->src[0]->type, shexp->src[0]->type, + ggml_cuda_moe_wmma_is_repacked(down->src[0])) || + !ggml_node_has_n_uses(cgraph, j, 1)) { + return -1; + } + const int device = ggml_cuda_get_device(); + const int cc = ggml_cuda_info().devices[device].cc; + const int warp_size = ggml_cuda_info().devices[device].warp_size; + const ggml_tensor * gw = gate->op == GGML_OP_MUL_MAT ? gate->src[0] : nullptr; + if (gw == nullptr || gw->type != GGML_TYPE_F32 || gate->src[1] != x || !ggml_is_contiguous(gw) || gw->ne[1] != 1 || + gw->ne[0] % 2 != 0 || gw->ne[0] != x->ne[0] || ggml_nrows(x) != 1 || !ggml_is_contiguous(x) || + x->type != GGML_TYPE_F32 || !ggml_node_has_n_uses(cgraph, j + 1, 1) || + !ggml_cuda_should_use_mmvf(gw, cc, warp_size, 1)) { + return -1; + } + // the block size mul_mat_vec_f picks, see ggml_cuda_mul_mat_vec_f + int64_t block_size_best = warp_size; + int64_t niter_best = (gw->ne[0] + 2*warp_size - 1) / (2*warp_size); + for (int64_t block_size = 2*warp_size; block_size <= 256; block_size += warp_size) { + const int64_t niter = (gw->ne[0] + 2*block_size - 1) / (2*block_size); + if (niter < niter_best) { + niter_best = niter; + block_size_best = block_size; + } + } + if (block_size_best != 256 || + !ggml_cuda_can_fuse(cgraph, j + 2, { GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_ADD }, { GGML_UNARY_OP_SIGMOID })) { + return -1; + } + const ggml_tensor * sig = cgraph->nodes[j + 2]; + const ggml_tensor * mul = cgraph->nodes[j + 3]; + const ggml_tensor * add = cgraph->nodes[j + 4]; + if (sig->src[0] != gate || (mul->src[0] == sig ? mul->src[1] : mul->src[0]) != shexp || + (add->src[0] == mul ? add->src[1] : add->src[0]) != match.dst || !ggml_is_contiguous(add)) { + return -1; + } + gate_idx = j + 1; + return j + 4; +} + +// Whether node i starts the alpha and beta inputs of a gated delta net for one token, which ggml_cuda_op_gdn_alpha_beta +// computes: MUL_MAT(w_alpha, x), RESHAPE, ADD dt, SOFTPLUS, MUL a, RESHAPE, MUL_MAT(w_beta, x), RESHAPE, SIGMOID, with F32 +// weights that mul_mat_vec_f sums with 256 threads per row. Every block reads all of x, so the outputs (the MUL and +// the SIGMOID) may overlap none of the inputs. +static bool ggml_cuda_gdn_alpha_beta_fusion(const ggml_cgraph * cgraph, int i) { + if (i + 8 >= cgraph->n_nodes) { + return false; + } + const ggml_tensor * const * n = cgraph->nodes + i; + const ggml_op ops[] = { GGML_OP_MUL_MAT, GGML_OP_RESHAPE, GGML_OP_ADD, GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_RESHAPE, + GGML_OP_MUL_MAT, GGML_OP_RESHAPE, GGML_OP_UNARY }; + for (int k = 0; k < 9; ++k) { + if (n[k]->op != ops[k]) { + return false; + } + } + const ggml_tensor * mm_a = n[0]; + const ggml_tensor * add = n[2]; + const ggml_tensor * sp = n[3]; + const ggml_tensor * mul = n[4]; + const ggml_tensor * mm_b = n[6]; + const ggml_tensor * sig = n[8]; + const ggml_tensor * x = mm_a->src[1]; + const ggml_tensor * w_a = mm_a->src[0]; + const ggml_tensor * w_b = mm_b->src[0]; + if (ggml_get_unary_op(sp) != GGML_UNARY_OP_SOFTPLUS || ggml_get_unary_op(sig) != GGML_UNARY_OP_SIGMOID || + n[1]->src[0] != mm_a || n[7]->src[0] != mm_b || sp->src[0] != add || sig->src[0] != n[7] || + mm_b->src[1] != x || x->type != GGML_TYPE_F32 || !ggml_is_contiguous(x) || ggml_nrows(x) != 1) { + return false; + } + const ggml_tensor * dt = add->src[0] == n[1] ? add->src[1] : add->src[0]; + const ggml_tensor * a = mul->src[0] == sp ? mul->src[1] : mul->src[0]; + if ((add->src[0] != n[1] && add->src[1] != n[1]) || (mul->src[0] != sp && mul->src[1] != sp)) { + return false; + } + const int64_t nrows = w_a->ne[1]; + for (const ggml_tensor * w : { w_a, w_b }) { + if (w->type != GGML_TYPE_F32 || !ggml_is_contiguous(w) || w->ne[0] != x->ne[0] || w->ne[1] != nrows || + w->ne[2] != 1 || w->ne[3] != 1 || w->ne[0] % 2 != 0) { + return false; + } + } + for (const ggml_tensor * t : { dt, a, (const ggml_tensor *) add, (const ggml_tensor *) mul, (const ggml_tensor *) sig }) { + if (t->type != GGML_TYPE_F32 || !ggml_is_contiguous(t) || ggml_nelements(t) != nrows) { + return false; + } + } + for (int k : { 0, 1, 2, 3, 6, 7 }) { + if (ggml_node_get_use_count(cgraph, i + k) != 1 || (n[k]->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + } + const int device = ggml_cuda_get_device(); + const int cc = ggml_cuda_info().devices[device].cc; + const int warp_size = ggml_cuda_info().devices[device].warp_size; + if (warp_size != 32 || !ggml_cuda_should_use_mmvf(w_a, cc, warp_size, 1) || !ggml_cuda_should_use_mmvf(w_b, cc, warp_size, 1) || + (cc > GGML_CUDA_CC_OFFSET_AMD && cc < GGML_CUDA_CC_RDNA1)) { + return false; + } + // the block size mul_mat_vec_f picks, see ggml_cuda_mul_mat_vec_f + int64_t block_size_best = warp_size; + int64_t niter_best = (w_a->ne[0] + 2*warp_size - 1) / (2*warp_size); + for (int64_t block_size = 2*warp_size; block_size <= 256; block_size += warp_size) { + const int64_t niter = (w_a->ne[0] + 2*block_size - 1) / (2*block_size); + if (niter < niter_best) { + niter_best = niter; + block_size_best = block_size; + } + } + if (block_size_best != 256) { + return false; + } + const auto overlap = [](const ggml_tensor * p, const ggml_tensor * q) { + const char * p0 = (const char *) p->data; + const char * q0 = (const char *) q->data; + return p0 < q0 + ggml_nbytes(q) && q0 < p0 + ggml_nbytes(p); + }; + for (const ggml_tensor * out : { mul, sig }) { + for (const ggml_tensor * in : { x, w_a, w_b, dt, a }) { + if (overlap(out, in)) { + return false; + } + } + } + return !overlap(mul, sig); +} + +// Whether node i starts the k-pool update of a QSA indexer for one token that ggml_cuda_op_qsa_kpool_step computes: +// FILL, CONCAT(k, fill), RESHAPE, VIEW, SET_ROWS of it into an F16 cache, VIEW of the cache, GET_ROWS of 4 rows, +// RESHAPE, then CONT and three ADDs of its rows, and SCALE. rows receives the order the ADD chain sums the rows in. +static bool ggml_cuda_qsa_kpool_fusion(const ggml_cgraph * cgraph, int i, int * rows) { + if (i + 16 >= cgraph->n_nodes) { + return false; + } + const ggml_tensor * const * n = cgraph->nodes + i; + const ggml_op ops[] = { GGML_OP_FILL, GGML_OP_CONCAT, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_SET_ROWS, GGML_OP_VIEW, + GGML_OP_GET_ROWS, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_CONT, GGML_OP_VIEW, GGML_OP_ADD, + GGML_OP_VIEW, GGML_OP_ADD, GGML_OP_VIEW, GGML_OP_ADD, GGML_OP_SCALE }; + for (int k = 0; k < 17; ++k) { + if (n[k]->op != ops[k]) { + return false; + } + } + const ggml_tensor * fill = n[0]; + const ggml_tensor * cat = n[1]; + const ggml_tensor * knew = cat->src[0]; + const ggml_tensor * set = n[4]; + const ggml_tensor * get = n[6]; + const ggml_tensor * g2 = n[7]; + const int64_t n_cols = get->ne[0]; + if (fill->type != GGML_TYPE_F32 || ggml_nrows(fill) != 1 || cat->src[1] != fill || ggml_get_op_params_i32(cat, 0) != 0 || + knew->type != GGML_TYPE_F32 || !ggml_is_contiguous(knew) || ggml_nrows(knew) != 1 || ggml_nrows(cat) != 1 || + n[2]->src[0] != cat || n[3]->src[0] != n[2] || n[3]->view_offs != 0 || ggml_nelements(n[3]) != ggml_nelements(cat)) { + return false; + } + const ggml_tensor * set_idx = set->src[1]; + const ggml_tensor * get_idx = get->src[1]; + if (set->src[0] != n[3] || set->type != GGML_TYPE_F16 || set->nb[0] != sizeof(half) || set->ne[0] != cat->ne[0] || + (set_idx->type != GGML_TYPE_I64 && set_idx->type != GGML_TYPE_I32) || ggml_nelements(set_idx) != 1 || + n[5]->type != GGML_TYPE_F16 || n[5]->nb[0] != sizeof(half) || get->src[0] != n[5] || n[5]->view_src != set->view_src || + n[5]->view_offs != set->view_offs || n[5]->nb[1] != set->nb[1] || n_cols > cat->ne[0] || + (get_idx->type != GGML_TYPE_I64 && get_idx->type != GGML_TYPE_I32) || ggml_nelements(get_idx) != 4 || + get->type != GGML_TYPE_F32 || get->ne[1] != 4 || ggml_nrows(get) != 4 || !ggml_is_contiguous(get) || + g2->src[0] != get || ggml_nelements(g2) != 4*n_cols) { + return false; + } + // the four row views, their CONT and the ADD chain + const int view_idx[4] = { 8, 10, 12, 14 }; + for (int k = 0; k < 4; ++k) { + const ggml_tensor * v = n[view_idx[k]]; + if (v->src[0] != g2 || v->ne[0] != n_cols || ggml_nrows(v) != 1 || v->view_offs % (n_cols*sizeof(float)) != 0) { + return false; + } + rows[k] = v->view_offs / (n_cols*sizeof(float)); + } + if (n[9]->src[0] != n[8] || n[11]->src[0] != n[9] || n[11]->src[1] != n[10] || n[13]->src[0] != n[11] || + n[13]->src[1] != n[12] || n[15]->src[0] != n[13] || n[15]->src[1] != n[14] || n[16]->src[0] != n[15] || + n[16]->type != GGML_TYPE_F32 || !ggml_is_contiguous(n[16]) || ggml_nelements(n[16]) != n_cols) { + return false; + } + for (int k : { 0, 1, 2, 3, 6, 9, 11, 13, 15 }) { + if (ggml_node_get_use_count(cgraph, i + k) != (k == 6 ? 1 : 1) || (n[k]->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + } + return ggml_node_get_use_count(cgraph, i + 7) == 4 && !(n[7]->flags & GGML_TENSOR_FLAG_OUTPUT); +} + +// the DSV4_HC_POST at post_idx with the RMS_NORM + MUL after it, whose result MMVQ reads, see +// ggml_cuda_op_hc_post_rms_norm +static bool ggml_cuda_try_hc_post_rms_norm(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int post_idx, + const ggml_tensor * gate_scale_in, const ggml_tensor * gate_scale_out, const float * post_data) { + if (post_idx + 2 >= cgraph->n_nodes || !ggml_cuda_can_fuse(cgraph, post_idx + 1, { GGML_OP_RMS_NORM, GGML_OP_MUL }, {})) { + return false; + } + ggml_tensor * post = cgraph->nodes[post_idx]; + ggml_tensor * rms = cgraph->nodes[post_idx + 1]; + ggml_tensor * mul = cgraph->nodes[post_idx + 2]; + if (!ggml_cuda_hc_post_rms_norm_supported(post, gate_scale_in, post_data, rms, mul) || ggml_nrows(mul) > MMVQ_MAX_BATCH_SIZE || + !ggml_cuda_mmvq_reads_soon(cgraph, post_idx + 2, mul)) { + return false; + } + char * q8_1 = cuda_ctx->q8_1_cache.reserve(ggml_nrows(mul) * GGML_PAD(mul->ne[0], MATRIX_ROW_PADDING)/QK8_1 * sizeof(block_q8_1)); + if (q8_1 == nullptr) { + return false; + } + ggml_cuda_op_hc_post_rms_norm(*cuda_ctx, post, gate_scale_in, gate_scale_out, post_data, rms, mul, (block_q8_1 *) q8_1); + cuda_ctx->q8_1_cache.commit(mul); + return true; +} + +// The F32 router MUL_MAT at i with the top-k MoE selection right after, as the topk-moe fusion below matches it, in one +// kernel (see ggml_cuda_op_router_topk_moe). Returns the number of nodes after i it computed, or 0. +static int ggml_cuda_try_router_topk_moe(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + ggml_tensor * mm = cgraph->nodes[i]; + if (mm->op != GGML_OP_MUL_MAT || i + 1 >= cgraph->n_nodes || ggml_node_get_use_count(cgraph, i) != 1 || + !cuda_ctx->stream_context().concurrent_events.empty()) { + return 0; + } + const int g = i + 1; + ggml_tensor * gating = cgraph->nodes[g]; + if ((gating->op != GGML_OP_UNARY && gating->op != GGML_OP_SOFT_MAX) || gating->src[0] != mm || + !ggml_cuda_router_topk_moe_supported(mm, gating->src[0])) { + return 0; + } + ggml_cuda_topk_moe_args args; + if (!ggml_cuda_topk_moe_fusion(cgraph, g, args) || args.delayed_softmax || args.n_groups > 0) { + return 0; + } + std::vector ops; + ops.reserve(13); + const ggml_tensor * bias = nullptr; + const ggml_tensor * clamp = nullptr; + const ggml_tensor * scale = nullptr; + if (args.sigmoid) { + ops.insert(ops.end(), { GGML_OP_UNARY }); + } else if (args.sqrt_softplus) { + ops.insert(ops.end(), { GGML_OP_UNARY, GGML_OP_SQRT }); + } else { + ops.insert(ops.end(), { GGML_OP_SOFT_MAX }); + } + ops.push_back(GGML_OP_RESHAPE); + if (args.prob_bias) { + ops.push_back(GGML_OP_ADD); + bias = cgraph->nodes[g + ops.size() - 1]->src[1]; + } + ops.insert(ops.end(), { GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS }); + int out_nodes[2]; + out_nodes[0] = g + ops.size() - 2; + ggml_tensor * ids = cgraph->nodes[out_nodes[0]]; + if (args.norm) { + ops.insert(ops.end(), { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV, GGML_OP_RESHAPE }); + clamp = cgraph->nodes[g + ops.size() - 3]; + } + if (args.scale) { + ops.insert(ops.end(), { GGML_OP_SCALE }); + scale = cgraph->nodes[g + ops.size() - 1]; + } + ggml_tensor * weights = cgraph->nodes[g + ops.size() - 1]; + out_nodes[1] = g + ops.size() - 1; + if (!ggml_can_fuse_subgraph(cgraph, g, ops.size(), ops.data(), out_nodes, 2) || + !ggml_cuda_should_use_topk_moe(gating, mm, weights, ids) || + !ggml_cuda_check_fusion_memory_ranges(cgraph, g, ops.size(), out_nodes, 2, /*is_topk_moe=*/true)) { + return 0; + } + if (cuda_ctx->router_topk_counter == nullptr) { + CUDA_CHECK(ggml_cuda_device_malloc((void **) &cuda_ctx->router_topk_counter, sizeof(int), cuda_ctx->device, true)); + CUDA_CHECK(cudaMemsetAsync(cuda_ctx->router_topk_counter, 0, sizeof(int), cuda_ctx->stream())); + } + ggml_cuda_op_router_topk_moe(*cuda_ctx, mm, weights, ids, clamp, scale, bias, args, cuda_ctx->router_topk_counter); + return ops.size(); +} + +// For the fused HC norm of a prompt batch: the buffer for the MMQ q8_1 copy of its output xn if the next MUL_MAT that +// reads xn is a Q8_0 MMQ (D4 layout), which then skips its quantization (see ggml_cuda_mul_mat_q), else null. +static void * ggml_cuda_hc_norm_mmq_q8_1(ggml_backend_cuda_context * cuda_ctx, const ggml_cgraph * cgraph, const int last, + const ggml_tensor * xn) { + constexpr int64_t k = 10240; + cuda_ctx->mmq_q8_1_dst = nullptr; + const int64_t n_tokens = ggml_nelements(xn) / k; + if (n_tokens <= MMVQ_MAX_BATCH_SIZE || ggml_nelements(xn) != k*n_tokens || !ggml_is_contiguous(xn)) { + return nullptr; + } + const ggml_tensor * mm = nullptr; + for (int j = last + 1; j < cgraph->n_nodes && mm == nullptr; ++j) { + const ggml_tensor * node = cgraph->nodes[j]; + if (node->op == GGML_OP_MUL_MAT && node->src[1]->data == xn->data) { + mm = node; + } + } + if (mm == nullptr) { + return nullptr; + } + const ggml_tensor * w = mm->src[0]; + const ggml_tensor * src1 = mm->src[1]; + const int cc = ggml_cuda_info().devices[cuda_ctx->device].cc; + if (w->type != GGML_TYPE_Q8_0 || w->ne[0] != k || src1->type != GGML_TYPE_F32 || !ggml_is_contiguous(src1) || + src1->ne[0] != k || src1->ne[1] != n_tokens || src1->ne[2] != 1 || src1->ne[3] != 1 || + !ggml_cuda_should_use_mmq(w->type, cc, n_tokens, 0)) { + return nullptr; + } + + // MMQ may read up to one tile width (at most 128) of columns past the last row + const size_t nbytes = ((size_t) n_tokens*(k/128) + 128) * 144; + if (nbytes > cuda_ctx->mmq_q8_1_size) { + if (cuda_ctx->mmq_q8_1_buf != nullptr) { + CUDA_CHECK(cudaStreamSynchronize(cuda_ctx->stream())); + ggml_cuda_device_free(cuda_ctx->mmq_q8_1_buf, cuda_ctx->device); + } + CUDA_CHECK(ggml_cuda_device_malloc(&cuda_ctx->mmq_q8_1_buf, nbytes, cuda_ctx->device, true)); + cuda_ctx->mmq_q8_1_size = nbytes; + } + cuda_ctx->mmq_q8_1_dst = mm; + cuda_ctx->mmq_q8_1_data = xn->data; + return cuda_ctx->mmq_q8_1_buf; +} + +// For the result t of node i in a prompt batch: the buffer for the MMQ q8_1 copy of t if the next MUL_MAT that reads t +// (through views) as src1 is a Q8_0 MMQ that takes it (see ggml_cuda_mul_mat_q), else null; then *only says whether that +// MUL_MAT is the only node that reads t. +static void * ggml_cuda_mmq_q8_1_producer(ggml_backend_cuda_context * cuda_ctx, const ggml_cgraph * cgraph, const int i, + const ggml_tensor * t, int64_t * k, int64_t * n_tokens, bool * only) { + cuda_ctx->mmq_q8_1_dst = nullptr; + if (t->type != GGML_TYPE_F32 || !ggml_is_contiguous(t) || (t->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return nullptr; + } + const ggml_tensor * mm = nullptr; + int readers = 0; + for (int j = i + 1; j < cgraph->n_nodes; ++j) { + const ggml_tensor * node = cgraph->nodes[j]; + if (ggml_cuda_is_view_or_noop(node)) { + readers += (node->view_src == t && (node->flags & GGML_TENSOR_FLAG_OUTPUT)) ? 2 : 0; + continue; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + const ggml_tensor * src = node->src[s]; + if (src != nullptr && (src == t || src->view_src == t)) { + ++readers; + if (mm == nullptr && node->op == GGML_OP_MUL_MAT && s == 1) { + mm = node; + } + } + } + } + if (mm == nullptr) { + return nullptr; + } + const ggml_tensor * w = mm->src[0]; + const ggml_tensor * src1 = mm->src[1]; + const int cc = ggml_cuda_info().devices[cuda_ctx->device].cc; + *k = src1->ne[0]; + *n_tokens = src1->ne[1]; + if (w->type != GGML_TYPE_Q8_0 || w->ne[0] != *k || *k % MATRIX_ROW_PADDING != 0 || src1->type != GGML_TYPE_F32 || + !ggml_is_contiguous(src1) || src1->data != t->data || src1->ne[2] != 1 || src1->ne[3] != 1 || + ggml_nelements(t) != *k * *n_tokens || *n_tokens <= MMVQ_MAX_BATCH_SIZE || + !ggml_cuda_should_use_mmq(w->type, cc, *n_tokens, 0)) { + return nullptr; + } + + // MMQ may read up to one tile width (at most 128) of columns past the last row + const size_t nbytes = ((size_t) *n_tokens * (*k/128) + 128) * 144; + if (nbytes > cuda_ctx->mmq_q8_1_size) { + if (cuda_ctx->mmq_q8_1_buf != nullptr) { + CUDA_CHECK(cudaStreamSynchronize(cuda_ctx->stream())); + ggml_cuda_device_free(cuda_ctx->mmq_q8_1_buf, cuda_ctx->device); + } + CUDA_CHECK(ggml_cuda_device_malloc(&cuda_ctx->mmq_q8_1_buf, nbytes, cuda_ctx->device, true)); + cuda_ctx->mmq_q8_1_size = nbytes; + } + cuda_ctx->mmq_q8_1_dst = mm; + cuda_ctx->mmq_q8_1_data = t->data; + *only = readers == 1; + return cuda_ctx->mmq_q8_1_buf; +} + +static bool ggml_cuda_tensors_overlap(const ggml_tensor * a, const ggml_tensor * b) { + if (a == nullptr || b == nullptr || a->data == nullptr || b->data == nullptr) { + return false; + } + const char * a0 = (const char *) a->data; + const char * b0 = (const char *) b->data; + return a0 < b0 + ggml_nbytes(b) && b0 < a0 + ggml_nbytes(a); +} + +// a MUL_MAT that ggml_cuda_mul_mat gives to ggml_cuda_dense_wmma: weights of the model, a batch of columns that no MMQ, +// MMF or vector kernel takes +static bool ggml_cuda_dense_wmma_takes(const ggml_backend_cuda_context & ctx, const ggml_tensor * node) { + const ggml_tensor * src0 = node->src[0]; + const ggml_tensor * src1 = node->src[1]; + if (node->op != GGML_OP_MUL_MAT || (node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0 || src1->ne[1] < 512 || + ggml_cuda_op_mul_mat_use_fwht(node) || src0->buffer == nullptr || + ggml_backend_buffer_get_usage(src0->buffer) != GGML_BACKEND_BUFFER_USAGE_WEIGHTS) { + return false; + } + const int cc = ggml_cuda_info().devices[ctx.device].cc; + if (ggml_is_quantized(src0->type) && ggml_cuda_should_use_mmq(src0->type, cc, src1->ne[1], /*n_experts =*/ 0)) { + return false; + } + return ggml_cuda_dense_wmma_supported(ctx, src0, src1, node); +} + +// node i and the next MUL_MATs of its activations (within 32 nodes) in one launch of ggml_cuda_dense_wmma; the later +// ones are computed ahead, so their results must not overlap any tensor of the nodes in between, nor may those nodes +// write the activations. True if node i was computed (with at least one other). +static bool ggml_cuda_try_dense_wmma_group(ggml_backend_cuda_context * ctx, const ggml_cgraph * cgraph, const int i) { + // the products computed ahead by an earlier group (still to be skipped) leave fewer for this one + int free = 0; + for (const ggml_tensor * done : ctx->dense_done) { + free += done == nullptr; + } + const ggml_tensor * node = cgraph->nodes[i]; + if (free == 0 || !ctx->stream_context().concurrent_events.empty() || !ggml_cuda_dense_wmma_takes(*ctx, node)) { + return false; + } + const ggml_tensor * x = node->src[1]; + const bool f32 = ggml_cuda_dense_wmma_is_f32(node->src[0]); + const ggml_tensor * group[GGML_CUDA_DENSE_GROUP_MAX] = { node }; + int n = 1; + for (int j = i + 1; j < cgraph->n_nodes && j <= i + 32 && n < GGML_CUDA_DENSE_GROUP_MAX && n <= free; ++j) { + const ggml_tensor * nj = cgraph->nodes[j]; + bool pending = false; + for (const ggml_tensor * done : ctx->dense_done) { + pending = pending || done == nj; + } + if (!pending && nj->src[1] == x && ggml_cuda_dense_wmma_takes(*ctx, nj) && ggml_cuda_dense_wmma_is_f32(nj->src[0]) == f32) { + bool clear = true; + for (int k = i + 1; k < j && clear; ++k) { + const ggml_tensor * nk = cgraph->nodes[k]; + clear = !ggml_cuda_tensors_overlap(nj, nk); + for (int s = 0; s < GGML_MAX_SRC && clear; ++s) { + clear = !ggml_cuda_tensors_overlap(nj, nk->src[s]); + } + } + if (clear) { + group[n++] = nj; + continue; + } + } + if (!ggml_cuda_is_view_or_noop(nj) && ggml_cuda_tensors_overlap(nj, x)) { + break; + } + } + if (n == 1) { + return false; + } + for (int g = 0; g < n; ++g) { + ctx->q8_1_cache.invalidate(group[g]); + } + for (int g = 1, s = 0; g < n; ++g) { + while (ctx->dense_done[s] != nullptr) { + ++s; + } + ctx->dense_done[s] = group[g]; + } + ggml_cuda_dense_wmma(*ctx, group, n); + return true; +} + +// the convolution of a linear attention layer and the L2 norms of its q and k (see ggml_cuda_gdn_conv_nodes), with only +// views in between (the model orders them so for prompt batches): one kernel. Returns the nodes to skip. +static int ggml_cuda_try_gdn_conv(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, const int i) { + if (cgraph->nodes[i]->op != GGML_OP_CONCAT || i + 3 >= cgraph->n_nodes || !cuda_ctx->stream_context().concurrent_events.empty()) { + return 0; + } + ggml_cuda_gdn_conv_nodes n = {}; + n.concat = cgraph->nodes[i]; + n.conv = cgraph->nodes[i + 1]; + n.silu = cgraph->nodes[i + 2]; + if (n.conv->op != GGML_OP_SSM_CONV || n.conv->src[0] != n.concat || n.silu->op != GGML_OP_UNARY || + ggml_get_unary_op(n.silu) != GGML_UNARY_OP_SILU || n.silu->src[0] != n.conv) { + return 0; + } + // views, then RMS_NORM -> SCALE of a view of the silu output, twice + int last = -1, n_norm = 0; + for (int j = i + 3; j + 1 < std::min(cgraph->n_nodes, i + 16) && n_norm < 2; ++j) { + ggml_tensor * t = cgraph->nodes[j]; + if (t->op == GGML_OP_RMS_NORM && t->src[0]->view_src == n.silu && cgraph->nodes[j + 1]->op == GGML_OP_SCALE && + cgraph->nodes[j + 1]->src[0] == t && ggml_node_get_use_count(cgraph, j) == 1 && !(t->flags & GGML_TENSOR_FLAG_OUTPUT)) { + n.rms[n_norm] = t; + n.scale[n_norm] = cgraph->nodes[j + 1]; + ++n_norm; + last = ++j; + } else if (!ggml_cuda_is_view_or_noop(t)) { + return 0; + } + } + if (n_norm != 2) { + return 0; + } + if (n.rms[0]->src[0]->view_offs > n.rms[1]->src[0]->view_offs) { + std::swap(n.rms[0], n.rms[1]); + std::swap(n.scale[0], n.scale[1]); + } + // the convolution and its SiLU are read only within the chain (the SiLU by the views of q, k and v) + if (ggml_node_get_use_count(cgraph, i) != 1 || ggml_node_get_use_count(cgraph, i + 1) != 1 || + ggml_node_get_use_count(cgraph, i + 2) != 3 || (n.concat->flags & GGML_TENSOR_FLAG_OUTPUT) || + (n.conv->flags & GGML_TENSOR_FLAG_OUTPUT) || (n.silu->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return 0; + } + const int out_nodes[] = { i + 2, (int) (std::find(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, n.scale[0]) - cgraph->nodes), last }; + if (!ggml_cuda_gdn_conv_supported(*cuda_ctx, n) || + !ggml_cuda_check_fusion_memory_ranges(cgraph, i, last - i + 1, out_nodes, 3)) { + return 0; + } + for (const ggml_tensor * t : { n.silu, n.scale[0], n.scale[1] }) { + cuda_ctx->q8_1_cache.invalidate(t); + } + ggml_cuda_op_gdn_conv(*cuda_ctx, n); + return last - i; +} + +static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + + if (ggml_cuda_fusion_disabled()) { + return 0; + } + + if (const int skip = ggml_cuda_try_gdn_conv(cuda_ctx, cgraph, i)) { + return skip; + } + + // the combine of a block and the mix of the next one + if (cgraph->nodes[i]->op == GGML_OP_DSV4_HC_POST && i + 1 < cgraph->n_nodes && cgraph->nodes[i + 1]->op == GGML_OP_RMS_NORM && + cuda_ctx->stream_context().concurrent_events.empty()) { + ggml_cuda_hc_mix_nodes mix; + const int mix_last = ggml_cuda_hc_mix_match(cgraph, i + 1, mix); + if (mix_last > i + 1 && ggml_cuda_hc_post_mix_supported(cgraph->nodes[i], mix)) { + for (const ggml_tensor * t : { (const ggml_tensor *) cgraph->nodes[i], (const ggml_tensor *) mix.inject, + (const ggml_tensor *) mix.lo, (const ggml_tensor *) mix.pre }) { + cuda_ctx->q8_1_cache.invalidate(t); + } + ggml_cuda_hc_mix(*cuda_ctx, mix, cgraph->nodes[i]); + return mix_last - i; + } + } + + if (cgraph->nodes[i]->op == GGML_OP_RMS_NORM && cuda_ctx->stream_context().concurrent_events.empty()) { + ggml_cuda_hc_mix_nodes mix; + const int mix_last = ggml_cuda_hc_mix_match(cgraph, i, mix); + if (mix_last > i) { + for (const ggml_tensor * t : { mix.inject, mix.lo, mix.pre }) { + cuda_ctx->q8_1_cache.invalidate(t); + } + ggml_cuda_hc_mix(*cuda_ctx, mix); + return mix_last - i; + } + } + + if (ggml_cuda_hc_inject_on(cuda_ctx)) { + const int inj_last = ggml_cuda_hc_inject_find(cgraph, i, /*require_adjacent =*/ true, nullptr); + if (inj_last > i) { + const int out_nodes[] = { inj_last }; + const ggml_tensor * produced = cgraph->nodes[inj_last]; + const ggml_tensor * xn = cgraph->nodes[i + 1]; + const bool aliases_xn = produced->data && xn->data && + (const char *) produced->data < (const char *) xn->data + ggml_nbytes(xn) && + (const char *) xn->data < (const char *) produced->data + ggml_nbytes(produced); + if (!aliases_xn && ggml_cuda_check_fusion_memory_ranges(cgraph, i, inj_last - i + 1, out_nodes, 1)) { + int mm_i = inj_last; + const ggml_tensor * scale = nullptr; + if (cgraph->nodes[inj_last]->op == GGML_OP_SCALE) { + scale = cgraph->nodes[inj_last]; + mm_i -= 1; + } + ggml_cuda_op_rms_norm_hc_inject(*cuda_ctx, cgraph->nodes[i], cgraph->nodes[i + 1], cgraph->nodes[mm_i], scale, + ggml_cuda_hc_norm_mmq_q8_1(cuda_ctx, cgraph, inj_last, xn)); + return inj_last - i; + } + } + } + + ggml_tensor * node = cgraph->nodes[i]; + + if (node->op == GGML_OP_FILL) { + int rows[4]; + if (ggml_cuda_qsa_kpool_fusion(cgraph, i, rows)) { + ggml_tensor * dst = cgraph->nodes[i + 16]; + cuda_ctx->q8_1_cache.invalidate(cgraph->nodes[i + 4]); + cuda_ctx->q8_1_cache.invalidate(dst); + ggml_cuda_op_qsa_kpool_step(*cuda_ctx, cgraph->nodes[i + 1]->src[0], node, cgraph->nodes[i + 4], + cgraph->nodes[i + 6], rows, dst, dst); + return 16; + } + } + + if (node->op == GGML_OP_RMS_NORM && cuda_ctx->stream_context().concurrent_events.empty()) { + int mm_idx = -1; + const ggml_tensor * norm_w = nullptr; + const int last = ggml_cuda_norm_gate_fusion(cgraph, i, mm_idx, norm_w); + const ggml_tensor * q8_1_tensor = last > i ? ggml_cuda_mmvq_q8_1_target(cgraph, last, cgraph->nodes[last]) : nullptr; + if (q8_1_tensor != nullptr) { + ggml_cuda_mul_mat_vec_q_norm_gate(*cuda_ctx, cgraph->nodes[mm_idx], node, norm_w, cgraph->nodes[last], q8_1_tensor); + return last - i; + } + } + + if (node->op == GGML_OP_MUL_MAT) { + const int n_fused = ggml_cuda_try_router_topk_moe(cuda_ctx, cgraph, i); + if (n_fused > 0) { + return n_fused; + } + // the nodes of a concurrent region run on several streams, ordered by the events of each node + const int pre_idx = cuda_ctx->stream_context().concurrent_events.empty() ? ggml_cuda_hc_up_pre_fusion(cgraph, i) : -1; + if (pre_idx > i) { + ggml_tensor * pre = cgraph->nodes[pre_idx]; + cuda_ctx->q8_1_cache.invalidate(pre); + ggml_cuda_hc_up_pre(*cuda_ctx, node, pre); + return pre_idx - i; + } + } + + if (node == cuda_ctx->conv_done_node) { + // computed with its SiLU by the convolution step, see ggml_cuda_conv_step_fusion + cuda_ctx->conv_done_node = nullptr; + return 1; + } + + for (const ggml_tensor *& done : cuda_ctx->conv_norm_done) { + if (node == done) { + // computed with its SCALE by the convolution step, see ggml_cuda_conv_step_norms + done = nullptr; + return 1; + } + } + + if (node->op == GGML_OP_CONCAT && cuda_ctx->conv_done_node == nullptr) { + const int conv_idx = ggml_cuda_conv_step_fusion(cgraph, i); + if (conv_idx > i) { + ggml_tensor * state_out = cgraph->nodes[i + 2]; + ggml_tensor * silu = cgraph->nodes[conv_idx + 1]; + cuda_ctx->q8_1_cache.invalidate(state_out); + cuda_ctx->q8_1_cache.invalidate(silu); + const ggml_tensor * norm[2] = { nullptr, nullptr }; + const ggml_tensor * norm_scale[2] = { nullptr, nullptr }; + ggml_cuda_conv_step_norms(cgraph, conv_idx + 1, norm, norm_scale); + for (int k = 0; k < 2; ++k) { + if (norm_scale[k] != nullptr) { + cuda_ctx->q8_1_cache.invalidate(norm_scale[k]); + } + cuda_ctx->conv_norm_done[k] = norm[k]; + } + ggml_cuda_op_ssm_conv_step(*cuda_ctx, node->src[0]->view_src, node->src[1]->view_src, + cgraph->nodes[conv_idx]->src[1], state_out, silu, norm, norm_scale); + cuda_ctx->conv_done_node = cgraph->nodes[conv_idx]; + return 3; + } + } + + if (node == cuda_ctx->moe_down_node) { + // prepared by the fused routed + shared expert gate/up, see ggml_cuda_moe_down_fusion + cuda_ctx->moe_down_node = nullptr; + const ggml_tensor * routed = node->src[1]; + int gate_idx = -1; + const int last = ggml_cuda_moe_down_fusion(cgraph, i, routed, cgraph->nodes[i - 1], cgraph->nodes[i - 1]->src[1]->src[1], gate_idx); + const char * y_q8_1 = cuda_ctx->q8_1_cache.find(routed); + const char * y_s_q8_1 = last > i ? cuda_ctx->q8_1_cache.find(cgraph->nodes[last - 4]->src[1]) : nullptr; + if (last > i && y_q8_1 && y_s_q8_1) { + ggml_cuda_mul_mat_vec_q_moe_down_shared(*cuda_ctx, node, cgraph->nodes[last - 4], cgraph->nodes[last], + cuda_ctx->moe_scratch, y_q8_1, y_s_q8_1); + return last - i; + } + } + + if (node->op == GGML_OP_MUL_MAT && cuda_ctx->stream_context().concurrent_events.empty() && + ggml_cuda_gdn_alpha_beta_fusion(cgraph, i)) { + ggml_tensor * add = cgraph->nodes[i + 2]; + ggml_tensor * mul = cgraph->nodes[i + 4]; + ggml_tensor * sig = cgraph->nodes[i + 8]; + const ggml_tensor * dt = add->src[0] == cgraph->nodes[i + 1] ? add->src[1] : add->src[0]; + const ggml_tensor * a = mul->src[0] == cgraph->nodes[i + 3] ? mul->src[1] : mul->src[0]; + cuda_ctx->q8_1_cache.invalidate(mul); + cuda_ctx->q8_1_cache.invalidate(sig); + ggml_cuda_op_gdn_alpha_beta(*cuda_ctx, node, dt, a, mul, cgraph->nodes[i + 6], sig); + return 8; + } + + if (node->op == GGML_OP_MUL_MAT && cuda_ctx->stream_context().concurrent_events.empty()) { + const int hc_idx = ggml_cuda_hc_pre_gate_fusion(cgraph, i); + if (hc_idx > i) { + ggml_tensor * hc_pre = cgraph->nodes[hc_idx]; + // the pre-mix read by MMVQ also writes its q8_1 copy, as the separate op does + const bool write_q8_1 = hc_pre->ne[0] % MATRIX_ROW_PADDING == 0 && ggml_cuda_mmvq_reads_soon(cgraph, hc_idx, hc_pre, 32); + const float * src1_copy = cuda_ctx->hc_lo_copy == node->src[1] ? (const float *) node->data : nullptr; + cuda_ctx->hc_lo_copy = nullptr; + const int inject_idx = cuda_ctx->hc_inject_node == nullptr ? ggml_cuda_hc_inject_ahead(cgraph, hc_idx) : -1; + if (inject_idx > 0 && cuda_ctx->hc_inject_buf == nullptr) { + CUDA_CHECK(ggml_cuda_device_malloc((void **) &cuda_ctx->hc_inject_buf, 32*sizeof(float), cuda_ctx->device, true)); + } + const ggml_tensor * inject = inject_idx > 0 ? cgraph->nodes[inject_idx] : nullptr; + ggml_cuda_mul_mat_vec_q_hc_pre(*cuda_ctx, node->src[0], node->src[1], src1_copy, hc_pre, write_q8_1, + inject, inject ? cuda_ctx->hc_inject_buf : nullptr); + cuda_ctx->hc_inject_node = inject; + return hc_idx - i; + } + if (node == cuda_ctx->hc_inject_node) { + // computed ahead by the fused pre-mix, see ggml_cuda_hc_inject_ahead + cuda_ctx->hc_inject_node = nullptr; + ggml_tensor * post = cgraph->nodes[i + 4]; + cuda_ctx->q8_1_cache.invalidate(post); + if (ggml_cuda_try_hc_post_rms_norm(cuda_ctx, cgraph, i + 4, cgraph->nodes[i + 1], cgraph->nodes[i + 3], + cuda_ctx->hc_inject_buf)) { + return 6; + } + ggml_cuda_op_dsv4_hc_post(*cuda_ctx, post, cgraph->nodes[i + 1], cgraph->nodes[i + 3], cuda_ctx->hc_inject_buf); + return 4; + } + if (ggml_cuda_mmvq_scale_silu_fusion(cgraph, i)) { + ggml_tensor * unary = cgraph->nodes[i + 2]; + // The hyper-connection gate product right after reads the activation, and its fused pre-mix may overwrite + // the activation's buffer: a copy goes to the buffer of the gate product, which the fusion does not write, + // and which overlaps neither the activation nor the pre-mix, both live with it. + float * copy = nullptr; + if (i + 3 < cgraph->n_nodes && cgraph->nodes[i + 3]->op == GGML_OP_MUL_MAT && cgraph->nodes[i + 3]->src[1] == unary && + ggml_cuda_hc_pre_gate_fusion(cgraph, i + 3) > i + 3) { + copy = (float *) cgraph->nodes[i + 3]->data; + cuda_ctx->hc_lo_copy = unary; + } + ggml_cuda_mul_mat_vec_q_scale_silu(*cuda_ctx, node->src[0], node->src[1], cgraph->nodes[i + 1], unary, copy); + return 2; + } + } + + if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() && + ggml_cuda_match_shared_expert(cgraph, i, i + 3) && + ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1])) { + const int outputs[] = { i + 2, i + 5 }; + ggml_tensor * routed = cgraph->nodes[i + 2]; + ggml_tensor * shared = cgraph->nodes[i + 5]; + const bool same_type = routed->src[1]->src[0]->type == shared->src[1]->src[0]->type; + // a shared expert of another type runs in a kernel of its own (one warp per row, the RDNA3.5 parameters) + const int device = ggml_cuda_get_device(); + const bool other_type_ok = !same_type && GGML_CUDA_CC_IS_RDNA3_5(ggml_cuda_info().devices[device].cc) && + ggml_cuda_info().devices[device].warp_size == QK8_1 && routed->ne[2] == 1 && routed->src[1]->src[1]->ne[2] == 1; + if (other_type_ok && ggml_cuda_check_fusion_memory_ranges(cgraph, i, 6, outputs, 2)) { + // the down products read both through MMVQ, which finds the q8_1 copies the kernel writes + const bool q8_1 = routed->ne[0] % QK8_1 == 0 && ggml_cuda_mmvq_reads_soon(cgraph, i + 5, routed, 16); + const bool q8_1_s = shared->ne[0] % QK8_1 == 0 && ggml_cuda_mmvq_reads_soon(cgraph, i + 5, shared, 32); + // the down stage right after in one kernel too, with the gate and routing this kernel copies + int gate_idx = -1; + const int last = q8_1 && q8_1_s ? ggml_cuda_moe_down_fusion(cgraph, i + 6, routed, shared, shared->src[1]->src[1], gate_idx) : -1; + if (last > 0 && cuda_ctx->moe_scratch == nullptr) { + CUDA_CHECK(ggml_cuda_device_malloc((void **) &cuda_ctx->moe_scratch, 2*QK8_1*sizeof(float), cuda_ctx->device, true)); + } + const bool prepare = last > 0 && routed->src[1]->src[2] == cgraph->nodes[i + 6]->src[2]; + ggml_cuda_moe_weighted_reduction_match match; + const ggml_tensor * weights = prepare && ggml_cuda_match_moe_weighted_reduction(cgraph, i + 7, match) ? match.weights : nullptr; + ggml_cuda_mul_mat_vec_q_moe_glu_shared(*cuda_ctx, routed, shared, q8_1, q8_1_s, + weights ? cgraph->nodes[gate_idx] : nullptr, weights, weights ? cuda_ctx->moe_scratch : nullptr); + cuda_ctx->moe_down_node = weights ? cgraph->nodes[i + 6] : nullptr; + return 5; + } + if (same_type && !ggml_cuda_moe_wmma_is_repacked(node->src[0]) && ggml_cuda_check_fusion_memory_ranges(cgraph, i, 6, outputs, 2)) { + const ggml_tensor * up = routed->src[1]; + ggml_cuda_mm_fusion_args_host fusion{}; + fusion.gate = routed->src[0]->src[0]; + fusion.glu_op = ggml_get_glu_op(routed); + fusion.glu_limit = ggml_get_op_params_f32(routed, 3); + fusion.shared_up = shared->src[1]->src[0]; + fusion.shared_gate = shared->src[0]->src[0]; + fusion.shared_dst = shared; + ggml_cuda_mul_mat_vec_q(*cuda_ctx, up->src[0], up->src[1], up->src[2], routed, &fusion); + return 5; + } + } + + // the routed + shared expert kernels above read repacked experts, the other fusions with a MUL_MAT_ID the GGUF layout + if (node->op == GGML_OP_MUL_MAT_ID && ggml_cuda_moe_wmma_is_repacked(node->src[0])) { + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL_MAT_ID, GGML_OP_GLU }, {})) { + ggml_tensor * glu = cgraph->nodes[i + 2]; + ggml_tensor * gate = glu->src[0]; + ggml_tensor * up = glu->src[1]; + const bool ok = (gate == cgraph->nodes[i] && up == cgraph->nodes[i + 1]) || + (gate == cgraph->nodes[i + 1] && up == cgraph->nodes[i]); + if (ok && ggml_cuda_should_fuse_mul_mat(up, gate, glu) && ggml_cuda_moe_wmma_can_fuse_glu(gate, up, glu)) { + // the result as BF16 if only the repacked down product of a prompt reads it (it would convert it) + bool bf16 = glu->ne[2] > 1 && ggml_is_contiguous(glu) && !(glu->flags & GGML_TENSOR_FLAG_OUTPUT) && + ggml_node_get_use_count(cgraph, i + 2) == 1; + if (bf16) { + const ggml_tensor * down = nullptr; + for (int j = i + 3; j < cgraph->n_nodes && down == nullptr; ++j) { + for (int s = 0; s < GGML_MAX_SRC; ++s) { + if (cgraph->nodes[j]->src[s] == glu) { + down = cgraph->nodes[j]; + } + } + } + bf16 = down != nullptr && down->op == GGML_OP_MUL_MAT_ID && down->src[1] == glu && + ggml_cuda_moe_wmma_is_repacked(down->src[0]); + } + ggml_cuda_moe_wmma_glu(*cuda_ctx, gate, up, glu, bf16); + return 2; + } + } + // a down product of a prompt that only the weighted reduction reads writes the experts' rows as BF16 + static const bool no_down_bf16 = getenv("GGML_CUDA_NO_MOE_DOWN_BF16") != nullptr; + if (!no_down_bf16 && node->ne[2] > 1 && !(node->flags & GGML_TENSOR_FLAG_OUTPUT) && ggml_node_get_use_count(cgraph, i) == 1 && + ggml_cuda_moe_weighted_reduction_bf16_supported(node)) { + int j = i + 1; + while (j < cgraph->n_nodes && cgraph->nodes[j]->src[0] != node && cgraph->nodes[j]->src[1] != node) { + ++j; + } + ggml_cuda_moe_weighted_reduction_match match; + if (j < cgraph->n_nodes && ggml_cuda_match_moe_weighted_reduction(cgraph, j, match) && match.experts == node) { + const int output_idx = j + match.node_count - 1; + if (ggml_cuda_check_fusion_memory_ranges(cgraph, j, match.node_count, &output_idx, 1)) { + cuda_ctx->moe_down_bf16 = node; + } + } + } + return 0; + } + + if (node->op == GGML_OP_MUL) { + ggml_cuda_moe_weighted_reduction_match match; + if (ggml_cuda_match_moe_weighted_reduction(cgraph, i, match)) { + const int output_idx = i + match.node_count - 1; + if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, match.node_count, &output_idx, 1)) { + // the reduction also writes the q8_1 copy for the MMVQ product that reads its result + const ggml_tensor * q8_1_tensor = ggml_cuda_mmvq_q8_1_target(cgraph, output_idx, match.dst); + block_q8_1 * q8_1 = q8_1_tensor ? (block_q8_1 *) cuda_ctx->q8_1_cache.reserve( + ggml_nrows(q8_1_tensor) * q8_1_tensor->ne[0]/QK8_1 * sizeof(block_q8_1)) : nullptr; + const bool experts_bf16 = cuda_ctx->moe_down_bf16 != nullptr && cuda_ctx->moe_down_bf16 == match.experts; + cuda_ctx->moe_down_bf16 = nullptr; + if (ggml_cuda_op_moe_weighted_reduction( + *cuda_ctx, match.experts, match.expert_scale, match.weights, match.dst, q8_1, experts_bf16) && q8_1) { + cuda_ctx->q8_1_cache.commit(q8_1_tensor); + } + return match.node_count - 1; + } + } + } + + // gated_delta_net -> cpy: scatter recurrent-state snapshots into the cache + if (node->op == GGML_OP_GATED_DELTA_NET) { + ggml_cuda_gated_delta_net_fused_cache fused_state_cpy; + const int nodes_to_skip = ggml_cuda_try_gdn_cache_fusion(cgraph, i, fused_state_cpy); + if (nodes_to_skip > 0) { +#ifdef GGML_CUDA_DEBUG + GGML_LOG_INFO("%s: fused gated_delta_net snapshot copies for %s (skipped %d nodes)\n", + __func__, node->name, nodes_to_skip); +#endif + ggml_cuda_op_gated_delta_net_fused_cache(*cuda_ctx, node, fused_state_cpy); + return nodes_to_skip; + } + } + + // ssm_scan -> cpy: scatter recurrent-state snapshots into the cache + if (node->op == GGML_OP_SSM_SCAN) { + ggml_cuda_ssm_scan_fused_cache fused_state_cpy; + const int nodes_to_skip = ggml_cuda_try_ssm_scan_cache_fusion(cgraph, i, fused_state_cpy); + if (nodes_to_skip > 0) { +#ifdef GGML_CUDA_DEBUG GGML_LOG_INFO("%s: fused ssm_scan snapshot copies for %s (skipped %d nodes)\n", __func__, node->name, nodes_to_skip); #endif @@ -4924,6 +6559,13 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph } } + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_ADD, GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SOFTPLUS }) || + ggml_cuda_can_fuse(cgraph, i, { GGML_OP_ADD, GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SIGMOID }) || + ggml_cuda_can_fuse(cgraph, i, { GGML_OP_ADD, GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SILU })) { + ggml_cuda_op_add_unary_mul(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); + return 2; + } + // multi-(add or mul) if (node->op == GGML_OP_ADD || node->op == GGML_OP_MUL) { int n_fuse = 0; @@ -5538,6 +7180,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph } if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL }, {})) { + ggml_tensor * mul = cgraph->nodes[i + 1]; // a norm read by MMVQ also writes the q8_1 copy, which saves the consumers' quantization kernel char * q8_1 = nullptr; @@ -5555,6 +7198,17 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph return 1; } + if (node->op == GGML_OP_CONCAT) { + const int n_conv = ggml_cuda_ssm_conv_concat_match(cgraph, i); + const int out = i + n_conv; + if (n_conv > 0 && ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_conv + 1, &out, 1)) { + ggml_tensor * bias_add = n_conv == 3 ? cgraph->nodes[i + 2] : nullptr; + ggml_tensor * silu = n_conv >= 2 ? cgraph->nodes[out] : nullptr; + ggml_cuda_op_ssm_conv(*cuda_ctx, cgraph->nodes[i + 1], bias_add, silu, /*fuse_concat =*/ true); + return n_conv; + } + } + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SSM_CONV, GGML_OP_ADD, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { ggml_cuda_op_ssm_conv(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); return 2; @@ -5565,10 +7219,34 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph return 1; } + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_ADD }, { GGML_UNARY_OP_SIGMOID })) { + cuda_ctx->q8_1_cache.invalidate(cgraph->nodes[i + 1]); + cuda_ctx->q8_1_cache.invalidate(cgraph->nodes[i + 2]); + ggml_cuda_op_unary_mul_add(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); + return 2; + } + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SILU }) || ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SIGMOID }) || ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SOFTPLUS })) { - ggml_cuda_op_unary_mul(*cuda_ctx, node, cgraph->nodes[i + 1]); + ggml_tensor * mul = cgraph->nodes[i + 1]; + // a gated product whose result (reshaped) feeds MMVQ also writes the q8_1 copy, see ggml_cuda_mmvq_q8_1_target + const ggml_tensor * q8_1_tensor = mul->type == GGML_TYPE_F32 ? ggml_cuda_mmvq_q8_1_target(cgraph, i + 1, mul) : nullptr; + // of a prompt batch, the MMQ q8_1 copy (and the F32 result only if something else reads it) + int64_t k_mmq = 0, n_mmq = 0; + bool only = false; + void * q8_mmq = q8_1_tensor == nullptr && node->src[0]->type == GGML_TYPE_F32 ? + ggml_cuda_mmq_q8_1_producer(cuda_ctx, cgraph, i + 1, mul, &k_mmq, &n_mmq, &only) : nullptr; + if (q8_mmq != nullptr) { + cuda_ctx->q8_1_cache.invalidate(mul); + ggml_cuda_op_unary_mul_mmq_q8_1(*cuda_ctx, node, mul, q8_mmq, k_mmq, n_mmq, !only); + return 1; + } + block_q8_1 * q8_1 = q8_1_tensor ? (block_q8_1 *) cuda_ctx->q8_1_cache.reserve( + ggml_nrows(q8_1_tensor) * q8_1_tensor->ne[0]/QK8_1 * sizeof(block_q8_1)) : nullptr; + if (ggml_cuda_op_unary_mul(*cuda_ctx, node, mul, q8_1) && q8_1) { + cuda_ctx->q8_1_cache.commit(q8_1_tensor); + } return 1; } @@ -5578,6 +7256,9 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph } if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_DSV4_HC_POST }, { GGML_UNARY_OP_SIGMOID })) { + if (ggml_cuda_try_hc_post_rms_norm(cuda_ctx, cgraph, i + 3, node, cgraph->nodes[i + 2], nullptr)) { + return 5; + } ggml_cuda_op_dsv4_hc_post(*cuda_ctx, cgraph->nodes[i + 3], node, cgraph->nodes[i + 2]); return 3; } @@ -5587,6 +7268,20 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph return 2; } + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SCALE, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { + ggml_tensor * unary = cgraph->nodes[i + 1]; + cuda_ctx->q8_1_cache.invalidate(unary); + // an activation read by MMVQ also writes the q8_1 copy, as the RMS_NORM + MUL fusion does + char * q8_1 = nullptr; + if (ggml_nrows(unary) <= MMVQ_MAX_BATCH_SIZE && ggml_cuda_mmvq_reads_soon(cgraph, i + 1, unary)) { + q8_1 = cuda_ctx->q8_1_cache.reserve(ggml_nrows(unary) * GGML_PAD(unary->ne[0], MATRIX_ROW_PADDING)/QK8_1 * sizeof(block_q8_1)); + } + if (ggml_cuda_op_scale_unary(*cuda_ctx, node, unary, (block_q8_1 *) q8_1) && q8_1) { + cuda_ctx->q8_1_cache.commit(unary); + } + return 1; + } + return 0; } @@ -5697,6 +7392,19 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud // q8_1 copies are reused in stream order, so not across concurrent streams cuda_ctx->q8_1_cache.reset(!should_launch_concurrent_events); + cuda_ctx->hc_inject_node = nullptr; + cuda_ctx->hc_bf16_src = nullptr; + cuda_ctx->dense_x_src = nullptr; + for (const ggml_tensor *& done : cuda_ctx->dense_done) { + done = nullptr; + } + cuda_ctx->moe_bf16_src = nullptr; + cuda_ctx->moe_down_bf16 = nullptr; + cuda_ctx->hc_lo_copy = nullptr; + cuda_ctx->moe_down_node = nullptr; + cuda_ctx->conv_done_node = nullptr; + cuda_ctx->conv_norm_done[0] = nullptr; + cuda_ctx->conv_norm_done[1] = nullptr; for (int i = 0; i < cgraph->n_nodes; i++) { ggml_tensor * node = cgraph->nodes[i]; @@ -5749,6 +7457,22 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud continue; } + if (ggml_cuda_gdn_state_rows_unused(cgraph, i) || ggml_cuda_conv_state_rows_unused(cgraph, i)) { + continue; + } + + bool dense_done = false; + for (const ggml_tensor *& done : cuda_ctx->dense_done) { + if (node == done) { + // computed with an earlier product of the same activations, see ggml_cuda_try_dense_wmma_group + done = nullptr; + dense_done = true; + } + } + if (dense_done) { + continue; + } + cuda_ctx->q8_1_cache.invalidate(node); int nodes_to_skip = ggml_cuda_try_fuse(cuda_ctx, cgraph, i); @@ -5763,6 +7487,9 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud i += nodes_to_skip; continue; } + if (ggml_cuda_try_dense_wmma_group(cuda_ctx, cgraph, i)) { + continue; + } #ifndef NDEBUG // On integrated GPUs (APUs, e.g. RDNA3.5) the scheduler may place a // node's output on the host-visible buffer, which the compute path @@ -5780,20 +7507,30 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud GGML_UNUSED(integrated); #endif // NDEBUG - // a flash attention whose result (reshaped) feeds MMVQ writes its q8_1 copy, see ggml_cuda_mmvq_q8_1_target - const ggml_tensor * fa_q8_1_tensor = node->op == GGML_OP_FLASH_ATTN_EXT ? ggml_cuda_mmvq_q8_1_target(cgraph, i, node) : nullptr; - if (fa_q8_1_tensor) { - cuda_ctx->fa_q8_1 = (block_q8_1 *) cuda_ctx->q8_1_cache.reserve( - ggml_nrows(fa_q8_1_tensor) * fa_q8_1_tensor->ne[0]/QK8_1 * sizeof(block_q8_1)); - cuda_ctx->fa_q8_1_written = false; + // A flash attention whose result (reshaped) feeds MMVQ writes its q8_1 copy, see + // ggml_cuda_mmvq_q8_1_target, and so does a hyper-connection pre-mix read by MMVQ; the op writes the copy + // only where it can, see out_q8_1_written. The pre-mix of a full-attention layer is read through the + // Q/K/V projections some 30 nodes on, after the indexer. + const ggml_tensor * out_q8_1_tensor = nullptr; + if (node->op == GGML_OP_FLASH_ATTN_EXT) { + out_q8_1_tensor = ggml_cuda_mmvq_q8_1_target(cgraph, i, node); + } else if (node->op == GGML_OP_DSV4_HC_PRE && ggml_is_contiguous(node) && + node->ne[0] % MATRIX_ROW_PADDING == 0 && ggml_nrows(node) <= MMVQ_MAX_BATCH_SIZE && + ggml_cuda_mmvq_reads_soon(cgraph, i, node, 32)) { + out_q8_1_tensor = node; + } + if (out_q8_1_tensor) { + cuda_ctx->out_q8_1 = (block_q8_1 *) cuda_ctx->q8_1_cache.reserve( + ggml_nrows(out_q8_1_tensor) * out_q8_1_tensor->ne[0]/QK8_1 * sizeof(block_q8_1)); + cuda_ctx->out_q8_1_written = false; } bool ok = ggml_cuda_compute_forward(*cuda_ctx, node); - if (fa_q8_1_tensor && cuda_ctx->fa_q8_1 && cuda_ctx->fa_q8_1_written) { - cuda_ctx->q8_1_cache.commit(fa_q8_1_tensor); + if (out_q8_1_tensor && cuda_ctx->out_q8_1 && cuda_ctx->out_q8_1_written) { + cuda_ctx->q8_1_cache.commit(out_q8_1_tensor); } - cuda_ctx->fa_q8_1 = nullptr; + cuda_ctx->out_q8_1 = nullptr; if (!ok) { GGML_LOG_ERROR("%s: op not supported %s (%s)\n", __func__, node->name, ggml_op_name(node->op)); } @@ -5854,10 +7591,68 @@ static bool ggml_cuda_graph_set_enabled(ggml_backend_cuda_context * cuda_ctx, co } #endif // USE_CUDA_GRAPH +// BF16 copies of the F32 router weights of the fused router + top-k MoE selection (see ggml_cuda_try_router_topk_moe), +// made before any CUDA graph capture; GGML_CUDA_ROUTER_F32 keeps the F32 weights +static void ggml_cuda_prepare_router_bf16(ggml_backend_cuda_context * cuda_ctx, const ggml_cgraph * cgraph) { + static const bool keep_f32 = getenv("GGML_CUDA_ROUTER_F32") != nullptr; + if (keep_f32) { + return; + } + for (int i = 0; i + 1 < cgraph->n_nodes; ++i) { + const ggml_tensor * mm = cgraph->nodes[i]; + const ggml_tensor * gating = cgraph->nodes[i + 1]; + if (mm->op != GGML_OP_MUL_MAT || mm->src[0]->type != GGML_TYPE_F32 || !ggml_is_contiguous(mm->src[0]) || + (gating->op != GGML_OP_UNARY && gating->op != GGML_OP_SOFT_MAX) || gating->src[0] != mm || + !ggml_cuda_router_topk_moe_supported(mm, mm) || cuda_ctx->router_bf16.count(mm->src[0]->data) != 0) { + continue; + } + const ggml_tensor * w = mm->src[0]; + void * buf = nullptr; + CUDA_CHECK(ggml_cuda_device_malloc(&buf, ggml_nelements(w)*sizeof(uint16_t), cuda_ctx->device, true)); + ggml_cuda_router_weights_to_bf16((const float *) w->data, buf, ggml_nelements(w), cuda_ctx->stream()); + cuda_ctx->router_bf16[w->data] = buf; + } +} + +// the tiled BF16 copies of the weights that ggml_cuda_dense_wmma multiplies a prompt batch with, made before any CUDA +// graph capture +static void ggml_cuda_prepare_dense_bf16(ggml_backend_cuda_context * cuda_ctx, const ggml_cgraph * cgraph) { + for (int i = 0; i < cgraph->n_nodes; ++i) { + const ggml_tensor * mm = cgraph->nodes[i]; + if (mm->op == GGML_OP_MUL_MAT) { + ggml_cuda_dense_wmma_prepare_f32(*cuda_ctx, mm->src[0]); + } + if (mm->op != GGML_OP_MUL_MAT || !ggml_cuda_dense_wmma_wants_copy(*cuda_ctx, mm->src[0])) { + continue; + } + const ggml_tensor * w = mm->src[0]; + void * buf = nullptr; + CUDA_CHECK(ggml_cuda_device_malloc(&buf, ggml_nelements(w)*sizeof(uint16_t), cuda_ctx->device, true)); + if (w->type == GGML_TYPE_BF16) { + ggml_cuda_dense_wmma_retile(w->data, w->nb[1] / sizeof(uint16_t), buf, w->ne[1], w->ne[0], cuda_ctx->stream()); + } else { + ggml_cuda_pool_alloc rows(cuda_ctx->pool(), ggml_nelements(w)); + ggml_get_to_bf16_cuda(w->type)(w->data, rows.get(), ggml_nelements(w), cuda_ctx->stream()); + ggml_cuda_dense_wmma_retile(rows.get(), w->ne[0], buf, w->ne[1], w->ne[0], cuda_ctx->stream()); + } + cuda_ctx->dense_bf16[w->data] = buf; + } +} + static enum ggml_status ggml_backend_cuda_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) { ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context; ggml_cuda_set_device(cuda_ctx->device); + ggml_cuda_blas_prewarm(*cuda_ctx); + ggml_cuda_prepare_router_bf16(cuda_ctx, cgraph); + ggml_cuda_prepare_dense_bf16(cuda_ctx, cgraph); + ggml_cuda_moe_wmma_prepare(*cuda_ctx, cgraph); + ggml_cuda_qsa_attn_plan(*cuda_ctx, cgraph); + cuda_ctx->mmq_q8_1_dst = nullptr; + + if (ggml_cuda_hc_inject_on(cuda_ctx)) { + ggml_cuda_hc_inject_reorder(cgraph); + } bool use_cuda_graph = false; bool cuda_graph_update_required = false; @@ -5962,10 +7757,20 @@ static void ggml_backend_cuda_graph_optimize(ggml_backend_t backend, ggml_cgraph } }; + if (!disable_fusion && ggml_cuda_hc_inject_on(cuda_ctx)) { + ggml_cuda_hc_inject_reorder(cgraph); + } + if (!disable_fusion) { // add alloc deps for performance positive fusions. This may increase the overall compute buffer size. // TODO: consolidate fusion paths in graph_optimize and graph_compute ggml_cuda_set_device(cuda_ctx->device); + for (int i = 0; i + 2 < cgraph->n_nodes; ++i) { + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_ADD }, { GGML_UNARY_OP_SIGMOID })) { + add_alloc_deps(i, i + 2); + i += 2; + } + } for (int i = 0; i + 5 < cgraph->n_nodes; ++i) { if (cgraph->nodes[i]->op != GGML_OP_MUL_MAT_ID) { continue; @@ -6008,6 +7813,16 @@ static void ggml_backend_cuda_graph_optimize(ggml_backend_t backend, ggml_cgraph } for (int i = 0; i < cgraph->n_nodes; ++i) { + // The SSM_CONV fused with its input CONCAT reads the concat inputs, keep them alive until its last node. + if (cgraph->nodes[i]->op == GGML_OP_CONCAT) { + const int n_conv = ggml_cuda_ssm_conv_concat_match(cgraph, i); + if (n_conv > 0) { + params->add_alloc_dep(params->user_data, cgraph->nodes[i]->src[0], cgraph->nodes[i + n_conv]); + params->add_alloc_dep(params->user_data, cgraph->nodes[i]->src[1], cgraph->nodes[i + n_conv]); + i += n_conv; + continue; + } + } // Keep the inputs of the fused gate/up/GLU MMQ kernel alive until the GLU so that they cannot alias its output (under op offload the weights are buffer copies). if (i + 2 < cgraph->n_nodes && cgraph->nodes[i + 2]->op == GGML_OP_GLU) { ggml_tensor * glu = cgraph->nodes[i + 2]; diff --git a/ggml/src/ggml-cuda/hc-wmma.cu b/ggml/src/ggml-cuda/hc-wmma.cu new file mode 100644 index 000000000000..f2cdafcb8b93 --- /dev/null +++ b/ggml/src/ggml-cuda/hc-wmma.cu @@ -0,0 +1,654 @@ +// Hyper-connection up product + gated pre-mix for a prompt batch with BF16 WMMA (RDNA3). +// +// gate[s*n_embd + e, t] = w_up[s*n_embd + e, :] . lo[:, t] for the HC_N streams s, then +// pre[e, t] = scale * sum_s x[e, s, t] * sigmoid(gate[s*n_embd + e, t]). +// A block computes the gates of HC_EB embedding positions of all streams for HC_TILE tokens: wave w the 16 rows +// e0 + 16*(w % 2) + .. of stream w / 2, with the w_up blocks dequantized to BF16 in registers (lanes 0..15 the first +// 16 values of a Q8_0 block, lanes 16..31 the others, swapped with permlanex16) against the BF16 lo tile in LDS. The +// sigmoids go through LDS so that the pre-mix reads x and writes pre with whole cache lines. + +#include "hc-wmma.cuh" + +#if defined(GGML_USE_HIP) + +static constexpr int HC_N = 4; +static constexpr int HC_EB = 32; // embedding positions per block +static constexpr int HC_TILE = 64; // tokens per block +static constexpr int HC_NW = HC_N * HC_EB / 16; +static constexpr int HC_KMAX = 640; // the lo tile holds all of K + +typedef short hc_short16 __attribute__((ext_vector_type(16))); +typedef float hc_float8 __attribute__((ext_vector_type(8))); + +// two values exact in BF16 (integers of 8 bits): the high halves of their floats +static __device__ __forceinline__ uint32_t hc_pack_bf16_exact(const float lo, const float hi) { + return __builtin_amdgcn_perm(__float_as_uint(hi), __float_as_uint(lo), 0x07060302u); +} + +static __device__ __forceinline__ uint32_t hc_pack_bf16(const float lo, const float hi) { + const uint32_t ul = __float_as_uint(lo), uh = __float_as_uint(hi); + return ((uh + 0x7FFFu + ((uh >> 16) & 1u)) & 0xFFFF0000u) | ((ul + 0x7FFFu + ((ul >> 16) & 1u)) >> 16); +} + +// barrier for the LDS only: __syncthreads also waits for the global loads in flight (prefetched values) +static __device__ __forceinline__ void hc_lds_sync() { + asm volatile("s_waitcnt lgkmcnt(0)\n\ts_barrier" ::: "memory"); +} + +static __global__ void __launch_bounds__(32 * HC_NW) hc_up_pre_kernel( + const uint8_t * __restrict__ w, const int64_t w_row, const int K, + const float * __restrict__ lo, const int64_t s_lo, + const float * __restrict__ x, const int64_t sx1, const int64_t sx2, + const float * __restrict__ rstd, const float * __restrict__ gamma, + float * __restrict__ dst, const int64_t sd1, uint16_t * __restrict__ dst16, + const int n_embd, const int n_tokens, const float scale) { + // with rstd the normalized streams are x * rstd[stream of token] * gamma[position of stream]; + // dst16: the result also as BF16 (rounded to nearest even), contiguous +#if defined(AMD_WMMA_256B_AVAILABLE) + extern __shared__ uint4 hc_smem[]; + uint16_t * ys = (uint16_t *) hc_smem; // [HC_TILE][K + 8] BF16 + float * gs = (float *) hc_smem; // [HC_N][HC_TILE][HC_EB + 1] sigmoids, after the products + const int ystride = K + 8; + + const int tid = threadIdx.y * 32 + threadIdx.x; + const int e0 = blockIdx.x * HC_EB; + const int t0 = blockIdx.y * HC_TILE; + + // the lo tile, BF16 + for (int i = tid; i < HC_TILE * (K / 4); i += 32 * HC_NW) { + const int t = i / (K / 4), k = 4 * (i % (K / 4)); + float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + if (t0 + t < n_tokens) { + v = *(const float4 *) (lo + (int64_t) (t0 + t) * s_lo + k); + } + *(uint2 *) (ys + t * ystride + k) = make_uint2(hc_pack_bf16(v.x, v.y), hc_pack_bf16(v.z, v.w)); + } + // the streams the pre-mix of this thread reads, loaded during the products + constexpr int XT = HC_TILE / (32 * HC_NW / HC_EB); + const int e = tid % HC_EB; + float xp[XT][HC_N]; +#pragma unroll + for (int it = 0; it < XT; ++it) { + const int t = tid / HC_EB + it * (32 * HC_NW / HC_EB); +#pragma unroll + for (int ih = 0; ih < HC_N; ++ih) { + xp[it][ih] = t0 + t < n_tokens ? x[(int64_t) (t0 + t) * sx2 + ih * sx1 + e0 + e] : 0.0f; + } + } + hc_lds_sync(); + + const int lane = threadIdx.x, hw = lane / 16, r16 = lane % 16; + const int s = threadIdx.y / (HC_EB / 16); + const int el = 16 * (threadIdx.y % (HC_EB / 16)); + const uint16_t * wr = (const uint16_t *) (w + (int64_t) (s * n_embd + e0 + el + r16) * w_row); + + // half hw of Q8_0 block b of this lane's row: d at 0, the quants at 2, 2 byte aligned; the next block's is loaded + // during the products of a block + // two blocks ahead + uint16_t wn[9], wn2[9]; + auto load_w = [&](const int b, uint16_t (&w9)[9]) { + const uint16_t * p = wr + b * (sizeof(block_q8_0) / 2); + w9[0] = p[0]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + w9[1 + j] = p[1 + 8 * hw + j]; + } + }; + load_w(0, wn); + if (K / QK8_0 > 1) { + load_w(1, wn2); + } + + hc_float8 acc[HC_TILE / 16] = {}; + const hc_float8 zero = {}; + for (int b = 0; b < K / QK8_0; ++b) { + // the quants are exact in BF16, d scales the products of the block + uint16_t wc[9]; +#pragma unroll + for (int j = 0; j < 9; ++j) { + wc[j] = wn[j]; + wn[j] = wn2[j]; + } + if (b + 2 < K / QK8_0) { + load_w(b + 2, wn2); + } + const float d = __half2float(__ushort_as_half(wc[0])); + uint32_t own[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint16_t q2 = wc[1 + j]; + own[j] = hc_pack_bf16_exact((float) (int8_t) (q2 & 0xFF), (float) (int8_t) (q2 >> 8)); + } + uint32_t fr[2][8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint32_t o = __builtin_amdgcn_permlanex16(own[j], own[j], 0x76543210u, 0xFEDCBA98u, false, false); + fr[0][j] = hw == 0 ? own[j] : o; + fr[1][j] = hw == 0 ? o : own[j]; + } + hc_float8 part[HC_TILE / 16]; +#pragma unroll + for (int hh = 0; hh < 2; ++hh) { + hc_short16 av; + __builtin_memcpy(&av, fr[hh], sizeof(av)); +#pragma unroll + for (int c = 0; c < HC_TILE / 16; ++c) { + const hc_short16 bv = *(const hc_short16 *) (ys + (16 * c + r16) * ystride + b * QK8_0 + hh * 16); + part[c] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(av, bv, hh == 0 ? zero : part[c]); + } + } + // D holds rows 2*i + lane / 16, whose scales lanes 2*i + lane / 16 have +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float dr = __shfl(d, 2 * i + hw, 32); +#pragma unroll + for (int c = 0; c < HC_TILE / 16; ++c) { + acc[c][i] = fmaf(dr, part[c][i], acc[c][i]); + } + } + } + hc_lds_sync(); // the lo tile is no longer read + + // D: lane holds token 16*c + lane % 16 and rows 2*i + lane / 16 +#pragma unroll + for (int c = 0; c < HC_TILE / 16; ++c) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float g = acc[c][i]; + gs[(s * HC_TILE + 16 * c + r16) * (HC_EB + 1) + el + 2 * i + hw] = 1.0f / (1.0f + expf(-g)); + } + } + hc_lds_sync(); + + // as dsv4_hc_pre_f32: the streams in order, then the scale +#pragma unroll + for (int it = 0; it < XT; ++it) { + const int t = tid / HC_EB + it * (32 * HC_NW / HC_EB); + if (t0 + t >= n_tokens) { + break; + } + float sum = 0.0f; +#pragma unroll + for (int ih = 0; ih < HC_N; ++ih) { + float xv = xp[it][ih]; + if (rstd != nullptr) { + xv = xv * rstd[(int64_t) (t0 + t) * HC_N + ih] * gamma[ih * n_embd + e0 + e]; + } + sum += xv * gs[(ih * HC_TILE + t) * (HC_EB + 1) + e]; + } + const float v = scale * sum; + dst[(int64_t) (t0 + t) * sd1 + e0 + e] = v; + if (dst16 != nullptr) { + const uint32_t u = __float_as_uint(v); + dst16[(int64_t) (t0 + t) * n_embd + e0 + e] = (u + 0x7FFFu + ((u >> 16) & 1u)) >> 16; + } + } +#else + GGML_UNUSED_VARS(w, w_row, K, lo, s_lo, x, sx1, sx2, rstd, gamma, dst, sd1, dst16, n_embd, n_tokens, scale); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + +bool ggml_cuda_hc_up_pre_supported(const ggml_tensor * mm, const ggml_tensor * pre) { + const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + if (!GGML_CUDA_CC_IS_RDNA3(cc) || getenv("GGML_CUDA_NO_HC_WMMA")) { + return false; + } + const ggml_tensor * w = mm->src[0]; + const ggml_tensor * lo = mm->src[1]; + const ggml_tensor * x = pre->src[0]; + const int64_t K = w->ne[0]; + return w->type == GGML_TYPE_Q8_0 && ggml_is_contiguous(w) && w->ne[2] == 1 && w->ne[3] == 1 && + K % QK8_0 == 0 && K % 4 == 0 && K <= HC_KMAX && + lo->type == GGML_TYPE_F32 && lo->nb[0] == sizeof(float) && lo->nb[1] % 16 == 0 && lo->ne[2] == 1 && lo->ne[3] == 1 && + lo->ne[1] >= 32 && + x->type == GGML_TYPE_F32 && ggml_is_contiguous(x) && x->ne[1] == HC_N && x->ne[0] % HC_EB == 0 && + x->ne[0] * HC_N == w->ne[1] && x->ne[2] == lo->ne[1] && x->ne[3] == 1 && + pre->type == GGML_TYPE_F32 && ggml_is_contiguous(pre) && ggml_get_op_params_i32(pre, 1) != 0; +} + +// x: the normalized streams, or with rstd the streams before the norm +static void hc_up_pre_run(ggml_backend_cuda_context & ctx, const ggml_tensor * mm, ggml_tensor * pre, const ggml_tensor * x, + const float * rstd, const float * gamma) { + const ggml_tensor * w = mm->src[0]; + const ggml_tensor * lo = mm->src[1]; + const int K = w->ne[0]; + const int n_embd = x->ne[0]; + const int n_tokens = x->ne[2]; + + // the pre-mix may take the memory of lo (dead after the up product) or of x (in place), which other blocks of this + // kernel may still read: the result goes to a scratch buffer then + auto overlaps = [&](const ggml_tensor * t) { + const char * a = (const char *) t->data; + const char * b = (const char *) pre->data; + return a < b + ggml_nbytes(pre) && b < a + ggml_nbytes(t); + }; + ggml_cuda_pool_alloc scratch(ctx.pool()); + float * out = (float *) pre->data; + if (overlaps(lo) || overlaps(x)) { + out = (float *) scratch.alloc(ggml_nbytes(pre)); + } + // the products of the dense and expert weights read the pre-mix as BF16 (see ggml_cuda_dense_wmma, moe_wmma_run) + uint16_t * out16 = ggml_cuda_hc_bf16_reserve(ctx, (size_t) n_embd * n_tokens); + const size_t nbytes_shared = std::max((size_t) HC_TILE * (K + 8) * sizeof(uint16_t), + (size_t) HC_N * HC_TILE * (HC_EB + 1) * sizeof(float)); + const size_t smpbo = ggml_cuda_info().devices[ggml_cuda_get_device()].smpbo; + GGML_ASSERT(nbytes_shared <= smpbo); + CUDA_SET_SHARED_MEMORY_LIMIT(hc_up_pre_kernel, smpbo); + const dim3 grid(n_embd / HC_EB, (n_tokens + HC_TILE - 1) / HC_TILE, 1); + const dim3 block(32, HC_NW, 1); + hc_up_pre_kernel<<>>( + (const uint8_t *) w->data, w->nb[1], K, (const float *) lo->data, lo->nb[1] / sizeof(float), + (const float *) x->data, x->nb[1] / sizeof(float), x->nb[2] / sizeof(float), rstd, gamma, + out, pre->nb[1] / sizeof(float), out16, n_embd, n_tokens, ggml_get_op_params_f32(pre, 0)); + CUDA_CHECK(cudaGetLastError()); + ctx.hc_bf16_src = pre; + if (out != pre->data) { + CUDA_CHECK(cudaMemcpyAsync(pre->data, out, ggml_nbytes(pre), cudaMemcpyDeviceToDevice, ctx.stream())); + } +} + +void ggml_cuda_hc_up_pre(ggml_backend_cuda_context & ctx, const ggml_tensor * mm, ggml_tensor * pre) { + hc_up_pre_run(ctx, mm, pre, pre->src[0], nullptr, nullptr); +} + +// --------------------------------------------------------------------------------------------------------------- +// The whole mix of a prompt batch from the streams x [n_embd, HC_N, T], see ggml_cuda_hc_mix_match: the RMS norm is not +// written, its scale per stream and token goes to the down product and the pre-mix, which read x. + +static constexpr int HC_DOWN_TILE = 32; // tokens per block of the down product +static constexpr int HC_DOWN_ROWS = 320; // rows of w_dn, 16 per wave +static constexpr int HC_DOWN_NW = HC_DOWN_ROWS / 16 + 1; // and one wave for the HC_N rows of w_inj +static constexpr int HC_DOWN_KC = 512; // K per chunk in LDS, within one stream + +// Block (token tile, stream s) of the down product and the injection over the K range of stream s, where +// xn = x * rstd[t, s] * gamma: the products of x * gamma (BF16 in LDS) times the rstd of the block's own sums of squares. +// The partial sums per stream go to part and part_inj; the last block of a token tile adds them in stream order: +// lo[t, r] = silu(scale * sum_s part[s, t, r]), inject[t, j] = inj_scale * sum_s part_inj[s, t, j]. +// With POST the streams are first the combine of the previous block, x = res + out * p[stream] as dsv4_hc_post_f32, +// written to x_new. The blocks of a token tile are consecutive (they read the same out). +struct hc_post_args { + const float * res; // [n_embd, HC_N, T] contiguous, possibly x_new itself + const float * out; // [n_embd, T], token stride so1 + int64_t so1; + const float * p; // p[stream * sp0 + token * sp1] + int64_t sp0, sp1; + float * x_new; // [n_embd, HC_N, T] contiguous +}; + +template +static __global__ void __launch_bounds__(32 * HC_DOWN_NW) hc_down_kernel( + const uint8_t * __restrict__ w, const int64_t w_row, const float * __restrict__ w_inj, + const float * __restrict__ x, const float * __restrict__ gamma, float * __restrict__ rstd, + float * __restrict__ part, float * __restrict__ part_inj, int * __restrict__ done, + float * __restrict__ lo, float * __restrict__ inject, + const int n_embd, const int n_tokens, const float eps, const float scale, const float inj_scale, const hc_post_args pa) { +#if defined(AMD_WMMA_256B_AVAILABLE) + constexpr int ystride = HC_DOWN_KC + 8; + __shared__ uint16_t ys[HC_DOWN_TILE * ystride]; + __shared__ float ss[HC_DOWN_TILE]; + __shared__ float ssp[HC_DOWN_TILE][HC_DOWN_KC / 128]; + __shared__ int last; + const int K = HC_N * n_embd; + const int tid = threadIdx.y * 32 + threadIdx.x; + const int t0 = blockIdx.y * HC_DOWN_TILE; + const int s = blockIdx.x; + + const int lane = threadIdx.x, hw = lane / 16, r16 = lane % 16; + const bool is_inj = threadIdx.y == HC_DOWN_ROWS / 16; + const uint8_t * wr = w + (int64_t) (16 * threadIdx.y + r16) * w_row; + const float * wi = w_inj + (int64_t) (r16 < HC_N ? r16 : 0) * K; + + // half hw of Q8_0 block kb of this lane's row, the next block's loaded during the products of a block (macros, not + // lambdas: the arrays a lambda captures stay in scratch memory) + uint16_t wn[9]; +#define HC_DOWN_LOAD_W(kb) { \ + const uint16_t * p = (const uint16_t *) (wr + (kb) * sizeof(block_q8_0)); \ + wn[0] = p[0]; \ + _Pragma("unroll") for (int j = 0; j < 8; ++j) { \ + wn[1 + j] = p[1 + 8 * hw + j]; \ + } \ + } + if (!is_inj) { + HC_DOWN_LOAD_W(s * n_embd / QK8_0); + } + + if (tid < HC_DOWN_TILE) { + ss[tid] = 0.0f; + } + hc_float8 acc[HC_DOWN_TILE / 16] = {}; + for (int k0 = s * n_embd; k0 < (s + 1) * n_embd; k0 += HC_DOWN_KC) { + hc_lds_sync(); + // the KC / 4 items of a token are whole waves + for (int i = tid; i < HC_DOWN_TILE * (HC_DOWN_KC / 4); i += 32 * HC_DOWN_NW) { + const int t = i / (HC_DOWN_KC / 4), k = 4 * (i % (HC_DOWN_KC / 4)); + float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + if (t0 + t < n_tokens) { + const int64_t o = (int64_t) (t0 + t) * K + k0 + k; + if constexpr (POST) { + const float4 r = *(const float4 *) (pa.res + o); + const float4 b = *(const float4 *) (pa.out + (int64_t) (t0 + t) * pa.so1 + k0 + k - s * n_embd); + const float pw = pa.p[s * pa.sp0 + (int64_t) (t0 + t) * pa.sp1]; + v = make_float4(b.x * pw + r.x, b.y * pw + r.y, b.z * pw + r.z, b.w * pw + r.w); + *(float4 *) (pa.x_new + o) = v; + } else { + v = *(const float4 *) (x + o); + } + } + const float sq = warp_reduce_sum<32>(v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w); + if (lane == 0) { + ssp[t][(i % (HC_DOWN_KC / 4)) / 32] = sq; + } + const float4 g = *(const float4 *) (gamma + k0 + k); + *(uint2 *) (ys + t * ystride + k) = make_uint2(hc_pack_bf16(v.x * g.x, v.y * g.y), hc_pack_bf16(v.z * g.z, v.w * g.w)); + } + hc_lds_sync(); + // the sums of squares in a fixed order, the results are the same in every run + if (tid < HC_DOWN_TILE) { +#pragma unroll + for (int q = 0; q < HC_DOWN_KC / 128; ++q) { + ss[tid] += ssp[tid][q]; + } + } + for (int b = 0; b < HC_DOWN_KC / QK8_0; ++b) { + // half hw of the 32 values of block b of this lane's row: Q8_0 with d folded in, or F32 w_inj + uint32_t own[8]; + if (!is_inj) { + uint16_t wc[9]; +#pragma unroll + for (int j = 0; j < 9; ++j) { + wc[j] = wn[j]; + } + const int kb = (k0 + b * QK8_0) / QK8_0; + if (kb + 1 < (s + 1) * n_embd / QK8_0) { + HC_DOWN_LOAD_W(kb + 1); + } + const float d = __half2float(__ushort_as_half(wc[0])); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint16_t q2 = wc[1 + j]; + own[j] = hc_pack_bf16(d * (float) (int8_t) (q2 & 0xFF), d * (float) (int8_t) (q2 >> 8)); + } + } else { +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float2 v = *(const float2 *) (wi + k0 + b * QK8_0 + 16 * hw + 2 * j); + own[j] = r16 < HC_N ? hc_pack_bf16(v.x, v.y) : 0u; + } + } + uint32_t fr[2][8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint32_t o = __builtin_amdgcn_permlanex16(own[j], own[j], 0x76543210u, 0xFEDCBA98u, false, false); + fr[0][j] = hw == 0 ? own[j] : o; + fr[1][j] = hw == 0 ? o : own[j]; + } +#pragma unroll + for (int hh = 0; hh < 2; ++hh) { + hc_short16 av; + __builtin_memcpy(&av, fr[hh], sizeof(av)); +#pragma unroll + for (int c = 0; c < HC_DOWN_TILE / 16; ++c) { + const hc_short16 bv = *(const hc_short16 *) (ys + (16 * c + r16) * ystride + b * QK8_0 + hh * 16); + acc[c] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(av, bv, acc[c]); + } + } + } + } + + hc_lds_sync(); + // D: lane holds token 16*c + lane % 16 and rows 2*i + lane / 16 + if (tid < HC_DOWN_TILE && t0 + tid < n_tokens) { + rstd[(int64_t) (t0 + tid) * HC_N + s] = rsqrtf(ss[tid] / n_embd + eps); + } +#pragma unroll + for (int c = 0; c < HC_DOWN_TILE / 16; ++c) { + const int t = t0 + 16 * c + r16; + const float r = rsqrtf(ss[16 * c + r16] / n_embd + eps); + if (is_inj) { +#pragma unroll + for (int i = 0; i < HC_N / 2; ++i) { + if (t < n_tokens) { + part_inj[((int64_t) s * n_tokens + t) * HC_N + 2 * i + hw] = r * acc[c][i]; + } + } + continue; + } + const int r0 = 16 * threadIdx.y; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float v = r * acc[c][i]; + const float vo = __uint_as_float(__builtin_amdgcn_permlanex16(__float_as_uint(v), __float_as_uint(v), 0x76543210u, 0xFEDCBA98u, false, false)); + if ((hw == 0) == (i < 4) && t < n_tokens) { + *(float2 *) (part + ((int64_t) s * n_tokens + t) * HC_DOWN_ROWS + r0 + 2 * i) = hw == 0 ? make_float2(v, vo) : make_float2(vo, v); + } + } + } + + __threadfence(); + __syncthreads(); + if (tid == 0) { + last = atomicAdd(&done[blockIdx.y], 1) == HC_N - 1; + } + __syncthreads(); + if (!last) { + return; + } + __threadfence(); + const int nt = min(HC_DOWN_TILE, n_tokens - t0); + for (int i = tid; i < nt * HC_DOWN_ROWS; i += 32 * HC_DOWN_NW) { + const int64_t o = (int64_t) t0 * HC_DOWN_ROWS + i; + float sum = 0.0f; +#pragma unroll + for (int ih = 0; ih < HC_N; ++ih) { + sum += part[(int64_t) ih * n_tokens * HC_DOWN_ROWS + o]; + } + const float v = scale * sum; + lo[o] = v / (1.0f + expf(-v)); + } + if (tid < nt * HC_N) { + const int64_t o = (int64_t) t0 * HC_N + tid; + float sum = 0.0f; +#pragma unroll + for (int ih = 0; ih < HC_N; ++ih) { + sum += part_inj[(int64_t) ih * n_tokens * HC_N + o]; + } + inject[o] = inj_scale * sum; + } +#undef HC_DOWN_LOAD_W +#else + GGML_UNUSED_VARS(w, w_row, w_inj, x, gamma, rstd, part, part_inj, done, lo, inject, n_embd, n_tokens, eps, scale, inj_scale, pa); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + +int ggml_cuda_hc_mix_match(const ggml_cgraph * cgraph, int i, ggml_cuda_hc_mix_nodes & m) { + static const bool off = getenv("GGML_CUDA_NO_HC_WMMA") != nullptr || getenv("GGML_CUDA_NO_HC_MIX") != nullptr; + static const bool dbg = getenv("GGML_CUDA_HC_MIX_DEBUG") != nullptr; + const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + if (off || !GGML_CUDA_CC_IS_RDNA3(cc) || i + 2 >= cgraph->n_nodes) { + return -1; + } +#define HC_MIX_FAIL(why) do { if (dbg) { fprintf(stderr, "hc_mix %d %s: %s\n", i, cgraph->nodes[i]->name, why); } return -1; } while (0) + m = {}; + m.rms = cgraph->nodes[i]; + ggml_tensor * mul = cgraph->nodes[i + 1]; + if (m.rms->op != GGML_OP_RMS_NORM || mul->op != GGML_OP_MUL || mul->src[0] != m.rms || m.rms->ne[2] < 32) { + return -1; + } + // the roles of the nodes after the norm, in any order: the mix ends with the last of them + int last = -1; + for (int j = i + 2; j < std::min(cgraph->n_nodes, i + 24); ++j) { + ggml_tensor * t = cgraph->nodes[j]; + bool known = true; + if (!m.xn && t->op == GGML_OP_RESHAPE && t->src[0] == mul) { + m.xn = t; + } else if (m.xn && !m.xn3 && t->op == GGML_OP_RESHAPE && t->src[0] == m.xn) { + m.xn3 = t; + } else if (m.xn && !m.inj_mm && t->op == GGML_OP_MUL_MAT && t->src[1] == m.xn && t->src[0]->type == GGML_TYPE_F32) { + m.inj_mm = t; + } else if (m.inj_mm && !m.inject && t->op == GGML_OP_SCALE && t->src[0] == m.inj_mm) { + m.inject = t; + } else if (m.xn && !m.dn_mm && t->op == GGML_OP_MUL_MAT && t->src[1] == m.xn && t->src[0]->type == GGML_TYPE_Q8_0) { + m.dn_mm = t; + } else if (m.dn_mm && !m.dn_scale && t->op == GGML_OP_SCALE && t->src[0] == m.dn_mm) { + m.dn_scale = t; + } else if (m.dn_scale && !m.lo && t->op == GGML_OP_UNARY && ggml_get_unary_op(t) == GGML_UNARY_OP_SILU && t->src[0] == m.dn_scale) { + m.lo = t; + } else if (m.lo && !m.up_mm && t->op == GGML_OP_MUL_MAT && t->src[1] == m.lo) { + m.up_mm = t; + } else if (m.up_mm && !m.gate && t->op == GGML_OP_RESHAPE && t->src[0] == m.up_mm) { + m.gate = t; + } else if (m.xn3 && m.gate && !m.pre && t->op == GGML_OP_DSV4_HC_PRE && t->src[0] == m.xn3 && t->src[1] == m.gate) { + m.pre = t; + } else { + known = false; + } + if (!known) { + if (dbg) { + fprintf(stderr, "hc_mix %d: unknown %d %s %s (src0 %s src1 %s), have xn %d xn3 %d inj %d %d dn %d %d lo %d up %d gate %d\n", i, j, + ggml_op_desc(t), t->name, t->src[0] ? t->src[0]->name : "-", t->src[1] ? t->src[1]->name : "-", + !!m.xn, !!m.xn3, !!m.inj_mm, !!m.inject, !!m.dn_mm, !!m.dn_scale, !!m.lo, !!m.up_mm, !!m.gate); + } + return -1; + } + if (m.xn && m.xn3 && m.inj_mm && m.inject && m.dn_mm && m.dn_scale && m.lo && m.up_mm && m.gate && m.pre) { + last = j; + break; + } + } + if (last < 0) { + HC_MIX_FAIL("incomplete"); + } + // the intermediate nodes are read only by the mix (views by their use count, their sources have one use each) + for (int j = i; j < last; ++j) { + ggml_tensor * t = cgraph->nodes[j]; + if (t == m.inject || t == m.pre) { + continue; + } + const int want = t == m.xn ? 3 : 1; + if (ggml_node_get_use_count(cgraph, j) != want || (t->flags & GGML_TENSOR_FLAG_OUTPUT)) { + HC_MIX_FAIL("uses"); + } + } + const ggml_tensor * x = m.rms->src[0]; + const ggml_tensor * gamma = mul->src[1]; + const ggml_tensor * w_inj = m.inj_mm->src[0]; + const ggml_tensor * w_dn = m.dn_mm->src[0]; + const int64_t n_embd = x->ne[0], T = x->ne[2]; + const bool shapes = + x->type == GGML_TYPE_F32 && ggml_is_contiguous(x) && x->ne[1] == HC_N && x->ne[3] == 1 && T >= 32 && + n_embd % HC_DOWN_KC == 0 && n_embd % HC_EB == 0 && + gamma->type == GGML_TYPE_F32 && ggml_is_contiguous(gamma) && gamma->ne[0] == n_embd && gamma->ne[1] == HC_N && ggml_nrows(gamma) == HC_N && + w_inj->type == GGML_TYPE_F32 && ggml_is_contiguous(w_inj) && w_inj->ne[0] == HC_N * n_embd && w_inj->ne[1] == HC_N && w_inj->ne[2] == 1 && + w_dn->type == GGML_TYPE_Q8_0 && ggml_is_contiguous(w_dn) && w_dn->ne[0] == HC_N * n_embd && w_dn->ne[1] == HC_DOWN_ROWS && w_dn->ne[2] == 1 && + m.inject->type == GGML_TYPE_F32 && ggml_is_contiguous(m.inject) && m.lo->type == GGML_TYPE_F32 && ggml_is_contiguous(m.lo) && + ggml_get_op_params_f32(m.inject, 1) == 0.0f && ggml_get_op_params_f32(m.dn_scale, 1) == 0.0f && + ggml_get_op_params_i32(m.pre, 1) != 0 && ggml_cuda_hc_up_pre_supported(m.up_mm, m.pre) && m.up_mm->src[0]->ne[0] == HC_DOWN_ROWS; + if (!shapes) { + HC_MIX_FAIL("shapes"); + } +#undef HC_MIX_FAIL + if (dbg) { + fprintf(stderr, "hc_mix %d: match %d\n", i, last); + } + return last; +} + +bool ggml_cuda_hc_post_mix_supported(const ggml_tensor * post, const ggml_cuda_hc_mix_nodes & m) { + static const bool off = getenv("GGML_CUDA_NO_HC_POST_MIX") != nullptr; + if (off || post->op != GGML_OP_DSV4_HC_POST || m.rms->src[0] != post || post->src[3] != nullptr) { + return false; + } + const ggml_tensor * out = post->src[0]; + const ggml_tensor * res = post->src[1]; + const ggml_tensor * pw = post->src[2]; + // the blocks of a tile read out while the others write x_new + const char * a = (const char *) out->data, * b = (const char *) post->data; + const bool overlap = a < b + ggml_nbytes(post) && b < a + ggml_nbytes(out); + return !overlap && post->type == GGML_TYPE_F32 && ggml_is_contiguous(post) && + res->type == GGML_TYPE_F32 && ggml_is_contiguous(res) && ggml_are_same_shape(res, post) && + out->type == GGML_TYPE_F32 && out->nb[0] == sizeof(float) && out->ne[0] == post->ne[0] && out->ne[1] == post->ne[2] && + out->nb[1] % 16 == 0 && ((uintptr_t) out->data) % 16 == 0 && + pw->type == GGML_TYPE_F32 && pw->ne[0] == HC_N && pw->ne[1] == post->ne[2]; +} + +void ggml_cuda_hc_mix(ggml_backend_cuda_context & ctx, const ggml_cuda_hc_mix_nodes & m, const ggml_tensor * post) { + const ggml_tensor * x = m.rms->src[0]; + const ggml_tensor * gamma = m.xn->src[0]->src[1]; + const ggml_tensor * w_inj = m.inj_mm->src[0]; + const ggml_tensor * w_dn = m.dn_mm->src[0]; + const int n_embd = x->ne[0], T = x->ne[2]; + cudaStream_t stream = ctx.stream(); + + const int n_tiles = (T + HC_DOWN_TILE - 1) / HC_DOWN_TILE; + ggml_cuda_pool_alloc rstd(ctx.pool(), (size_t) HC_N * T); + ggml_cuda_pool_alloc part(ctx.pool(), (size_t) HC_N * T * HC_DOWN_ROWS); + ggml_cuda_pool_alloc part_inj(ctx.pool(), (size_t) HC_N * T * HC_N); + ggml_cuda_pool_alloc done(ctx.pool(), n_tiles); + CUDA_CHECK(cudaMemsetAsync(done.get(), 0, n_tiles * sizeof(int), stream)); + hc_post_args pa = {}; + float * lo = (float *) m.lo->data; + float * inject = (float *) m.inject->data; + ggml_cuda_pool_alloc lo_tmp(ctx.pool()), inject_tmp(ctx.pool()); + if (post != nullptr) { + const ggml_tensor * out = post->src[0]; + const ggml_tensor * pw = post->src[2]; + pa = { (const float *) post->src[1]->data, (const float *) out->data, (int64_t) (out->nb[1] / sizeof(float)), + (const float *) pw->data, (int64_t) (pw->nb[0] / sizeof(float)), (int64_t) (pw->nb[1] / sizeof(float)), (float *) post->data }; + // lo and inject may take the memory of the inputs of the combine (dead after it), which other blocks still read + auto overlaps = [&](const ggml_tensor * t) { + for (const ggml_tensor * in : { out, (const ggml_tensor *) post->src[1], pw }) { + const char * a = (const char *) t->data, * b = (const char *) in->data; + if (a < b + ggml_nbytes(in) && b < a + ggml_nbytes(t)) { + return true; + } + } + return false; + }; + if (overlaps(m.lo)) { + lo = lo_tmp.alloc(ggml_nelements(m.lo)); + } + if (overlaps(m.inject)) { + inject = inject_tmp.alloc(ggml_nelements(m.inject)); + } + } + auto kernel = post != nullptr ? hc_down_kernel : hc_down_kernel; + kernel<<>>( + (const uint8_t *) w_dn->data, w_dn->nb[1], (const float *) w_inj->data, (const float *) x->data, (const float *) gamma->data, + rstd.get(), part.get(), part_inj.get(), done.get(), lo, inject, + n_embd, T, ggml_get_op_params_f32(m.rms, 0), ggml_get_op_params_f32(m.dn_scale, 0), ggml_get_op_params_f32(m.inject, 0), pa); + CUDA_CHECK(cudaGetLastError()); + if (lo != m.lo->data) { + CUDA_CHECK(cudaMemcpyAsync(m.lo->data, lo, ggml_nbytes(m.lo), cudaMemcpyDeviceToDevice, stream)); + } + if (inject != m.inject->data) { + CUDA_CHECK(cudaMemcpyAsync(m.inject->data, inject, ggml_nbytes(m.inject), cudaMemcpyDeviceToDevice, stream)); + } + + hc_up_pre_run(ctx, m.up_mm, m.pre, x, rstd.get(), (const float *) gamma->data); +} + +#else + +bool ggml_cuda_hc_up_pre_supported(const ggml_tensor *, const ggml_tensor *) { + return false; +} + +void ggml_cuda_hc_up_pre(ggml_backend_cuda_context &, const ggml_tensor *, ggml_tensor *) { + GGML_ABORT("fatal error"); +} + +int ggml_cuda_hc_mix_match(const ggml_cgraph *, int, ggml_cuda_hc_mix_nodes &) { + return -1; +} + +bool ggml_cuda_hc_post_mix_supported(const ggml_tensor *, const ggml_cuda_hc_mix_nodes &) { + return false; +} + +void ggml_cuda_hc_mix(ggml_backend_cuda_context &, const ggml_cuda_hc_mix_nodes &, const ggml_tensor *) { + GGML_ABORT("fatal error"); +} + +#endif // defined(GGML_USE_HIP) diff --git a/ggml/src/ggml-cuda/hc-wmma.cuh b/ggml/src/ggml-cuda/hc-wmma.cuh new file mode 100644 index 000000000000..3cbcf212eed1 --- /dev/null +++ b/ggml/src/ggml-cuda/hc-wmma.cuh @@ -0,0 +1,23 @@ +#pragma once + +#include "common.cuh" + +// The hyper-connection up product of a prompt batch and the gated pre-mix after it in one kernel (RDNA3 BF16 WMMA): +// pre = DSV4_HC_PRE(x, gate) with gate = mm = w_up . lo, w_up Q8_0. The gate is not written. +bool ggml_cuda_hc_up_pre_supported(const ggml_tensor * mm, const ggml_tensor * pre); +void ggml_cuda_hc_up_pre(ggml_backend_cuda_context & ctx, const ggml_tensor * mm, ggml_tensor * pre); + +// The whole hyper-connection mix of a prompt batch at the RMS_NORM node i, without the normalized streams xn: +// xn = RESHAPE(MUL(RMS_NORM(x), gamma)), inject = SCALE(MUL_MAT(w_inject F32, xn)), lo = SILU(SCALE(MUL_MAT(w_down Q8_0, xn))), +// pre = DSV4_HC_PRE(RESHAPE(xn), RESHAPE(MUL_MAT(w_up Q8_0, lo))), in any order with nothing else in between. +struct ggml_cuda_hc_mix_nodes { + ggml_tensor * rms, * xn, * xn3, * inj_mm, * inject, * dn_mm, * dn_scale, * lo, * up_mm, * gate, * pre; +}; +// the index of the last node of the mix, -1 if the nodes at i are not one +int ggml_cuda_hc_mix_match(const ggml_cgraph * cgraph, int i, ggml_cuda_hc_mix_nodes & m); +// with post, the DSV4_HC_POST node right before the mix that the mix's streams are, computed in the mix as well +bool ggml_cuda_hc_post_mix_supported(const ggml_tensor * post, const ggml_cuda_hc_mix_nodes & m); +void ggml_cuda_hc_mix(ggml_backend_cuda_context & ctx, const ggml_cuda_hc_mix_nodes & m, const ggml_tensor * post = nullptr); + +// ctx.hc_bf16_buf with room for n values (ggml-cuda.cu) +uint16_t * ggml_cuda_hc_bf16_reserve(ggml_backend_cuda_context & ctx, size_t n); diff --git a/ggml/src/ggml-cuda/lightning-indexer.cu b/ggml/src/ggml-cuda/lightning-indexer.cu index b7939243b74b..49025a253507 100644 --- a/ggml/src/ggml-cuda/lightning-indexer.cu +++ b/ggml/src/ggml-cuda/lightning-indexer.cu @@ -486,6 +486,199 @@ static __global__ void lightning_indexer_kernel_tile( } } +#if defined(GGML_USE_HIP) + +// RDNA3 WMMA tile kernel for few heads (4 heads of 128 dims, the Qwen QSA indexer): the 4 heads of 4 tokens make the +// 16 rows of the A operand, so the 16 keys of a column tile are scored for 4 tokens per wave. Keys are staged in half +// precision like the tile kernel does, the float queries are split into a high and a low half so that the products +// keep the float precision: q*k = (q_hi + q_lo)*k with both parts accumulated in float. The rows are ordered so that +// one lane of the accumulator holds the 4 heads of 2 tokens: row m = 2*j + g is head j%4 of token 2*(j/4) + g. +#define LIGHTNING_INDEXER_WMMA_WAVES 8 +#define LIGHTNING_INDEXER_WMMA_TOKENS (4*LIGHTNING_INDEXER_WMMA_WAVES) +#define LIGHTNING_INDEXER_WMMA_KEYS 64 // keys per staged chunk +#define LIGHTNING_INDEXER_WMMA_CHUNKS 16 // chunks per block + +template +static __global__ void __launch_bounds__(32*LIGHTNING_INDEXER_WMMA_WAVES) lightning_indexer_kernel_wmma4( + const float * Q, const char * K, const float * W, const half * M, float * dst, + int64_t n_stream, int64_t n_batch, int64_t n_kv, + size_t nb1, size_t nb2, size_t nb3, + size_t nbq1, size_t nbq2, size_t nbq3, + size_t nbk1, size_t nbk2, size_t nbk3, + size_t nbw1, size_t nbw2, size_t nbw3, + size_t nbm1, size_t nbm2, size_t nbm3, + int64_t nem3 + ) { +#if defined(AMD_WMMA_256B_AVAILABLE) + constexpr int N_EMBD = 128; + constexpr int WAVES = LIGHTNING_INDEXER_WMMA_WAVES; + constexpr int THREADS = 32*WAVES; + constexpr int KC = LIGHTNING_INDEXER_WMMA_KEYS; + constexpr int KSTEPS = N_EMBD/16; + constexpr int ROW = N_EMBD + 8; // halves, 16 byte aligned rows that do not share banks + constexpr int LOADS = KC*(N_EMBD/4)/THREADS; // float4 loads of a chunk per thread + + using halfx16_t = __attribute__((ext_vector_type(16))) _Float16; + using floatx8_t = __attribute__((ext_vector_type(8))) float; + + const int tid = threadIdx.x; + const int lane = tid % 32; + const int wave = tid / 32; + const int g = lane / 16; + const int col = lane % 16; + + const int64_t i_stream = blockIdx.z; + const int64_t tok0 = (int64_t) blockIdx.y*LIGHTNING_INDEXER_WMMA_TOKENS + wave*4; + const int64_t kv_first = (int64_t) blockIdx.x*(KC*LIGHTNING_INDEXER_WMMA_CHUNKS); + + __shared__ _Float16 k_shared[2][KC][ROW]; + + // A operand: lane col holds row m = col, that is head (m/2)%4 of token 2*(m/8) + m%2 + halfx16_t q_hi[KSTEPS]; + halfx16_t q_lo[KSTEPS]; + { + const int j = col/2; + const int t = 2*(j/4) + col%2; + const int h = j%4; + const int64_t tok = tok0 + t; + if (tok < n_batch) { + const float4 * q_row = (const float4 *) ((const char *) Q + h*nbq1 + tok*nbq2 + i_stream*nbq3); +#pragma unroll + for (int ks = 0; ks < KSTEPS; ++ks) { +#pragma unroll + for (int v = 0; v < 4; ++v) { + const float4 x = q_row[ks*4 + v]; + const float xs[4] = {x.x, x.y, x.z, x.w}; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const _Float16 hi = (_Float16) xs[e]; + q_hi[ks][v*4 + e] = hi; + q_lo[ks][v*4 + e] = (_Float16) (xs[e] - (float) hi); + } + } + } + } else { +#pragma unroll + for (int ks = 0; ks < KSTEPS; ++ks) { + q_hi[ks] = halfx16_t{}; + q_lo[ks] = halfx16_t{}; + } + } + } + + // weights of the 2 tokens this lane accumulates: token g and token 2 + g of the wave + float4 w_tok[2]; +#pragma unroll + for (int p = 0; p < 2; ++p) { + const int64_t tok = tok0 + 2*p + g; + w_tok[p] = tok < n_batch ? + *(const float4 *) ((const char *) W + tok*nbw1 + i_stream*nbw3) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + + const int64_t tok_out[2] = {tok0 + g, tok0 + 2 + g}; + const half * m_base[2]; + float * d_base[2]; +#pragma unroll + for (int p = 0; p < 2; ++p) { + m_base[p] = (const half *) ((const char *) M + tok_out[p]*nbm1 + (i_stream%nem3)*nbm3); + d_base[p] = (float *) ((char *) dst + tok_out[p]*nb1 + i_stream*nb3); + } + + // chunk staging: a thread converts LOADS float4 of the chunk to half + float4 k_regs[LOADS]; + auto load_chunk = [&](const int64_t kv0) { +#pragma unroll + for (int l = 0; l < LOADS; ++l) { + const int i = tid + l*THREADS; + const int r = i / (N_EMBD/4); + const int c4 = i % (N_EMBD/4); + float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + if (kv0 + r < n_kv) { + const char * k_row = K + (kv0 + r)*nbk2 + i_stream*nbk3; + if constexpr (TYPE_K == GGML_TYPE_F32) { + v = ((const float4 *) k_row)[c4]; + } else { + const half2 lo = ((const half2 *) k_row)[2*c4 + 0]; + const half2 hi = ((const half2 *) k_row)[2*c4 + 1]; + v = make_float4(__low2float(lo), __high2float(lo), __low2float(hi), __high2float(hi)); + } + } + k_regs[l] = v; + } + }; + auto store_chunk = [&](const int buf) { +#pragma unroll + for (int l = 0; l < LOADS; ++l) { + const int i = tid + l*THREADS; + const int r = i / (N_EMBD/4); + const int c4 = i % (N_EMBD/4); + typedef __attribute__((ext_vector_type(4))) _Float16 halfx4_t; + const halfx4_t h4 = {(_Float16) k_regs[l].x, (_Float16) k_regs[l].y, (_Float16) k_regs[l].z, (_Float16) k_regs[l].w}; + *(halfx4_t *) &k_shared[buf][r][c4*4] = h4; + } + }; + + int n_chunks = (int) ((n_kv - kv_first + KC - 1) / KC); + n_chunks = n_chunks < LIGHTNING_INDEXER_WMMA_CHUNKS ? n_chunks : LIGHTNING_INDEXER_WMMA_CHUNKS; + + load_chunk(kv_first); + store_chunk(0); + __syncthreads(); + + for (int c = 0; c < n_chunks; ++c) { + const int64_t kv0 = kv_first + (int64_t) c*KC; + const bool has_next = c + 1 < n_chunks; + if (has_next) { + load_chunk(kv0 + KC); + } + +#pragma unroll + for (int nt = 0; nt < KC/16; ++nt) { + floatx8_t acc_hi = {0, 0, 0, 0, 0, 0, 0, 0}; + floatx8_t acc_lo = {0, 0, 0, 0, 0, 0, 0, 0}; +#pragma unroll + for (int ks = 0; ks < KSTEPS; ++ks) { + // B operand: lane col holds the 16 dims of key col of the tile + const int4 * b_ptr = (const int4 *) &k_shared[c & 1][nt*16 + col][ks*16]; + const int4 b0 = b_ptr[0]; + const int4 b1 = b_ptr[1]; + union { int4 i[2]; halfx16_t h; } b; + b.i[0] = b0; + b.i[1] = b1; + acc_hi = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(q_hi[ks], b.h, acc_hi); + acc_lo = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(q_lo[ks], b.h, acc_lo); + } + + // accumulator i of this lane is row 2*i + g: head i%4 of token 2*(i/4) + g, key col of the tile + const int64_t i_kv = kv0 + nt*16 + col; + if (i_kv < n_kv) { +#pragma unroll + for (int p = 0; p < 2; ++p) { + if (tok_out[p] < n_batch) { + float s = fmaxf(acc_hi[4*p + 0] + acc_lo[4*p + 0], 0.0f) * w_tok[p].x; + s = fmaf(fmaxf(acc_hi[4*p + 1] + acc_lo[4*p + 1], 0.0f), w_tok[p].y, s); + s = fmaf(fmaxf(acc_hi[4*p + 2] + acc_lo[4*p + 2], 0.0f), w_tok[p].z, s); + s = fmaf(fmaxf(acc_hi[4*p + 3] + acc_lo[4*p + 3], 0.0f), w_tok[p].w, s); + d_base[p][i_kv] = s + __half2float(m_base[p][i_kv]); + } + } + } + } + + if (has_next) { + store_chunk((c + 1) & 1); + } + __syncthreads(); + } +#else + GGML_UNUSED_VARS(Q, K, W, M, dst, n_stream, n_batch, n_kv, nb1, nb2, nb3, nbq1, nbq2, nbq3, nbk1, nbk2, nbk3, + nbw1, nbw2, nbw3, nbm1, nbm2, nbm3, nem3); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + +#endif // defined(GGML_USE_HIP) + #define LIGHTNING_INDEXER_CASE(lightning_indexer_kernel, n_embd, n_head, K, type_K) \ if (K->type == (type_K)) { \ lightning_indexer_kernel \ @@ -550,6 +743,30 @@ void ggml_cuda_lightning_indexer(ggml_backend_cuda_context & ctx, ggml_tensor * const int device = ggml_cuda_get_device(); const int cc = ggml_cuda_info().devices[device].cc; +#if defined(GGML_USE_HIP) + // 4 heads of 128 dims, prompt batches of the Qwen QSA indexer: WMMA on the 4 heads of 4 tokens + static const int env_wmma = ggml_cuda_env_switch("GGML_HIP_INDEXER_WMMA"); + if (n_embd == 128 && n_head == 4 && n_batch >= 16 && GGML_CUDA_CC_IS_RDNA3(cc) && + (k->type == GGML_TYPE_F32 || k->type == GGML_TYPE_F16) && ggml_cuda_switch_or_rdna3_5(env_wmma, cc)) { + constexpr int KEYS_PER_BLOCK = LIGHTNING_INDEXER_WMMA_KEYS*LIGHTNING_INDEXER_WMMA_CHUNKS; + + dim3 block(32*LIGHTNING_INDEXER_WMMA_WAVES, 1, 1); + dim3 grid((n_kv + KEYS_PER_BLOCK - 1)/KEYS_PER_BLOCK, (n_batch + LIGHTNING_INDEXER_WMMA_TOKENS - 1)/LIGHTNING_INDEXER_WMMA_TOKENS, n_stream); + + if (k->type == GGML_TYPE_F32) { + lightning_indexer_kernel_wmma4<<>>( + q_d, k_d, w_d, m_d, dst_d, n_stream, n_batch, n_kv, nb1, nb2, nb3, nbq1, nbq2, nbq3, + nbk1, nbk2, nbk3, nbw1, nbw2, nbw3, nbm1, nbm2, nbm3, nem3); + } else { + lightning_indexer_kernel_wmma4<<>>( + q_d, k_d, w_d, m_d, dst_d, n_stream, n_batch, n_kv, nb1, nb2, nb3, nbq1, nbq2, nbq3, + nbk1, nbk2, nbk3, nbw1, nbw2, nbw3, nbm1, nbm2, nbm3, nem3); + } + CUDA_CHECK(cudaGetLastError()); + return; + } +#endif // defined(GGML_USE_HIP) + if (n_embd == 128 && n_head == 64) { if ((turing_mma_available(cc) || amd_mfma_available(cc) || amd_wmma_available(cc)) && k->type != GGML_TYPE_F32 && k->type != GGML_TYPE_BF16) { constexpr int K_VECS_PER_BLOCK = 32; diff --git a/ggml/src/ggml-cuda/mmid.cu b/ggml/src/ggml-cuda/mmid.cu index 64de4fb27b60..9d23b5d5cf2d 100644 --- a/ggml/src/ggml-cuda/mmid.cu +++ b/ggml/src/ggml-cuda/mmid.cu @@ -30,8 +30,9 @@ template <> struct mm_ids_pow2<0> { static constexpr int value = 1; }; // The first (n_tokens*n_expert_used + J - 1) / tile_width elements of tile_spec contain the specication for // matrix multiplication tiles at token positions which are exactly divided by tile_width. // Additionally the following n_expert elements of tile_spec may contain additional tiles that fall between these seams. -template -__launch_bounds__(ggml_cuda_get_physical_warp_size(), 1) +// Each of the nwarps warps of a block scans a contiguous chunk of the tokens, so the compact slice stays sorted by token. +template +__launch_bounds__(nwarps*ggml_cuda_get_physical_warp_size(), 1) static __global__ void mm_ids_helper( const int32_t * __restrict__ ids, int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, ggml_cuda_mm_id_tile_spec * __restrict__ tile_spec, @@ -40,16 +41,24 @@ static __global__ void mm_ids_helper( constexpr int warp_size = ggml_cuda_get_physical_warp_size(); const int n_expert_used = n_expert_used_template == 0 ? n_expert_used_var : n_expert_used_template; const int expert = blockIdx.x; + const int warp = threadIdx.y; extern __shared__ char data_mm_ids_helper[]; mm_ids_helper_store * store = (mm_ids_helper_store *) data_mm_ids_helper; + __shared__ int warp_compact[nwarps]; + __shared__ int warp_nex_prev[nwarps]; + + // the chunk of this warp, whose entries go to store[it_begin..] + const int chunk = (n_tokens + nwarps - 1) / nwarps; + const int it_begin = min(n_tokens, warp*chunk); + const int it_end = min(n_tokens, it_begin + chunk); int nex_prev = 0; // Number of columns for experts with a lower index. int it_compact = 0; // Running index for the compact slice of this expert. if constexpr (n_expert_used_template == 0) { // Generic implementation: - for (int it = 0; it < n_tokens; ++it) { + for (int it = it_begin; it < it_end; ++it) { int iex_used = -1; // The index at which the expert is used, if any. for (int iex = threadIdx.x; iex < n_expert_used; iex += warp_size) { const int expert_used = ids[it*si1 + iex]; @@ -60,7 +69,7 @@ static __global__ void mm_ids_helper( } if (iex_used != -1) { - store[it_compact] = mm_ids_helper_store(it, iex_used); + store[it_begin + it_compact] = mm_ids_helper_store(it, iex_used); } if (warp_reduce_any(iex_used != -1)) { @@ -72,11 +81,11 @@ static __global__ void mm_ids_helper( // a warp holds a whole number of token slots, so the slot count is padded to a power of 2 constexpr int neu_padded = mm_ids_pow2::value; static_assert(neu_padded <= warp_size && warp_size % neu_padded == 0, "bad n_expert_used"); - for (int it0 = 0; it0 < n_tokens; it0 += warp_size/neu_padded) { + for (int it0 = it_begin; it0 < it_end; it0 += warp_size/neu_padded) { const int it = it0 + threadIdx.x / neu_padded; const int iex = threadIdx.x % neu_padded; // The index at which the expert is used, if any. - const int expert_used = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + const int expert_used = (neu_padded == n_expert_used || iex < n_expert_used) && it < it_end ? ids[it*si1 + iex] : INT_MAX; const int iex_used = expert_used == expert ? iex : -1; nex_prev += expert_used < expert; @@ -95,7 +104,7 @@ static __global__ void mm_ids_helper( } if (iex_used != -1) { - store[it_compact + it_compact_add_lower] = mm_ids_helper_store(it, iex_used); + store[it_begin + it_compact + it_compact_add_lower] = mm_ids_helper_store(it, iex_used); } // The thread with the highest index in the warp always has the sum over the whole warp, use it to increment all threads: @@ -103,27 +112,43 @@ static __global__ void mm_ids_helper( } } nex_prev = warp_reduce_sum(nex_prev); - ggml_cuda_syncwarp(); + if (threadIdx.x == 0) { + warp_compact[warp] = it_compact; + warp_nex_prev[warp] = nex_prev; + } + __syncthreads(); + + // the compact rows of this warp follow those of the warps with lower token chunks + int compact_offset = 0; + int compact_total = 0; + nex_prev = 0; +#pragma unroll + for (int w = 0; w < nwarps; ++w) { + compact_offset += w < warp ? warp_compact[w] : 0; + compact_total += warp_compact[w]; + nex_prev += warp_nex_prev[w]; + } for (int itc = threadIdx.x; itc < it_compact; itc += warp_size) { - const mm_ids_helper_store store_it = store[itc]; + const mm_ids_helper_store store_it = store[it_begin + itc]; const int it = store_it.it(); const int iex_used = store_it.iex_used(); - ids_dst[nex_prev + itc] = it*n_expert_used + iex_used; + const int ic = nex_prev + compact_offset + itc; + ids_dst[ic] = it*n_expert_used + iex_used; // ids_src1 holds the forward map, or the inverse map (token slot -> compact row) for quant dedup if (write_inverse) { - ids_src1[it*n_expert_used + iex_used] = nex_prev + itc; + ids_src1[it*n_expert_used + iex_used] = ic; } else { - ids_src1[nex_prev + itc] = it*sis1 + iex_used % nchannels_y; + ids_src1[ic] = it*sis1 + iex_used % nchannels_y; } } - if (threadIdx.x != 0) { + if (threadIdx.x != 0 || threadIdx.y != 0) { return; } int col_low = nex_prev; - int col_high = nex_prev + min(int(tile_width.z), it_compact); + int col_high = nex_prev + min(int(tile_width.z), compact_total); // The while loop covers all tiles at the seams containing the column with % tile_width == 0. while (col_high > fastdiv(col_low + tile_width.z - 1, tile_width) * tile_width.z) { @@ -131,7 +156,7 @@ static __global__ void mm_ids_helper( = {expert, col_low, col_high, /*padding =*/ 0}; col_low = col_high; - col_high = min(col_high + int(tile_width.z), nex_prev + it_compact); + col_high = min(col_high + int(tile_width.z), nex_prev + compact_total); } // Finally, at most one extra tile_spec between the seams per expert. @@ -151,16 +176,23 @@ static void launch_mm_ids_helper( const int id = ggml_cuda_get_device(); const int warp_size = ggml_cuda_info().devices[id].warp_size; const size_t smpbo = ggml_cuda_info().devices[id].smpbo; - CUDA_SET_SHARED_MEMORY_LIMIT(mm_ids_helper, smpbo); + // 8 warps per expert to scan the tokens of a prompt batch, one warp for a few tokens + constexpr int nwarps = 8; const uint3 tile_width_fd = init_fastdiv_values(tile_width); const dim3 num_blocks(n_experts, 1, 1); - const dim3 block_size(warp_size, 1, 1); const size_t nbytes_shared = n_tokens*sizeof(mm_ids_helper_store); - GGML_ASSERT(nbytes_shared <= smpbo); - mm_ids_helper<<>> - (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse); + GGML_ASSERT(nbytes_shared + 2*nwarps*sizeof(int) <= smpbo); + if (n_tokens >= 4*nwarps) { + CUDA_SET_SHARED_MEMORY_LIMIT((mm_ids_helper), smpbo); + mm_ids_helper<<>> + (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse); + } else { + CUDA_SET_SHARED_MEMORY_LIMIT((mm_ids_helper), smpbo); + mm_ids_helper<<>> + (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse); + } } void ggml_cuda_launch_mm_ids_helper( diff --git a/ggml/src/ggml-cuda/mmq.cu b/ggml/src/ggml-cuda/mmq.cu index 2e6199766839..4992b6b08aec 100644 --- a/ggml/src/ggml-cuda/mmq.cu +++ b/ggml/src/ggml-cuda/mmq.cu @@ -139,6 +139,10 @@ static int ggml_cuda_mmq_get_J_best( int ntiles_J_best = INT_MAX; for (int J = 8; J <= 128 && ntiles_J_best > 1; J += 8) { + // the J = 32 kernels use all 256 VGPRs and spill on RDNA3.5 + if (J == 32 && GGML_CUDA_CC_IS_RDNA3_5(cc)) { + continue; + } const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc, prec_src1); if (config.type == GGML_TYPE_COUNT) { continue; @@ -269,14 +273,24 @@ void ggml_cuda_mul_mat_q( if (!ids) { const int ntj = (ne1 + J_best - 1) / J_best; + // a fused HC norm may have written the q8_1 copy of src1 for this MUL_MAT already (see ggml_cuda_hc_norm_mmq_q8_1) + const bool prepared = ctx.mmq_q8_1_dst == dst && ctx.mmq_q8_1_data == src1->data && !use_native_fp4 && + mmq_get_q8_1_ds_layout(src0->type) == MMQ_Q8_1_DS_LAYOUT_D4 && ne10_padded == ne10 && ne12 == 1 && ne13 == 1; + if (prepared) { + ctx.mmq_q8_1_dst = nullptr; + } + const size_t nbytes_src1_q8_1 = ne13*ne12 * ne11*ne10_padded * y_block_size/y_values_per_block + src1_q8_1_padding; - ggml_cuda_pool_alloc src1_q8_1(ctx.pool(), nbytes_src1_q8_1); + ggml_cuda_pool_alloc src1_q8_1(ctx.pool()); + if (!prepared) { + src1_q8_1.alloc(nbytes_src1_q8_1); + } ggml_cuda_pool_alloc src1_scale(ctx.pool()); if (src0->type == GGML_TYPE_NVFP4 && use_native_fp4) { src1_scale.alloc(ne13*ne12*ne11); } - { + if (!prepared) { const int64_t s11 = src1->nb[1] / ts_src1; const int64_t s12 = src1->nb[2] / ts_src1; const int64_t s13 = src1->nb[3] / ts_src1; @@ -301,7 +315,7 @@ void ggml_cuda_mul_mat_q( const int64_t s13 = ne12*s12; const mmq_args args = { - src0_d, src0->type, (const int *) src1_q8_1.ptr, nullptr, nullptr, dst_d, + src0_d, src0->type, prepared ? (const int *) ctx.mmq_q8_1_buf : (const int *) src1_q8_1.ptr, nullptr, nullptr, dst_d, src0->type == GGML_TYPE_NVFP4 && use_native_fp4 ? src1_scale.ptr : nullptr, ne00, ne01, ne1, s01, ne11, s1, ne02, ne12, s02, s12, s2, diff --git a/ggml/src/ggml-cuda/mmq.cuh b/ggml/src/ggml-cuda/mmq.cuh index d645a8aacd4d..8aaabc0a76df 100644 --- a/ggml/src/ggml-cuda/mmq.cuh +++ b/ggml/src/ggml-cuda/mmq.cuh @@ -1018,7 +1018,9 @@ static __device__ __forceinline__ void mul_mat_q_process_tile( // The mul_mat_q kernel implements "stream-k" work partitioning as described in https://arxiv.org/abs/2301.03598 -template +// ksplit: compile the stream-k body for one Q8_0 tile even when the arch config leaves stream-k off, +// so a few-row prefill can cut K without changing every other Q8_0 matmul. +template __launch_bounds__(ggml_cuda_mmq_get_nthreads(type, J, fallback, prec_src1), ggml_cuda_mmq_get_occupancy(type, J, fallback, prec_src1)) static __global__ void mul_mat_q( const char * __restrict__ x, const char * __restrict__ x_gate, const int * __restrict__ y, const int32_t * __restrict__ ids_dst, @@ -1072,7 +1074,7 @@ static __global__ void mul_mat_q( __syncthreads(); // The fused kernel needs the whole K range of a tile in one block, so it always uses tiling. - if constexpr (has_fusion || !ggml_cuda_mmq_get_stream_k(type, J, fallback, prec_src1)) { + if constexpr (has_fusion || (!ggml_cuda_mmq_get_stream_k(type, J, fallback, prec_src1) && !ksplit)) { // The fused kernel writes the GLU of I/2 up rows and I/2 gate rows per tile. constexpr int I_dst = has_fusion ? I/2 : I; @@ -1498,6 +1500,53 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a const uint3 channel_ratio_fd = init_fastdiv_values(channel_ratio); const uint3 sample_ratio_fd = init_fastdiv_values(sample_ratio); + // Q8_0 with a few output rows and a long K (HC down, 320 x 10240) leaves too few tiles to hide + // DRAM latency. Cut K into `splits` slices per tile and add the partials with the stream-k fixup. + // The RDNA stream-k launch caps the grid at nsm, which is the wrong direction here, so this path + // launches splits * ntiles blocks instead of turning config.stream_k on for every Q8_0 matmul. + if constexpr (!has_fusion && type == GGML_TYPE_Q8_0 && J == 128 && fallback) { + static int ksplit_env = -2; + if (ksplit_env == -2) { + const char * env = getenv("GGML_HIP_MMQ_KSPLIT"); + ksplit_env = env ? atoi(env) : 4; + } + const int qk = ggml_cuda_type_traits::qk; + const bool few_rows = ksplit_env > 1 && args.ids_dst == nullptr && GGML_CUDA_CC_IS_RDNA3_5(cc) && + args.nrows_x >= 256 && args.nrows_x <= 384 && args.ncols_x >= 8192 && args.ncols_dst >= 32 && + args.nchannels_y == 1 && args.nsamples_y == 1 && args.ncols_x % qk == 0; + if (few_rows) { + const int k_blocks = (int) (args.ncols_x / qk); + int splits = ksplit_env; + while (splits > 1 && k_blocks % splits != 0) { + --splits; + } + if (splits > 1) { + CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q), nbytes_shared); + const int ntiles = (int) args.ntj * nti * ntzw; + const int nblocks = ntiles * splits; + ggml_cuda_pool & pool = ctx.pool(id); + ggml_cuda_pool_alloc tmp_fixup(pool); + tmp_fixup.alloc((size_t) nblocks * config.J * config.I); + const dim3 block_nums(nblocks, 1, 1); + mul_mat_q<<>> + (args.x, (const char *) args.fusion.gate, args.y, args.ids_dst, args.tile_spec, args.dst, tmp_fixup.ptr, + args.y_scale, args.fusion.glu_op, args.fusion.glu_limit, (const float *) args.fusion.x_scale, (const float *) args.fusion.gate_scale, + blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst, + channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst, + sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst, + ntj_fd); + const dim3 block_nums_fixup(nblocks, config.I / warp_size, 1); + const dim3 block_dims_fixup(block_dims.x, block_dims.y / 2, block_dims.z); + CUDA_CHECK(cudaGetLastError()); + mul_mat_q_stream_k_fixup<<>> + (args.ids_dst, args.tile_spec, args.dst, tmp_fixup.ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, + args.nrows_dst, nchannels_y_fd, args.stride_channel_dst, nsamples_y_fd, args.stride_sample_dst, + ntj_fd); + return; + } + } + } + if (has_fusion || !config.stream_k) { GGML_ASSERT(nti <= 65535); // gridDim.y limit mul_mat_q<<>> diff --git a/ggml/src/ggml-cuda/mmvf.cu b/ggml/src/ggml-cuda/mmvf.cu index 154a621fac92..7c5aa4c60146 100644 --- a/ggml/src/ggml-cuda/mmvf.cu +++ b/ggml/src/ggml-cuda/mmvf.cu @@ -505,6 +505,17 @@ void launch_mul_mat_vec_f_cuda( block_size_best = block_size; } } + // RDNA3.5: a grid of a few blocks (tiny f32 projections in decode) is latency bound, shorten its K loop + if (ncols_dst == 1 && GGML_CUDA_CC_IS_RDNA3_5(ggml_cuda_info().devices[device].cc) && + nrows*nchannels_dst*nsamples_or_ntokens < ggml_cuda_info().devices[device].nsm) { + for (int64_t block_size : {512, 1024}) { + const int64_t niter = (ncols + 2*block_size - 1) / (2*block_size); + if (niter < niter_best) { + niter_best = niter; + block_size_best = block_size; + } + } + } const bool has_fusion = fusion.gate != nullptr || fusion.x_bias != nullptr || fusion.gate_bias != nullptr; @@ -560,6 +571,22 @@ void launch_mul_mat_vec_f_cuda( channel_ratio_fd, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio_fd, stride_sample_x, stride_sample_y, stride_sample_dst, block_dims, block_nums, nbytes_shared, ids_stride, stream); } break; + case 512: { + if constexpr (ncols_dst == 1) { + mul_mat_vec_f_switch_fusion + (x, y, ids, fusion, dst, ncols/2, nchannels_y_fd, stride_row, stride_col_y/2, stride_col_dst, + channel_ratio_fd, stride_channel_x, stride_channel_y, stride_channel_dst, + sample_ratio_fd, stride_sample_x, stride_sample_y, stride_sample_dst, block_dims, block_nums, nbytes_shared, ids_stride, stream); + } + } break; + case 1024: { + if constexpr (ncols_dst == 1) { + mul_mat_vec_f_switch_fusion + (x, y, ids, fusion, dst, ncols/2, nchannels_y_fd, stride_row, stride_col_y/2, stride_col_dst, + channel_ratio_fd, stride_channel_x, stride_channel_y, stride_channel_dst, + sample_ratio_fd, stride_sample_x, stride_sample_y, stride_sample_dst, block_dims, block_nums, nbytes_shared, ids_stride, stream); + } + } break; default: GGML_ABORT("fatal error"); } diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 66ccb212ad7f..8b04e357cb82 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -1,4 +1,6 @@ #include "mmvq.cuh" +#include "moe-wmma.cuh" +#include "moe-wmma-vecdot.cuh" #include "quantize.cuh" #include "unary.cuh" #include "vecdotq.cuh" @@ -1677,3 +1679,824 @@ void ggml_cuda_op_mul_mat_vec_q( GGML_UNUSED_VARS(src1, dst, src1_ddf_i, src1_ncols, src1_padded_row_size); } + +// The hyper-connection pre-mix of qwen4exp fused with the MMVQ product that makes its gate, for one token: warp w of +// block b computes the hc gate rows of position i = 32*b + w, each as mul_mat_vec_q does with one warp per row and +// block (the RDNA3.5 parameters), then dst[i] = scale * sum_s x[i, s] * sigmoid(gate[s*n_embd + i]) as dsv4_hc_pre_f32 +// does. The 32 positions of a block make one block of MMVQ's q8_1 copy of dst. +// With quantize_y the warps of the block first quantize y_f32 (ne10 values, at most 32 blocks) to q8_1 in shared memory +// as quantize_q8_1 does. +template +__launch_bounds__(QK8_1*QK8_1, 1) +static __global__ void mul_mat_vec_q_hc_pre( + const void * __restrict__ vx, const block_q8_1 * __restrict__ y, const float * __restrict__ y_f32, + const float * __restrict__ x, float * __restrict__ dst, block_q8_1 * __restrict__ q8_1, const int ncols_x, + const int ne10, const int stride_row_x, const int n_embd, const int hc, const float scale, + const float * __restrict__ inj_w, const float * __restrict__ inj_x, float * __restrict__ inj_dst, const int inj_ncols2, + const int inj_stride_row) { + constexpr int qk = ggml_cuda_type_traits::qk; + constexpr int qi = ggml_cuda_type_traits::qi; + constexpr int vdr = get_vdr_mmvq(type); + constexpr int warp_size = QK8_1; + constexpr int blocks_per_iter = vdr * warp_size / qi; + constexpr vec_dot_q_cuda_t vec_dot_q_cuda = get_vec_dot_q_cuda(type); + + // the injection product goes first, block 0, as its rows take longer than a block of positions + const int b = inj_dst != nullptr ? (int) blockIdx.x - 1 : (int) blockIdx.x; + const int tid = threadIdx.x; + const int i = b*warp_size + threadIdx.y; + const int blocks_per_row_x = ncols_x / qk; + + if (b < 0) { + // the extra block: the hc rows of the injection product, each by 8 warps as mul_mat_vec_f sums a row with 256 + // threads (F32 weights) + constexpr int inj_block_size = 256; + const int r = threadIdx.y / (inj_block_size/warp_size); + const int iw = threadIdx.y % (inj_block_size/warp_size); + __shared__ float buf_iw[warp_size][warp_size]; + buf_iw[threadIdx.y][tid] = 0.0f; + __syncthreads(); + float sumf = 0.0f; + if (r < hc) { + const float2 * x2 = (const float2 *) (inj_w + (int64_t) r*inj_stride_row); + const float2 * y2 = (const float2 *) inj_x; + for (int col2 = iw*warp_size + tid; col2 < inj_ncols2; col2 += inj_block_size) { + const float2 tmpx = x2[col2]; + const float2 tmpy = y2[col2]; + ggml_cuda_mad(sumf, tmpx.x, tmpy.x); + ggml_cuda_mad(sumf, tmpx.y, tmpy.y); + } + } + sumf = warp_reduce_sum(sumf); + buf_iw[r][iw] = sumf; + __syncthreads(); + if (iw == 0 && r < hc) { + sumf = buf_iw[r][tid]; + sumf = warp_reduce_sum(sumf); + if (tid == 0) { + inj_dst[r] = sumf; + } + } + return; + } + + __shared__ block_q8_1 y_shared[quantize_y ? warp_size : 1]; + if constexpr (quantize_y) { + if (threadIdx.y < ncols_x / QK8_1) { + const int k = threadIdx.y*QK8_1 + tid; + const float xi = k < ne10 ? y_f32[k] : 0.0f; + const float amax = warp_reduce_max(fabsf(xi)); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const int sum_q = warp_reduce_sum((int) q); + y_shared[threadIdx.y].qs[tid] = q; + if (tid == 0) { + y_shared[threadIdx.y].ds = make_half2(d, d * sum_q); + } + } + __syncthreads(); + } + // not through y, whose restrict lets the compiler move its loads before the barrier + const block_q8_1 * y_row = quantize_y ? y_shared : y; + + float sum = 0.0f; + for (int ih = 0; ih < hc; ++ih) { + const int row = ih*n_embd + i; + float gate = 0.0f; + for (int kbx = tid / (qi/vdr); kbx < blocks_per_row_x; kbx += blocks_per_iter) { + const int kby = kbx * (qk/QK8_1); + const int kqs = vdr * (tid % (qi/vdr)); + gate += vec_dot_q_cuda(vx, &y_row[kby], row*stride_row_x + kbx, kqs); + } + gate = warp_reduce_sum(gate); + + const float xv = x[ih*n_embd + i]; + const float wv = 1.0f / (1.0f + expf(-gate)); + sum += xv * wv; + } + + const float v = scale * sum; + __shared__ float v_shared[warp_size]; + if (tid == 0) { + dst[i] = v; + v_shared[threadIdx.y] = v; + } + if (q8_1 == nullptr) { + return; + } + __syncthreads(); + if (threadIdx.y != 0) { + return; + } + + const float vq = v_shared[tid]; + const float amax = warp_reduce_max(fabsf(vq)); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(vq / d); + const int sum_q = warp_reduce_sum((int) q); + block_q8_1 & yb = q8_1[b]; + yb.qs[tid] = q; + if (tid == 0) { + yb.ds = make_half2(d, d * sum_q); + } +} + +// the q8_1 copy of src1 (one row) as ggml_cuda_mul_mat_vec_q makes it once per graph evaluation, see ggml_cuda_q8_1_cache +static const char * ggml_cuda_mmvq_src1_q8_1(ggml_backend_cuda_context & ctx, const ggml_tensor * src1, + ggml_cuda_pool_alloc & pool) { + const char * src1_q8_1 = ctx.q8_1_cache.find(src1); + if (src1_q8_1 != nullptr) { + return src1_q8_1; + } + const int64_t ne10 = src1->ne[0]; + const int64_t ne10_padded = GGML_PAD(ne10, MATRIX_ROW_PADDING); + const size_t nbytes_src1_q8_1 = ne10_padded * sizeof(block_q8_1)/QK8_1; + char * buf = ctx.q8_1_cache.reserve(nbytes_src1_q8_1); + const bool cached = buf != nullptr; + if (!cached) { + buf = pool.alloc(nbytes_src1_q8_1); + } + const int64_t s11 = src1->nb[1] / sizeof(float); + const int64_t s12 = src1->nb[2] / sizeof(float); + const int64_t s13 = src1->nb[3] / sizeof(float); + quantize_row_q8_1_cuda((const float *) src1->data, buf, ne10, s11, s12, s13, ne10_padded, 1, 1, 1, ctx.stream()); + if (cached) { + ctx.q8_1_cache.commit(src1); + } + return buf; +} + +// silu(s*(row . y) + b), the MMVQ product for one token followed by SCALE -> SILU, each row summed as mul_mat_vec_q does +// with one warp per row and block (the RDNA3.5 parameters for one column) +template +__launch_bounds__(QK8_1, 1) +static __global__ void mul_mat_vec_q_scale_silu( + const void * __restrict__ vx, const block_q8_1 * __restrict__ y, float * __restrict__ dst, + float * __restrict__ dst_copy, const int ncols_x, const int stride_row_x, const float s, const float b) { + constexpr int qk = ggml_cuda_type_traits::qk; + constexpr int qi = ggml_cuda_type_traits::qi; + constexpr int vdr = get_vdr_mmvq(type); + constexpr int warp_size = QK8_1; + constexpr int blocks_per_iter = vdr * warp_size / qi; + constexpr vec_dot_q_cuda_t vec_dot_q_cuda = get_vec_dot_q_cuda(type); + + const int tid = threadIdx.x; + const int row = blockIdx.x; + const int blocks_per_row_x = ncols_x / qk; + + float tmp = 0.0f; + for (int kbx = tid / (qi/vdr); kbx < blocks_per_row_x; kbx += blocks_per_iter) { + const int kby = kbx * (qk/QK8_1); + const int kqs = vdr * (tid % (qi/vdr)); + tmp += vec_dot_q_cuda(vx, &y[kby], row*stride_row_x + kbx, kqs); + } + tmp = warp_reduce_sum(tmp); + + if (tid == 0) { + const float v = ggml_cuda_op_silu_single(s * tmp + b); + dst[row] = v; + if (dst_copy != nullptr) { + dst_copy[row] = v; + } + } +} + +void ggml_cuda_mul_mat_vec_q_scale_silu(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, + const ggml_tensor * scale_node, ggml_tensor * unary_node, float * dst_copy) { + ggml_cuda_pool_alloc src1_q8_1_pool(ctx.pool()); + const char * src1_q8_1 = ggml_cuda_mmvq_src1_q8_1(ctx, src1, src1_q8_1_pool); + + float s; + float b; + memcpy(&s, (const float *) scale_node->op_params + 0, sizeof(float)); + memcpy(&b, (const float *) scale_node->op_params + 1, sizeof(float)); + + ctx.q8_1_cache.invalidate(unary_node); + switch (src0->type) { + case GGML_TYPE_Q8_0: + mul_mat_vec_q_scale_silu<<ne[1], QK8_1, 0, ctx.stream()>>>( + src0->data, (const block_q8_1 *) src1_q8_1, (float *) unary_node->data, dst_copy, src0->ne[0], + src0->nb[1] / ggml_type_size(src0->type), s, b); + break; + default: + GGML_ABORT("unsupported type for the fused MMVQ + scale + silu"); + } +} + +void ggml_cuda_mul_mat_vec_q_hc_pre(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, + const float * src1_copy, ggml_tensor * hc_pre, const bool write_q8_1, + const ggml_tensor * inject, float * inject_dst) { + const ggml_tensor * x = hc_pre->src[0]; + cudaStream_t stream = ctx.stream(); + + // A short src1 without a q8_1 copy is quantized in the kernel, from src1_copy: the output may overlap src1, whose + // last reader the fused product is, and the blocks that finish first would overwrite it for the later ones. + ggml_cuda_pool_alloc src1_q8_1_pool(ctx.pool()); + const char * src1_q8_1 = ctx.q8_1_cache.find(src1); + const bool quantize_y = src1_q8_1 == nullptr && src1_copy != nullptr && src1->ne[0] <= QK8_1*QK8_1 && + src0->ne[0] <= QK8_1*QK8_1; + if (src1_q8_1 == nullptr && !quantize_y) { + src1_q8_1 = ggml_cuda_mmvq_src1_q8_1(ctx, src1, src1_q8_1_pool); + } + + const int64_t n_embd = x->ne[0]; + const int hc = x->ne[1]; + const float scale = ggml_get_op_params_f32(hc_pre, 0); + + ctx.q8_1_cache.invalidate(hc_pre); + block_q8_1 * q8_1 = write_q8_1 ? (block_q8_1 *) ctx.q8_1_cache.reserve(n_embd/QK8_1 * sizeof(block_q8_1)) : nullptr; + + // with the injection product, one more block (the first) computes it, see mul_mat_vec_q_hc_pre + const float * inj_w = inject_dst ? (const float *) inject->src[0]->data : nullptr; + const float * inj_x = inject_dst ? (const float *) inject->src[1]->data : nullptr; + const int inj_ncols2 = inject_dst ? inject->src[0]->ne[0] / 2 : 0; + const int inj_stride_row = inject_dst ? inject->src[0]->nb[1] / sizeof(float) : 0; + + const dim3 grid_dims(n_embd/QK8_1 + (inject_dst ? 1 : 0), 1, 1); + const dim3 block_dims(QK8_1, QK8_1, 1); + switch (src0->type) { + case GGML_TYPE_Q8_0: + if (quantize_y) { + mul_mat_vec_q_hc_pre<<>>( + src0->data, nullptr, src1_copy, (const float *) x->data, (float *) hc_pre->data, q8_1, + src0->ne[0], src1->ne[0], src0->nb[1] / ggml_type_size(src0->type), n_embd, hc, scale, + inj_w, inj_x, inject_dst, inj_ncols2, inj_stride_row); + } else { + mul_mat_vec_q_hc_pre<<>>( + src0->data, (const block_q8_1 *) src1_q8_1, nullptr, (const float *) x->data, (float *) hc_pre->data, + q8_1, src0->ne[0], src1->ne[0], src0->nb[1] / ggml_type_size(src0->type), n_embd, hc, scale, + inj_w, inj_x, inject_dst, inj_ncols2, inj_stride_row); + } + break; + default: + GGML_ABORT("unsupported type for the fused hyper-connection pre-mix"); + } + + if (q8_1) { + ctx.q8_1_cache.commit(hc_pre); + } +} + +bool ggml_cuda_mmvq_moe_glu_shared_supported(ggml_type type, ggml_type type_s) { + return type_s == GGML_TYPE_Q6_K && (type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ4_XS || type == GGML_TYPE_IQ2_S); +} + +// the GLU of the up and gate products of a row as mul_mat_vec_q applies it with the fusion +static __device__ __forceinline__ float mmvq_moe_glu_apply(const float tmp, const float tmp_gate, const ggml_glu_op glu_op, + const float glu_limit) { + // the zero biases mul_mat_vec_q adds with the fusion + float result = tmp + 0.0f; + float gate_value = tmp_gate + 0.0f; + switch (glu_op) { + case GGML_GLU_OP_SWIGLU: + result *= ggml_cuda_op_silu_single(gate_value); + break; + case GGML_GLU_OP_GEGLU: + result *= ggml_cuda_op_gelu_single(gate_value); + break; + case GGML_GLU_OP_SWIGLU_OAI: + result = ggml_cuda_op_swiglu_oai_single(gate_value, result); + break; + case GGML_GLU_OP_SWIGLU_CLAMP: + result = ggml_cuda_op_swiglu_clamp_single(gate_value, result, glu_limit); + break; + default: + result = result * gate_value; + break; + } + return result; +} + +// up . y and gate . y for one row with the GLU, as mul_mat_vec_q computes them with one warp per row and block +template +static __device__ __forceinline__ float mmvq_moe_glu_row( + const void * __restrict__ vup, const void * __restrict__ vgate, const block_q8_1 * __restrict__ y, + const int kbx_offset, const int ncols_x, const ggml_glu_op glu_op, const float glu_limit) { + constexpr int qk = ggml_cuda_type_traits::qk; + constexpr int qi = ggml_cuda_type_traits::qi; + constexpr int vdr = get_vdr_mmvq(type); + constexpr int warp_size = QK8_1; + constexpr int blocks_per_iter = vdr * warp_size / qi; + constexpr vec_dot_q_cuda_t vec_dot_q_cuda = get_vec_dot_q_cuda(type); + + const int tid = threadIdx.x; + const int blocks_per_row_x = ncols_x / qk; + + float tmp = 0.0f; + float tmp_gate = 0.0f; + for (int kbx = tid / (qi/vdr); kbx < blocks_per_row_x; kbx += blocks_per_iter) { + const int kby = kbx * (qk/QK8_1); + const int kqs = vdr * (tid % (qi/vdr)); + tmp += vec_dot_q_cuda(vup, &y[kby], kbx_offset + kbx, kqs); + tmp_gate += vec_dot_q_cuda(vgate, &y[kby], kbx_offset + kbx, kqs); + } + tmp = warp_reduce_sum(tmp); + tmp_gate = warp_reduce_sum(tmp_gate); + return mmvq_moe_glu_apply(tmp, tmp_gate, glu_op, glu_limit); +} + +// the same on experts repacked by moe-wmma.cu, up_e and gate_e the expert, nrows its rows +template +static __device__ __forceinline__ float mmvq_moe_glu_row_rp( + const uint8_t * __restrict__ up_e, const uint8_t * __restrict__ gate_e, const block_q8_1 * __restrict__ y, + const int row, const int nrows, const int ncols_x, const ggml_glu_op glu_op, const float glu_limit) { + constexpr int qk = ggml_cuda_type_traits::qk; + constexpr int qi = ggml_cuda_type_traits::qi; + constexpr int vdr = get_vdr_mmvq(type); + constexpr int warp_size = QK8_1; + constexpr int blocks_per_iter = vdr * warp_size / qi; + + const int tid = threadIdx.x; + const int blocks_per_row_x = ncols_x / qk; + + float tmp = 0.0f; + float tmp_gate = 0.0f; + for (int kbx = tid / (qi/vdr); kbx < blocks_per_row_x; kbx += blocks_per_iter) { + const int kby = kbx * (qk/QK8_1); + const int kqs = vdr * (tid % (qi/vdr)); + tmp += vec_dot_rp_q8_1(up_e, nrows, blocks_per_row_x, row, kbx, &y[kby], kqs); + tmp_gate += vec_dot_rp_q8_1(gate_e, nrows, blocks_per_row_x, row, kbx, &y[kby], kqs); + } + tmp = warp_reduce_sum(tmp); + tmp_gate = warp_reduce_sum(tmp_gate); + return mmvq_moe_glu_apply(tmp, tmp_gate, glu_op, glu_limit); +} + +// The routed experts' gate and up products with the GLU for one token and, in the first nblocks blocks (so that they +// overlap with the routed ones), those of the shared expert, whose weights may have another type. Warp w of block +// e*nblocks + b computes row 32*b + w of expert e - 1 (e = 0: the shared expert, see mmvq_moe_glu_row). +// The 32 rows of a block make one block of MMVQ's q8_1 copy of the result, whose rows are padded to nblocks_padded +// blocks: the blocks past the rows are zero, as quantize_q8_1 makes them, and written by the blocks with rows. +// With rp the routed experts are repacked by moe-wmma.cu, estride bytes apart. +template +__launch_bounds__(QK8_1*QK8_1, 1) +static __global__ void mul_mat_vec_q_moe_glu_shared( + const void * __restrict__ up, const void * __restrict__ gate, const void * __restrict__ up_s, + const void * __restrict__ gate_s, const block_q8_1 * __restrict__ y, const int32_t * __restrict__ ids, + float * __restrict__ dst, float * __restrict__ dst_s, block_q8_1 * __restrict__ q8_1, + block_q8_1 * __restrict__ q8_1_s, const int ncols_x, const int nrows, const int stride_row_x, + const int stride_channel_x, const int stride_channel_dst, const int stride_row_x_s, const int nblocks, + const int nblocks_padded, const ggml_glu_op glu_op, const float glu_limit, const float * __restrict__ sg_w, const float * __restrict__ sg_x, + const int sg_ncols2, const float * __restrict__ weights, float * __restrict__ scratch, const int n_used, + const size_t estride) { + if (scratch != nullptr && blockIdx.x == gridDim.x - 1) { + // the extra last block: the shared expert's gate (F32 weights), with 8 warps as mul_mat_vec_f sums a row with + // 256 threads, and copies of the routing for the fused down stage (see ggml_cuda_mul_mat_vec_q_moe_down_shared), + // whose output may overlap the routing tensors + constexpr int sg_block_size = 256; + const int tid = threadIdx.x; + const int iw = threadIdx.y; + __shared__ float buf_iw[QK8_1]; + if (iw == 0) { + buf_iw[tid] = 0.0f; + } + __syncthreads(); + float sumf = 0.0f; + if (iw < sg_block_size/QK8_1) { + const float2 * x2 = (const float2 *) sg_w; + const float2 * y2 = (const float2 *) sg_x; + for (int col2 = iw*QK8_1 + tid; col2 < sg_ncols2; col2 += sg_block_size) { + const float2 tmpx = x2[col2]; + const float2 tmpy = y2[col2]; + ggml_cuda_mad(sumf, tmpx.x, tmpy.x); + ggml_cuda_mad(sumf, tmpx.y, tmpy.y); + } + } + sumf = warp_reduce_sum(sumf); + if (iw < sg_block_size/QK8_1) { + buf_iw[iw] = sumf; + } + __syncthreads(); + if (iw == 0) { + sumf = buf_iw[tid]; + sumf = warp_reduce_sum(sumf); + if (tid == 0) { + scratch[0] = sumf; + } + } else if (iw == 1 && tid < n_used) { + scratch[1 + tid] = weights[tid]; + ((int *) scratch)[QK8_1 + tid] = ids[tid]; + } + return; + } + + const int b = blockIdx.x % nblocks; + const bool shared = blockIdx.x < nblocks; + const int e = (int) (blockIdx.x / nblocks) - 1; + const int row = b*QK8_1 + threadIdx.y; + + float v = 0.0f; + if (row < nrows) { + if (shared) { + v = mmvq_moe_glu_row(up_s, gate_s, y, row*stride_row_x_s, ncols_x, glu_op, glu_limit); + } else if constexpr (rp) { + const size_t eo = (size_t) ids[e] * estride; + v = mmvq_moe_glu_row_rp((const uint8_t *) up + eo, (const uint8_t *) gate + eo, y, row, nrows, ncols_x, + glu_op, glu_limit); + } else { + v = mmvq_moe_glu_row(up, gate, y, ids[e]*stride_channel_x + row*stride_row_x, ncols_x, glu_op, glu_limit); + } + if (threadIdx.x == 0) { + if (shared) { + dst_s[row] = v; + } else { + dst[e*stride_channel_dst + row] = v; + } + } + } + + block_q8_1 * q = shared ? q8_1_s : (q8_1 ? q8_1 + e*nblocks_padded : nullptr); + if (q == nullptr) { + return; + } + __shared__ float v_shared[QK8_1]; + if (threadIdx.x == 0) { + v_shared[threadIdx.y] = v; + } + __syncthreads(); + if (threadIdx.y != 0) { + return; + } + const int tid = threadIdx.x; + const float vq = v_shared[tid]; + const float amax = warp_reduce_max(fabsf(vq)); + const float d = amax / 127.0f; + const int8_t qv = amax == 0.0f ? 0 : roundf(vq / d); + const int sum_q = warp_reduce_sum((int) qv); + block_q8_1 & yb = q[b]; + yb.qs[tid] = qv; + if (tid == 0) { + yb.ds = make_half2(d, d * sum_q); + } + for (int bp = nblocks + b; bp < nblocks_padded; bp += nblocks) { + q[bp].qs[tid] = 0; + if (tid == 0) { + q[bp].ds = make_half2(0.0f, 0.0f); + } + } +} + +void ggml_cuda_mul_mat_vec_q_moe_glu_shared(ggml_backend_cuda_context & ctx, const ggml_tensor * routed, + const ggml_tensor * shared, const bool write_q8_1, const bool write_q8_1_s, + const ggml_tensor * shared_gate, const ggml_tensor * weights, float * scratch) { + const ggml_tensor * gate_w = routed->src[0]->src[0]; + const ggml_tensor * up_mm = routed->src[1]; + const ggml_tensor * up_w = up_mm->src[0]; + const ggml_tensor * src1 = up_mm->src[1]; + const ggml_tensor * ids = up_mm->src[2]; + const ggml_tensor * gate_w_s = shared->src[0]->src[0]; + const ggml_tensor * up_w_s = shared->src[1]->src[0]; + + ggml_cuda_pool_alloc src1_q8_1_pool(ctx.pool()); + const char * src1_q8_1 = ggml_cuda_mmvq_src1_q8_1(ctx, src1, src1_q8_1_pool); + + const int ncols_x = up_w->ne[0]; + const int nrows = up_w->ne[1]; + const int n_used = routed->ne[1]; + const int nblocks = (nrows + QK8_1 - 1) / QK8_1; + const int nblocks_padded = GGML_PAD(nrows, MATRIX_ROW_PADDING) / QK8_1; + + // the q8_1 copies MMVQ reads for the down products, rows padded to MATRIX_ROW_PADDING (see ggml_cuda_q8_1_cache) + ctx.q8_1_cache.invalidate(routed); + ctx.q8_1_cache.invalidate(shared); + block_q8_1 * q8_1 = nullptr; + if (write_q8_1) { + q8_1 = (block_q8_1 *) ctx.q8_1_cache.reserve(n_used * nblocks_padded * sizeof(block_q8_1)); + if (q8_1) { + ctx.q8_1_cache.commit(routed); + } + } + block_q8_1 * q8_1_s = nullptr; + if (write_q8_1_s) { + q8_1_s = (block_q8_1 *) ctx.q8_1_cache.reserve(nblocks_padded * sizeof(block_q8_1)); + if (q8_1_s) { + ctx.q8_1_cache.commit(shared); + } + } + + const ggml_glu_op glu_op = ggml_get_glu_op(routed); + const float glu_limit = ggml_get_op_params_f32(routed, 3); + + // with scratch, one more block computes the shared expert's gate and copies the routing there + const float * sg_w = scratch ? (const float *) shared_gate->src[0]->data : nullptr; + const float * sg_x = scratch ? (const float *) shared_gate->src[1]->data : nullptr; + const int sg_ncols2 = scratch ? shared_gate->src[0]->ne[0] / 2 : 0; + + const dim3 grid_dims(nblocks*(n_used + 1) + (scratch ? 1 : 0), 1, 1); + const dim3 block_dims(QK8_1, QK8_1, 1); + const bool rp = ggml_cuda_moe_wmma_is_repacked(up_w); + GGML_ASSERT(rp == ggml_cuda_moe_wmma_is_repacked(gate_w)); +#define MMVQ_MOE_GLU_SHARED_LAUNCH(T, TS, RP) \ + mul_mat_vec_q_moe_glu_shared<<>>( \ + up_w->data, gate_w->data, up_w_s->data, gate_w_s->data, (const block_q8_1 *) src1_q8_1, \ + (const int32_t *) ids->data, (float *) routed->data, (float *) shared->data, q8_1, q8_1_s, ncols_x, nrows, \ + up_w->nb[1] / ggml_type_size(T), up_w->nb[2] / ggml_type_size(T), routed->nb[1] / sizeof(float), \ + up_w_s->nb[1] / ggml_type_size(TS), nblocks, nblocks_padded, glu_op, glu_limit, sg_w, sg_x, sg_ncols2, \ + scratch ? (const float *) weights->data : nullptr, scratch, n_used, up_w->nb[2]) +#define MMVQ_MOE_GLU_SHARED_CASE(T, TS) \ + if (up_w->type == T && up_w_s->type == TS) { \ + if (rp) { \ + MMVQ_MOE_GLU_SHARED_LAUNCH(T, TS, true); \ + } else { \ + MMVQ_MOE_GLU_SHARED_LAUNCH(T, TS, false); \ + } \ + return; \ + } + MMVQ_MOE_GLU_SHARED_CASE(GGML_TYPE_IQ3_XXS, GGML_TYPE_Q6_K) + MMVQ_MOE_GLU_SHARED_CASE(GGML_TYPE_IQ4_XS, GGML_TYPE_Q6_K) + MMVQ_MOE_GLU_SHARED_CASE(GGML_TYPE_IQ2_S, GGML_TYPE_Q6_K) +#undef MMVQ_MOE_GLU_SHARED_CASE +#undef MMVQ_MOE_GLU_SHARED_LAUNCH + GGML_ABORT("unsupported types for the fused routed + shared expert gate/up"); +} + +bool ggml_cuda_mmvq_moe_down_shared_supported(ggml_type type, ggml_type type_s, bool rp) { + if (rp) { + return type_s == GGML_TYPE_Q8_0 && (type == GGML_TYPE_Q5_0 || type == GGML_TYPE_IQ4_NL || type == GGML_TYPE_Q2_0); + } + return type_s == GGML_TYPE_Q8_0 && (type == GGML_TYPE_Q5_0 || type == GGML_TYPE_IQ4_NL || type == GGML_TYPE_Q8_0 || + type == GGML_TYPE_Q4_0); +} + +// row . y for one row, as mul_mat_vec_q computes it with one warp per row and block +template +static __device__ __forceinline__ float mmvq_dot_row( + const void * __restrict__ vx, const block_q8_1 * __restrict__ y, const int kbx_offset, const int ncols_x) { + constexpr int qk = ggml_cuda_type_traits::qk; + constexpr int qi = ggml_cuda_type_traits::qi; + constexpr int vdr = get_vdr_mmvq(type); + constexpr int warp_size = QK8_1; + constexpr int blocks_per_iter = vdr * warp_size / qi; + constexpr vec_dot_q_cuda_t vec_dot_q_cuda = get_vec_dot_q_cuda(type); + + const int tid = threadIdx.x; + const int blocks_per_row_x = ncols_x / qk; + + float tmp = 0.0f; + for (int kbx = tid / (qi/vdr); kbx < blocks_per_row_x; kbx += blocks_per_iter) { + const int kby = kbx * (qk/QK8_1); + const int kqs = vdr * (tid % (qi/vdr)); + tmp += vec_dot_q_cuda(vx, &y[kby], kbx_offset + kbx, kqs); + } + return warp_reduce_sum(tmp); +} + + +bool ggml_cuda_mmvq_norm_gate_supported(ggml_type type) { + return type == GGML_TYPE_Q6_K || type == GGML_TYPE_Q8_0; +} + +// as op_sigmoid in unary.cu +static __device__ __forceinline__ float mmvq_norm_gate_sigmoid(const float x) { + return 1.0f / (1.0f + expf(-x)); +} + +// dst = sigmoid(x . y) * (the RMS norm of the row of 128 values of nx holding each row, times nw), the MMVQ product for +// one token (one warp per row, see mmvq_dot_row) followed by the gated output norm of a gated delta net as +// rms_norm_f32<32, 1, true, true> and unary_gated_op_q8_1_kernel compute it, with MMVQ's q8_1 copy of dst: the 32 rows +// of a block make one of its blocks. +template +__launch_bounds__(QK8_1*QK8_1, 1) +static __global__ void mul_mat_vec_q_norm_gate( + const void * __restrict__ vx, const block_q8_1 * __restrict__ y, const float * __restrict__ nx, + const float * __restrict__ nw, float * __restrict__ dst, block_q8_1 * __restrict__ q8_1, const int ncols_x, + const int stride_row_x, const float eps) { + constexpr int ncols_norm = 128; + const int tid = threadIdx.x; + const int row = blockIdx.x*QK8_1 + threadIdx.y; + + const float z = mmvq_dot_row(vx, y, row*stride_row_x, ncols_x); + + const int h = row / ncols_norm; + const float4 xs = ((const float4 *) (nx + h*ncols_norm))[tid]; + float tmp = 0.0f; + tmp += xs.x*xs.x + xs.y*xs.y + xs.z*xs.z + xs.w*xs.w; + tmp = warp_reduce_sum(tmp); + const float scale = rsqrtf(tmp / ncols_norm + eps); + + __shared__ float v_shared[QK8_1]; + if (tid == 0) { + const int c = row % ncols_norm; + float n = scale*nx[h*ncols_norm + c]; + n *= nw[c]; + const float v = mmvq_norm_gate_sigmoid(z) * n; + dst[row] = v; + v_shared[threadIdx.y] = v; + } + __syncthreads(); + if (threadIdx.y != 0) { + return; + } + const float v = v_shared[tid]; + const float amax = warp_reduce_max(fabsf(v)); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(v / d); + const int sum_q = warp_reduce_sum((int) q); + block_q8_1 & yb = q8_1[blockIdx.x]; + yb.qs[tid] = q; + if (tid == 0) { + yb.ds = make_half2(d, d * sum_q); + } +} + +void ggml_cuda_mul_mat_vec_q_norm_gate(ggml_backend_cuda_context & ctx, const ggml_tensor * mm, const ggml_tensor * rms, + const ggml_tensor * norm_w, ggml_tensor * dst, const ggml_tensor * q8_1_tensor) { + const ggml_tensor * src0 = mm->src[0]; + const ggml_tensor * src1 = mm->src[1]; + + ggml_cuda_pool_alloc src1_q8_1_pool(ctx.pool()); + const char * src1_q8_1 = ggml_cuda_mmvq_src1_q8_1(ctx, src1, src1_q8_1_pool); + + // the q8_1 copy MMVQ reads through q8_1_tensor, or one nothing reads if the cache has no room + const size_t nbytes_q8_1 = ggml_nrows(q8_1_tensor) * q8_1_tensor->ne[0]/QK8_1 * sizeof(block_q8_1); + ctx.q8_1_cache.invalidate(dst); + ctx.q8_1_cache.invalidate(q8_1_tensor); + ggml_cuda_pool_alloc q8_1_pool(ctx.pool()); + block_q8_1 * q8_1 = (block_q8_1 *) ctx.q8_1_cache.reserve(nbytes_q8_1); + const bool cached = q8_1 != nullptr; + if (!cached) { + q8_1 = (block_q8_1 *) q8_1_pool.alloc(nbytes_q8_1); + } + + float eps = 0.0f; + memcpy(&eps, rms->op_params, sizeof(float)); + + const int nrows = src0->ne[1]; + const dim3 grid_dims(nrows / QK8_1, 1, 1); + const dim3 block_dims(QK8_1, QK8_1, 1); + switch (src0->type) { + case GGML_TYPE_Q6_K: + mul_mat_vec_q_norm_gate<<>>( + src0->data, (const block_q8_1 *) src1_q8_1, (const float *) rms->src[0]->data, (const float *) norm_w->data, + (float *) dst->data, q8_1, src0->ne[0], src0->nb[1] / ggml_type_size(GGML_TYPE_Q6_K), eps); + break; + case GGML_TYPE_Q8_0: + mul_mat_vec_q_norm_gate<<>>( + src0->data, (const block_q8_1 *) src1_q8_1, (const float *) rms->src[0]->data, (const float *) norm_w->data, + (float *) dst->data, q8_1, src0->ne[0], src0->nb[1] / ggml_type_size(GGML_TYPE_Q8_0), eps); + break; + default: + GGML_ABORT("unsupported type for the fused gated norm"); + } + if (cached) { + ctx.q8_1_cache.commit(q8_1_tensor); + } +} + +// the weighted sum of the experts' rows as moe_weighted_reduction_f32 computes it +static __device__ __forceinline__ float moe_weighted_sum( + const float * experts, const float * expert_scale, const float * weights, const int n_expert_used) { + const float first_scale = expert_scale != nullptr ? expert_scale[0] : 1.0f; + float sum = (experts[0] * first_scale) * weights[0]; + for (int expert = 1; expert < n_expert_used; ++expert) { + const float scale = expert_scale != nullptr ? expert_scale[expert] : 1.0f; + sum += (experts[expert] * scale) * weights[expert]; + } + return sum; +} + +static __device__ __forceinline__ float moe_shared_gate_sigmoid(const float x) { + return 1.0f / (1.0f + expf(-x)); +} + +// a + x*sigmoid(g) as unary_mul_add_kernel computes it, the product rounded before the sum +static __device__ __forceinline__ float moe_shared_gated_add(const float a, const float x, const float g) { +#ifdef GGML_USE_HIP +#pragma clang fp contract(off) + const float m = x * moe_shared_gate_sigmoid(g); + return a + m; +#else + return __fadd_rn(a, __fmul_rn(x, moe_shared_gate_sigmoid(g))); +#endif // GGML_USE_HIP +} + +// The down stage of the routed experts and the shared expert for one token: block r computes row r, warp e < n_used +// that of routed expert ids[e] and warp n_used that of the shared expert, then dst[r] = the routing-weighted sum of the +// routed rows + shared row*sigmoid(gate). The routing and the gate come from scratch, see mul_mat_vec_q_moe_glu_shared. +// warps per routed expert with repacked experts, each for a part of the row +static constexpr int MMVQ_MOE_DOWN_RP_PARTS = 2; + +// With rp the routed experts are repacked by moe-wmma.cu, estride bytes apart, with nrows rows. +template +__launch_bounds__(QK8_1*QK8_1, 1) +static __global__ void mul_mat_vec_q_moe_down_shared( + const void * __restrict__ down, const void * __restrict__ down_s, const block_q8_1 * __restrict__ y, + const block_q8_1 * __restrict__ y_s, const float * __restrict__ scratch, const float * __restrict__ expert_scale, + float * __restrict__ dst, const int ncols_x, const int stride_row_x, const int stride_channel_x, + const int stride_row_x_s, const int stride_channel_y, const int n_used, const size_t estride, const int nrows) { + const int w = threadIdx.y; + + if constexpr (rp) { + // the routed experts with one lane per row: lane l of warp w < 2*n_used computes half w % 2 of row + // 32*blockIdx.x + l of expert ids[w / 2], the 32 rows of a warp read whole cache lines of the repacked planes; + // the 32 rows of the shared expert (GGUF layout) one warp per row, spread over all warps + constexpr int np = MMVQ_MOE_DOWN_RP_PARTS; + const int nw = np*n_used + 1; + const int row = blockIdx.x*QK8_1 + threadIdx.x; + __shared__ float rows_lpr[np*QK8_1 + 1][QK8_1]; + if (w < np*n_used) { + float v = 0.0f; + if (row < nrows) { + const int e = ((const int *) scratch)[QK8_1 + w/np]; + v = vec_dot_rp_row((const uint8_t *) down + (size_t) e * estride, y + (w/np)*stride_channel_y, row, nrows, + ncols_x, w % np, np); + } + rows_lpr[w][threadIdx.x] = v; + } + for (int r = w; r < QK8_1; r += nw) { + const int row_s = blockIdx.x*QK8_1 + r; + if (row_s < nrows) { + const float v_s = mmvq_dot_row(down_s, y_s, row_s*stride_row_x_s, ncols_x); + if (threadIdx.x == 0) { + rows_lpr[np*n_used][r] = v_s; + } + } + } + __syncthreads(); + if (w == 0 && row < nrows) { + // as moe_weighted_sum + auto expert_row = [&](const int e) { + float s = 0.0f; +#pragma unroll + for (int p = 0; p < np; ++p) { + s += rows_lpr[np*e + p][threadIdx.x]; + } + return s; + }; + const float * weights = scratch + 1; + float sum = (expert_row(0) * (expert_scale != nullptr ? expert_scale[0] : 1.0f)) * weights[0]; + for (int e = 1; e < n_used; ++e) { + sum += (expert_row(e) * (expert_scale != nullptr ? expert_scale[e] : 1.0f)) * weights[e]; + } + dst[row] = moe_shared_gated_add(sum, rows_lpr[np*n_used][threadIdx.x], scratch[0]); + } + return; + } + + const int row = blockIdx.x; + float v; + if (w < n_used) { + const int e = ((const int *) scratch)[QK8_1 + w]; + v = mmvq_dot_row(down, y + w*stride_channel_y, e*stride_channel_x + row*stride_row_x, ncols_x); + } else { + v = mmvq_dot_row(down_s, y_s, row*stride_row_x_s, ncols_x); + } + + __shared__ float rows[QK8_1]; + if (threadIdx.x == 0) { + rows[w] = v; + } + __syncthreads(); + if (w == 0 && threadIdx.x == 0) { + const float sum = moe_weighted_sum(rows, expert_scale, scratch + 1, n_used); + dst[row] = moe_shared_gated_add(sum, rows[n_used], scratch[0]); + } +} + +void ggml_cuda_mul_mat_vec_q_moe_down_shared(ggml_backend_cuda_context & ctx, const ggml_tensor * down, + const ggml_tensor * shared_down, ggml_tensor * dst, const float * scratch, + const char * y_q8_1, const char * y_s_q8_1) { + const ggml_tensor * w = down->src[0]; + const ggml_tensor * w_s = shared_down->src[0]; + const int ncols_x = w->ne[0]; + const int n_used = down->ne[1]; + const int stride_channel_y = GGML_PAD(ncols_x, MATRIX_ROW_PADDING) / QK8_1; + + ctx.q8_1_cache.invalidate(dst); + const bool rp = ggml_cuda_moe_wmma_is_repacked(w); + const dim3 grid_dims(rp ? (w->ne[1] + QK8_1 - 1) / QK8_1 : w->ne[1], 1, 1); + const dim3 block_dims(QK8_1, (rp ? MMVQ_MOE_DOWN_RP_PARTS : 1)*n_used + 1, 1); + GGML_ASSERT(block_dims.y <= QK8_1); +#define MMVQ_MOE_DOWN_SHARED_LAUNCH(T, TS, RP) \ + mul_mat_vec_q_moe_down_shared<<>>( \ + w->data, w_s->data, (const block_q8_1 *) y_q8_1, (const block_q8_1 *) y_s_q8_1, scratch, nullptr, \ + (float *) dst->data, ncols_x, w->nb[1] / ggml_type_size(T), w->nb[2] / ggml_type_size(T), \ + w_s->nb[1] / ggml_type_size(TS), stride_channel_y, n_used, w->nb[2], w->ne[1]) +#define MMVQ_MOE_DOWN_SHARED_CASE(T, TS) \ + if (w->type == T && w_s->type == TS) { \ + MMVQ_MOE_DOWN_SHARED_LAUNCH(T, TS, false); \ + return; \ + } +#define MMVQ_MOE_DOWN_SHARED_CASE_RP(T, TS) \ + if (w->type == T && w_s->type == TS) { \ + if (rp) { \ + MMVQ_MOE_DOWN_SHARED_LAUNCH(T, TS, true); \ + } else { \ + MMVQ_MOE_DOWN_SHARED_LAUNCH(T, TS, false); \ + } \ + return; \ + } + MMVQ_MOE_DOWN_SHARED_CASE_RP(GGML_TYPE_Q5_0, GGML_TYPE_Q8_0) + MMVQ_MOE_DOWN_SHARED_CASE_RP(GGML_TYPE_IQ4_NL, GGML_TYPE_Q8_0) + if (rp && w->type == GGML_TYPE_Q2_0 && w_s->type == GGML_TYPE_Q8_0) { + MMVQ_MOE_DOWN_SHARED_LAUNCH(GGML_TYPE_Q2_0, GGML_TYPE_Q8_0, true); + return; + } + GGML_ASSERT(!rp); + MMVQ_MOE_DOWN_SHARED_CASE(GGML_TYPE_Q8_0, GGML_TYPE_Q8_0) + MMVQ_MOE_DOWN_SHARED_CASE(GGML_TYPE_Q4_0, GGML_TYPE_Q8_0) +#undef MMVQ_MOE_DOWN_SHARED_CASE +#undef MMVQ_MOE_DOWN_SHARED_CASE_RP +#undef MMVQ_MOE_DOWN_SHARED_LAUNCH + GGML_ABORT("unsupported types for the fused routed + shared expert down stage"); +} diff --git a/ggml/src/ggml-cuda/mmvq.cuh b/ggml/src/ggml-cuda/mmvq.cuh index 5605bf7a4e60..ebde5cc76d0f 100644 --- a/ggml/src/ggml-cuda/mmvq.cuh +++ b/ggml/src/ggml-cuda/mmvq.cuh @@ -11,6 +11,47 @@ int get_mmvq_mmid_max_batch(ggml_type type, int cc); void ggml_cuda_mul_mat_vec_q(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const ggml_cuda_mm_fusion_args_host * fusion = nullptr); +// hc_pre (a gated DSV4_HC_PRE) mixing the streams with the sigmoid of src0 x src1, one token, in one kernel; also +// writes MMVQ's q8_1 copy of hc_pre when write_q8_1 (see ggml_cuda_q8_1_cache). src1_copy, if not nullptr, holds the +// values of src1 where hc_pre cannot overlap them. With inject_dst, the same kernel also writes there the product inject +// (F32 weights, one token) as mul_mat_vec_f computes it with 256 threads per row. +void ggml_cuda_mul_mat_vec_q_hc_pre(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, + const float * src1_copy, ggml_tensor * hc_pre, bool write_q8_1, + const ggml_tensor * inject = nullptr, float * inject_dst = nullptr); + +// unary_node = silu(scale_node(src0 x src1)) for one token in one kernel, also written to dst_copy if not nullptr +void ggml_cuda_mul_mat_vec_q_scale_silu(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, + const ggml_tensor * scale_node, ggml_tensor * unary_node, float * dst_copy); + +// whether ggml_cuda_mul_mat_vec_q_moe_glu_shared supports routed experts of type and a shared expert of type_s +bool ggml_cuda_mmvq_moe_glu_shared_supported(ggml_type type, ggml_type type_s); + +// routed (the GLU of the routed experts' gate and up MUL_MAT_IDs) and shared (that of the shared expert, weights of +// another type) for one token in one kernel; also writes MMVQ's q8_1 copies of routed and shared when asked +// With scratch, the kernel also computes there the shared expert's gate shared_gate (F32 weights, as mul_mat_vec_f +// sums a row with 256 threads) and copies the routing weights and ids, see ggml_cuda_mul_mat_vec_q_moe_down_shared. +void ggml_cuda_mul_mat_vec_q_moe_glu_shared(ggml_backend_cuda_context & ctx, const ggml_tensor * routed, + const ggml_tensor * shared, bool write_q8_1, bool write_q8_1_s, + const ggml_tensor * shared_gate = nullptr, const ggml_tensor * weights = nullptr, + float * scratch = nullptr); + +// whether ggml_cuda_mul_mat_vec_q_moe_down_shared supports routed down weights of type and shared ones of type_s +// the MMVQ product mm of one token followed by the gated output norm of a gated delta net: dst = SIGMOID(mm) * (RMS_NORM +// (rms, rows of 128) * norm_w), with MMVQ's q8_1 copy of dst in q8_1, in one kernel +bool ggml_cuda_mmvq_norm_gate_supported(ggml_type type); +void ggml_cuda_mul_mat_vec_q_norm_gate(ggml_backend_cuda_context & ctx, const ggml_tensor * mm, const ggml_tensor * rms, + const ggml_tensor * norm_w, ggml_tensor * dst, const ggml_tensor * q8_1_tensor); + +// rp: routed experts repacked by moe-wmma.cu +bool ggml_cuda_mmvq_moe_down_shared_supported(ggml_type type, ggml_type type_s, bool rp = false); + +// dst = the routing-weighted sum of the routed experts' down products (down, a MUL_MAT_ID) + the shared expert's down +// product times the sigmoid of its gate, for one token in one kernel: y_q8_1 and y_s_q8_1 are MMVQ's q8_1 copies of the +// inputs, scratch the gate and routing ggml_cuda_mul_mat_vec_q_moe_glu_shared wrote +void ggml_cuda_mul_mat_vec_q_moe_down_shared(ggml_backend_cuda_context & ctx, const ggml_tensor * down, + const ggml_tensor * shared_down, ggml_tensor * dst, const float * scratch, + const char * y_q8_1, const char * y_s_q8_1); + void ggml_cuda_op_mul_mat_vec_q( ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const char * src0_dd_i, const float * src1_ddf_i, diff --git a/ggml/src/ggml-cuda/moe-weighted-reduction.cu b/ggml/src/ggml-cuda/moe-weighted-reduction.cu index 2fb085abf8c0..1a124bb3d866 100644 --- a/ggml/src/ggml-cuda/moe-weighted-reduction.cu +++ b/ggml/src/ggml-cuda/moe-weighted-reduction.cu @@ -38,6 +38,99 @@ static __global__ void moe_weighted_reduction_f32(const float * __restrict__ exp } } +// 4 consecutive values of an expert's row: F32, or BF16 (the MoE down products of a prompt batch) +template +static __device__ __forceinline__ float4 moe_reduce_load4(const T * row, const int64_t col); + +template <> +__device__ __forceinline__ float4 moe_reduce_load4(const float * row, const int64_t col) { + return *(const float4 *) (row + col); +} + +template <> +__device__ __forceinline__ float4 moe_reduce_load4(const uint16_t * row, const int64_t col) { + const uint2 u = *(const uint2 *) (row + col); + return make_float4(__uint_as_float(u.x << 16), __uint_as_float(u.x & 0xFFFF0000u), + __uint_as_float(u.y << 16), __uint_as_float(u.y & 0xFFFF0000u)); +} + +// Prompt batches: 4 columns per thread, the rows of all N experts loaded before the sum. The sum is that of +// moe_weighted_reduction_f32, bit for bit: (e * s) * w rounded twice for the first expert, then fma(e * s, w, sum), +// written out because the compiler is free to contract the scalar loop differently here. +template +static __global__ void __launch_bounds__(128) moe_weighted_reduction_x4(const T * __restrict__ experts, + const float * __restrict__ expert_scale, + const float * __restrict__ weights, + float * __restrict__ dst, + const int64_t n_embd) { + const int64_t token = blockIdx.y; + const int64_t col = 4 * ((int64_t) blockIdx.x * blockDim.x + threadIdx.x); + if (col >= n_embd) { + return; + } + const uint64_t row0 = (uint64_t) token * N; + + float4 e[N]; +#pragma unroll + for (int i = 0; i < N; ++i) { + e[i] = moe_reduce_load4(experts + (row0 + i) * n_embd, col); + } + float s[N], w[N]; +#pragma unroll + for (int i = 0; i < N; ++i) { + s[i] = expert_scale != nullptr ? expert_scale[row0 + i] : 1.0f; + w[i] = weights[row0 + i]; + } + + float4 sum; + sum.x = __fmul_rn(__fmul_rn(e[0].x, s[0]), w[0]); + sum.y = __fmul_rn(__fmul_rn(e[0].y, s[0]), w[0]); + sum.z = __fmul_rn(__fmul_rn(e[0].z, s[0]), w[0]); + sum.w = __fmul_rn(__fmul_rn(e[0].w, s[0]), w[0]); +#pragma unroll + for (int i = 1; i < N; ++i) { + sum.x = fmaf(__fmul_rn(e[i].x, s[i]), w[i], sum.x); + sum.y = fmaf(__fmul_rn(e[i].y, s[i]), w[i], sum.y); + sum.z = fmaf(__fmul_rn(e[i].z, s[i]), w[i], sum.z); + sum.w = fmaf(__fmul_rn(e[i].w, s[i]), w[i], sum.w); + } + *(float4 *) (dst + token * n_embd + col) = sum; +} + +// the most experts per token that the x4 kernel is instantiated for +#define MOE_WEIGHTED_REDUCTION_MAX_EXPERTS_X4 15 + +template +static void launch_moe_weighted_reduction_x4(const T * experts, const float * expert_scale, const float * weights, + float * dst, const int64_t n_embd, const int64_t n_tokens, + const int n_expert_used, cudaStream_t stream) { + if constexpr (N > 1) { + if (n_expert_used < N) { + launch_moe_weighted_reduction_x4(experts, expert_scale, weights, dst, n_embd, n_tokens, + n_expert_used, stream); + return; + } + constexpr int threads = 128; + const dim3 blocks((n_embd / 4 + threads - 1) / threads, n_tokens, 1); + moe_weighted_reduction_x4<<>>(experts, expert_scale, weights, dst, n_embd); + } else { + GGML_ABORT("the x4 MoE reduction needs at least 2 experts"); + } +} + +// the x4 kernel takes it: a prompt batch of 2..15 experts per token, whole aligned 4-column groups +static bool moe_weighted_reduction_x4_shape(const ggml_tensor * experts, const ggml_tensor * dst) { + const int64_t n_embd = experts->ne[0]; + const int64_t n_expert_used = experts->ne[1]; + const int64_t n_tokens = experts->ne[2] * experts->ne[3]; + return n_tokens >= 16 && n_embd % 4 == 0 && n_expert_used >= 2 && n_expert_used <= MOE_WEIGHTED_REDUCTION_MAX_EXPERTS_X4 && + ggml_is_contiguous(experts) && (uintptr_t) experts->data % 16 == 0 && (dst == nullptr || (uintptr_t) dst->data % 16 == 0); +} + +bool ggml_cuda_moe_weighted_reduction_bf16_supported(const ggml_tensor * experts) { + return moe_weighted_reduction_x4_shape(experts, nullptr); +} + static void launch_moe_weighted_reduction(const float * experts, const float * expert_scale, const float * weights, @@ -58,7 +151,8 @@ bool ggml_cuda_op_moe_weighted_reduction(ggml_backend_cuda_context & ctx, const ggml_tensor * expert_scale, const ggml_tensor * weights, ggml_tensor * dst, - block_q8_1 * dst_q8_1) { + block_q8_1 * dst_q8_1, + const bool experts_bf16) { GGML_ASSERT(experts->type == GGML_TYPE_F32); GGML_ASSERT(weights->type == GGML_TYPE_F32); GGML_ASSERT(expert_scale == nullptr || expert_scale->type == GGML_TYPE_F32); @@ -76,6 +170,27 @@ bool ggml_cuda_op_moe_weighted_reduction(ggml_backend_cuda_context & ctx, // the q8_1 copy needs whole, unpadded 32-value blocks per row and 32-lane warps const bool q8_1 = dst_q8_1 && n_embd % MATRIX_ROW_PADDING == 0 && ggml_cuda_info().devices[ctx.device].warp_size == QK8_1; + if (experts_bf16) { + // the experts' rows as BF16, see ggml_cuda_moe_weighted_reduction_bf16_supported + GGML_ASSERT(moe_weighted_reduction_x4_shape(experts, dst)); + launch_moe_weighted_reduction_x4((const uint16_t *) experts->data, + expert_scale ? (const float *) expert_scale->data : nullptr, (const float *) weights->data, (float *) dst->data, + n_embd, n_tokens, (int) n_expert_used, stream); + CUDA_CHECK(cudaGetLastError()); + return false; + } + + // RDNA3.5 prompt batches without the q8_1 copy: 4 columns per thread (GGML_HIP_MOE_REDUCE_X4=0 turns it off) + static const int env_x4 = ggml_cuda_env_switch("GGML_HIP_MOE_REDUCE_X4"); + if (!q8_1 && moe_weighted_reduction_x4_shape(experts, dst) && + ggml_cuda_switch_or_rdna3_5(env_x4, ggml_cuda_info().devices[ctx.device].cc)) { + launch_moe_weighted_reduction_x4((const float *) experts->data, + expert_scale ? (const float *) expert_scale->data : nullptr, (const float *) weights->data, (float *) dst->data, + n_embd, n_tokens, (int) n_expert_used, stream); + CUDA_CHECK(cudaGetLastError()); + return false; + } + launch_moe_weighted_reduction((const float *) experts->data, expert_scale ? (const float *) expert_scale->data : nullptr, (const float *) weights->data, diff --git a/ggml/src/ggml-cuda/moe-weighted-reduction.cuh b/ggml/src/ggml-cuda/moe-weighted-reduction.cuh index a31299436cc3..b7d93922f679 100644 --- a/ggml/src/ggml-cuda/moe-weighted-reduction.cuh +++ b/ggml/src/ggml-cuda/moe-weighted-reduction.cuh @@ -1,9 +1,13 @@ #include "common.cuh" -// dst_q8_1, if not null: also write MMVQ's q8_1 copy of dst there; returns whether it was written +// dst_q8_1, if not null: also write MMVQ's q8_1 copy of dst there; returns whether it was written. +// experts_bf16: the experts' rows are BF16 (in the memory of experts), only where ggml_cuda_moe_weighted_reduction_bf16_supported bool ggml_cuda_op_moe_weighted_reduction(ggml_backend_cuda_context & ctx, const ggml_tensor * experts, const ggml_tensor * expert_scale, const ggml_tensor * weights, ggml_tensor * dst, - block_q8_1 * dst_q8_1 = nullptr); + block_q8_1 * dst_q8_1 = nullptr, + bool experts_bf16 = false); + +bool ggml_cuda_moe_weighted_reduction_bf16_supported(const ggml_tensor * experts); diff --git a/ggml/src/ggml-cuda/moe-wmma-vecdot.cuh b/ggml/src/ggml-cuda/moe-wmma-vecdot.cuh new file mode 100644 index 000000000000..9e1965aeacd3 --- /dev/null +++ b/ggml/src/ggml-cuda/moe-wmma-vecdot.cuh @@ -0,0 +1,181 @@ +#pragma once + +#include "common.cuh" +#include "vecdotq.cuh" + +// The vec_dot_*_q8_1 products of MMVQ on expert weights repacked by moe-wmma.cu. we is the expert, R its rows, U the +// blocks per row; the parts of block u of row row are in the planes of moe-wmma.cu at gk = (row/32)*U + u and +// r32 = row % 32. iqs and the arithmetic are those of the vec_dot_*_q8_1 function of the type. +template +static __device__ __forceinline__ float vec_dot_rp_q8_1( + const uint8_t * __restrict__ we, const int R, const int U, const int row, const int u, + const block_q8_1 * __restrict__ bq8_1, const int iqs) { +#if defined(GGML_USE_HIP) + const size_t gk = (size_t) (row / 32) * U + u; + const int r32 = row % 32; + const size_t RU = (size_t) R * U; + + if constexpr (type == GGML_TYPE_IQ3_XXS) { + const int ib = iqs / 2; + const int2 q3_packed = make_int2(*(const int *) (we + ((gk * 2 + 0) * 32 + r32) * 32 + 4 * ib), + *(const int *) (we + ((gk * 2 + 1) * 32 + r32) * 32 + 4 * ib)); + const uint8_t * q3 = (const uint8_t *) &q3_packed; + const uint32_t aux32 = *(const uint32_t *) (we + RU * 64 + (gk * 32 + r32) * 32 + 4 * ib); + const half d = *(const half *) (we + RU * 96 + (gk * 32 + r32) * 2); + + int sumi = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int2 grid_pos = make_int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); + const uint8_t v = aux32 >> (7*l0/2); + const uint32_t s8 = v ^ (__popc(v) & 1) << 7; + const int grid_l = iq_grid_signed(grid_pos.x, s8); + const int grid_h = iq_grid_signed(grid_pos.y, s8 >> 4); + sumi = ggml_cuda_dp4a(grid_l, get_int_b4(bq8_1[ib].qs, l0 + 0), sumi); + sumi = ggml_cuda_dp4a(grid_h, get_int_b4(bq8_1[ib].qs, l0 + 1), sumi); + } + const int ls = aux32 >> 28; + sumi = (ls*sumi + sumi/2)/2; + return __half2float(d) * __low2float(bq8_1[ib].ds) * sumi; + } else if constexpr (type == GGML_TYPE_IQ2_S) { + const int ib = iqs / 2; + const uint32_t w0 = *(const uint32_t *) (we + ((gk * 2 + 0) * 32 + r32) * 32 + 4 * ib); + const uint32_t w1 = *(const uint32_t *) (we + ((gk * 2 + 1) * 32 + r32) * 32 + 4 * ib); + const uint32_t qs_packed = (w0 & 0xFFFF) | (w1 << 16); + const uint32_t signs_packed = (w0 >> 16) | (w1 & 0xFFFF0000); + const uint8_t * qs = (const uint8_t *) &qs_packed; + const uint8_t * signs_packed_8 = (const uint8_t *) &signs_packed; + const uint8_t * meta = we + RU * 64 + (gk * 32 + r32) * 16; + const int qh = meta[ib]; + const int ls0 = meta[8 + ib] & 0x0F; + const int ls1 = meta[8 + ib] >> 4; + const half d = *(const half *) (we + RU * 80 + (gk * 32 + r32) * 2); + + int sumi0 = 0; + int sumi1 = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int * grid_pos = (const int *)(iq2s_grid + (qs[l0/2] | ((qh << (8-l0)) & 0x300))); + const int grid_l = iq_grid_signed(grid_pos[0], signs_packed_8[l0/2]); + const int grid_h = iq_grid_signed(grid_pos[1], signs_packed_8[l0/2] >> 4); + const int u0 = get_int_b4(bq8_1[ib].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[ib].qs, l0 + 1); + if (l0 < 4) { + sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0); + sumi0 = ggml_cuda_dp4a(grid_h, u1, sumi0); + } else { + sumi1 = ggml_cuda_dp4a(grid_l, u0, sumi1); + sumi1 = ggml_cuda_dp4a(grid_h, u1, sumi1); + } + } + const int sumi = (sumi0*ls0 + sumi1*ls1 + (sumi0 + sumi1)/2)/4; + return __half2float(d) * __low2float(bq8_1[ib].ds) * sumi; + } else if constexpr (type == GGML_TYPE_IQ4_XS) { + // half h holds values 16 h + 8 w + j (low nibble of byte j of word w) and 16 h + 8 w + j + 4 (high nibble) + const int ib = iqs / 4; + const uint2 h0 = *(const uint2 *) (we + ((gk * 2 + 0) * 32 + r32) * 64 + 8 * ib); + const uint2 h1 = *(const uint2 *) (we + ((gk * 2 + 1) * 32 + r32) * 64 + 8 * ib); + const uint2 meta = *(const uint2 *) (we + RU * 128 + (gk * 32 + r32) * 8); + const uint32_t * values = (const uint32_t *) kvalues_iq4nl; + auto lut = [&](const uint32_t q) { + const uint32_t lo = ggml_hip_perm(values[1], values[0], q & 0x07070707); + const uint32_t hi = ggml_hip_perm(values[3], values[2], q & 0x07070707); + return (int) ggml_hip_perm(hi, lo, 0x03020100 | ((q & 0x08080808) >> 1)); + }; + const uint32_t x[4] = { h0.x, h0.y, h1.x, h1.y }; + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + sumi = ggml_cuda_dp4a(lut(x[j]), get_int_b4(bq8_1[ib].qs, 2*j + 0), sumi); + sumi = ggml_cuda_dp4a(lut(x[j] >> 4), get_int_b4(bq8_1[ib].qs, 2*j + 1), sumi); + } + const int ls = ((meta.y >> (4*ib)) & 0x0F) | (((meta.x >> (16 + 2*ib)) & 0x03) << 4); + sumi *= ls - 32; + return __half2float(__ushort_as_half((uint16_t) meta.x)) * __low2float(bq8_1[ib].ds) * sumi; + } else if constexpr (type == GGML_TYPE_Q5_0) { + const size_t gi = gk * 32 + r32; + const int qh = *(const int *) (we + RU * 16 + gi * 4); + int vl[VDR_Q5_0_Q8_1_MMVQ]; + int vh[VDR_Q5_0_Q8_1_MMVQ]; + int u[2*VDR_Q5_0_Q8_1_MMVQ]; +#pragma unroll + for (int i = 0; i < VDR_Q5_0_Q8_1_MMVQ; ++i) { + vl[i] = *(const int *) (we + gi * 16 + 4 * (iqs + i)); + vh[i] = qh >> (4 * (iqs + i)); + u[2*i+0] = get_int_b4(bq8_1->qs, iqs + i); + u[2*i+1] = get_int_b4(bq8_1->qs, iqs + i + QI5_0); + } + const float d = __half2float(*(const half *) (we + RU * 20 + gi * 2)); + return vec_dot_q5_0_q8_1_impl(vl, vh, u, d, bq8_1->ds); + } else if constexpr (type == GGML_TYPE_IQ4_NL) { + const size_t gi = gk * 32 + r32; + const int * q8 = (const int *) bq8_1->qs + iqs; + int sumi = 0; +#pragma unroll + for (int l = 0; l < VDR_Q4_0_Q8_1_MMVQ; ++l) { + const int2 v = get_int_from_table_16(*(const int *) (we + gi * 16 + 4 * (iqs + l)), kvalues_iq4nl); + sumi = ggml_cuda_dp4a(v.x, q8[l + 0], sumi); + sumi = ggml_cuda_dp4a(v.y, q8[l + 4], sumi); + } + return __half2float(*(const half *) (we + RU * 16 + gi * 2)) * __low2float(bq8_1->ds) * sumi; + } else if constexpr (type == GGML_TYPE_Q2_0) { + // word 2 iqs + h holds values 32 iqs + 16 h + v, v at bits 2 (v / 4) of byte v % 4 + const size_t gi = gk * 32 + r32; + const uint2 x = *(const uint2 *) (we + gi * 16 + 8 * iqs); + const block_q8_1 * bq8_1_chunk = bq8_1 + iqs; + int sumi = 0; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int q0 = ggml_hip_perm(0x020100FF, 0x020100FF, (x.x >> (2 * i)) & 0x03030303); + const int q1 = ggml_hip_perm(0x020100FF, 0x020100FF, (x.y >> (2 * i)) & 0x03030303); + sumi = ggml_cuda_dp4a(get_int_b4(bq8_1_chunk->qs, i + 0), q0, sumi); + sumi = ggml_cuda_dp4a(get_int_b4(bq8_1_chunk->qs, i + 4), q1, sumi); + } + const float d2 = __half2float(*(const half *) (we + RU * 16 + gi * 2)); + return d2 * __low2float(bq8_1_chunk->ds) * sumi; + } else { + static_assert(type == GGML_TYPE_COUNT, "unsupported type"); + return 0.0f; + } +#else + GGML_UNUSED_VARS(we, R, U, row, u, bq8_1, iqs); + return 0.0f; +#endif // defined(GGML_USE_HIP) +} + +// the VDR of the vec_dot_*_q8_1 functions for MMVQ +template +static constexpr __device__ int vec_dot_rp_vdr() { + switch (type) { + case GGML_TYPE_IQ3_XXS: return VDR_IQ3_XXS_Q8_1_MMVQ; + case GGML_TYPE_IQ2_S: return VDR_IQ2_S_Q8_1_MMVQ; + case GGML_TYPE_IQ4_XS: return VDR_IQ4_XS_Q8_1_MMVQ; + case GGML_TYPE_Q5_0: return VDR_Q5_0_Q8_1_MMVQ; + case GGML_TYPE_IQ4_NL: return VDR_IQ4_NL_Q8_1_MMVQ; + case GGML_TYPE_Q2_0: return VDR_Q2_0_Q8_1_MMVQ; + default: return 1; + } +} + +// row . y for the row of this lane alone, on an expert we repacked by moe-wmma.cu with nrows rows; the blocks of +// part ip of np equal parts of the row +template +static __device__ __forceinline__ float vec_dot_rp_row( + const uint8_t * __restrict__ we, const block_q8_1 * __restrict__ y, const int row, const int nrows, const int ncols_x, + const int ip = 0, const int np = 1) { + constexpr int qk = ggml_cuda_type_traits::qk; + constexpr int qi = ggml_cuda_type_traits::qi; + constexpr int vdr = vec_dot_rp_vdr(); + + const int blocks_per_row_x = ncols_x / qk; + const int kb0 = ip * blocks_per_row_x / np; + const int kb1 = (ip + 1) * blocks_per_row_x / np; + float tmp = 0.0f; + for (int kbx = kb0; kbx < kb1; ++kbx) { +#pragma unroll + for (int kqs = 0; kqs < qi; kqs += vdr) { + tmp += vec_dot_rp_q8_1(we, nrows, blocks_per_row_x, row, kbx, &y[kbx * (qk/QK8_1)], kqs); + } + } + return tmp; +} diff --git a/ggml/src/ggml-cuda/moe-wmma.cu b/ggml/src/ggml-cuda/moe-wmma.cu new file mode 100644 index 000000000000..e22aab5b7082 --- /dev/null +++ b/ggml/src/ggml-cuda/moe-wmma.cu @@ -0,0 +1,890 @@ +// MoE expert matrix multiplication with BF16 WMMA on RDNA3, on expert weights repacked in place. +// +// The bytes of each expert are permuted once (the size does not change): per group of 32 rows and block of a row +// the parts of the block go to separate planes, so that a wave reading 16 rows (lanes 0..15 one half of a 32 value +// step, lanes 16..31 the other) issues 16 byte loads that cover whole cache lines. Each lane dequantizes its 16 +// values to BF16 in registers, the halves are swapped with permlanex16 and multiplied with +// v_wmma_f32_16x16x16_bf16 against a BF16 tile of up to 48 activation columns in LDS. +// +// A block has 20 waves of 16 rows each. The gate/up kernel gives waves 0..9 gate rows and waves 10..19 the same up +// rows; the up results go to the gate waves through LDS for the GLU. + +#include "moe-wmma.cuh" +#include "moe-wmma-vecdot.cuh" +#include "mmid.cuh" +#include "quantize.cuh" + +#include +#include +#include + +#if defined(GGML_USE_HIP) + +// waves per block: 20, 16 for the tiles of 96 columns, whose accumulators take more registers +static constexpr __host__ __device__ int moe_wmma_nw(const int tile) { + return tile == 96 ? 16 : 20; +} + +// K per activation chunk in LDS at most, the chunk is prefetched in registers +static constexpr __host__ __device__ int moe_wmma_kcmax(const int tile) { + return tile == 96 ? 256 : 640; +} + +typedef short moe_wmma_short16 __attribute__((ext_vector_type(16))); +typedef float moe_wmma_float8 __attribute__((ext_vector_type(8))); + +static __device__ __forceinline__ uint32_t moe_wmma_pack_bf16(const float lo, const float hi) { + return (__float_as_uint(hi) & 0xFFFF0000u) | (__float_as_uint(lo) >> 16); +} + +// 4 values d * byte + m of the bytes of u, as 2 words of BF16 pairs +static __device__ __forceinline__ void moe_wmma_cvt4(const uint32_t u, const float d, const float m, uint32_t * aw) { + aw[0] = moe_wmma_pack_bf16(fmaf(d, (float) (u & 0xFF), m), fmaf(d, (float) ((u >> 8) & 0xFF), m)); + aw[1] = moe_wmma_pack_bf16(fmaf(d, (float) ((u >> 16) & 0xFF), m), fmaf(d, (float) (u >> 24), m)); +} + +// magnitudes with the sign mask m (0xFF in the bytes of negative values), biased by 128 +static __device__ __forceinline__ uint32_t moe_wmma_sign(const uint32_t mag, const uint32_t m) { + return ((mag ^ m) + (m & 0x01010101u)) ^ 0x80808080u; +} + +// 8 sign bits -> 2 words of 0xFF byte masks +static __device__ __forceinline__ uint2 moe_wmma_sign_masks(const uint32_t s8) { + return make_uint2((((s8 & 0xF) * 0x00204081u) & 0x01010101u) * 0xFFu, (((s8 >> 4) * 0x00204081u) & 0x01010101u) * 0xFFu); +} + +// kvalues_iq4nl + 128, looked up with 4 bit indices in the low nibbles of the bytes of q +static __device__ __forceinline__ uint32_t moe_wmma_lut_iq4nl(const uint32_t q) { + const uint32_t lo = __builtin_amdgcn_perm(0x766A5D4Fu, 0x3F2D1801u, q & 0x07070707u); + const uint32_t hi = __builtin_amdgcn_perm(0xF1D9C5B5u, 0xA6998D81u, q & 0x07070707u); + return __builtin_amdgcn_perm(hi, lo, 0x03020100u | ((q & 0x08080808u) >> 1)); +} + +static __device__ __forceinline__ void moe_wmma_copy(uint8_t * dst, const uint8_t * src, const int n) { + for (int i = 0; i < n; ++i) { + dst[i] = src[i]; + } +} + +// Per type: the block in registers, its load from the repacked layout, the dequantization of 16 values of step sub +// (32 values) for half hw, and the repacking of a GGUF block. R rows and U blocks per row of an expert; gk the +// index of a group of 32 rows and a block, r32 the row in the group. +template struct moe_wmma_type; + +struct moe_wmma_no_tables { + uint32_t unused[4]; + __device__ void init(const int, const int) {} +}; + +// IQ3_XXS: grid [g][u][half][32][32 B] (the 4 grid indices of half h of each 32 values), aux [g][u][32][32 B], d [g][u][32][2 B] +template <> struct moe_wmma_type { + static constexpr int QK = QK_K, PF = 1; + struct tables { + uint32_t grid[256]; + uint2 sgn[128]; + __device__ void init(const int tid, const int nt) { + for (int i = tid; i < 256; i += nt) { + grid[i] = iq3xxs_grid[i]; + } + for (int i = tid; i < 128; i += nt) { + sgn[i] = moe_wmma_sign_masks(i | ((__popc(i) & 1) << 7)); + } + } + }; + struct blk { uint4 grid[2]; uint4 aux[2]; uint32_t dh; }; + + static __device__ __forceinline__ void load(const uint8_t * we, const int R, const int U, const int row, const int u, const int hw, blk & o) { + const size_t gk = (size_t) (row / 32) * U + u; + const int r32 = row % 32; + const uint4 * pg = (const uint4 *) (we + ((gk * 2 + hw) * 32 + r32) * 32); + const uint4 * pa = (const uint4 *) (we + (size_t) R * U * 64 + (gk * 32 + r32) * 32); + o.grid[0] = pg[0]; + o.grid[1] = pg[1]; + o.aux[0] = pa[0]; + o.aux[1] = pa[1]; + o.dh = *(const uint16_t *) (we + (size_t) R * U * 96 + (gk * 32 + r32) * 2); + } + static __device__ __forceinline__ void deq16(const blk & b, const int sub, const int hw, const tables & t, uint32_t * aw) { + const uint32_t a32 = ((const uint32_t *) b.aux)[sub]; + const uint32_t idx4 = ((const uint32_t *) b.grid)[sub]; + const float db = __half2float(__ushort_as_half((uint16_t) b.dh)) * (0.5f + (float) (a32 >> 28)) * 0.5f; + const uint2 s0 = t.sgn[(a32 >> (14 * hw)) & 127u]; + const uint2 s1 = t.sgn[(a32 >> (14 * hw + 7)) & 127u]; + const uint32_t m[4] = { s0.x, s0.y, s1.x, s1.y }; +#pragma unroll + for (int e = 0; e < 4; ++e) { + moe_wmma_cvt4(moe_wmma_sign(t.grid[(idx4 >> (8 * e)) & 0xFF], m[e]), db, -128.0f * db, aw + 2 * e); + } + } + static __device__ void repack(const uint8_t * b, uint8_t * we, const int R, const int U, const int row, const int u) { + const size_t gk = (size_t) (row / 32) * U + u; + const int r32 = row % 32; + for (int hw = 0; hw < 2; ++hw) { + for (int ib = 0; ib < 8; ++ib) { + moe_wmma_copy(we + ((gk * 2 + hw) * 32 + r32) * 32 + 4 * ib, b + 2 + 8 * ib + 4 * hw, 4); + } + } + moe_wmma_copy(we + (size_t) R * U * 64 + (gk * 32 + r32) * 32, b + 2 + 64, 32); + moe_wmma_copy(we + (size_t) R * U * 96 + (gk * 32 + r32) * 2, b, 2); + } +}; + +// IQ4_XS: qs [g][u][half][32][64 B] (per 32 values 2 words, byte j of word w = value 8w+j | value 8w+j+4 << 4), +// meta [g][u][32][8 B] (d, scales_h, scales_l) +template <> struct moe_wmma_type { + static constexpr int QK = QK_K, PF = 1; + typedef moe_wmma_no_tables tables; + struct blk { uint4 q[4]; uint2 meta; }; + + static __device__ __forceinline__ void load(const uint8_t * we, const int R, const int U, const int row, const int u, const int hw, blk & o) { + const size_t gk = (size_t) (row / 32) * U + u; + const int r32 = row % 32; + const uint4 * pq = (const uint4 *) (we + ((gk * 2 + hw) * 32 + r32) * 64); + o.q[0] = pq[0]; + o.q[1] = pq[1]; + o.q[2] = pq[2]; + o.q[3] = pq[3]; + o.meta = *(const uint2 *) (we + (size_t) R * U * 128 + (gk * 32 + r32) * 8); + } + static __device__ __forceinline__ void deq16(const blk & b, const int sub, const int, const tables &, uint32_t * aw) { + const uint32_t * q = (const uint32_t *) b.q; + const int ls = (int) (((b.meta.y >> (4 * sub)) & 0xF) | (((b.meta.x >> (16 + 2 * sub)) & 3) << 4)); + const float db = __half2float(__ushort_as_half((uint16_t) b.meta.x)) * (float) (ls - 32); +#pragma unroll + for (int w = 0; w < 2; ++w) { + const uint32_t x = q[2 * sub + w]; + moe_wmma_cvt4(moe_wmma_lut_iq4nl(x), db, -128.0f * db, aw + 4 * w); + moe_wmma_cvt4(moe_wmma_lut_iq4nl(x >> 4), db, -128.0f * db, aw + 4 * w + 2); + } + } + static __device__ void repack(const uint8_t * b, uint8_t * we, const int R, const int U, const int row, const int u) { + const size_t gk = (size_t) (row / 32) * U + u; + const int r32 = row % 32; + const uint8_t * qs = b + 8; + for (int hw = 0; hw < 2; ++hw) { + uint8_t * o = we + ((gk * 2 + hw) * 32 + r32) * 64; + for (int ib = 0; ib < 8; ++ib) { + for (int w = 0; w < 2; ++w) { + for (int j = 0; j < 4; ++j) { + const int v0 = 8 * w + j, v1 = v0 + 4; + const int n0 = hw == 0 ? (qs[16 * ib + v0] & 0xF) : (qs[16 * ib + v0] >> 4); + const int n1 = hw == 0 ? (qs[16 * ib + v1] & 0xF) : (qs[16 * ib + v1] >> 4); + o[8 * ib + 4 * w + j] = n0 | (n1 << 4); + } + } + } + } + moe_wmma_copy(we + (size_t) R * U * 128 + (gk * 32 + r32) * 8, b, 8); + } +}; + +// IQ2_S: q [g][u][half][32][32 B] (per 32 values a word: grid index low bits of groups 2h, 2h+1, their signs), +// meta [g][u][32][16 B] (qh[8], scales[8]), d [g][u][32][2 B] +template <> struct moe_wmma_type { + static constexpr int QK = QK_K, PF = 1; + struct tables { + uint2 grid[1024]; + uint2 sgn[256]; + __device__ void init(const int tid, const int nt) { + for (int i = tid; i < 1024; i += nt) { + grid[i] = make_uint2((uint32_t) iq2s_grid[i], (uint32_t) (iq2s_grid[i] >> 32)); + } + for (int i = tid; i < 256; i += nt) { + sgn[i] = moe_wmma_sign_masks(i); + } + } + }; + struct blk { uint4 q[2]; uint4 meta; uint32_t dh; }; + + static __device__ __forceinline__ void load(const uint8_t * we, const int R, const int U, const int row, const int u, const int hw, blk & o) { + const size_t gk = (size_t) (row / 32) * U + u; + const int r32 = row % 32; + const uint4 * pq = (const uint4 *) (we + ((gk * 2 + hw) * 32 + r32) * 32); + o.q[0] = pq[0]; + o.q[1] = pq[1]; + o.meta = *(const uint4 *) (we + (size_t) R * U * 64 + (gk * 32 + r32) * 16); + o.dh = *(const uint16_t *) (we + (size_t) R * U * 80 + (gk * 32 + r32) * 2); + } + static __device__ __forceinline__ void deq16(const blk & b, const int sub, const int hw, const tables & t, uint32_t * aw) { + const uint32_t x = ((const uint32_t *) b.q)[sub]; + const uint32_t qh = (((const uint32_t *) &b.meta)[sub / 4] >> (8 * (sub % 4))) & 0xFF; + const uint32_t sc = (((const uint32_t *) &b.meta)[2 + sub / 4] >> (8 * (sub % 4) + 4 * hw)) & 0xF; + const float db = __half2float(__ushort_as_half((uint16_t) b.dh)) * (0.5f + (float) sc) * 0.25f; +#pragma unroll + for (int l = 0; l < 2; ++l) { + const uint32_t idx = ((x >> (8 * l)) & 0xFF) | (((qh >> (2 * (2 * hw + l))) & 3) << 8); + const uint2 g = t.grid[idx]; + const uint2 m = t.sgn[(x >> (16 + 8 * l)) & 0xFF]; + moe_wmma_cvt4(moe_wmma_sign(g.x, m.x), db, -128.0f * db, aw + 4 * l); + moe_wmma_cvt4(moe_wmma_sign(g.y, m.y), db, -128.0f * db, aw + 4 * l + 2); + } + } + static __device__ void repack(const uint8_t * b, uint8_t * we, const int R, const int U, const int row, const int u) { + const size_t gk = (size_t) (row / 32) * U + u; + const int r32 = row % 32; + const uint8_t * qs = b + 2, * signs = b + 2 + 32, * qh = b + 2 + 64, * scales = b + 2 + 72; + for (int hw = 0; hw < 2; ++hw) { + for (int ib = 0; ib < 8; ++ib) { + uint8_t * o = we + ((gk * 2 + hw) * 32 + r32) * 32 + 4 * ib; + o[0] = qs[4 * ib + 2 * hw]; + o[1] = qs[4 * ib + 2 * hw + 1]; + o[2] = signs[4 * ib + 2 * hw]; + o[3] = signs[4 * ib + 2 * hw + 1]; + } + } + moe_wmma_copy(we + (size_t) R * U * 64 + (gk * 32 + r32) * 16, qh, 8); + moe_wmma_copy(we + (size_t) R * U * 64 + (gk * 32 + r32) * 16 + 8, scales, 8); + moe_wmma_copy(we + (size_t) R * U * 80 + (gk * 32 + r32) * 2, b, 2); + } +}; + +// Q5_0: qs [g][u][32][16 B], qh [g][u][32][4 B], d [g][u][32][2 B] +template <> struct moe_wmma_type { + static constexpr int QK = QK5_0, PF = 2; + typedef moe_wmma_no_tables tables; + struct blk { uint4 qs; uint32_t qh; uint32_t dh; }; + + static __device__ __forceinline__ void load(const uint8_t * we, const int R, const int U, const int row, const int u, const int, blk & o) { + const size_t gi = ((size_t) (row / 32) * U + u) * 32 + row % 32; + o.qs = *(const uint4 *) (we + gi * 16); + o.qh = *(const uint32_t *) (we + (size_t) R * U * 16 + gi * 4); + o.dh = *(const uint16_t *) (we + (size_t) R * U * 20 + gi * 2); + } + static __device__ __forceinline__ void deq16(const blk & b, const int, const int hw, const tables &, uint32_t * aw) { + const uint32_t * qs = (const uint32_t *) &b.qs; + const float d = __half2float(__ushort_as_half((uint16_t) b.dh)); +#pragma unroll + for (int w = 0; w < 4; ++w) { + uint32_t x = (qs[w] >> (4 * hw)) & 0x0F0F0F0Fu; + x |= ((((b.qh >> (4 * w + 16 * hw)) & 0xFu) * 0x00204081u) & 0x01010101u) << 4; + moe_wmma_cvt4(x, d, -16.0f * d, aw + 2 * w); + } + } + static __device__ void repack(const uint8_t * b, uint8_t * we, const int R, const int U, const int row, const int u) { + const size_t gi = ((size_t) (row / 32) * U + u) * 32 + row % 32; + moe_wmma_copy(we + gi * 16, b + 6, 16); + moe_wmma_copy(we + (size_t) R * U * 16 + gi * 4, b + 2, 4); + moe_wmma_copy(we + (size_t) R * U * 20 + gi * 2, b, 2); + } +}; + +// IQ4_NL: qs [g][u][32][16 B], d [g][u][32][2 B] +template <> struct moe_wmma_type { + static constexpr int QK = QK4_NL, PF = 2; + typedef moe_wmma_no_tables tables; + struct blk { uint4 qs; uint32_t dh; }; + + static __device__ __forceinline__ void load(const uint8_t * we, const int R, const int U, const int row, const int u, const int, blk & o) { + const size_t gi = ((size_t) (row / 32) * U + u) * 32 + row % 32; + o.qs = *(const uint4 *) (we + gi * 16); + o.dh = *(const uint16_t *) (we + (size_t) R * U * 16 + gi * 2); + } + static __device__ __forceinline__ void deq16(const blk & b, const int, const int hw, const tables &, uint32_t * aw) { + const uint32_t * qs = (const uint32_t *) &b.qs; + const float d = __half2float(__ushort_as_half((uint16_t) b.dh)); +#pragma unroll + for (int w = 0; w < 4; ++w) { + moe_wmma_cvt4(moe_wmma_lut_iq4nl(qs[w] >> (4 * hw)), d, -128.0f * d, aw + 2 * w); + } + } + static __device__ void repack(const uint8_t * b, uint8_t * we, const int R, const int U, const int row, const int u) { + const size_t gi = ((size_t) (row / 32) * U + u) * 32 + row % 32; + moe_wmma_copy(we + gi * 16, b + 2, 16); + moe_wmma_copy(we + (size_t) R * U * 16 + gi * 2, b, 2); + } +}; + +// Q2_0: qs [g][u][32][16 B] (word 2 sub + h holds values 32 sub + 16 h + v, v at bits 2 (v / 4) of byte v % 4), +// d [g][u][32][2 B] +template <> struct moe_wmma_type { + static constexpr int QK = QK2_0, PF = 2; + typedef moe_wmma_no_tables tables; + struct blk { uint4 qs; uint32_t dh; }; + + static __device__ __forceinline__ void load(const uint8_t * we, const int R, const int U, const int row, const int u, const int, blk & o) { + const size_t gi = ((size_t) (row / 32) * U + u) * 32 + row % 32; + o.qs = *(const uint4 *) (we + gi * 16); + o.dh = *(const uint16_t *) (we + (size_t) R * U * 16 + gi * 2); + } + static __device__ __forceinline__ void deq16(const blk & b, const int sub, const int hw, const tables &, uint32_t * aw) { + const uint32_t * qs = (const uint32_t *) &b.qs; + const uint32_t x = hw ? qs[2 * sub + 1] : qs[2 * sub]; + const float d = __half2float(__ushort_as_half((uint16_t) b.dh)); +#pragma unroll + for (int i = 0; i < 4; ++i) { + moe_wmma_cvt4((x >> (2 * i)) & 0x03030303u, d, -d, aw + 2 * i); + } + } + static __device__ void repack(const uint8_t * b, uint8_t * we, const int R, const int U, const int row, const int u) { + const size_t gi = ((size_t) (row / 32) * U + u) * 32 + row % 32; + uint8_t o[16] = {}; + for (int j = 0; j < 64; ++j) { + const int q = (b[2 + j / 4] >> (2 * (j % 4))) & 3; + const int v = j % 16; + o[4 * (j / 16) + v % 4] |= q << (2 * (v / 4)); + } + moe_wmma_copy(we + gi * 16, o, 16); + moe_wmma_copy(we + (size_t) R * U * 16 + gi * 2, b, 2); + } +}; + +template +static constexpr size_t moe_wmma_tables_size() { + return (sizeof(typename moe_wmma_type::tables) + 15) & ~size_t(15); +} + +// one thread per row and block of n experts: GGUF blocks from src, repacked into dst +template +static __global__ void moe_wmma_repack_kernel(const uint8_t * __restrict__ src, uint8_t * __restrict__ dst, + const int n, const int R, const int U, const size_t blk_size, const size_t estride) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= (int64_t) n * R * U) { + return; + } + const int u = i % U; + const int row = (i / U) % R; + const int e = i / ((int64_t) U * R); + const size_t eo = e * estride; + moe_wmma_type::repack(src + eo + ((size_t) row * U + u) * blk_size, dst + eo, R, U, row, u); +} + +struct moe_wmma_args { + const uint8_t * w0; // the matrix, the gate matrix of the GLU kernel + const uint8_t * w1; // the up matrix of the GLU kernel + size_t estride; // bytes per expert + int R, K, U, KC; // rows, columns, blocks per row of an expert, K per activation chunk + const uint16_t * y; // BF16 activations, K per column + const int32_t * ids_src1; // compact column -> activation column + const int32_t * ids_dst; // compact column -> dst column + const ggml_cuda_mm_id_tile_spec * tiles; + float * dst; // R floats per column + uint16_t * dst16; // if not null: dst as BF16 (as moe_wmma_to_bf16 rounds), R per column +}; + +template +static __global__ void __launch_bounds__(32 * moe_wmma_nw(TILE)) +__attribute__((amdgpu_waves_per_eu(GLU ? 2 * moe_wmma_nw(TILE) / 4 : 1))) +moe_wmma_kernel(const moe_wmma_args a) { +#if defined(AMD_WMMA_256B_AVAILABLE) + typedef moe_wmma_type T; + typedef typename T::blk blk; + constexpr int NW = moe_wmma_nw(TILE); + constexpr int ROWS_WG = GLU ? 16 * NW / 2 : 16 * NW; + constexpr int NVMAX = (TILE * moe_wmma_kcmax(TILE) / 8 + 32 * NW - 1) / (32 * NW); + constexpr int SUBS = T::QK / 32, PF = T::PF; + + const ggml_cuda_mm_id_tile_spec ts = a.tiles[blockIdx.y]; + const int count = ts.col_high - ts.col_low; + if (count <= 0) { + return; + } + + extern __shared__ uint4 moe_wmma_smem[]; + typename T::tables & tab = *(typename T::tables *) moe_wmma_smem; + uint16_t * ys = (uint16_t *) ((char *) moe_wmma_smem + moe_wmma_tables_size()); + const int ystride = a.KC + 8; + + const int tid = threadIdx.y * 32 + threadIdx.x; + tab.init(tid, 32 * NW); + + const int lane = threadIdx.x, hw = lane / 16, r16 = lane % 16; + const bool is_up = GLU && threadIdx.y >= NW / 2; + const int wrow = GLU ? threadIdx.y % (NW / 2) : threadIdx.y; + const int row0 = blockIdx.x * ROWS_WG + wrow * 16; + const bool active = row0 < a.R; + const uint8_t * we = (is_up ? a.w1 : a.w0) + (size_t) ts.expert * a.estride; + const int row = row0 + r16; + + moe_wmma_float8 acc[TILE / 16] = {}; + + // the activation chunk after the one that is computed, in registers + const int nv = TILE * (a.KC / 8); + uint4 yv[NVMAX]; +#define MOE_WMMA_LOAD_Y(k0) \ + _Pragma("unroll") for (int j = 0; j < NVMAX; ++j) { \ + const int i = tid + j * 32 * NW; \ + const int t = i / (a.KC / 8), c = i % (a.KC / 8); \ + yv[j] = make_uint4(0, 0, 0, 0); \ + if (i < nv && t < count) { \ + yv[j] = ((const uint4 *) (a.y + (int64_t) a.ids_src1[ts.col_low + t] * a.K + (k0)))[c]; \ + } \ + } + + blk pf[PF]; +#pragma unroll + for (int j = 0; j < PF; ++j) { + if (active && j < a.U) { + T::load(we, a.R, a.U, row, j, hw, pf[j]); + } + } + MOE_WMMA_LOAD_Y(0); + + const int UC = a.KC / T::QK; + for (int k0 = 0; k0 < a.K; k0 += a.KC) { + __syncthreads(); // the previous chunk is no longer read (and the tables are written) +#pragma unroll + for (int j = 0; j < NVMAX; ++j) { + const int i = tid + j * 32 * NW; + if (i < nv) { + *(uint4 *) (ys + (i / (a.KC / 8)) * ystride + (i % (a.KC / 8)) * 8) = yv[j]; + } + } + __syncthreads(); + if (k0 + a.KC < a.K) { + MOE_WMMA_LOAD_Y(k0 + a.KC); + } + if (!active) { + continue; + } + for (int uc = 0; uc < UC; ++uc) { + const int u = k0 / T::QK + uc; + const blk cur = pf[0]; +#pragma unroll + for (int j = 0; j < PF - 1; ++j) { + pf[j] = pf[j + 1]; + } + if (u + PF < a.U) { + T::load(we, a.R, a.U, row, u + PF, hw, pf[PF - 1]); + } +#pragma unroll + for (int sub = 0; sub < SUBS; ++sub) { + uint32_t own[8], fr[2][8]; + T::deq16(cur, sub, hw, tab, own); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint32_t o = __builtin_amdgcn_permlanex16(own[j], own[j], 0x76543210u, 0xFEDCBA98u, false, false); + fr[0][j] = hw == 0 ? own[j] : o; + fr[1][j] = hw == 0 ? o : own[j]; + } +#pragma unroll + for (int hh = 0; hh < 2; ++hh) { + moe_wmma_short16 av; + __builtin_memcpy(&av, fr[hh], sizeof(av)); + const int kk = uc * T::QK + sub * 32 + hh * 16; +#pragma unroll + for (int c = 0; c < TILE / 16; ++c) { + // a third of the tiles of a prompt have at most 16 columns + if (16 * c < count) { + const moe_wmma_short16 bv = *(const moe_wmma_short16 *) (ys + (16 * c + r16) * ystride + kk); + acc[c] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(av, bv, acc[c]); + } + } + } + } + } + } + + // D: lane holds column lane % 16 and rows 2*i + lane / 16; rows 2*i and 2*i + 1 go out in one store, + // lanes 0..15 store i < 4 and lanes 16..31 i >= 4 + const float * xs = (const float *) ys; + if constexpr (GLU) { + __syncthreads(); + if (is_up) { +#pragma unroll + for (int c = 0; c < TILE / 16; ++c) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + ((float *) ys)[((wrow * (TILE / 16) + c) * 8 + i) * 32 + lane] = acc[c][i]; + } + } + } + __syncthreads(); + if (is_up) { + return; + } + } + if (!active) { + return; + } +#pragma unroll + for (int c = 0; c < TILE / 16; ++c) { + const int t = 16 * c + r16; + const int64_t o = t < count ? (int64_t) a.ids_dst[ts.col_low + t] * a.R + row0 : -1; +#pragma unroll + for (int i = 0; i < 8; ++i) { + float v = acc[c][i]; + if constexpr (GLU) { + v = v / (1.0f + __expf(-v)) * xs[((wrow * (TILE / 16) + c) * 8 + i) * 32 + lane]; + } + const float vo = __uint_as_float(__builtin_amdgcn_permlanex16(__float_as_uint(v), __float_as_uint(v), 0x76543210u, 0xFEDCBA98u, false, false)); + if ((hw == 0) == (i < 4) && o >= 0) { + const float2 pair = hw == 0 ? make_float2(v, vo) : make_float2(vo, v); + if (a.dst16 != nullptr) { + const uint32_t ul = __float_as_uint(pair.x), uh = __float_as_uint(pair.y); + *(uint32_t *) (a.dst16 + o + 2 * i) = ((ul + 0x7FFFu + ((ul >> 16) & 1u)) >> 16) | + (((uh + 0x7FFFu + ((uh >> 16) & 1u)) >> 16) << 16); + } else { + *(float2 *) (a.dst + o + 2 * i) = pair; + } + } + } + } +#undef MOE_WMMA_LOAD_Y +#else + GGML_UNUSED(a); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + +// one token: lane l of warp w computes row 32*(4*blockIdx.x + w) + l of the expert in slot blockIdx.y, q8_1 activations +template +static __global__ void __launch_bounds__(4 * 32) moe_rp_mmvq_kernel( + const uint8_t * __restrict__ w, const size_t estride, const int R, const int K, const int32_t * __restrict__ ids, + const block_q8_1 * __restrict__ y, const int y_stride, const int ne11, float * __restrict__ dst) { + const int slot = blockIdx.y; + const int expert = ids[slot]; + const int row = (4 * blockIdx.x + threadIdx.y) * 32 + threadIdx.x; + if (expert < 0 || row >= R) { + return; + } + dst[(int64_t) slot * R + row] = vec_dot_rp_row(w + (size_t) expert * estride, y + (int64_t) (slot % ne11) * y_stride, row, R, K); +} + +// the same for the gate (wg) and up (wu) products of a row with dst = silu(gate) * up +template +static __global__ void __launch_bounds__(4 * 32) moe_rp_mmvq_glu_kernel( + const uint8_t * __restrict__ wg, const uint8_t * __restrict__ wu, const size_t estride, const int R, const int K, + const int32_t * __restrict__ ids, const block_q8_1 * __restrict__ y, const int y_stride, const int ne11, + float * __restrict__ dst) { + const int slot = blockIdx.y; + const int expert = ids[slot]; + const int row = (4 * blockIdx.x + threadIdx.y) * 32 + threadIdx.x; + if (expert < 0 || row >= R) { + return; + } + const block_q8_1 * ys = y + (int64_t) (slot % ne11) * y_stride; + const float g = vec_dot_rp_row(wg + (size_t) expert * estride, ys, row, R, K); + const float u = vec_dot_rp_row(wu + (size_t) expert * estride, ys, row, R, K); + dst[(int64_t) slot * R + row] = g / (1.0f + expf(-g)) * u; +} + +static __global__ void moe_wmma_to_bf16(const float * __restrict__ x, uint16_t * __restrict__ y, const int K, + const int64_t ncols, const int64_t sx) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= ncols * K) { + return; + } + const int64_t col = i / K; + const uint32_t u = __float_as_uint(x[col * sx + i % K]); + y[i] = (u + 0x7FFFu + ((u >> 16) & 1u)) >> 16; +} + +// --------------------------------------------------------------------------------------------------------------- + +static char moe_wmma_repacked_tag; + +static int moe_wmma_mode() { + static const int mode = [] { + const char * env = getenv("GGML_CUDA_MOE_WMMA"); + return env ? atoi(env) : 0; + }(); + return mode; +} + +static int moe_wmma_qk(const ggml_type type) { + switch (type) { + case GGML_TYPE_IQ3_XXS: + case GGML_TYPE_IQ4_XS: + case GGML_TYPE_IQ2_S: return QK_K; + case GGML_TYPE_Q5_0: return QK5_0; + case GGML_TYPE_IQ4_NL: return QK4_NL; + case GGML_TYPE_Q2_0: return QK2_0; + default: return 0; + } +} + +bool ggml_cuda_moe_wmma_is_repacked(const ggml_tensor * w) { + return w != nullptr && w->extra == &moe_wmma_repacked_tag; +} + +static bool moe_wmma_eligible(const ggml_tensor * w) { + const int mode = moe_wmma_mode(); + if (mode == 0 || w->extra != nullptr || w->view_src != nullptr || w->buffer == nullptr) { + return false; + } + const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + if (!GGML_CUDA_CC_IS_RDNA3(cc)) { + return false; + } + const int qk = moe_wmma_qk(w->type); + if (qk == 0 || !ggml_is_contiguous(w) || w->ne[3] != 1 || w->ne[1] % 32 != 0 || w->ne[0] % qk != 0) { + return false; + } + return mode >= 2 || ggml_backend_buffer_get_usage(w->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS; +} + +template +static void moe_wmma_repack(ggml_backend_cuda_context & ctx, ggml_tensor * w) { + cudaStream_t stream = ctx.stream(); + const int R = w->ne[1], U = w->ne[0] / moe_wmma_qk(type); + const size_t estride = w->nb[2]; + const int64_t n_exp = w->ne[2]; + const int64_t batch = std::max(1, std::min(n_exp, (64 << 20) / estride)); + + ggml_cuda_pool_alloc tmp(ctx.pool(), batch * estride); + for (int64_t e0 = 0; e0 < n_exp; e0 += batch) { + const int64_t n = std::min(batch, n_exp - e0); + uint8_t * data = (uint8_t *) w->data + e0 * estride; + CUDA_CHECK(cudaMemcpyAsync(tmp.get(), data, n * estride, cudaMemcpyDeviceToDevice, stream)); + const int64_t nthreads = n * R * U; + moe_wmma_repack_kernel<<<(nthreads + 255) / 256, 256, 0, stream>>>(tmp.get(), data, n, R, U, + ggml_type_size(type), estride); + CUDA_CHECK(cudaGetLastError()); + } + w->extra = &moe_wmma_repacked_tag; + + static bool logged = false; + if (!logged) { + logged = true; + GGML_LOG_INFO("%s: repacking MoE experts for BF16 WMMA, first %s (%s)\n", __func__, w->name, ggml_type_name(type)); + } +} + +void ggml_cuda_moe_wmma_prepare(ggml_backend_cuda_context & ctx, const ggml_cgraph * cgraph) { + if (moe_wmma_mode() == 0) { + return; + } + for (int i = 0; i < cgraph->n_nodes; ++i) { + const ggml_tensor * node = cgraph->nodes[i]; + if (node->op != GGML_OP_MUL_MAT_ID || !moe_wmma_eligible(node->src[0])) { + continue; + } + ggml_tensor * w = node->src[0]; + switch (w->type) { + case GGML_TYPE_IQ3_XXS: moe_wmma_repack(ctx, w); break; + case GGML_TYPE_IQ4_XS: moe_wmma_repack (ctx, w); break; + case GGML_TYPE_IQ2_S: moe_wmma_repack (ctx, w); break; + case GGML_TYPE_Q5_0: moe_wmma_repack (ctx, w); break; + case GGML_TYPE_IQ4_NL: moe_wmma_repack (ctx, w); break; + case GGML_TYPE_Q2_0: moe_wmma_repack (ctx, w); break; + default: GGML_ABORT("fatal error"); + } + } +} + +template +static void moe_wmma_launch(const moe_wmma_args & a, const int ntiles, cudaStream_t stream) { + constexpr int NW = moe_wmma_nw(TILE); + constexpr int ROWS_WG = GLU ? 16 * NW / 2 : 16 * NW; + const size_t nbytes_shared = moe_wmma_tables_size() + (size_t) TILE * (a.KC + 8) * sizeof(uint16_t); + const size_t smpbo = ggml_cuda_info().devices[ggml_cuda_get_device()].smpbo; + GGML_ASSERT(nbytes_shared <= smpbo); + CUDA_SET_SHARED_MEMORY_LIMIT((moe_wmma_kernel), smpbo); + const dim3 grid((a.R + ROWS_WG - 1) / ROWS_WG, ntiles, 1); + const dim3 block(32, NW, 1); + moe_wmma_kernel<<>>(a); + CUDA_CHECK(cudaGetLastError()); +} + +template +static void moe_wmma_switch_type(const ggml_type type, const moe_wmma_args & a, const int ntiles, cudaStream_t stream) { + switch (type) { + case GGML_TYPE_IQ3_XXS: moe_wmma_launch(a, ntiles, stream); break; + case GGML_TYPE_IQ4_XS: moe_wmma_launch(a, ntiles, stream); break; + case GGML_TYPE_IQ2_S: moe_wmma_launch(a, ntiles, stream); break; + case GGML_TYPE_Q5_0: moe_wmma_launch(a, ntiles, stream); break; + case GGML_TYPE_IQ4_NL: moe_wmma_launch(a, ntiles, stream); break; + case GGML_TYPE_Q2_0: moe_wmma_launch(a, ntiles, stream); break; + default: GGML_ABORT("fatal error"); + } +} + +// columns per tile: the experts of a prompt get dozens of tokens each, fewer tiles dequantize the weights fewer times +static int moe_wmma_tile(const int64_t n_tokens) { + static const int big = [] { + const char * env = getenv("GGML_CUDA_MOE_WMMA_TILE"); + return env ? atoi(env) : 96; + }(); + return n_tokens >= 256 ? big : n_tokens > 8 ? 48 : 16; +} + +// the largest K per activation chunk that divides K, holds whole blocks and fits in LDS with the tables +static int moe_wmma_kc(const ggml_type type, const int K, const int tile, const bool glu) { + size_t tables = 16; + if (type == GGML_TYPE_IQ3_XXS) { + tables = moe_wmma_tables_size(); + } else if (type == GGML_TYPE_IQ2_S) { + tables = moe_wmma_tables_size(); + } + const size_t smpbo = ggml_cuda_info().devices[ggml_cuda_get_device()].smpbo; + const int qk = moe_wmma_qk(type); + // the GLU kernel hands the up results to the gate waves in the activation buffer + const size_t glu_bytes = glu ? (size_t) (moe_wmma_nw(tile) / 2) * (tile / 16) * 8 * 32 * sizeof(float) : 0; + for (int kc = std::min(K, moe_wmma_kcmax(tile)) / qk * qk; kc >= qk; kc -= qk) { + const size_t ybytes = (size_t) tile * (kc + 8) * sizeof(uint16_t); + if (K % kc == 0 && kc % 8 == 0 && tables + ybytes <= smpbo && ybytes >= glu_bytes) { + return kc; + } + } + return 0; +} + +// dst16: the result as BF16 into the memory of dst; y16: src1 is the BF16 result of an earlier run, not F32 +static void moe_wmma_run(ggml_backend_cuda_context & ctx, const ggml_tensor * w0, const ggml_tensor * w1, + const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const bool glu, const bool dst16 = false, + const bool y16 = false) { + cudaStream_t stream = ctx.stream(); + + GGML_ASSERT(src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 && ids->type == GGML_TYPE_I32); + GGML_ASSERT(src1->nb[0] == sizeof(float) && src1->nb[2] == src1->ne[1] * src1->nb[1] && src1->ne[3] == 1); + GGML_ASSERT(ggml_is_contiguous(dst)); + GGML_ASSERT(ids->nb[0] == ggml_element_size(ids)); + + const int R = w0->ne[1], K = w0->ne[0]; + const int64_t n_tokens = src1->ne[2]; + const int64_t n_expert_used = ids->ne[0]; + const int64_t n_slots = n_tokens * n_expert_used; + GGML_ASSERT(src1->ne[0] == K && dst->ne[0] == R && dst->ne[1] == n_expert_used && dst->ne[2] == n_tokens); + + if (n_tokens == 1) { + // one token: MMVQ with one lane per row on the q8_1 activations + const int64_t ne10_padded = GGML_PAD(K, MATRIX_ROW_PADDING); + ggml_cuda_pool_alloc y_q8_1(ctx.pool(), src1->ne[1] * ne10_padded / QK8_1 * sizeof(block_q8_1)); + quantize_row_q8_1_cuda((const float *) src1->data, y_q8_1.get(), K, src1->nb[1] / sizeof(float), + src1->nb[2] / sizeof(float), src1->nb[3] / sizeof(float), ne10_padded, src1->ne[1], 1, 1, stream); + CUDA_CHECK(cudaGetLastError()); + const dim3 grid((R / 32 + 3) / 4, n_expert_used, 1); + const dim3 block(32, 4, 1); +#define MOE_RP_MMVQ_CASE(T) \ + case T: \ + if (glu) { \ + moe_rp_mmvq_glu_kernel<<>>((const uint8_t *) w0->data, (const uint8_t *) w1->data, \ + w0->nb[2], R, K, (const int32_t *) ids->data, (const block_q8_1 *) y_q8_1.get(), ne10_padded / QK8_1, \ + src1->ne[1], (float *) dst->data); \ + } else { \ + moe_rp_mmvq_kernel<<>>((const uint8_t *) w0->data, w0->nb[2], R, K, \ + (const int32_t *) ids->data, (const block_q8_1 *) y_q8_1.get(), ne10_padded / QK8_1, src1->ne[1], \ + (float *) dst->data); \ + } \ + break; + switch (w0->type) { + MOE_RP_MMVQ_CASE(GGML_TYPE_IQ3_XXS) + MOE_RP_MMVQ_CASE(GGML_TYPE_IQ4_XS) + MOE_RP_MMVQ_CASE(GGML_TYPE_IQ2_S) + MOE_RP_MMVQ_CASE(GGML_TYPE_Q5_0) + MOE_RP_MMVQ_CASE(GGML_TYPE_IQ4_NL) + MOE_RP_MMVQ_CASE(GGML_TYPE_Q2_0) + default: GGML_ABORT("fatal error"); + } +#undef MOE_RP_MMVQ_CASE + CUDA_CHECK(cudaGetLastError()); + return; + } + + const int tile = moe_wmma_tile(n_tokens); + const int kc = moe_wmma_kc(w0->type, K, tile, glu); + GGML_ASSERT(kc > 0); + + ggml_cuda_pool_alloc ids_src1(ctx.pool(), n_slots); + ggml_cuda_pool_alloc ids_dst(ctx.pool(), n_slots + tile); + const int ntiles = (n_slots + tile - 1) / tile + w0->ne[2]; + ggml_cuda_pool_alloc tiles(ctx.pool(), ntiles); + ggml_cuda_launch_mm_ids_helper((const int32_t *) ids->data, ids_src1.get(), ids_dst.get(), tiles.get(), + w0->ne[2], n_tokens, n_expert_used, src1->ne[1], tile, ids->nb[1] / ggml_element_size(ids), + src1->nb[2] / src1->nb[1], /*write_inverse =*/ false, stream); + CUDA_CHECK(cudaGetLastError()); + if (getenv("GGML_CUDA_MOE_WMMA_STATS") && n_tokens > 8) { + std::vector h(ntiles); + CUDA_CHECK(cudaMemcpyAsync(h.data(), tiles.get(), ntiles * sizeof(h[0]), cudaMemcpyDeviceToHost, stream)); + CUDA_CHECK(cudaStreamSynchronize(stream)); + int hist[7] = {}, nonempty = 0; + for (const auto & t : h) { + const int c = t.col_high - t.col_low; + if (c > 0) { + nonempty++; + hist[std::min(6, (c - 1) / 8)]++; + } + } + fprintf(stderr, "%s: %s %lld slots, %d tiles, columns 1-8 %d, 9-16 %d, 17-24 %d, 25-32 %d, 33-40 %d, 41-48 %d\n", __func__, + w0->name, (long long) n_slots, nonempty, hist[0], hist[1], hist[2], hist[3], hist[4], hist[5] + hist[6]); + } + + const int64_t ncols = src1->ne[1] * n_tokens; + ggml_cuda_pool_alloc y(ctx.pool()); + // the hyper-connection pre-mix wrote these activations as BF16 already (same rounding as moe_wmma_to_bf16) + const ggml_tensor * hc = ctx.hc_bf16_src; + const bool y_hc = !y16 && hc != nullptr && src1->data == hc->data && ggml_nelements(src1) == ggml_nelements(hc) && + src1->nb[1] == K * sizeof(float) && hc->nb[1] == K * sizeof(float); + if (!y16 && !y_hc) { + y.alloc(ncols * K); + moe_wmma_to_bf16<<<(ncols * K + 255) / 256, 256, 0, stream>>>((const float *) src1->data, y.get(), K, ncols, + src1->nb[1] / sizeof(float)); + CUDA_CHECK(cudaGetLastError()); + } else if (y16) { + GGML_ASSERT(ggml_is_contiguous(src1)); + } + + moe_wmma_args a; + a.w0 = (const uint8_t *) w0->data; + a.w1 = w1 ? (const uint8_t *) w1->data : nullptr; + a.estride = w0->nb[2]; + a.R = R; + a.K = K; + a.U = K / moe_wmma_qk(w0->type); + a.KC = kc; + a.y = y16 ? (const uint16_t *) src1->data : y_hc ? ctx.hc_bf16_buf : y.get(); + a.ids_src1 = ids_src1.get(); + a.ids_dst = ids_dst.get(); + a.tiles = tiles.get(); + a.dst = (float *) dst->data; + a.dst16 = dst16 ? (uint16_t *) dst->data : nullptr; + + switch (tile) { + case 96: glu ? moe_wmma_switch_type<96, true>(w0->type, a, ntiles, stream) : moe_wmma_switch_type<96, false>(w0->type, a, ntiles, stream); break; + case 48: glu ? moe_wmma_switch_type<48, true>(w0->type, a, ntiles, stream) : moe_wmma_switch_type<48, false>(w0->type, a, ntiles, stream); break; + case 16: glu ? moe_wmma_switch_type<16, true>(w0->type, a, ntiles, stream) : moe_wmma_switch_type<16, false>(w0->type, a, ntiles, stream); break; + default: GGML_ABORT("fatal error"); + } +} + +void ggml_cuda_moe_wmma_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + const bool y16 = ctx.moe_bf16_src != nullptr && ctx.moe_bf16_src == dst->src[1] && dst->src[1]->ne[2] > 1; + ctx.moe_bf16_src = nullptr; + const bool dst16 = ctx.moe_down_bf16 == dst && dst->src[1]->ne[2] > 1; + moe_wmma_run(ctx, dst->src[0], nullptr, dst->src[1], dst->src[2], dst, /*glu =*/ false, dst16, y16); +} + +bool ggml_cuda_moe_wmma_can_fuse_glu(const ggml_tensor * gate, const ggml_tensor * up, const ggml_tensor * glu) { + const ggml_tensor * wg = gate->src[0]; + const ggml_tensor * wu = up->src[0]; + if (!ggml_cuda_moe_wmma_is_repacked(wg) || !ggml_cuda_moe_wmma_is_repacked(wu) || wg->type != wu->type || + !ggml_are_same_shape(wg, wu) || wg->nb[2] != wu->nb[2]) { + return false; + } + if (ggml_get_glu_op(glu) != GGML_GLU_OP_SWIGLU || ggml_get_op_params_i32(glu, 1) != 0) { + return false; + } + if (glu->type != GGML_TYPE_F32 || !ggml_is_contiguous(glu) || !ggml_are_same_shape(glu, gate)) { + return false; + } + return moe_wmma_kc(wg->type, wg->ne[0], moe_wmma_tile(up->src[1]->ne[2]), true) > 0; +} + +void ggml_cuda_moe_wmma_glu(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up, ggml_tensor * glu, + const bool bf16) { + moe_wmma_run(ctx, gate->src[0], up->src[0], up->src[1], up->src[2], glu, /*glu =*/ true, bf16); + ctx.moe_bf16_src = bf16 ? glu : nullptr; +} + +#else + +bool ggml_cuda_moe_wmma_is_repacked(const ggml_tensor *) { + return false; +} + +void ggml_cuda_moe_wmma_prepare(ggml_backend_cuda_context &, const ggml_cgraph *) { +} + +void ggml_cuda_moe_wmma_mul_mat_id(ggml_backend_cuda_context &, ggml_tensor *) { + GGML_ABORT("fatal error"); +} + +bool ggml_cuda_moe_wmma_can_fuse_glu(const ggml_tensor *, const ggml_tensor *, const ggml_tensor *) { + return false; +} + +void ggml_cuda_moe_wmma_glu(ggml_backend_cuda_context &, const ggml_tensor *, const ggml_tensor *, ggml_tensor *, bool) { + GGML_ABORT("fatal error"); +} + +#endif // defined(GGML_USE_HIP) diff --git a/ggml/src/ggml-cuda/moe-wmma.cuh b/ggml/src/ggml-cuda/moe-wmma.cuh new file mode 100644 index 000000000000..5f085cc8e62b --- /dev/null +++ b/ggml/src/ggml-cuda/moe-wmma.cuh @@ -0,0 +1,20 @@ +#pragma once + +#include "common.cuh" + +// MoE experts repacked in place for BF16 WMMA kernels (RDNA3), see moe-wmma.cu. +// Enabled with GGML_CUDA_MOE_WMMA=1 for the expert weights of a model (=2: any buffer, for tests). + +// whether the expert weights w were repacked; every MUL_MAT_ID with them must go through this file then +bool ggml_cuda_moe_wmma_is_repacked(const ggml_tensor * w); + +// repacks the eligible expert weights read by the MUL_MAT_ID nodes of cgraph that are not repacked yet +void ggml_cuda_moe_wmma_prepare(ggml_backend_cuda_context & ctx, const ggml_cgraph * cgraph); + +void ggml_cuda_moe_wmma_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst); + +// gate and up MUL_MAT_ID with repacked weights followed by glu = swiglu(gate, up), in one kernel +bool ggml_cuda_moe_wmma_can_fuse_glu(const ggml_tensor * gate, const ggml_tensor * up, const ggml_tensor * glu); +// bf16: glu holds the result as BF16 (in its first half), only for the repacked MUL_MAT_ID that reads it next as src1 +void ggml_cuda_moe_wmma_glu(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up, ggml_tensor * glu, + bool bf16 = false); diff --git a/ggml/src/ggml-cuda/mul-mat-f32-wmma.cu b/ggml/src/ggml-cuda/mul-mat-f32-wmma.cu new file mode 100644 index 000000000000..f1a450848176 --- /dev/null +++ b/ggml/src/ggml-cuda/mul-mat-f32-wmma.cu @@ -0,0 +1,223 @@ +#include "mul-mat-f32-wmma.cuh" + +// F32 x F32 -> F32 product on RDNA3 WMMA for the router of a MoE layer at prompt batch sizes (512 outputs, K = 2560). +// +// The WMMA units take half precision, so both operands are split into a high and a low half, x = x_hi + x_lo with +// x_hi = half(x) and x_lo = half(x - x_hi), which keeps 22 of the 24 bits of a float. A product is the sum of three +// WMMA products, x_hi*w_hi + x_lo*w_hi + x_hi*w_lo (x_lo*w_lo is below the float rounding of the sum). The three +// products of 16 values of K are summed in a fresh WMMA accumulator and then added to the running float sum: the +// accumulation inside a WMMA does not round to nearest, and chaining all of K through it loses about 2^-15 of the +// result, 20 times more than a float GEMM. This way the error against a double precision product is that of a +// float GEMM or a little smaller (max 4e-6 against 1e-5 of hipBLAS sgemm at K = 2560, activations ~N(0,1), +// weights ~N(0,0.03)); only the order of the sum differs, so a router decision can only change for near ties. +// +// Both operands are read as float, split on the way into LDS and shared by the 4 waves of a block. dst[token][output]: +// the tokens are the rows of the A operand and the outputs the columns of the B operand, so that a lane's accumulator +// is one output of 8 tokens and the 16 lanes of a half wave store 16 consecutive outputs of a token. The activations +// and weights must stay inside the half range (|x| < 65504 and not below ~1e-7 to keep the low half), which holds +// for normalized activations and router weights. +#define MUL_MAT_F32_WMMA_KC 32 // K per staged chunk +#define MUL_MAT_F32_WMMA_MAX_ROWS 1024 // most rows of the first operand +#define MUL_MAT_F32_WMMA_ROW 40 // halves per LDS row: 16 byte aligned, and the 8 lanes of a 16 byte read hit different banks + +template +static __global__ void __launch_bounds__(32*WAVES_M*WAVES_N) mul_mat_f32_wmma_kernel( + const float * __restrict__ W, const float * __restrict__ X, float * __restrict__ dst, + const int64_t n_out, const int64_t n_tok, const int K, const int64_t sw, const int64_t sx, const int64_t sd) { +#if defined(AMD_WMMA_256B_AVAILABLE) + constexpr int KC = MUL_MAT_F32_WMMA_KC; + constexpr int ROW = MUL_MAT_F32_WMMA_ROW; + constexpr int THREADS = 32*WAVES_M*WAVES_N; + constexpr int FA = TM/WAVES_M/16; // 16 token tiles per wave + constexpr int FB = TN/WAVES_N/16; // 16 output tiles per wave + constexpr int LX = TM*(KC/4)/THREADS; // float4 loads of the tokens per thread and chunk + constexpr int LW = TN*(KC/4)/THREADS; + static_assert(LX >= 1 && TM*(KC/4) % THREADS == 0 && LW >= 1 && TN*(KC/4) % THREADS == 0, "tile does not fit the block"); + + using halfx16_t = __attribute__((ext_vector_type(16))) _Float16; + using halfx4_t = __attribute__((ext_vector_type(4))) _Float16; + using floatx8_t = __attribute__((ext_vector_type(8))) float; + + const int tid = threadIdx.x; + const int lane = tid % 32; + const int wave = tid / 32; + const int g = lane / 16; + const int col = lane % 16; + const int wave_m = wave / WAVES_N; + const int wave_n = wave % WAVES_N; + + const int64_t out0 = (int64_t) blockIdx.x*TN; + const int64_t tok0 = (int64_t) blockIdx.y*TM; + + __shared__ _Float16 s_x[2][2][TM][ROW]; // [buffer][hi, lo][token][k] + __shared__ _Float16 s_w[2][2][TN][ROW]; // [buffer][hi, lo][output][k] + + float4 x_regs[LX]; + float4 w_regs[LW]; + auto load_chunk = [&](const int k0) { +#pragma unroll + for (int l = 0; l < LX; ++l) { + const int i = tid + l*THREADS; + const int r = i / (KC/4); + const int c = i % (KC/4); + x_regs[l] = tok0 + r < n_tok ? *(const float4 *) (X + (tok0 + r)*sx + k0 + c*4) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } +#pragma unroll + for (int l = 0; l < LW; ++l) { + const int i = tid + l*THREADS; + const int r = i / (KC/4); + const int c = i % (KC/4); + w_regs[l] = out0 + r < n_out ? *(const float4 *) (W + (out0 + r)*sw + k0 + c*4) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + }; + auto split_store = [&](const float4 v, _Float16 * hi, _Float16 * lo) { + const float xs[4] = {v.x, v.y, v.z, v.w}; + halfx4_t h4, l4; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const _Float16 h = (_Float16) xs[e]; + h4[e] = h; + l4[e] = (_Float16) (xs[e] - (float) h); + } + *(halfx4_t *) hi = h4; + *(halfx4_t *) lo = l4; + }; + auto store_chunk = [&](const int buf) { +#pragma unroll + for (int l = 0; l < LX; ++l) { + const int i = tid + l*THREADS; + const int r = i / (KC/4); + const int c = i % (KC/4); + split_store(x_regs[l], &s_x[buf][0][r][c*4], &s_x[buf][1][r][c*4]); + } +#pragma unroll + for (int l = 0; l < LW; ++l) { + const int i = tid + l*THREADS; + const int r = i / (KC/4); + const int c = i % (KC/4); + split_store(w_regs[l], &s_w[buf][0][r][c*4], &s_w[buf][1][r][c*4]); + } + }; + auto frag = [](const _Float16 * p) { + const int4 * q = (const int4 *) p; + union { int4 i[2]; halfx16_t h; } u; + u.i[0] = q[0]; + u.i[1] = q[1]; + return u.h; + }; + + floatx8_t acc[FA][FB]; +#pragma unroll + for (int ta = 0; ta < FA; ++ta) { +#pragma unroll + for (int tb = 0; tb < FB; ++tb) { + acc[ta][tb] = floatx8_t{0, 0, 0, 0, 0, 0, 0, 0}; + } + } + + const int n_chunks = K / KC; + load_chunk(0); + store_chunk(0); + __syncthreads(); + + for (int c = 0; c < n_chunks; ++c) { + const int buf = c & 1; + const bool has_next = c + 1 < n_chunks; + if (has_next) { + load_chunk((c + 1)*KC); + } + +#pragma unroll + for (int ks = 0; ks < KC/16; ++ks) { + halfx16_t a_hi[FA], a_lo[FA], b_hi[FB], b_lo[FB]; +#pragma unroll + for (int ta = 0; ta < FA; ++ta) { + const int row = wave_m*(FA*16) + ta*16 + col; + a_hi[ta] = frag(&s_x[buf][0][row][ks*16]); + a_lo[ta] = frag(&s_x[buf][1][row][ks*16]); + } +#pragma unroll + for (int tb = 0; tb < FB; ++tb) { + const int row = wave_n*(FB*16) + tb*16 + col; + b_hi[tb] = frag(&s_w[buf][0][row][ks*16]); + b_lo[tb] = frag(&s_w[buf][1][row][ks*16]); + } + // the three products of 16 values of K are summed on their own and then added to the running sum: + // chaining all of K through the WMMA accumulator loses about 2^-15 of the result (the accumulation + // inside a WMMA does not round to nearest), the float adds here do +#pragma unroll + for (int ta = 0; ta < FA; ++ta) { +#pragma unroll + for (int tb = 0; tb < FB; ++tb) { + floatx8_t p = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a_lo[ta], b_hi[tb], floatx8_t{0, 0, 0, 0, 0, 0, 0, 0}); + p = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a_hi[ta], b_lo[tb], p); + p = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a_hi[ta], b_hi[tb], p); + acc[ta][tb] += p; + } + } + } + if (has_next) { + store_chunk(buf ^ 1); + } + __syncthreads(); + } + + // accumulator i of this lane is token 2*i + g of the tile, output col +#pragma unroll + for (int ta = 0; ta < FA; ++ta) { +#pragma unroll + for (int tb = 0; tb < FB; ++tb) { + const int64_t out = out0 + wave_n*(FB*16) + tb*16 + col; + if (out < n_out) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int64_t tok = tok0 + wave_m*(FA*16) + ta*16 + 2*i + g; + if (tok < n_tok) { + dst[tok*sd + out] = acc[ta][tb][i]; + } + } + } + } + } +#else + GGML_UNUSED_VARS(W, X, dst, n_out, n_tok, K, sw, sx, sd); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + +bool ggml_cuda_should_use_mul_mat_f32_wmma(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * dst, int cc) { +#if defined(GGML_USE_HIP) + // tuned on RDNA3.5 (Strix Halo); GGML_HIP_F32_WMMA=0 / 1 turns it off / on + static const int env_wmma = ggml_cuda_env_switch("GGML_HIP_F32_WMMA"); + static const int min_tok = getenv("GGML_HIP_F32_WMMA_MIN_TOKENS") ? atoi(getenv("GGML_HIP_F32_WMMA_MIN_TOKENS")) : 16; + if (!GGML_CUDA_CC_IS_RDNA3(cc) || !ggml_cuda_switch_or_rdna3_5(env_wmma, cc)) { + return false; + } + return src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 && + src0->ne[2] == 1 && src0->ne[3] == 1 && src1->ne[2] == 1 && src1->ne[3] == 1 && + src0->nb[0] == sizeof(float) && src1->nb[0] == sizeof(float) && dst->nb[0] == sizeof(float) && + src0->ne[0] % MUL_MAT_F32_WMMA_KC == 0 && src0->nb[1] % 16 == 0 && src1->nb[1] % 16 == 0 && dst->nb[1] % sizeof(float) == 0 && + (uintptr_t) src0->data % 16 == 0 && (uintptr_t) src1->data % 16 == 0 && + // router-like shapes only: a few hundred outputs (the half range of the split also rules out unnormalized activations) + src0->ne[1] >= 16 && src0->ne[1] <= MUL_MAT_F32_WMMA_MAX_ROWS && src1->ne[1] >= min_tok; +#else + GGML_UNUSED_VARS(src0, src1, dst, cc); + return false; +#endif // defined(GGML_USE_HIP) +} + +template +static void launch_mul_mat_f32_wmma(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + const dim3 block(32*WAVES_M*WAVES_N, 1, 1); + const dim3 grid((src0->ne[1] + TN - 1)/TN, (src1->ne[1] + TM - 1)/TM, 1); + mul_mat_f32_wmma_kernel<<>>( + (const float *) src0->data, (const float *) src1->data, (float *) dst->data, + src0->ne[1], src1->ne[1], (int) src0->ne[0], + src0->nb[1]/sizeof(float), src1->nb[1]/sizeof(float), dst->nb[1]/sizeof(float)); + CUDA_CHECK(cudaGetLastError()); +} + +void ggml_cuda_mul_mat_f32_wmma(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32); + launch_mul_mat_f32_wmma<64, 64, 2, 2>(ctx, src0, src1, dst); +} diff --git a/ggml/src/ggml-cuda/mul-mat-f32-wmma.cuh b/ggml/src/ggml-cuda/mul-mat-f32-wmma.cuh new file mode 100644 index 000000000000..76f8c244745f --- /dev/null +++ b/ggml/src/ggml-cuda/mul-mat-f32-wmma.cuh @@ -0,0 +1,6 @@ +#include "common.cuh" + +// F32 x F32 -> F32 matrix product of a few hundred outputs for a prompt batch (the router of a MoE layer) on RDNA3 WMMA +bool ggml_cuda_should_use_mul_mat_f32_wmma(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * dst, int cc); + +void ggml_cuda_mul_mat_f32_wmma(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/norm.cu b/ggml/src/ggml-cuda/norm.cu index 3ec0252b93cd..296c79864eb2 100644 --- a/ggml/src/ggml-cuda/norm.cu +++ b/ggml/src/ggml-cuda/norm.cu @@ -99,6 +99,56 @@ static __device__ __forceinline__ void rms_norm_store_q8_1(block_q8_1 * y, const } } +// The identity-comb hyper-connection combine of one token, gated (see dsv4_hc_post_f32), followed by the RMS norm of +// each stream times mul with MMVQ's q8_1 copy: block row combines stream row and normalizes it as +// rms_norm_f32 does, from the combined values instead of loading them. +// Thread tid reads and writes the values 4*tid ... 4*tid + 3 of its stream only, so dst may be residual. +template +static __global__ void hc_post_rms_norm_f32( + const float * x, const float * residual, const float * post, float * post_dst, float * dst, + const float * mul, block_q8_1 * q8_1, const int ncols, const int64_t sr1, const int64_t sp0, + const int64_t sd1, const int64_t mul_stride_row, const float gate_scale_in, const float gate_scale_out, + const float eps) { + const int row = blockIdx.x; + const int tid = threadIdx.x; + + extern __shared__ float s_sum[]; + + float p = post[row*sp0]; + p = gate_scale_out * (1.0f / (1.0f + expf(-(gate_scale_in * p)))); + + const int ncols4 = ncols / 4; + float4 xs = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + float tmp = 0.0f; + if (tid < ncols4) { + const float4 xv = ((const float4 *) x)[tid]; + const float4 rv = ((const float4 *) (residual + row*sr1))[tid]; + xs.x = xv.x * p; + xs.x += rv.x; + xs.y = xv.y * p; + xs.y += rv.y; + xs.z = xv.z * p; + xs.z += rv.z; + xs.w = xv.w * p; + xs.w += rv.w; + ((float4 *) (post_dst + row*sd1))[tid] = xs; + tmp += xs.x*xs.x + xs.y*xs.y + xs.z*xs.z + xs.w*xs.w; + } + tmp = block_reduce(tmp, s_sum); + const float scale = rsqrtf(tmp / ncols + eps); + + if (tid < ncols4) { + float4 r = make_float4(scale*xs.x, scale*xs.y, scale*xs.z, scale*xs.w); + const float4 m = ((const float4 *) (mul + row*mul_stride_row))[tid]; + r.x *= m.x; + r.y *= m.y; + r.z *= m.z; + r.w *= m.w; + ((float4 *) (dst + row*ncols))[tid] = r; + rms_norm_store_q8_1(q8_1 + row*(ncols/QK8_1), tid, r); + } +} + template static __global__ void rms_norm_f32(const float * x, @@ -817,6 +867,75 @@ bool ggml_cuda_op_rms_norm_fused(ggml_backend_cuda_context & ctx, ggml_tensor * eps, stream, q8_1); } +static bool ggml_cuda_ranges_overlap(const ggml_tensor * a, const ggml_tensor * b) { + const char * a0 = (const char *) a->data; + const char * b0 = (const char *) b->data; + return a0 < b0 + ggml_nbytes(b) && b0 < a0 + ggml_nbytes(a); +} + +bool ggml_cuda_hc_post_rms_norm_supported(const ggml_tensor * post, const ggml_tensor * gate_scale_in, + const float * post_data, const ggml_tensor * rms, const ggml_tensor * mul) { + if (gate_scale_in == nullptr || post->src[3] != nullptr || rms->src[0] != post) { + return false; + } + const ggml_tensor * x = post->src[0]; + const ggml_tensor * residual = post->src[1]; + const ggml_tensor * p = gate_scale_in->src[0]; + const ggml_tensor * mul_src = mul->src[0] == rms ? mul->src[1] : mul->src[0]; + const int64_t ncols = post->ne[0]; + const int64_t hc = residual->ne[1]; + if (x->type != GGML_TYPE_F32 || residual->type != GGML_TYPE_F32 || p->type != GGML_TYPE_F32 || + post->type != GGML_TYPE_F32 || mul->type != GGML_TYPE_F32 || mul_src->type != GGML_TYPE_F32) { + return false; + } + // one token, contiguous rows, the shapes of the separate ops + if (x->ne[1] != 1 || residual->ne[2] != 1 || post->ne[1] != hc || ggml_nrows(post) != hc || + x->nb[0] != sizeof(float) || residual->nb[0] != sizeof(float) || post->nb[0] != sizeof(float) || + !ggml_is_contiguous(mul) || !ggml_are_same_shape(mul, post) || ggml_nrows(rms) != hc) { + return false; + } + if (mul_src->ne[0] != ncols || (mul_src->ne[1] != hc && mul_src->ne[1] != 1) || ggml_nrows(mul_src) != mul_src->ne[1] || + mul_src->nb[0] != sizeof(float)) { + return false; + } + // the configuration rms_norm_f32_dispatch picks for the RMS_NORM + MUL fusion with the q8_1 copy + const int64_t n4 = ncols / 4; + if (ncols % MATRIX_ROW_PADDING != 0 || n4 <= 512 || n4 > 1024 || ((uintptr_t) mul->data & 15) != 0 || + !ggml_cuda_is_aligned(post, 16) || !ggml_cuda_is_aligned(mul_src, 16) || !ggml_cuda_is_aligned(x, 16) || + !ggml_cuda_is_aligned(residual, 16) || residual->nb[1] % 16 != 0 || post->nb[1] % 16 != 0) { + return false; + } + // the norm is written while other blocks still read the inputs of the combine (post_data in place of p), except + // where each block reads it, the same stream of residual + const bool on_residual = mul->data == residual->data && residual->nb[1] == ncols*sizeof(float); + return !ggml_cuda_ranges_overlap(mul, x) && (on_residual || !ggml_cuda_ranges_overlap(mul, residual)) && + (post_data != nullptr || !ggml_cuda_ranges_overlap(mul, p)) && !ggml_cuda_ranges_overlap(mul, post); +} + +void ggml_cuda_op_hc_post_rms_norm(ggml_backend_cuda_context & ctx, ggml_tensor * post, + const ggml_tensor * gate_scale_in, const ggml_tensor * gate_scale_out, + const float * post_data, const ggml_tensor * rms, ggml_tensor * mul, + block_q8_1 * q8_1) { + const ggml_tensor * x = post->src[0]; + const ggml_tensor * residual = post->src[1]; + const ggml_tensor * p = gate_scale_in->src[0]; + const ggml_tensor * mul_src = mul->src[0] == rms ? mul->src[1] : mul->src[0]; + + float eps = 0.0f; + memcpy(&eps, rms->op_params, sizeof(float)); + + const int ncols = post->ne[0]; + const int64_t hc = residual->ne[1]; + + const int64_t mul_stride_row = mul_src->ne[1] == 1 ? 0 : mul_src->nb[1] / sizeof(float); + constexpr int block_size = 1024; + hc_post_rms_norm_f32<<>>( + (const float *) x->data, (const float *) residual->data, post_data ? post_data : (const float *) p->data, + (float *) post->data, (float *) mul->data, (const float *) mul_src->data, q8_1, ncols, + residual->nb[1] / sizeof(float), p->nb[0] / sizeof(float), post->nb[1] / sizeof(float), mul_stride_row, + ggml_get_op_params_f32(gate_scale_in, 0), ggml_get_op_params_f32(gate_scale_out, 0), eps); +} + void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * mul_tensor, @@ -1026,3 +1145,133 @@ void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { l2_norm_f32_cuda(src0_d, dst_d, ne00, ne01, ne02, ne03, s01, s02, s03, eps, stream); } + +// block_q8_1_mmq with the D4 layout +struct rms_norm_q8_1_mmq_d4 { + float d4[4]; + int8_t qs[128]; +}; +static_assert(sizeof(rms_norm_q8_1_mmq_d4) == 144, "unexpected block_q8_1_mmq size"); + +// One token of the Qwen HC norm: 4 streams of 2560. The normalized values stay in shared memory +// for the 4-row inject dot, so that matmul does not read the 84 MB activation again. +// q8, if not null: also the MMQ q8_1 copy of xn with the D4 layout, as quantize_mmq_q8_1 writes it. +static __global__ void rms_norm_hc_inject_f32( + const float * __restrict__ x, + const float * __restrict__ gamma, + const float * __restrict__ w, + float * __restrict__ xn, + float * __restrict__ inj, + rms_norm_q8_1_mmq_d4 * __restrict__ q8, + int n_tokens, float eps, float scale_s, float scale_b) { + constexpr int n_embd = 2560; + constexpr int hc = 4; + constexpr int k = n_embd * hc; + constexpr int nth = 256; + + __shared__ float vals[k]; + __shared__ float red[nth]; + + const int token = blockIdx.x; + const int tid = threadIdx.x; + if (token >= n_tokens) { + return; + } + + const float * x_t = x + (int64_t) token * k; + float * y_t = xn + (int64_t) token * k; + + for (int s = 0; s < hc; ++s) { + float ss = 0.0f; + for (int i = tid; i < n_embd; i += nth) { + const float v = x_t[s * n_embd + i]; + ss += v * v; + } + red[tid] = ss; + __syncthreads(); + for (int off = nth / 2; off > 0; off >>= 1) { + if (tid < off) { + red[tid] += red[tid + off]; + } + __syncthreads(); + } + const float inv = rsqrtf(red[0] / n_embd + eps); + for (int i = tid; i < n_embd; i += nth) { + const float y = inv * x_t[s * n_embd + i] * gamma[s * n_embd + i]; + vals[s * n_embd + i] = y; + y_t[s * n_embd + i] = y; + } + __syncthreads(); + } + + if (q8 != nullptr) { + // 4 values per thread, the 8 threads of 32 values share their scale + static_assert(k % (4*nth) == 0, "every thread must take part in each shuffle"); + for (int i0 = 4*tid; i0 < k; i0 += 4*nth) { + const float4 v = make_float4(vals[i0 + 0], vals[i0 + 1], vals[i0 + 2], vals[i0 + 3]); + float amax = fabsf(v.x); + amax = fmaxf(amax, fabsf(v.y)); + amax = fmaxf(amax, fabsf(v.z)); + amax = fmaxf(amax, fabsf(v.w)); +#pragma unroll + for (int offset = 4; offset > 0; offset >>= 1) { + amax = fmaxf(amax, __shfl_xor_sync(0xFFFFFFFF, amax, offset, WARP_SIZE)); + } + const float d_inv = 127.0f / amax; + char4 q; + q.x = roundf(v.x*d_inv); + q.y = roundf(v.y*d_inv); + q.z = roundf(v.z*d_inv); + q.w = roundf(v.w*d_inv); + + rms_norm_q8_1_mmq_d4 & yb = q8[(int64_t) (i0/128)*n_tokens + token]; + const int iqs = i0 % 128; + ((char4 *) yb.qs)[iqs/4] = q; + if (iqs % 32 == 0) { + yb.d4[iqs/32] = 1.0f / d_inv; + } + } + } + + float dot[hc] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (int i = tid; i < k; i += nth) { + const float y = vals[i]; +#pragma unroll + for (int r = 0; r < hc; ++r) { + dot[r] += y * w[r * k + i]; + } + } +#pragma unroll + for (int r = 0; r < hc; ++r) { + red[tid] = dot[r]; + __syncthreads(); + for (int off = nth / 2; off > 0; off >>= 1) { + if (tid < off) { + red[tid] += red[tid + off]; + } + __syncthreads(); + } + if (tid == 0) { + inj[(int64_t) token * hc + r] = scale_s * red[0] + scale_b; + } + __syncthreads(); + } +} + +void ggml_cuda_op_rms_norm_hc_inject(ggml_backend_cuda_context & ctx, + const ggml_tensor * rms, const ggml_tensor * mul, const ggml_tensor * mm, const ggml_tensor * scale, void * q8_1) { + float eps; + memcpy(&eps, rms->op_params, sizeof(float)); + const float scale_s = scale ? ggml_get_op_params_f32(scale, 0) : 1.0f; + const float scale_b = scale ? ggml_get_op_params_f32(scale, 1) : 0.0f; + const ggml_tensor * dst_inj = scale ? scale : mm; + + const int n_tokens = (int) rms->ne[2]; + const dim3 block(256, 1, 1); + const dim3 grid(n_tokens, 1, 1); + const ggml_cuda_kernel_launch_params launch = ggml_cuda_kernel_launch_params(grid, block, 0, ctx.stream()); + ggml_cuda_kernel_launch(rms_norm_hc_inject_f32, launch, + (const float *) rms->src[0]->data, (const float *) mul->src[1]->data, (const float *) mm->src[0]->data, + (float *) mul->data, (float *) dst_inj->data, (rms_norm_q8_1_mmq_d4 *) q8_1, + n_tokens, eps, scale_s, scale_b); +} diff --git a/ggml/src/ggml-cuda/norm.cuh b/ggml/src/ggml-cuda/norm.cuh index b78ee830ce26..b8895f0281c5 100644 --- a/ggml/src/ggml-cuda/norm.cuh +++ b/ggml/src/ggml-cuda/norm.cuh @@ -10,6 +10,15 @@ void ggml_cuda_op_rms_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst); bool ggml_cuda_op_rms_norm_fused(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * mul_tensor, block_q8_1 * q8_1 = nullptr); +// the gated identity-comb DSV4_HC_POST (see ggml_cuda_op_dsv4_hc_post) of one token followed by RMS_NORM + MUL with +// MMVQ's q8_1 copy, in one kernel +bool ggml_cuda_hc_post_rms_norm_supported(const ggml_tensor * post, const ggml_tensor * gate_scale_in, + const float * post_data, const ggml_tensor * rms, const ggml_tensor * mul); +void ggml_cuda_op_hc_post_rms_norm(ggml_backend_cuda_context & ctx, ggml_tensor * post, + const ggml_tensor * gate_scale_in, const ggml_tensor * gate_scale_out, + const float * post_data, const ggml_tensor * rms, ggml_tensor * mul, + block_q8_1 * q8_1); + void ggml_cuda_op_rms_norm_scale_fused(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * scale_tensor); void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx, @@ -24,4 +33,10 @@ bool ggml_cuda_op_rms_norm_fused_add_rms(ggml_backend_cuda_context & ctx, ggml_t void ggml_cuda_op_rms_norm_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst); +// RMSNorm+mul of [2560, 4, T] and the 4-row F32 inject that reads it, one pass over the normalized values. +// q8_1, if not null: also the MMQ q8_1 copy of the normalized values with the D4 layout, T rows of 10240. +void ggml_cuda_op_rms_norm_hc_inject(ggml_backend_cuda_context & ctx, + const ggml_tensor * rms, const ggml_tensor * mul, const ggml_tensor * mm, const ggml_tensor * scale, + void * q8_1 = nullptr); + void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/qsa-attn.cu b/ggml/src/ggml-cuda/qsa-attn.cu new file mode 100644 index 000000000000..d45f827ba899 --- /dev/null +++ b/ggml/src/ggml-cuda/qsa-attn.cu @@ -0,0 +1,462 @@ +// QSA prompt attention on RDNA3: each token attends to the cells of its top pools and its tail only. +// +// The mask path writes a [n_kv, n_tokens] mask and the flash attention skips the KV tiles that a query tile does not +// see, but a tile of a few queries sees the union of their picks, most of a long cache. Here the TOP_K_MASK writes the +// kept cells of each token as a list (in pool order, -1 padded) into its own buffer, and four waves per (token, KV head) +// gather the K/V rows of the list: the GQA heads of the KV head are the 16 columns of the WMMA tiles, the waves split +// the head dimension, sum their parts of the scores through LDS and accumulate their parts of the output. + +#include "qsa-attn.cuh" + +#include +#include + +#if defined(GGML_USE_HIP) + +// prompt batches only: the decode and draft verification batches keep the mask path +static constexpr int QSA_ATTN_MIN_TOKENS = 64; + +// cells per list: the picks times the pool size plus the tail, padded to the 16 keys of a step +static int64_t qsa_list_len(const ggml_tensor * mask) { + const ggml_tensor * top_k = mask->src[1]; + const ggml_tensor * blocks = mask->src[3]; + const ggml_tensor * extra = mask->src[4]; + return GGML_PAD(top_k->ne[0] * blocks->ne[0] + extra->ne[0], 16); +} + +// the views from fa->src[3] down to t, and no other reader of t or of them +static bool qsa_only_reader(const ggml_cgraph * cgraph, const ggml_tensor * t, const ggml_tensor * fa) { + if (t->flags & GGML_TENSOR_FLAG_OUTPUT) { + return false; + } + const ggml_tensor * chain[8]; + int nc = 0; + for (const ggml_tensor * c = fa->src[3]; c != t; c = c->src[0]) { + if (nc == 8 || (c->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + chain[nc++] = c; + } + auto in_chain = [&](const ggml_tensor * x) { + for (int k = 0; k < nc; ++k) { + if (x == chain[k]) { + return true; + } + } + return false; + }; + for (int i = 0; i < cgraph->n_nodes; ++i) { + const ggml_tensor * n = cgraph->nodes[i]; + if (n->view_src == t && !in_chain(n)) { + return false; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + const ggml_tensor * x = n->src[s]; + if (x != nullptr && (x == t || in_chain(x)) && n != fa && !in_chain(n)) { + return false; + } + } + } + return true; +} + +void ggml_cuda_qsa_attn_plan(ggml_backend_cuda_context & ctx, const ggml_cgraph * cgraph) { + static const bool off = getenv("GGML_CUDA_NO_QSA_ATTN") != nullptr; + ctx.qsa_fa.clear(); + ctx.qsa_masks.clear(); + if (off || !GGML_CUDA_CC_IS_RDNA3(ggml_cuda_info().devices[ctx.device].cc)) { + return; + } + for (int i = 0; i < cgraph->n_nodes; ++i) { + const ggml_tensor * fa = cgraph->nodes[i]; + if (fa->op != GGML_OP_FLASH_ATTN_EXT || fa->src[3] == nullptr || fa->src[4] != nullptr || fa->src[5] != nullptr) { + continue; + } + const ggml_tensor * t = fa->src[3]; + while (t != nullptr && (t->op == GGML_OP_RESHAPE || t->op == GGML_OP_VIEW)) { + t = t->src[0]; + } + if (t == nullptr || t->op != GGML_OP_TOP_K_MASK) { + continue; + } + const ggml_tensor * Q = fa->src[0]; + const ggml_tensor * K = fa->src[1]; + const ggml_tensor * V = fa->src[2]; + float params[3]; + memcpy(params, fa->op_params, sizeof(params)); + if (params[1] != 0.0f || params[2] != 0.0f || fa->type != GGML_TYPE_F32 || !ggml_is_contiguous(fa)) { + continue; + } + if (Q->type != GGML_TYPE_F32 || K->type != GGML_TYPE_F16 || V->type != GGML_TYPE_F16 || + Q->ne[0] != 256 || K->ne[0] != 256 || V->ne[0] != 256 || Q->ne[3] != 1 || K->ne[3] != 1 || V->ne[3] != 1 || + K->ne[2] != V->ne[2] || K->ne[1] != V->ne[1] || Q->ne[2] % K->ne[2] != 0 || Q->ne[2] / K->ne[2] > 16) { + continue; + } + if (Q->ne[1] < QSA_ATTN_MIN_TOKENS || Q->nb[0] != sizeof(float) || K->nb[0] != sizeof(half) || V->nb[0] != sizeof(half) || + Q->nb[1] % 16 != 0 || Q->nb[2] % 16 != 0 || K->nb[1] % 16 != 0 || K->nb[2] % 16 != 0 || + V->nb[1] % 16 != 0 || V->nb[2] % 16 != 0) { + continue; + } + const ggml_tensor * keep = t->src[0]; + const ggml_tensor * top_k = t->src[1]; + const ggml_tensor * score = t->src[2]; + const ggml_tensor * blocks = t->src[3]; + const ggml_tensor * extra = t->src[4]; + if (t->type != GGML_TYPE_F16 || t->ne[0] != K->ne[1] || t->ne[1] != Q->ne[1] || t->ne[2] != 1 || t->ne[3] != 1 || + t->nb[0] != sizeof(half) || t->nb[1] % sizeof(int32_t) != 0) { + continue; + } + if (score == nullptr || blocks == nullptr || extra == nullptr || top_k->type != GGML_TYPE_I32 || + score->type != GGML_TYPE_F32 || blocks->type != GGML_TYPE_I32 || extra->type != GGML_TYPE_I32 || + top_k->ne[1] != Q->ne[1] || score->ne[1] != Q->ne[1] || extra->ne[1] != Q->ne[1] || + top_k->ne[2] != 1 || score->ne[2] != 1 || extra->ne[2] != 1 || blocks->ne[2] != 1) { + continue; + } + // the kept cells take the value of keep: zero adds nothing to the scores + if (keep->op != GGML_OP_FILL || ggml_get_op_params_f32(keep, 0) != 0.0f) { + continue; + } + if (qsa_list_len(t) * (int64_t) sizeof(int32_t) > (int64_t) t->nb[1] || !qsa_only_reader(cgraph, t, fa)) { + continue; + } + ctx.qsa_fa[fa] = t; + ctx.qsa_masks.insert(t); + } +} + +// one block per token: the live picks into a bitmap of the pools, then their cells in pool order, then the tail +static __global__ void qsa_select_kernel( + const int32_t * __restrict__ top_k, const float * __restrict__ score, const int32_t * __restrict__ blocks, + const int32_t * __restrict__ extra, int32_t * __restrict__ lists, + const int n_top, const int n_pool, const int kpool, const int n_extra, const int n_kv, const int len, + const int64_t sk0, const int64_t sk1, const int64_t ss0, const int64_t ss1, const int64_t sb0, const int64_t sb1, + const int64_t se0, const int64_t se1, const int64_t sl) { + extern __shared__ uint32_t qsa_bits[]; + const int t = blockIdx.x, tid = threadIdx.x, nt = blockDim.x; + const int nw = (n_pool + 31) / 32; + uint32_t * cnt = qsa_bits + nw; + + for (int w = tid; w < nw; w += nt) { + qsa_bits[w] = 0; + } + __syncthreads(); + for (int i = tid; i < n_top; i += nt) { + const int p = top_k[i*sk0 + (int64_t) t*sk1]; + if (p >= 0 && p < n_pool && score[p*ss0 + (int64_t) t*ss1] > -INFINITY) { + atomicOr(&qsa_bits[p >> 5], 1u << (p & 31)); + } + } + __syncthreads(); + + const int per = (nw + nt - 1) / nt; + const int w0 = min(nw, tid * per), w1 = min(nw, w0 + per); + int c = 0; + for (int w = w0; w < w1; ++w) { + c += __popc(qsa_bits[w]); + } + cnt[tid] = c; + __syncthreads(); + if (tid == 0) { + uint32_t s = 0; + for (int i = 0; i < nt; ++i) { + const uint32_t x = cnt[i]; + cnt[i] = s; + s += x; + } + cnt[nt] = s; + } + __syncthreads(); + + int32_t * row = lists + (int64_t) t * sl; + int pos = cnt[tid]; + for (int w = w0; w < w1; ++w) { + uint32_t b = qsa_bits[w]; + while (b != 0) { + const int p = 32*w + __ffs(b) - 1; + b &= b - 1; + for (int k = 0; k < kpool; ++k) { + const int cell = blocks[k*sb0 + (int64_t) p*sb1]; + row[pos*kpool + k] = cell >= 0 && cell < n_kv ? cell : -1; + } + ++pos; + } + } + const int nl = cnt[nt] * kpool; + for (int j = nl + tid; j < len; j += nt) { + int v = -1; + if (j - nl < n_extra) { + const int cell = extra[(j - nl)*se0 + (int64_t) t*se1]; + v = cell >= 0 && cell < n_kv ? cell : -1; + } + row[j] = v; + } +} + +void ggml_cuda_qsa_select(ggml_backend_cuda_context & ctx, ggml_tensor * mask) { + const ggml_tensor * top_k = mask->src[1]; + const ggml_tensor * score = mask->src[2]; + const ggml_tensor * blocks = mask->src[3]; + const ggml_tensor * extra = mask->src[4]; + const int n_tokens = mask->ne[1]; + const int n_pool = blocks->ne[1]; + const int nt = 256; + const size_t nbytes_shared = ((size_t) (n_pool + 31) / 32 + nt + 1) * sizeof(uint32_t); + GGML_ASSERT(nbytes_shared <= ggml_cuda_info().devices[ctx.device].smpb); + const size_t si = sizeof(int32_t), sf = sizeof(float); + qsa_select_kernel<<>>( + (const int32_t *) top_k->data, (const float *) score->data, (const int32_t *) blocks->data, + (const int32_t *) extra->data, (int32_t *) mask->data, + top_k->ne[0], n_pool, blocks->ne[0], extra->ne[0], mask->ne[0], qsa_list_len(mask), + top_k->nb[0]/si, top_k->nb[1]/si, score->nb[0]/sf, score->nb[1]/sf, blocks->nb[0]/si, blocks->nb[1]/si, + extra->nb[0]/si, extra->nb[1]/si, mask->nb[1]/si); + CUDA_CHECK(cudaGetLastError()); +} + +typedef _Float16 qsa_half16 __attribute__((ext_vector_type(16))); +typedef float qsa_float8 __attribute__((ext_vector_type(8))); + +// A block of 4 waves per (token, KV head) pair, wave q takes dimensions 64 q .. 64 q + 63 of D = 256. +// WMMA (wave32): A lane holds row lane % 16, B lane holds column lane % 16, each with 16 values of the K dimension; D lane +// holds column lane % 16 and rows 2*i + lane / 16. The kernel works on transposes so that the head is the column: +// S^T = K Q^T (keys x heads), O^T = V^T P^T (dimensions x heads), the GQA heads of the KV head are the 16 columns. +// A D tile turns into an A/B operand of its transpose with the other half of the wave: lane l holds the even (l < 16) +// or odd (l >= 16) rows of column l % 16, permlanex16 brings the other half. V^T comes from V rows (keys as the A rows) +// times the identity, which is exact. + +// the other half of the wave, same column +static __device__ __forceinline__ float qsa_xhalf(const float v) { + return __uint_as_float(__builtin_amdgcn_permlanex16(__float_as_uint(v), __float_as_uint(v), 0x76543210u, 0xFEDCBA98u, false, false)); +} + +// the 16 rows of column lane % 16 of a D tile, in row order, as an F16 operand: r[i] holds row 2*i + lane / 16 in its +// low 16 bits; sel = 0x05040100 in lanes 0..15 and 0x01000504 in lanes 16..31 puts the other half's row next to it +static __device__ __forceinline__ qsa_half16 qsa_d_to_op(const uint32_t * r, const uint32_t sel) { + uint32_t w[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + w[i] = __builtin_amdgcn_perm(__builtin_amdgcn_permlanex16(r[i], r[i], 0x76543210u, 0xFEDCBA98u, false, false), r[i], sel); + } + qsa_half16 o; + __builtin_memcpy(&o, w, sizeof(o)); + return o; +} + +// a barrier that orders the LDS accesses only: __syncthreads also waits for the global loads in flight +static __device__ __forceinline__ void qsa_lds_barrier() { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); + __builtin_amdgcn_s_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); +} + +static __global__ void __launch_bounds__(128) qsa_attn_kernel( + const char * __restrict__ Q, const char * __restrict__ K, const char * __restrict__ V, + const int32_t * __restrict__ lists, float * __restrict__ dst, + const int n_head, const int gqa, const int len, const float scale_log2, + const int64_t nbq1, const int64_t nbq2, const int64_t nbk1, const int64_t nbk2, const int64_t nbv1, const int64_t nbv2, + const int64_t sl, const int n_head_kv) { +#if defined(AMD_WMMA_256B_AVAILABLE) + constexpr int D = 256, NW = 4, DW = D / NW, KS = DW / 16, NJ = DW / 16, QS = DW + 8; + __shared__ __align__(16) float sx[2][NW][32][8]; // [buffer][wave][lane][i]: the parts of S^T + __shared__ __align__(16) _Float16 sq[NW][16][QS]; // [wave][GQA head][dimension]: Q, rows padded against bank conflicts + + const int lane = threadIdx.x, q = __builtin_amdgcn_readfirstlane(threadIdx.y); + const int r16 = lane % 16, hi = lane / 16; + const int t = blockIdx.x / n_head_kv, g = blockIdx.x % n_head_kv; + + // Q as F16 in LDS, each wave its dimensions; Q^T is the B operand of the k-steps (column = GQA head r16) +#pragma unroll + for (int e = lane; e < 16*DW/4; e += 32) { + const int n = e / (DW/4), d = 4*(e % (DW/4)); + float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + if (n < gqa) { + v = *(const float4 *) (Q + t*nbq1 + (int64_t) (g*gqa + n)*nbq2 + (q*DW + d)*sizeof(float)); + } + sq[q][n][d + 0] = (_Float16) v.x; + sq[q][n][d + 1] = (_Float16) v.y; + sq[q][n][d + 2] = (_Float16) v.z; + sq[q][n][d + 3] = (_Float16) v.w; + } + qsa_half16 eye; +#pragma unroll + for (int e = 0; e < 16; ++e) { + eye[e] = (_Float16) (e == r16 ? 1.0f : 0.0f); + } + const qsa_half16 zero16 = {}; + const uint32_t sel = hi == 0 ? 0x05040100u : 0x01000504u; + __syncthreads(); + + const int32_t * lrow = lists + (int64_t) t * sl; + const _Float16 * qrow = &sq[q][r16][0]; + qsa_float8 o[NJ]; +#pragma unroll + for (int j = 0; j < NJ; ++j) { + o[j] = qsa_float8{}; + } + float m = -INFINITY, lacc = 0.0f; + + // software pipeline: the K rows of the next step are loaded after the QK of a step, its V rows after the PV + const int64_t koff = (int64_t) g*nbk2 + q*DW*sizeof(half), voff = (int64_t) g*nbv2 + q*DW*sizeof(half); + uint4 kx[KS][2], vx[NJ][2]; + auto load_k = [&](const int i) { + const uint4 * p = (const uint4 *) (K + (int64_t) max(i, 0)*nbk1 + koff); +#pragma unroll + for (int ks = 0; ks < KS; ++ks) { + kx[ks][0] = p[2*ks + 0]; + kx[ks][1] = p[2*ks + 1]; + } + }; + auto load_v = [&](const int i) { + const uint4 * p = (const uint4 *) (V + (int64_t) max(i, 0)*nbv1 + voff); +#pragma unroll + for (int j = 0; j < NJ; ++j) { + vx[j][0] = p[2*j + 0]; + vx[j][1] = p[2*j + 1]; + } + }; + int idx = lrow[r16]; + int idx_next = len > 16 ? lrow[16 + r16] : -1; + load_k(idx); + load_v(idx); + for (int c = 0; c < len; c += 16) { + const int buf = (c / 16) & 1; + const uint32_t vmask = (uint32_t) __ballot(idx >= 0) & 0xFFFFu; + const bool more = c + 16 < len; + + // this wave's part of S^T: A = the K rows of the 16 keys (key r16 in this lane) + qsa_float8 s = {}; +#pragma unroll + for (int ks = 0; ks < KS; ++ks) { + qsa_half16 ka, qb; + __builtin_memcpy(&ka, kx[ks], sizeof(ka)); + __builtin_memcpy(&qb, qrow + 16*ks, sizeof(qb)); + s = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(ka, qb, s); + } + if (more) { + load_k(idx_next); + } + *(qsa_float8 *) sx[buf][q][lane] = s; + qsa_lds_barrier(); + + // online softmax of head r16 over the keys 2*i + hi of this lane and the others of the other half; all + // waves add the parts in the same order + qsa_float8 sp[NW]; +#pragma unroll + for (int w = 0; w < NW; ++w) { + sp[w] = *(const qsa_float8 *) sx[buf][w][lane]; + } + float v[8]; + float mx = -INFINITY; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float sum = (sp[0][i] + sp[1][i]) + (sp[2][i] + sp[3][i]); + v[i] = (vmask >> (2*i + hi)) & 1 ? sum * scale_log2 : -INFINITY; + mx = fmaxf(mx, v[i]); + } + mx = fmaxf(mx, qsa_xhalf(mx)); + const float mn = fmaxf(m, mx); + const float mb = mn == -INFINITY ? 0.0f : mn; // no live key yet: a = p = 0 + const float a = __builtin_amdgcn_exp2f(m - mb); + uint32_t ph[8]; + float ps = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float p = __builtin_amdgcn_exp2f(v[i] - mb); + ps += p; + ph[i] = __builtin_bit_cast(uint16_t, (_Float16) p); + } + lacc = lacc * a + ps; + m = mn; + if (__ballot(a != 1.0f)) { +#pragma unroll + for (int j = 0; j < NJ; ++j) { + o[j] *= a; + } + } + + // P^T as the B operand: column = head r16, the 16 keys + const qsa_half16 pb = qsa_d_to_op(ph, sel); + + // per 16 dimensions: V rows of the keys times the identity (F16 result in the low halves) -> V^T as the + // A operand, then O^T += V^T P^T + qsa_half16 va[NJ]; +#pragma unroll + for (int j = 0; j < NJ; ++j) { + qsa_half16 x; + __builtin_memcpy(&x, vx[j], sizeof(x)); + const qsa_half16 vd = __builtin_amdgcn_wmma_f16_16x16x16_f16_w32(x, eye, zero16, false); + uint32_t vr[8]; + __builtin_memcpy(vr, &vd, sizeof(vr)); + va[j] = qsa_d_to_op(vr, sel); + } + if (more) { + idx = idx_next; + load_v(idx); + idx_next = c + 32 < len ? lrow[c + 32 + r16] : -1; + } +#pragma unroll + for (int j = 0; j < NJ; ++j) { + o[j] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(va[j], pb, o[j]); + } + } + + const float l = lacc + qsa_xhalf(lacc); + if (r16 >= gqa) { + return; + } + const float inv = l > 0.0f ? 1.0f / l : 0.0f; + float * orow = dst + ((int64_t) t * n_head + g*gqa + r16) * D + q*DW; + // O^T: lane holds head r16 and dimensions 16*j + 2*i + hi; lanes 0..15 store the pairs i < 4, lanes 16..31 i >= 4 +#pragma unroll + for (int j = 0; j < NJ; ++j) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float x = o[j][i] * inv; + const float xo = qsa_xhalf(x); + if ((hi == 0) == (i < 4)) { + *(float2 *) (orow + 16*j + 2*i) = hi == 0 ? make_float2(x, xo) : make_float2(xo, x); + } + } + } +#else + GGML_UNUSED(Q); GGML_UNUSED(K); GGML_UNUSED(V); GGML_UNUSED(lists); GGML_UNUSED(dst); GGML_UNUSED(n_head); + GGML_UNUSED(gqa); GGML_UNUSED(len); GGML_UNUSED(scale_log2); + GGML_UNUSED(nbq1); GGML_UNUSED(nbq2); GGML_UNUSED(nbk1); GGML_UNUSED(nbk2); GGML_UNUSED(nbv1); GGML_UNUSED(nbv2); + GGML_UNUSED(sl); GGML_UNUSED(n_head_kv); + NO_DEVICE_CODE; +#endif // defined(AMD_WMMA_256B_AVAILABLE) +} + +void ggml_cuda_qsa_attn(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const ggml_tensor * mask) { + const ggml_tensor * Q = dst->src[0]; + const ggml_tensor * K = dst->src[1]; + const ggml_tensor * V = dst->src[2]; + float scale; + memcpy(&scale, dst->op_params, sizeof(float)); + const int n_tokens = Q->ne[1]; + const int n_head = Q->ne[2]; + const int n_head_kv = K->ne[2]; + const dim3 grid(n_tokens * n_head_kv, 1, 1); + const dim3 block(32, 4, 1); + qsa_attn_kernel<<>>( + (const char *) Q->data, (const char *) K->data, (const char *) V->data, (const int32_t *) mask->data, (float *) dst->data, + n_head, n_head / n_head_kv, qsa_list_len(mask), scale * 1.4426950408889634f, + Q->nb[1], Q->nb[2], K->nb[1], K->nb[2], V->nb[1], V->nb[2], mask->nb[1] / sizeof(int32_t), n_head_kv); + CUDA_CHECK(cudaGetLastError()); +} + +#else + +void ggml_cuda_qsa_attn_plan(ggml_backend_cuda_context & ctx, const ggml_cgraph *) { + ctx.qsa_fa.clear(); + ctx.qsa_masks.clear(); +} + +void ggml_cuda_qsa_select(ggml_backend_cuda_context &, ggml_tensor *) { + GGML_ABORT("fatal error"); +} + +void ggml_cuda_qsa_attn(ggml_backend_cuda_context &, ggml_tensor *, const ggml_tensor *) { + GGML_ABORT("fatal error"); +} + +#endif // defined(GGML_USE_HIP) diff --git a/ggml/src/ggml-cuda/qsa-attn.cuh b/ggml/src/ggml-cuda/qsa-attn.cuh new file mode 100644 index 000000000000..6a4f0376c502 --- /dev/null +++ b/ggml/src/ggml-cuda/qsa-attn.cuh @@ -0,0 +1,16 @@ +#pragma once + +#include "common.cuh" + +// QSA prompt attention: a TOP_K_MASK whose only reader is a FLASH_ATTN_EXT writes per token the list of the cells it +// keeps into its own buffer instead of the [n_kv, n_tokens] mask, and the attention gathers just those K/V rows. + +// finds the TOP_K_MASK -> FLASH_ATTN_EXT pairs of the graph that the gather kernels handle, see ctx.qsa_fa +// (GGML_CUDA_NO_QSA_ATTN keeps the mask path) +void ggml_cuda_qsa_attn_plan(ggml_backend_cuda_context & ctx, const ggml_cgraph * cgraph); + +// the cell lists of the tokens into the memory of the TOP_K_MASK dst +void ggml_cuda_qsa_select(ggml_backend_cuda_context & ctx, ggml_tensor * mask); + +// the attention of a FLASH_ATTN_EXT dst over the cell lists of its TOP_K_MASK +void ggml_cuda_qsa_attn(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const ggml_tensor * mask); diff --git a/ggml/src/ggml-cuda/ssm-conv.cu b/ggml/src/ggml-cuda/ssm-conv.cu index f41438b3181a..286b9eb3537e 100644 --- a/ggml/src/ggml-cuda/ssm-conv.cu +++ b/ggml/src/ggml-cuda/ssm-conv.cu @@ -123,6 +123,98 @@ static __global__ void ssm_conv_long_token_f32(const float * __restrict__ src0, } } +// conv input given as the dim 0 concat of a (the first ne_a0 columns) and b, read in place without the concat: +// one thread per channel walks split_n_t tokens, so with a channel stride of one float the loads and stores are coalesced +template +static __global__ void __launch_bounds__(split_d_inner) ssm_conv_concat_f32( + const char * __restrict__ a, const char * __restrict__ b, const float * __restrict__ w, const float * __restrict__ bias, + const int64_t ne_a0, const int64_t a_nb0, const int64_t a_nb1, const int64_t a_nb2, + const int64_t b_nb0, const int64_t b_nb1, const int64_t b_nb2, const int64_t w_nb1, + float * __restrict__ dst, const int64_t dst_nb1, const int64_t dst_nb2, const int64_t nr, const int64_t n_t) { + const int64_t ir = (int64_t) blockIdx.y * split_d_inner + threadIdx.x; + const int64_t is = blockIdx.x; + const int64_t t0 = (int64_t) blockIdx.z * split_n_t; + + if (ir >= nr) { + return; + } + + const char * a_row = a + is * a_nb2 + ir * a_nb1; + const char * b_row = b + is * b_nb2 + ir * b_nb1; + + float wv[d_conv]; +#pragma unroll + for (int j = 0; j < d_conv; j++) { + wv[j] = w[ir * (w_nb1 / sizeof(float)) + j]; + } + const float bv = bias != nullptr ? bias[ir] : 0.0f; + + constexpr int n_cols = split_n_t + d_conv - 1; + const int64_t n_cols_total = n_t + d_conv - 1; + + float x[n_cols]; +#pragma unroll + for (int j = 0; j < n_cols; j++) { + const int64_t col = t0 + j; + float v = 0.0f; + if (col < ne_a0) { + v = *(const float *) (a_row + col * a_nb0); + } else if (col < n_cols_total) { + v = *(const float *) (b_row + (col - ne_a0) * b_nb0); + } + x[j] = v; + } + + float * y = (float *) ((char *) dst + is * dst_nb2) + ir; + const int64_t stride_y = dst_nb1 / sizeof(float); + +#pragma unroll + for (int i = 0; i < split_n_t; i++) { + if (t0 + i >= n_t) { + break; + } + float sumf = 0.0f; +#pragma unroll + for (int j = 0; j < d_conv; j++) { + sumf += x[i + j] * wv[j]; + } + sumf += bv; + y[(t0 + i) * stride_y] = apply_silu ? ggml_cuda_op_silu_single(sumf) : sumf; + } +} + +template +static void ssm_conv_concat_f32_cuda(const ggml_tensor * a, const ggml_tensor * b, const ggml_tensor * w, const float * bias, + ggml_tensor * dst, cudaStream_t stream) { + constexpr int threads = 128; + constexpr int split_n_t = 32; + + const int64_t nc = w->ne[0]; + const int64_t nr = dst->ne[0]; + const int64_t n_t = dst->ne[1]; + const int64_t n_s = dst->ne[2]; + + const dim3 blocks(n_s, (nr + threads - 1) / threads, (n_t + split_n_t - 1) / split_n_t); + + auto launch_kernel = [&](auto NC) { + constexpr int kNC = decltype(NC)::value; + ssm_conv_concat_f32<<>>( + (const char *) a->data, (const char *) b->data, (const float *) w->data, bias, + a->ne[0], a->nb[0], a->nb[1], a->nb[2], b->nb[0], b->nb[1], b->nb[2], w->nb[1], + (float *) dst->data, dst->nb[1], dst->nb[2], nr, n_t); + }; + + switch (nc) { + case 3: launch_kernel(std::integral_constant{}); break; + case 4: launch_kernel(std::integral_constant{}); break; + case 5: launch_kernel(std::integral_constant{}); break; + case 7: launch_kernel(std::integral_constant{}); break; + case 9: launch_kernel(std::integral_constant{}); break; + case 15: launch_kernel(std::integral_constant{}); break; + default: GGML_ABORT("Only support kernel sizes 3, 4, 5, 7, 9, 15 right now."); + } +} + template static void ssm_conv_f32_cuda(const float * src0, const float * src1, const float * bias, const int src0_nb0, const int src0_nb1, const int src0_nb2, const int src1_nb1, float * dst, const int dst_nb0, const int dst_nb1, @@ -158,7 +250,8 @@ static void ssm_conv_f32_cuda(const float * src0, const float * src1, const floa } } -void ggml_cuda_op_ssm_conv(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * bias_add_node, ggml_tensor * silu_dst) { +void ggml_cuda_op_ssm_conv(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * bias_add_node, ggml_tensor * silu_dst, + bool fuse_concat) { const struct ggml_tensor * src0 = dst->src[0]; // conv_x const struct ggml_tensor * src1 = dst->src[1]; // conv1d.weight const bool fuse_bias = bias_add_node != nullptr; @@ -179,8 +272,28 @@ void ggml_cuda_op_ssm_conv(ggml_backend_cuda_context & ctx, ggml_tensor * dst, g const int64_t n_s = out->ne[2]; // number of sequences in the batch GGML_ASSERT(out->ne[0] == nr); - GGML_ASSERT(src0->nb[0] == sizeof(float)); GGML_ASSERT(src1->nb[0] == sizeof(float)); + + if (fuse_concat) { + // src0 is the CONCAT, which is not computed: read its two inputs instead + const ggml_tensor * a = src0->src[0]; + const ggml_tensor * b = src0->src[1]; + GGML_ASSERT(src0->op == GGML_OP_CONCAT && ggml_get_op_params_i32(src0, 0) == 0); + GGML_ASSERT(a->type == GGML_TYPE_F32 && b->type == GGML_TYPE_F32 && out->type == GGML_TYPE_F32); + GGML_ASSERT(out->nb[0] == sizeof(float)); + if (fuse_bias) { + GGML_ASSERT(bias->type == GGML_TYPE_F32 && ggml_is_contiguous(bias) && ggml_nelements(bias) == nr); + } + const float * bias_d = fuse_bias ? (const float *) bias->data : nullptr; + if (fuse_silu) { + ssm_conv_concat_f32_cuda(a, b, src1, bias_d, const_cast(out), ctx.stream()); + } else { + ssm_conv_concat_f32_cuda(a, b, src1, bias_d, const_cast(out), ctx.stream()); + } + return; + } + + GGML_ASSERT(src0->nb[0] == sizeof(float)); GGML_ASSERT(src0->nb[1] == src0->ne[0] * sizeof(float)); const float * src0_d = (const float *) src0->data; @@ -205,3 +318,119 @@ void ggml_cuda_op_ssm_conv(ggml_backend_cuda_context & ctx, ggml_tensor * dst, g out->nb[2], nc, nr, n_t, n_s, stream); } } + +// RMS_NORM + SCALE of the rows of 128 channels [c0[k], c1[k]) of the convolution step's result into dst[k] +struct ssm_conv_step_norm { + float * dst[2]; + int c0[2]; + int c1[2]; + float eps[2]; + float scale[2]; +}; + +// One token of a short convolution with its state: channel c convolves its d_conv - 1 state values, read in place in +// the cache row rows[0] indexes, and x[c] with the weights as ssm_conv_f32 does (then SiLU), and writes the window's +// last d_conv - 1 values back as the new state. Each thread reads and writes the state of its own channel only. +// With has_norm, the blocks of 128 channels in a range of norm also normalize them as +// rms_norm_f32 does a row. +template +static __global__ void ssm_conv_step_f32(const float * __restrict__ cache, const int32_t * __restrict__ rows, + const int64_t row_stride, const float * __restrict__ x, + const float * __restrict__ w, const float * __restrict__ bias, + float * __restrict__ state_out, float * __restrict__ dst, const int n_channels, + const ssm_conv_step_norm norm) { + const int c = blockIdx.x*blockDim.x + threadIdx.x; + if (c >= n_channels) { + return; + } + const float * state = cache + rows[0]*row_stride + (int64_t) c*(d_conv - 1); + + float xw[d_conv]; +#pragma unroll + for (int j = 0; j < d_conv - 1; ++j) { + xw[j] = state[j]; + } + xw[d_conv - 1] = x[c]; + + float wc[d_conv]; +#pragma unroll + for (int j = 0; j < d_conv; ++j) { + wc[j] = w[c*d_conv + j]; + } + const float b = bias != nullptr ? bias[c] : 0.0f; + + float sumf = 0.0f; +#pragma unroll + for (int j = 0; j < d_conv; j++) { + sumf += xw[j] * wc[j]; + } + sumf += b; + const float y = ggml_cuda_op_silu_single(sumf); + dst[c] = y; + + if constexpr (has_norm) { + constexpr int ncols = 128; + const int c_block = blockIdx.x*blockDim.x; + int k = -1; +#pragma unroll + for (int kk = 0; kk < 2; ++kk) { + if (norm.dst[kk] != nullptr && c_block >= norm.c0[kk] && c_block < norm.c1[kk]) { + k = kk; + } + } + if (k >= 0) { + __shared__ float s_y[ncols]; + s_y[threadIdx.x] = y; + __syncthreads(); + if (threadIdx.x < WARP_SIZE) { + const float4 xs = ((const float4 *) s_y)[threadIdx.x]; + float tmp = 0.0f; + tmp += xs.x*xs.x + xs.y*xs.y + xs.z*xs.z + xs.w*xs.w; + tmp = warp_reduce_sum(tmp); + const float scale = rsqrtf(tmp / ncols + norm.eps[k]); + float4 r = make_float4(scale*xs.x, scale*xs.y, scale*xs.z, scale*xs.w); + r.x *= norm.scale[k]; + r.y *= norm.scale[k]; + r.z *= norm.scale[k]; + r.w *= norm.scale[k]; + ((float4 *) (norm.dst[k] + (c_block - norm.c0[k])))[threadIdx.x] = r; + } + } + } + +#pragma unroll + for (int j = 0; j < d_conv - 1; ++j) { + state_out[(int64_t) c*(d_conv - 1) + j] = xw[j + 1]; + } +} + +void ggml_cuda_op_ssm_conv_step(ggml_backend_cuda_context & ctx, const ggml_tensor * state_rows, const ggml_tensor * x, + const ggml_tensor * conv_w, ggml_tensor * state_out, ggml_tensor * dst, + const ggml_tensor * const * norm, const ggml_tensor * const * norm_scale) { + const int d_conv = conv_w->ne[0]; + const int n_channels = conv_w->ne[1]; + GGML_ASSERT(d_conv == 4); + const int threads = 128; + + ssm_conv_step_norm args = {}; + bool has_norm = false; + for (int k = 0; norm != nullptr && k < 2; ++k) { + if (norm[k] == nullptr) { + continue; + } + const ggml_tensor * view = norm[k]->src[0]; + GGML_ASSERT(n_channels % threads == 0 && view->ne[0] == threads && view->view_offs % (threads*sizeof(float)) == 0); + args.dst[k] = (float *) norm_scale[k]->data; + args.c0[k] = view->view_offs / sizeof(float); + args.c1[k] = args.c0[k] + ggml_nelements(view); + args.eps[k] = ggml_get_op_params_f32(norm[k], 0); + args.scale[k] = ggml_get_op_params_f32(norm_scale[k], 0); + has_norm = true; + } + + auto kernel = has_norm ? ssm_conv_step_f32<4, true> : ssm_conv_step_f32<4, false>; + kernel<<<(n_channels + threads - 1) / threads, threads, 0, ctx.stream()>>>( + (const float *) state_rows->src[0]->data, (const int32_t *) state_rows->src[1]->data, + state_rows->src[0]->nb[1] / sizeof(float), (const float *) x->data, (const float *) conv_w->data, nullptr, + (float *) state_out->data, (float *) dst->data, n_channels, args); +} diff --git a/ggml/src/ggml-cuda/ssm-conv.cuh b/ggml/src/ggml-cuda/ssm-conv.cuh index 8514ca84920f..33262deb280c 100644 --- a/ggml/src/ggml-cuda/ssm-conv.cuh +++ b/ggml/src/ggml-cuda/ssm-conv.cuh @@ -1,3 +1,13 @@ #include "common.cuh" -void ggml_cuda_op_ssm_conv(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * bias_add_node = nullptr, ggml_tensor * silu_dst = nullptr); +// fuse_concat: dst->src[0] is a dim 0 CONCAT that was not computed, the kernel reads its two inputs +void ggml_cuda_op_ssm_conv(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * bias_add_node = nullptr, ggml_tensor * silu_dst = nullptr, + bool fuse_concat = false); + +// dst = SiLU(the convolution of each channel's state, read in place through the row index of state_rows (a GET_ROWS +// of one cache row), and x with conv_w), and state_out = the window's last d_conv - 1 values, for one token +// norm[k], if not null: also RMS_NORM + SCALE (see ggml_cuda_op_rms_norm_scale_fused) of rows of 128 channels of dst, +// read through a view, into norm[k]'s SCALE node +void ggml_cuda_op_ssm_conv_step(ggml_backend_cuda_context & ctx, const ggml_tensor * state_rows, const ggml_tensor * x, + const ggml_tensor * conv_w, ggml_tensor * state_out, ggml_tensor * dst, + const ggml_tensor * const * norm = nullptr, const ggml_tensor * const * norm_scale = nullptr); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu index fd41e71b1421..c53598b04f65 100644 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu @@ -3,4 +3,7 @@ #include "../fattn-mma-f16.cuh" DECL_FATTN_MMA_F16_CASE(192, 128, 2, 16); +#if defined(GGML_USE_HIP) +DECL_FATTN_MMA_F16_CASE(256, 256, 2, 16); +#endif // defined(GGML_USE_HIP) DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16); diff --git a/ggml/src/ggml-cuda/template-instances/generate_cu_files.py b/ggml/src/ggml-cuda/template-instances/generate_cu_files.py index f49a015ae1f5..63ebeddd73de 100755 --- a/ggml/src/ggml-cuda/template-instances/generate_cu_files.py +++ b/ggml/src/ggml-cuda/template-instances/generate_cu_files.py @@ -34,6 +34,11 @@ SOURCE_FATTN_MMA_CASE = "DECL_FATTN_MMA_F16_CASE({head_size_kq}, {head_size_v}, {ncols1}, {ncols2});\n" +SOURCE_FATTN_MMA_CASE_HIP = """#if defined(GGML_USE_HIP) +DECL_FATTN_MMA_F16_CASE({head_size_kq}, {head_size_v}, {ncols1}, {ncols2}); +#endif // defined(GGML_USE_HIP) +""" + TYPES_MMQ = [ "GGML_TYPE_Q1_0", "GGML_TYPE_Q2_0", @@ -99,9 +104,12 @@ def get_short_name(long_quant_name): continue if head_size_kq == 576 and ncols2 not in (4, 16, 32): # Deepseek, GLM 4.7 Flash continue + head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq) + if head_size_kq == 256 and ncols1 == 2 and ncols2 == 16: # sparse Qwen QSA prompt batches on RDNA + f.write(SOURCE_FATTN_MMA_CASE_HIP.format(ncols1=ncols1, ncols2=ncols2, head_size_kq=head_size_kq, head_size_v=head_size_v)) + continue if head_size_kq not in (192, 320, 576) and ncols2 in (16, 32): continue - head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq) f.write(SOURCE_FATTN_MMA_CASE.format(ncols1=ncols1, ncols2=ncols2, head_size_kq=head_size_kq, head_size_v=head_size_v)) for type in TYPES_MMQ: diff --git a/ggml/src/ggml-cuda/top-k.cu b/ggml/src/ggml-cuda/top-k.cu index 19cb45d1f93c..f9173104dc9c 100644 --- a/ggml/src/ggml-cuda/top-k.cu +++ b/ggml/src/ggml-cuda/top-k.cu @@ -258,6 +258,223 @@ static __global__ void top_k_radix_gather( } } +#if defined(GGML_USE_HIP) + +// one block per row, the row stays in registers: a radix histogram of 4 passes of 8 bits over the keys that match the prefix +// found so far gives the k-th largest key T, then the keys above T and the lowest columns of the keys equal to T are written. +// Same selected set as the radix path below (the lowest columns win ties), but one launch instead of 10. +// The histogram has one copy per 4 lanes to keep the shared atomics of the dense first pass apart. +template +static __global__ void __launch_bounds__(BLOCK_SIZE) top_k_block_kernel( + const float * __restrict__ src, int * __restrict__ dst, const int ncols, const int k) { + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + constexpr int nwarps = BLOCK_SIZE / warp_size; + constexpr int NCOPY = 8; + constexpr int BPL = 256 / warp_size; // histogram bins per lane + using lane_mask_t = std::conditional_t; + constexpr uint64_t ballot_mask = ~(lane_mask_t) 0; + const auto popc = [](const lane_mask_t mask) { + if constexpr (warp_size == 64) { + return __popcll(mask); + } else { + return __popc(mask); + } + }; + + const int tid = threadIdx.x; + const int lane = tid % warp_size; + const int warp = tid / warp_size; + + const float * row_src = src + (size_t) blockIdx.x * ncols; + int * row_dst = dst + (size_t) blockIdx.x * k; + + uint32_t key[MPT]; +#pragma unroll + for (int j = 0; j < MPT; ++j) { + const int i = tid + j*BLOCK_SIZE; + key[j] = i < ncols ? top_k_float_to_ordered(row_src[i]) : 0u; + } + + __shared__ int hist[NCOPY][256 + 1]; // the odd row length puts the copies in different banks + __shared__ int sel[3]; + __shared__ int counters[2]; + __shared__ int scan[2][nwarps]; + + if (tid < 2) { + counters[tid] = 0; + } + + uint32_t prefix = 0; + uint32_t pmask = 0; + int rank = k; // rank of the wanted key among the keys that match the prefix +#pragma unroll 1 + for (int shift = 24; shift >= 0; shift -= 8) { + for (int i = tid; i < NCOPY*(256 + 1); i += BLOCK_SIZE) { + (&hist[0][0])[i] = 0; + } + __syncthreads(); + +#pragma unroll + for (int j = 0; j < MPT; ++j) { + if (tid + j*BLOCK_SIZE < ncols && (key[j] & pmask) == prefix) { + atomicAdd(&hist[lane % NCOPY][(key[j] >> shift) & 255], 1); + } + } + __syncthreads(); + + if (warp == 0) { + // lane l owns the bins BPL*l .. BPL*l + BPL - 1 + int c[BPL]; + int lane_sum = 0; +#pragma unroll + for (int b = 0; b < BPL; ++b) { + int s = 0; +#pragma unroll + for (int h = 0; h < NCOPY; ++h) { + s += hist[h][lane*BPL + b]; + } + c[b] = s; + lane_sum += s; + } + // keys in the bins of the lanes above + int above = lane_sum; +#pragma unroll + for (int offset = 1; offset < warp_size; offset *= 2) { + const int v = __shfl_down_sync(ballot_mask, above, offset, warp_size); + if (lane + offset < warp_size) { + above += v; + } + } + above -= lane_sum; + if (above < rank && above + lane_sum >= rank) { + int cum = above; +#pragma unroll + for (int b = BPL - 1; b >= 0; --b) { + if (cum + c[b] >= rank) { + sel[0] = lane*BPL + b; + sel[1] = rank - cum; + sel[2] = c[b]; + break; + } + cum += c[b]; + } + } + } + __syncthreads(); + prefix |= (uint32_t) sel[0] << shift; + pmask |= 255u << shift; + rank = sel[1]; + } + + // the keys above T all belong to the result, rank of the keys equal to T do + const uint32_t T = prefix; + const int n_gt = k - rank; + const int n_ties = sel[2]; + + if (rank == n_ties) { + // every key equal to T is taken, the order of the result is not specified +#pragma unroll + for (int j = 0; j < MPT; ++j) { + const int i = tid + j*BLOCK_SIZE; + const bool gt = i < ncols && key[j] > T; + const bool tie = i < ncols && key[j] == T; + const lane_mask_t below = ((lane_mask_t) 1 << lane) - 1; + const lane_mask_t m_gt = (lane_mask_t) __ballot_sync(ballot_mask, gt); + const lane_mask_t m_tie = (lane_mask_t) __ballot_sync(ballot_mask, tie); + int base_gt = 0; + int base_tie = 0; + if (lane == 0) { + if (m_gt) { base_gt = atomicAdd(&counters[0], popc(m_gt)); } + if (m_tie) { base_tie = atomicAdd(&counters[1], popc(m_tie)); } + } + base_gt = __shfl_sync(ballot_mask, base_gt, 0, warp_size); + base_tie = __shfl_sync(ballot_mask, base_tie, 0, warp_size); + if (gt) { + row_dst[base_gt + popc(m_gt & below)] = i; + } else if (tie) { + row_dst[n_gt + base_tie + popc(m_tie & below)] = i; + } + } + return; + } + + // more keys equal to T than slots left, the lowest columns win: count the ties in column order + int base = 0; +#pragma unroll + for (int j = 0; j < MPT; ++j) { + const int i = tid + j*BLOCK_SIZE; + const bool gt = i < ncols && key[j] > T; + const bool tie = i < ncols && key[j] == T; + const lane_mask_t below = ((lane_mask_t) 1 << lane) - 1; + const lane_mask_t m_gt = (lane_mask_t) __ballot_sync(ballot_mask, gt); + const lane_mask_t m_tie = (lane_mask_t) __ballot_sync(ballot_mask, tie); + + if (lane == 0) { + scan[j & 1][warp] = popc(m_tie); + } + int base_gt = 0; + if (lane == 0 && m_gt) { + base_gt = atomicAdd(&counters[0], popc(m_gt)); + } + base_gt = __shfl_sync(ballot_mask, base_gt, 0, warp_size); + __syncthreads(); + int before = 0; + int chunk = 0; +#pragma unroll + for (int w = 0; w < nwarps; ++w) { + const int v = scan[j & 1][w]; + before += w < warp ? v : 0; + chunk += v; + } + + const int pos_tie = base + before + popc(m_tie & below); + if (gt) { + row_dst[base_gt + popc(m_gt & below)] = i; + } else if (tie && pos_tie < rank) { + row_dst[n_gt + pos_tie] = i; + } + base += chunk; + } +} + +template +static void top_k_block_launch(const float * src, int * dst, int ncols, int64_t nrows, int k, cudaStream_t stream) { + top_k_block_kernel<<<(unsigned) nrows, BLOCK_SIZE, 0, stream>>>(src, dst, ncols, k); + CUDA_CHECK(cudaGetLastError()); +} + +// the widest row the block kernel holds in registers +#define GGML_CUDA_TOP_K_BLOCK_MAX_COLS 32768 + +template +static void top_k_block_mpt(const float * src, int * dst, int ncols, int64_t nrows, int k, cudaStream_t stream) { + const int mpt = (ncols + BLOCK_SIZE - 1) / BLOCK_SIZE; + if (mpt <= 4) { top_k_block_launch(src, dst, ncols, nrows, k, stream); } + else if (mpt <= 8) { top_k_block_launch(src, dst, ncols, nrows, k, stream); } + else if (mpt <= 12) { top_k_block_launch(src, dst, ncols, nrows, k, stream); } + else if (mpt <= 16) { top_k_block_launch(src, dst, ncols, nrows, k, stream); } + else if (mpt <= 24) { top_k_block_launch(src, dst, ncols, nrows, k, stream); } + else if (mpt <= 32) { top_k_block_launch(src, dst, ncols, nrows, k, stream); } + else if (mpt <= 40) { top_k_block_launch(src, dst, ncols, nrows, k, stream); } + else if (mpt <= 48) { top_k_block_launch(src, dst, ncols, nrows, k, stream); } + else { top_k_block_launch(src, dst, ncols, nrows, k, stream); } +} + +// a few rows (decode, verify batches) are latency bound and take 1024 threads, so do rows of up to 12288 columns (the pools +// of a 48K context); many wide rows run faster with 512 threads and more keys per thread +static bool top_k_block_cuda(const float * src, int * dst, int ncols, int64_t nrows, int k, cudaStream_t stream) { + if (k > ncols || ncols > GGML_CUDA_TOP_K_BLOCK_MAX_COLS) { + return false; + } + if (ncols <= 12288 || nrows <= 16) { + top_k_block_mpt<1024>(src, dst, ncols, nrows, k, stream); + } else { + top_k_block_mpt<512>(src, dst, ncols, nrows, k, stream); + } + return true; +} +#endif // defined(GGML_USE_HIP) + static void top_k_radix_cuda( ggml_cuda_pool & pool, const float * src, int * dst, int ncols, int64_t nrows, int k, cudaStream_t stream) { @@ -316,11 +533,12 @@ static void top_k_argsort_cuda( #else GGML_ABORT("CUB is not available"); #endif // GGML_CUDA_USE_CUB + CUDA_CHECK(cudaMemcpy2DAsync(dst, k * sizeof(int), tmp, ncols * sizeof(int), k * sizeof(int), iter_nrows, + cudaMemcpyDeviceToDevice, stream)); } else { - argsort_f32_i32_cuda_bitonic(src, tmp, ncols, iter_nrows, GGML_SORT_ORDER_DESC, stream); + // the bitonic sort writes the first k columns itself + argsort_f32_i32_cuda_bitonic(src, dst, ncols, iter_nrows, GGML_SORT_ORDER_DESC, stream, k); } - CUDA_CHECK(cudaMemcpy2DAsync(dst, k * sizeof(int), tmp, ncols * sizeof(int), k * sizeof(int), iter_nrows, - cudaMemcpyDeviceToDevice, stream)); src += (size_t) ncols * iter_nrows; dst += (size_t) k * iter_nrows; @@ -364,6 +582,15 @@ void ggml_cuda_op_top_k(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { } } +#if defined(GGML_USE_HIP) + // rows of a few thousand columns (e.g. the Qwen QSA indexer scores): one block per row instead of 10 launches + static const int env_block = ggml_cuda_env_switch("GGML_HIP_TOPK_BLOCK"); + if (ggml_cuda_switch_or_rdna3_5(env_block, ggml_cuda_info().devices[device].cc) && + top_k_block_cuda(src0_d, dst_d, ncols, nrows, k, stream)) { + return; + } +#endif // defined(GGML_USE_HIP) + if (nrows > GGML_CUDA_TOP_K_NROWS_THRESHOLD) { top_k_radix_cuda(pool, src0_d, dst_d, ncols, nrows, k, stream); return; diff --git a/ggml/src/ggml-cuda/topk-moe.cu b/ggml/src/ggml-cuda/topk-moe.cu index e99b2e84a3cb..dbb5aba53dd0 100644 --- a/ggml/src/ggml-cuda/topk-moe.cu +++ b/ggml/src/ggml-cuda/topk-moe.cu @@ -127,40 +127,16 @@ __device__ void group_mask_warp_inplace(float (&vals)[experts_per_thread], const } #endif // !defined(GGML_USE_HIP) || HIP_VERSION >= 60300000 -/* - This kernel does the following: - 1. optionally softmax over the logits per token [n_experts, n_tokens] - 2. argmax reduce over the top-k (n_experts_used) logits - 3. write weights + ids to global memory - 4. optionally normalize the weights or apply softmax over the selected logits - - It is intended as fusion of softmax->top-k->get_rows pipeline for MoE models -*/ +// The top-k selection of topk_moe_cuda for one row, by one warp (lane threadIdx.x) template -__launch_bounds__(TOPK_MOE_ROWS_PER_BLOCK * WARP_SIZE, 1) -__global__ void topk_moe_cuda(const float * logits, - float * weights, - int32_t * ids, - float * bias, - const int n_rows, - const int n_expert_used, - const float clamp_val, - const float scale_val, - const topk_moe_config config) { -#if defined(GGML_USE_MUSA) - // MUSA: every warp of a partially filled block must reach the barrier below. - const int row = MIN(blockIdx.x * blockDim.y + threadIdx.y, n_rows - 1); -#else - const int row = blockIdx.x * blockDim.y + threadIdx.y; -#endif // defined(GGML_USE_MUSA) - if (row >= n_rows) { - return; - } - - logits += n_experts * row; - weights += n_expert_used * row; - ids += n_experts * row; - +static __device__ __forceinline__ void topk_moe_row(const float * logits, + float * weights, + int32_t * ids, + float * bias, + const int n_expert_used, + const float clamp_val, + const float scale_val, + const topk_moe_config config) { constexpr int experts_per_thread = (n_experts > WARP_SIZE) ? n_experts / WARP_SIZE : 1; float wt[experts_per_thread]; @@ -340,6 +316,43 @@ __global__ void topk_moe_cuda(const float * logits, } } +/* + This kernel does the following: + 1. optionally softmax over the logits per token [n_experts, n_tokens] + 2. argmax reduce over the top-k (n_experts_used) logits + 3. write weights + ids to global memory + 4. optionally normalize the weights or apply softmax over the selected logits + + It is intended as fusion of softmax->top-k->get_rows pipeline for MoE models +*/ +template +__launch_bounds__(TOPK_MOE_ROWS_PER_BLOCK * WARP_SIZE, 1) +__global__ void topk_moe_cuda(const float * logits, + float * weights, + int32_t * ids, + float * bias, + const int n_rows, + const int n_expert_used, + const float clamp_val, + const float scale_val, + const topk_moe_config config) { +#if defined(GGML_USE_MUSA) + // MUSA: every warp of a partially filled block must reach the barrier below. + const int row = MIN(blockIdx.x * blockDim.y + threadIdx.y, n_rows - 1); +#else + const int row = blockIdx.x * blockDim.y + threadIdx.y; +#endif // defined(GGML_USE_MUSA) + if (row >= n_rows) { + return; + } + + logits += n_experts * row; + weights += n_expert_used * row; + ids += n_experts * row; + + topk_moe_row(logits, weights, ids, bias, n_expert_used, clamp_val, scale_val, config); +} + template static void launch_topk_moe_cuda(ggml_backend_cuda_context & ctx, const float * logits, @@ -472,6 +485,225 @@ void ggml_cuda_op_topk_moe(ggml_backend_cuda_context & ctx, } } +// The F32 router product of one token as mul_mat_vec_f computes it, block row computing logit +// row, and the top-k selection of topk_moe_cuda on the logits by the last block to finish (counted in counter, which it +// resets). +template +__launch_bounds__(256, 1) +static __global__ void router_topk_moe_cuda(const float * x, + const float * y, + float * logits, + const int ncols2, + const int stride_row, + float * weights, + int32_t * ids, + float * bias, + const int n_expert_used, + const float clamp_val, + const float scale_val, + const topk_moe_config config, + int * counter) { + constexpr int block_size = 256; + const int row = blockIdx.x; + const int tid = threadIdx.y*WARP_SIZE + threadIdx.x; + + __shared__ float buf_iw[WARP_SIZE]; + if (threadIdx.y == 0) { + buf_iw[threadIdx.x] = 0.0f; + } + __syncthreads(); + + float sumf = 0.0f; + const float2 * x2 = (const float2 *) (x + (int64_t) row*stride_row); + const float2 * y2 = (const float2 *) y; + for (int col2 = tid; col2 < ncols2; col2 += block_size) { + const float2 tmpx = x2[col2]; + const float2 tmpy = y2[col2]; + ggml_cuda_mad(sumf, tmpx.x, tmpy.x); + ggml_cuda_mad(sumf, tmpx.y, tmpy.y); + } + sumf = warp_reduce_sum(sumf); + buf_iw[threadIdx.y] = sumf; + __syncthreads(); + if (threadIdx.y != 0) { + return; + } + sumf = buf_iw[threadIdx.x]; + sumf = warp_reduce_sum(sumf); + if (threadIdx.x == 0) { + logits[row] = sumf; + } + + __threadfence(); + int arrived = 0; + if (threadIdx.x == 0) { + arrived = atomicAdd(counter, 1); + } + arrived = __shfl_sync(0xFFFFFFFF, arrived, 0, WARP_SIZE); + if (arrived != (int) gridDim.x - 1) { + return; + } + __threadfence(); + if (threadIdx.x == 0) { + *counter = 0; + } + topk_moe_row(logits, weights, ids, bias, n_expert_used, clamp_val, scale_val, config); +} + +static __global__ void router_weights_f32_to_bf16(const float * x, uint16_t * dst, const int64_t n) { + const int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x; + if (i < n) { + // round to nearest even, as SnowLLM stores the router + const uint32_t u = __float_as_uint(x[i]); + dst[i] = (u + 0x7FFF + ((u >> 16) & 1)) >> 16; + } +} + +void ggml_cuda_router_weights_to_bf16(const float * x, void * dst, const int64_t n, cudaStream_t stream) { + const int block_size = 256; + router_weights_f32_to_bf16<<<(n + block_size - 1) / block_size, block_size, 0, stream>>>(x, (uint16_t *) dst, n); +} + +// The router product of one token with BF16 weights (the F32 ones rounded, see ggml_cuda_router_weights_to_bf16), block +// row computing logit row with 4 weights per thread and step, and the top-k selection as router_topk_moe_cuda does it. +template +__launch_bounds__(256, 1) +static __global__ void router_topk_moe_bf16_cuda(const uint16_t * x, + const float * y, + float * logits, + const int ncols4, + const int stride_row, + float * weights, + int32_t * ids, + float * bias, + const int n_expert_used, + const float clamp_val, + const float scale_val, + const topk_moe_config config, + int * counter) { + constexpr int block_size = 256; + const int row = blockIdx.x; + const int tid = threadIdx.y*WARP_SIZE + threadIdx.x; + + __shared__ float buf_iw[WARP_SIZE]; + if (threadIdx.y == 0) { + buf_iw[threadIdx.x] = 0.0f; + } + __syncthreads(); + + float sumf = 0.0f; + const uint2 * x4 = (const uint2 *) (x + (int64_t) row*stride_row); + const float4 * y4 = (const float4 *) y; + for (int col4 = tid; col4 < ncols4; col4 += block_size) { + const uint2 w = x4[col4]; + const float4 yv = y4[col4]; + sumf += __uint_as_float(w.x << 16) * yv.x; + sumf += __uint_as_float(w.x & 0xFFFF0000u) * yv.y; + sumf += __uint_as_float(w.y << 16) * yv.z; + sumf += __uint_as_float(w.y & 0xFFFF0000u) * yv.w; + } + sumf = warp_reduce_sum(sumf); + buf_iw[threadIdx.y] = sumf; + __syncthreads(); + if (threadIdx.y != 0) { + return; + } + sumf = buf_iw[threadIdx.x]; + sumf = warp_reduce_sum(sumf); + if (threadIdx.x == 0) { + logits[row] = sumf; + } + + __threadfence(); + int arrived = 0; + if (threadIdx.x == 0) { + arrived = atomicAdd(counter, 1); + } + arrived = __shfl_sync(0xFFFFFFFF, arrived, 0, WARP_SIZE); + if (arrived != (int) gridDim.x - 1) { + return; + } + __threadfence(); + if (threadIdx.x == 0) { + *counter = 0; + } + topk_moe_row(logits, weights, ids, bias, n_expert_used, clamp_val, scale_val, config); +} + +bool ggml_cuda_router_topk_moe_supported(const ggml_tensor * mm, const ggml_tensor * logits) { + const ggml_tensor * x = mm->src[0]; + const ggml_tensor * y = mm->src[1]; + if (logits != mm || x->type != GGML_TYPE_F32 || y->type != GGML_TYPE_F32 || mm->type != GGML_TYPE_F32 || + mm->ne[0] != 512 || ggml_nrows(mm) != 1 || ggml_nrows(y) != 1 || x->ne[1] != mm->ne[0] || ggml_nrows(x) != x->ne[1] || + x->nb[0] != sizeof(float) || y->nb[0] != sizeof(float) || !ggml_is_contiguous(mm) || + x->ne[0] % 2 != 0 || (x->nb[1] / sizeof(float)) % 2 != 0 || ((uintptr_t) x->data & 7) != 0 || + ((uintptr_t) y->data & 7) != 0 || ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size != WARP_SIZE) { + return false; + } + // the block size ggml_cuda_mul_mat_vec_f picks + const int64_t ncols = x->ne[0]; + const int warp_size = WARP_SIZE; + const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + int64_t block_size_best = warp_size; + int64_t niter_best = (ncols + 2*warp_size - 1) / (2*warp_size); + const int64_t max_block_size = cc > GGML_CUDA_CC_OFFSET_AMD && cc < GGML_CUDA_CC_RDNA1 ? 128 : 256; + for (int64_t block_size = 2*warp_size; block_size <= max_block_size; block_size += warp_size) { + const int64_t niter = (ncols + 2*block_size - 1) / (2*block_size); + if (niter < niter_best) { + niter_best = niter; + block_size_best = block_size; + } + } + return block_size_best == 256; +} + +void ggml_cuda_op_router_topk_moe(ggml_backend_cuda_context & ctx, + const ggml_tensor * mm, + ggml_tensor * weights, + ggml_tensor * ids, + const ggml_tensor * clamp, + const ggml_tensor * scale, + const ggml_tensor * bias, + const ggml_cuda_topk_moe_args & args, + int * counter) { + const ggml_tensor * x = mm->src[0]; + const ggml_tensor * y = mm->src[1]; + const auto it_bf16 = ctx.router_bf16.find(x->data); + const uint16_t * x_bf16 = it_bf16 != ctx.router_bf16.end() && x->ne[0] % 4 == 0 && ((uintptr_t) y->data & 15) == 0 ? + (const uint16_t *) it_bf16->second : nullptr; + + GGML_ASSERT(!(clamp != nullptr && args.delayed_softmax) && args.n_groups == 0); + GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) mm->ne[0]); + + const float scale_val = scale ? ggml_get_op_params_f32(scale, 0) : 1.0f; + const float clamp_val = clamp ? ggml_get_op_params_f32(clamp, 0) : -INFINITY; + + topk_moe_config config; + config.use_sigmoid = args.sigmoid; + config.use_sqrt_softplus = args.sqrt_softplus; + config.with_norm = clamp != nullptr; + config.delayed_softmax = args.delayed_softmax; + config.n_groups = args.n_groups; + config.n_group_used = args.n_group_used; + + const int n_expert_used = weights->ne[1]; + const dim3 block_dims(WARP_SIZE, 256/WARP_SIZE, 1); + const dim3 grid_dims(mm->ne[0], 1, 1); + if (x_bf16) { + auto kernel_bf16 = bias ? router_topk_moe_bf16_cuda<512, true> : router_topk_moe_bf16_cuda<512, false>; + kernel_bf16<<>>( + x_bf16, (const float *) y->data, (float *) mm->data, x->ne[0] / 4, x->nb[1] / sizeof(float), + (float *) weights->data, (int32_t *) ids->data, bias ? (float *) bias->data : nullptr, n_expert_used, clamp_val, + scale_val, config, counter); + return; + } + auto kernel = bias ? router_topk_moe_cuda<512, true> : router_topk_moe_cuda<512, false>; + kernel<<>>( + (const float *) x->data, (const float *) y->data, (float *) mm->data, x->ne[0] / 2, x->nb[1] / sizeof(float), + (float *) weights->data, (int32_t *) ids->data, bias ? (float *) bias->data : nullptr, n_expert_used, clamp_val, + scale_val, config, counter); +} + bool ggml_cuda_should_use_topk_moe(const ggml_tensor * gating_op, const ggml_tensor * weights, const ggml_tensor * logits, diff --git a/ggml/src/ggml-cuda/topk-moe.cuh b/ggml/src/ggml-cuda/topk-moe.cuh index 3637500ff99d..ee579877a8d5 100644 --- a/ggml/src/ggml-cuda/topk-moe.cuh +++ b/ggml/src/ggml-cuda/topk-moe.cuh @@ -27,6 +27,21 @@ void ggml_cuda_op_topk_moe(ggml_backend_cuda_context & ctx, const ggml_tensor * bias, const ggml_cuda_topk_moe_args & args); +// the F32 router MUL_MAT mm of one token and the top-k MoE selection on its result in one kernel; counter: an int that +// is zero between the launches +bool ggml_cuda_router_topk_moe_supported(const ggml_tensor * mm, const ggml_tensor * logits); +// the BF16 copy of F32 router weights that ggml_cuda_op_router_topk_moe reads when in ctx.router_bf16 +void ggml_cuda_router_weights_to_bf16(const float * x, void * dst, const int64_t n, cudaStream_t stream); +void ggml_cuda_op_router_topk_moe(ggml_backend_cuda_context & ctx, + const ggml_tensor * mm, + ggml_tensor * weights, + ggml_tensor * ids, + const ggml_tensor * clamp, + const ggml_tensor * scale, + const ggml_tensor * bias, + const ggml_cuda_topk_moe_args & args, + int * counter); + bool ggml_cuda_should_use_topk_moe(const ggml_tensor * gating_op, const ggml_tensor * weights, const ggml_tensor * logits, diff --git a/ggml/src/ggml-cuda/unary.cu b/ggml/src/ggml-cuda/unary.cu index b3b6aa48d3ac..199e93a537db 100644 --- a/ggml/src/ggml-cuda/unary.cu +++ b/ggml/src/ggml-cuda/unary.cu @@ -702,10 +702,148 @@ void ggml_cuda_op_leaky_relu(ggml_backend_cuda_context & ctx, ggml_tensor * dst) } } +/* fused scale + unary */ + +// op(s*x + b), the SCALE -> UNARY chain. It may also write MMVQ's q8_1 copy of dst as quantize_q8_1 makes it (see +// ggml_cuda_q8_1_cache): rows of ne0_padded values with zeros past ne0, the 32 lanes of a warp holding one block. +template +static __global__ void scale_unary_kernel(const float * x, float * dst, block_q8_1 * q8_1, const int64_t ne0, + const int64_t ne0_padded, const int64_t n, const float s, const float b) { + const int64_t i = int64_t(blockDim.x)*blockIdx.x + threadIdx.x; + + if (i >= n) { + return; + } + + const int64_t row = i / ne0_padded; + const int64_t col = i % ne0_padded; + + float v = 0.0f; + if (col < ne0) { + v = op(s * x[row*ne0 + col] + b); + dst[row*ne0 + col] = v; + } + + if (q8_1 == nullptr) { + return; + } + + const float amax = warp_reduce_max(fabsf(v)); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(v / d); + const int sum_q = warp_reduce_sum((int) q); + block_q8_1 & y = q8_1[i / QK8_1]; + y.qs[i % QK8_1] = q; + if (i % QK8_1 == 0) { + y.ds = make_half2(d, d * sum_q); + } +} + +bool ggml_cuda_op_scale_unary(ggml_backend_cuda_context & ctx, ggml_tensor * scale_node, ggml_tensor * unary_node, + block_q8_1 * q8_1) { + const ggml_tensor * src = scale_node->src[0]; + + float s; + float b; + memcpy(&s, (const float *) scale_node->op_params + 0, sizeof(float)); + memcpy(&b, (const float *) scale_node->op_params + 1, sizeof(float)); + + const bool do_q8_1 = q8_1 && ggml_cuda_info().devices[ctx.device].warp_size == QK8_1; + const int64_t ne0 = unary_node->ne[0]; + const int64_t ne0_padded = do_q8_1 ? GGML_PAD(ne0, MATRIX_ROW_PADDING) : ne0; + const int64_t n = ggml_nrows(unary_node) * ne0_padded; + const int64_t num_blocks = (n + CUDA_GLU_BLOCK_SIZE - 1) / CUDA_GLU_BLOCK_SIZE; + + switch (ggml_get_unary_op(unary_node)) { + case GGML_UNARY_OP_SILU: + scale_unary_kernel<<>>( + (const float *) src->data, (float *) unary_node->data, do_q8_1 ? q8_1 : nullptr, ne0, ne0_padded, n, s, b); + break; + default: + GGML_ABORT("Unsupported unary op for fused scale+unary"); + } + return do_q8_1; +} + +/* fused unary + mul + add */ + +// a + x*op(g) with one gate value per row of x, the gated residual of a shared expert. The product is rounded before +// the sum, as the separate MUL and ADD do. +template +static __global__ void unary_mul_add_kernel(const float * g, const float * x, const float * a, float * dst, + const int64_t n, const int64_t ne0) { +#ifdef GGML_USE_HIP + // __fmul_rn and __fadd_rn are plain operations in HIP's headers, outside the reach of this pragma, which the + // compiler contracts into an FMA once they are inlined: the HIP build writes the operations here instead +#pragma clang fp contract(off) +#endif // GGML_USE_HIP + const int64_t i = int64_t(blockDim.x)*blockIdx.x + threadIdx.x; + + if (i >= n) { + return; + } + +#ifdef GGML_USE_HIP + const float m = x[i] * op(g[i / ne0]); + dst[i] = a[i] + m; +#else + dst[i] = __fadd_rn(a[i], __fmul_rn(x[i], op(g[i / ne0]))); +#endif // GGML_USE_HIP +} + +void ggml_cuda_op_unary_mul_add(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node, + ggml_tensor * add_node) { + const ggml_tensor * x = mul_node->src[0] == unary_node ? mul_node->src[1] : mul_node->src[0]; + const ggml_tensor * a = add_node->src[0] == mul_node ? add_node->src[1] : add_node->src[0]; + + const int64_t n = ggml_nelements(add_node); + const int64_t num_blocks = (n + CUDA_GLU_BLOCK_SIZE - 1) / CUDA_GLU_BLOCK_SIZE; + + switch (ggml_get_unary_op(unary_node)) { + case GGML_UNARY_OP_SIGMOID: + unary_mul_add_kernel<<>>( + (const float *) unary_node->src[0]->data, (const float *) x->data, (const float *) a->data, + (float *) add_node->data, n, add_node->ne[0]); + break; + default: + GGML_ABORT("Unsupported unary op for fused unary+mul+add"); + } +} + /* fused unary + mul */ +// the gated product that also writes MMVQ's q8_1 copy of dst as quantize_q8_1 makes it (see ggml_cuda_q8_1_cache): +// the 32 lanes of a warp hold one block, all of them active since k is a multiple of QK8_1, and the blocks run through +// dst in order, the layout of the reshape MMVQ reads (see ggml_cuda_mmvq_q8_1_target) +template +static __global__ void unary_gated_op_q8_1_kernel(const float * x, const float * g, float * dst, block_q8_1 * q8_1, + const int64_t k, const int64_t n, const int64_t o0, const int64_t o1) { + const int64_t i = int64_t(blockDim.x)*blockIdx.x + threadIdx.x; + + if (i >= k) { + return; + } + + const int64_t j0 = (i / n) * o0 + (i % n); + const int64_t j1 = o0 == o1 ? j0 : (i / n) * o1 + (i % n); + + const float v = op(x[j0]) * g[j1]; + dst[i] = v; + + const float amax = warp_reduce_max(fabsf(v)); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(v / d); + const int sum_q = warp_reduce_sum((int) q); + block_q8_1 & y = q8_1[i / QK8_1]; + y.qs[i % QK8_1] = q; + if (i % QK8_1 == 0) { + y.ds = make_half2(d, d * sum_q); + } +} + template -static void ggml_cuda_op_unary_mul_impl(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node) { +static bool ggml_cuda_op_unary_mul_impl(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node, + block_q8_1 * q8_1) { // unary_node: UNARY op applied to unary_node->src[0] // mul_node: MUL(a, b) where one of a/b is unary_node // Output goes to mul_node->data @@ -738,29 +876,219 @@ static void ggml_cuda_op_unary_mul_impl(ggml_backend_cuda_context & ctx, ggml_te unary_gated_cuda((const nv_bfloat16 *) unary_src->data, (const nv_bfloat16 *) other_src->data, (nv_bfloat16 *) mul_node->data, k, nc, unary_stride / sizeof(nv_bfloat16), other_stride / sizeof(nv_bfloat16), stream); + } else if (q8_1 && ggml_cuda_info().devices[ctx.device].warp_size == QK8_1 && ggml_is_contiguous(mul_node) && + k % QK8_1 == 0) { + const int64_t num_blocks = (k + CUDA_GLU_BLOCK_SIZE - 1) / CUDA_GLU_BLOCK_SIZE; + unary_gated_op_q8_1_kernel<<>>( + (const float *) unary_src->data, (const float *) other_src->data, (float *) mul_node->data, q8_1, k, nc, + unary_stride / sizeof(float), other_stride / sizeof(float)); + return true; } else { unary_gated_cuda((const float *) unary_src->data, (const float *) other_src->data, (float *) mul_node->data, k, nc, unary_stride / sizeof(float), other_stride / sizeof(float), stream); } + return false; } -void ggml_cuda_op_unary_mul(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node) { +// block_q8_1_mmq with the D4 layout +struct unary_q8_1_mmq_d4 { + float d4[4]; + int8_t qs[128]; +}; +static_assert(sizeof(unary_q8_1_mmq_d4) == 144, "unexpected block_q8_1_mmq size"); + +// as unary_gated_op_kernel for F32, the result for a MUL_MAT with k columns of src1 per token: the MMQ q8_1 copy with the +// D4 layout as quantize_mmq_q8_1 writes it, and the F32 result only if dst is not null. 4 values per thread, the 8 +// threads of 32 values share their scale. +template +static __global__ void unary_gated_op_mmq_q8_1_kernel(const float * x, const float * g, float * dst, void * vq8, + const int64_t n_elems, const int64_t nc, const int64_t o0, const int64_t o1, const int64_t k, const int64_t n_tokens) { + const int64_t i0 = 4 * (int64_t(blockDim.x)*blockIdx.x + threadIdx.x); + if (i0 >= n_elems) { + return; + } + float v[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int64_t i = i0 + e; + const int64_t j0 = (i / nc) * o0 + (i % nc); + const int64_t j1 = o0 == o1 ? j0 : (i / nc) * o1 + (i % nc); + v[e] = op(x[j0]) * g[j1]; + } + if (dst != nullptr) { + *(float4 *) (dst + i0) = make_float4(v[0], v[1], v[2], v[3]); + } + float amax = fmaxf(fmaxf(fabsf(v[0]), fabsf(v[1])), fmaxf(fabsf(v[2]), fabsf(v[3]))); +#pragma unroll + for (int offset = 4; offset > 0; offset >>= 1) { + amax = fmaxf(amax, __shfl_xor_sync(0xFFFFFFFF, amax, offset, WARP_SIZE)); + } + const float d_inv = 127.0f / amax; + char4 q; + q.x = roundf(v[0]*d_inv); + q.y = roundf(v[1]*d_inv); + q.z = roundf(v[2]*d_inv); + q.w = roundf(v[3]*d_inv); + + const int64_t t = i0 / k, kk = i0 % k; + unary_q8_1_mmq_d4 * yb = (unary_q8_1_mmq_d4 *) vq8 + (kk / 128) * n_tokens + t; + const int iqs = kk % 128; + ((char4 *) yb->qs)[iqs/4] = q; + if (iqs % 32 == 0) { + yb->d4[iqs/32] = 1.0f / d_inv; + } +} + +void ggml_cuda_op_unary_mul_mmq_q8_1(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node, + void * q8, const int64_t k, const int64_t n_tokens, const bool write_dst) { + const ggml_tensor * unary_src = unary_node->src[0]; + const ggml_tensor * other_src = (mul_node->src[0] == unary_node) ? mul_node->src[1] : mul_node->src[0]; + GGML_ASSERT(unary_src->type == GGML_TYPE_F32 && other_src->type == GGML_TYPE_F32 && mul_node->type == GGML_TYPE_F32); + GGML_ASSERT(ggml_are_same_shape(unary_src, other_src) && ggml_is_contiguous(mul_node)); + GGML_ASSERT(unary_src->ne[0] % 4 == 0 && k % 128 == 0 && ggml_nelements(mul_node) == k * n_tokens); + + const int64_t n_elems = ggml_nelements(mul_node); + const int64_t nc = unary_src->ne[0]; + const int64_t o0 = unary_src->nb[1] / sizeof(float); + const int64_t o1 = other_src->nb[1] / sizeof(float); + float * dst = write_dst ? (float *) mul_node->data : nullptr; + const int64_t num_blocks = (n_elems / 4 + CUDA_GLU_BLOCK_SIZE - 1) / CUDA_GLU_BLOCK_SIZE; + auto kernel = unary_gated_op_mmq_q8_1_kernel; + switch (ggml_get_unary_op(unary_node)) { + case GGML_UNARY_OP_SIGMOID: kernel = unary_gated_op_mmq_q8_1_kernel; break; + case GGML_UNARY_OP_SILU: kernel = unary_gated_op_mmq_q8_1_kernel; break; + case GGML_UNARY_OP_SOFTPLUS: kernel = unary_gated_op_mmq_q8_1_kernel; break; + default: GGML_ABORT("Unsupported unary op for fused unary+mul"); + } + kernel<<>>((const float *) unary_src->data, (const float *) other_src->data, + dst, q8, n_elems, nc, o0, o1, k, n_tokens); + CUDA_CHECK(cudaGetLastError()); +} + +bool ggml_cuda_op_unary_mul(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node, + block_q8_1 * q8_1) { switch (ggml_get_unary_op(unary_node)) { case GGML_UNARY_OP_SILU: - ggml_cuda_op_unary_mul_impl(ctx, unary_node, mul_node); - break; + return ggml_cuda_op_unary_mul_impl(ctx, unary_node, mul_node, q8_1); case GGML_UNARY_OP_SIGMOID: - ggml_cuda_op_unary_mul_impl(ctx, unary_node, mul_node); - break; + return ggml_cuda_op_unary_mul_impl(ctx, unary_node, mul_node, q8_1); case GGML_UNARY_OP_SOFTPLUS: - ggml_cuda_op_unary_mul_impl(ctx, unary_node, mul_node); - break; + return ggml_cuda_op_unary_mul_impl(ctx, unary_node, mul_node, q8_1); default: GGML_ABORT("Unsupported unary op for fused unary+mul"); } } +/* fused mul + add after a sigmoid gate: g * x + r, with one g per row */ + +static __global__ void sigmoid_mul_add_f32(const float * g, const float * x, const float * r, float * dst, const int ne0, const int k) { + ggml_cuda_pdl_lc(); + const int i = blockDim.x*blockIdx.x + threadIdx.x; + + if (i >= k) { + return; + } + + ggml_cuda_pdl_sync(); + // keep the MUL result rounded before ADD, as in the unfused graph + volatile float gated = x[i] * g[i / ne0]; + dst[i] = r[i] + gated; +} + +void ggml_cuda_op_sigmoid_mul_add(ggml_backend_cuda_context & ctx, ggml_tensor * sigmoid_node, ggml_tensor * mul_node, ggml_tensor * add_node) { + ggml_cuda_op_sigmoid(ctx, sigmoid_node); + + const ggml_tensor * g = sigmoid_node; + const ggml_tensor * x = mul_node->src[0] == sigmoid_node ? mul_node->src[1] : mul_node->src[0]; + const ggml_tensor * r = add_node->src[0] == mul_node ? add_node->src[1] : add_node->src[0]; + + GGML_ASSERT(g->type == GGML_TYPE_F32 && x->type == GGML_TYPE_F32 && r->type == GGML_TYPE_F32 && add_node->type == GGML_TYPE_F32); + GGML_ASSERT(ggml_is_contiguous(g) && ggml_is_contiguous(x) && ggml_is_contiguous(r) && ggml_is_contiguous(add_node)); + GGML_ASSERT(g->ne[0] == 1 && ggml_nelements(g) == ggml_nrows(x)); + + cudaStream_t stream = ctx.stream(); + + const int k = ggml_nelements(x); + const int num_blocks = (k + CUDA_NEG_BLOCK_SIZE - 1) / CUDA_NEG_BLOCK_SIZE; + const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params((dim3)num_blocks, CUDA_NEG_BLOCK_SIZE, 0, stream); + ggml_cuda_kernel_launch(sigmoid_mul_add_f32, launch_params, (const float *) g->data, (const float *) x->data, + (const float *) r->data, (float *) add_node->data, (int) x->ne[0], k); +} + +/* fused scale + silu */ + +static __global__ void scale_silu_f32(const float * x, float * dst, const float scale, const float bias, const int k) { + ggml_cuda_pdl_lc(); + const int i = blockDim.x*blockIdx.x + threadIdx.x; + + if (i >= k) { + return; + } + + ggml_cuda_pdl_sync(); + dst[i] = ggml_cuda_op_silu_single(scale * x[i] + bias); +} + +void ggml_cuda_op_scale_silu(ggml_backend_cuda_context & ctx, ggml_tensor * scale_node, ggml_tensor * silu_node) { + const ggml_tensor * src = scale_node->src[0]; + cudaStream_t stream = ctx.stream(); + + GGML_ASSERT(ggml_is_contiguous(src) && ggml_is_contiguous(silu_node)); + GGML_ASSERT(src->type == GGML_TYPE_F32 && silu_node->type == GGML_TYPE_F32); + + const float scale = ggml_get_op_params_f32(scale_node, 0); + const float bias = ggml_get_op_params_f32(scale_node, 1); + + const int k = ggml_nelements(src); + const int num_blocks = (k + CUDA_SILU_BLOCK_SIZE - 1) / CUDA_SILU_BLOCK_SIZE; + const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params((dim3)num_blocks, CUDA_SILU_BLOCK_SIZE, 0, stream); + ggml_cuda_kernel_launch(scale_silu_f32, launch_params, (const float *) src->data, (float *) silu_node->data, scale, bias, k); +} + +/* fused add + unary + mul: op(x + b) * a, with one b and one a per element of a row (the gate of a gated delta net) */ + +template +static __global__ void add_unary_mul_f32(const float * x, const float * b, const float * a, float * dst, const int ne0, const int k) { + ggml_cuda_pdl_lc(); + const int i = blockDim.x*blockIdx.x + threadIdx.x; + + if (i >= k) { + return; + } + + ggml_cuda_pdl_sync(); + const int i0 = i % ne0; + dst[i] = op(x[i] + b[i0]) * a[i0]; +} + +void ggml_cuda_op_add_unary_mul(ggml_backend_cuda_context & ctx, ggml_tensor * add_node, ggml_tensor * unary_node, ggml_tensor * mul_node) { + const ggml_tensor * x = add_node->src[0]; + const ggml_tensor * b = add_node->src[1]; + const ggml_tensor * a = mul_node->src[0] == unary_node ? mul_node->src[1] : mul_node->src[0]; + + GGML_ASSERT(x->type == GGML_TYPE_F32 && b->type == GGML_TYPE_F32 && a->type == GGML_TYPE_F32 && mul_node->type == GGML_TYPE_F32); + GGML_ASSERT(ggml_is_contiguous(x) && ggml_is_contiguous(b) && ggml_is_contiguous(a) && ggml_is_contiguous(mul_node)); + GGML_ASSERT(ggml_nelements(b) == x->ne[0] && ggml_nelements(a) == x->ne[0]); + + cudaStream_t stream = ctx.stream(); + + const int k = ggml_nelements(x); + const int num_blocks = (k + CUDA_NEG_BLOCK_SIZE - 1) / CUDA_NEG_BLOCK_SIZE; + const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params((dim3)num_blocks, CUDA_NEG_BLOCK_SIZE, 0, stream); + const auto launch = [&](auto kernel) { + ggml_cuda_kernel_launch(kernel, launch_params, (const float *) x->data, (const float *) b->data, (const float *) a->data, + (float *) mul_node->data, (int) x->ne[0], k); + }; + switch (ggml_get_unary_op(unary_node)) { + case GGML_UNARY_OP_SILU: launch(add_unary_mul_f32); break; + case GGML_UNARY_OP_SIGMOID: launch(add_unary_mul_f32); break; + case GGML_UNARY_OP_SOFTPLUS: launch(add_unary_mul_f32); break; + default: + GGML_ABORT("Unsupported unary op for fused add+unary+mul"); + } +} + /* fused relu + sqr */ void ggml_cuda_op_relu_sqr(ggml_backend_cuda_context & ctx, ggml_tensor * relu_node, ggml_tensor * sqr_node) { @@ -778,3 +1106,65 @@ void ggml_cuda_op_relu_sqr(ggml_backend_cuda_context & ctx, ggml_tensor * relu_n unary_cuda((const float *)src->data, (float *)sqr_node->data, k, stream); } } + +/* fused gated delta net inputs */ + +// The alpha and beta products of a gated delta net layer for one token (F32 weights, one row per block, each summed as +// mul_mat_vec_f sums a row with 256 threads) with what follows them: gate = softplus(alpha + dt)*a and +// beta = sigmoid(beta), as the separate ADD, the fused softplus + MUL and SIGMOID compute them. +static __global__ void __launch_bounds__(256, 1) gdn_alpha_beta_f32( + const float * __restrict__ w_alpha, const float * __restrict__ w_beta, const float * __restrict__ x, + const float * __restrict__ dt, const float * __restrict__ a, float * __restrict__ gate, float * __restrict__ beta, + const int ncols2, const int64_t stride_row_alpha, const int64_t stride_row_beta, const int nrows) { + constexpr int block_size = 256; + constexpr int warp_size = 32; + const int tid = threadIdx.x; + const int row = blockIdx.x; + + __shared__ float buf_iw[warp_size]; + if (tid < warp_size) { + buf_iw[tid] = 0.0f; + } + __syncthreads(); + + const bool is_alpha = row < nrows; + const float2 * x2 = (const float2 *) (is_alpha ? w_alpha + row*stride_row_alpha : w_beta + (row - nrows)*stride_row_beta); + const float2 * y2 = (const float2 *) x; + float sumf = 0.0f; + for (int col2 = tid; col2 < ncols2; col2 += block_size) { + const float2 tmpx = x2[col2]; + const float2 tmpy = y2[col2]; + ggml_cuda_mad(sumf, tmpx.x, tmpy.x); + ggml_cuda_mad(sumf, tmpx.y, tmpy.y); + } + sumf = warp_reduce_sum(sumf); + buf_iw[tid/warp_size] = sumf; + __syncthreads(); + if (tid >= warp_size) { + return; + } + sumf = buf_iw[tid]; + sumf = warp_reduce_sum(sumf); + if (tid != 0) { + return; + } + + if (is_alpha) { + const float biased = sumf + dt[row]; + gate[row] = op_softplus(biased) * a[row]; + } else { + beta[row - nrows] = op_sigmoid(sumf); + } +} + +void ggml_cuda_op_gdn_alpha_beta(ggml_backend_cuda_context & ctx, const ggml_tensor * alpha_mm, const ggml_tensor * dt, + const ggml_tensor * a, ggml_tensor * gate, const ggml_tensor * beta_mm, ggml_tensor * beta) { + const ggml_tensor * w_alpha = alpha_mm->src[0]; + const ggml_tensor * w_beta = beta_mm->src[0]; + const ggml_tensor * x = alpha_mm->src[1]; + const int nrows = w_alpha->ne[1]; + gdn_alpha_beta_f32<<<2*nrows, 256, 0, ctx.stream()>>>( + (const float *) w_alpha->data, (const float *) w_beta->data, (const float *) x->data, (const float *) dt->data, + (const float *) a->data, (float *) gate->data, (float *) beta->data, w_alpha->ne[0] / 2, + w_alpha->nb[1] / sizeof(float), w_beta->nb[1] / sizeof(float), nrows); +} diff --git a/ggml/src/ggml-cuda/unary.cuh b/ggml/src/ggml-cuda/unary.cuh index c6ffdb9d63e7..067f918ee6f3 100644 --- a/ggml/src/ggml-cuda/unary.cuh +++ b/ggml/src/ggml-cuda/unary.cuh @@ -91,10 +91,37 @@ void ggml_cuda_op_geglu_quick(ggml_backend_cuda_context & ctx, ggml_tensor * dst void ggml_cuda_op_xielu(ggml_backend_cuda_context & ctx, ggml_tensor * dst); -void ggml_cuda_op_unary_mul(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node); +// returns whether it also wrote q8_1, MMVQ's q8_1 copy of mul_node (when q8_1 is not nullptr and the layout allows) +bool ggml_cuda_op_unary_mul(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node, + block_q8_1 * q8_1 = nullptr); + +// unary+mul (F32) for a prompt-batch MMQ that reads the result as src1 with k columns: writes the MMQ q8_1 copy (D4 layout) +// into q8 and the F32 result only with write_dst +void ggml_cuda_op_unary_mul_mmq_q8_1(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node, + void * q8, int64_t k, int64_t n_tokens, bool write_dst); + +// unary(scale(x)); returns whether it also wrote q8_1, MMVQ's q8_1 copy of unary_node with its rows padded to +// MATRIX_ROW_PADDING (when q8_1 is not nullptr) +bool ggml_cuda_op_scale_unary(ggml_backend_cuda_context & ctx, ggml_tensor * scale_node, ggml_tensor * unary_node, + block_q8_1 * q8_1 = nullptr); + +// add_node = a + x*unary(g), mul_node = x*unary(g) with one value of unary(g) per row of x +void ggml_cuda_op_unary_mul_add(ggml_backend_cuda_context & ctx, ggml_tensor * unary_node, ggml_tensor * mul_node, + ggml_tensor * add_node); + +// gate = softplus(alpha_mm + dt)*a and beta = sigmoid(beta_mm) for one token, the alpha and beta products of a gated +// delta net layer (F32 weights) included, in one kernel +void ggml_cuda_op_gdn_alpha_beta(ggml_backend_cuda_context & ctx, const ggml_tensor * alpha_mm, const ggml_tensor * dt, + const ggml_tensor * a, ggml_tensor * gate, const ggml_tensor * beta_mm, ggml_tensor * beta); + +void ggml_cuda_op_sigmoid_mul_add(ggml_backend_cuda_context & ctx, ggml_tensor * sigmoid_node, ggml_tensor * mul_node, ggml_tensor * add_node); void ggml_cuda_op_relu_sqr(ggml_backend_cuda_context & ctx, ggml_tensor * relu_node, ggml_tensor * sqr_node); +void ggml_cuda_op_add_unary_mul(ggml_backend_cuda_context & ctx, ggml_tensor * add_node, ggml_tensor * unary_node, ggml_tensor * mul_node); + +void ggml_cuda_op_scale_silu(ggml_backend_cuda_context & ctx, ggml_tensor * scale_node, ggml_tensor * silu_node); + __device__ __forceinline__ float ggml_cuda_op_silu_single(float x) { return x / (1.0f + expf(-x)); } diff --git a/ggml/src/ggml-cuda/vecdotq.cuh b/ggml/src/ggml-cuda/vecdotq.cuh index d5ff93b91241..ed83a667208a 100644 --- a/ggml/src/ggml-cuda/vecdotq.cuh +++ b/ggml/src/ggml-cuda/vecdotq.cuh @@ -103,6 +103,17 @@ static __device__ __forceinline__ uint32_t unpack_ksigns(const uint8_t v) { return s * 0x01010101; } +#if defined(GGML_USE_HIP) +// The bytes of grid negated where the 4 low bits of s4 are set, as __vsub4(grid ^ m, m) with the __vcmpne4 byte mask m +// of those bits, which take several instructions each on AMD: the bits are spread to bytes with a multiply (the shifted +// copies do not overlap), and a byte g is negated as (g ^ 0xff) + 1, which cannot carry since the i-quant grids have no +// zero bytes. +static __device__ __forceinline__ int iq_grid_signed(const int grid, const uint32_t s4) { + const int m = ((s4 & 0x0F) * 0x00204081) & 0x01010101; + return (grid ^ (m * 0xFF)) + m; +} +#endif // defined(GGML_USE_HIP) + // VDR = vec dot ratio, how many contiguous integers each thread processes when the vec dot kernel is called // MMVQ = mul_mat_vec_q, MMQ = mul_mat_q @@ -1121,15 +1132,21 @@ static __device__ __forceinline__ float vec_dot_iq2_xxs_q8_1( #pragma unroll for (int k0 = 0; k0 < 8; k0 += 2) { const uint2 grid_pos = ((const uint2*)iq2xxs_grid)[aux8[k0/2]]; +#if defined(GGML_USE_HIP) + const uint8_t v = aux32 >> (7 * k0 / 2); + const uint32_t s8 = v ^ (__popc(v) & 1) << 7; + const int grid0 = iq_grid_signed(grid_pos.x, s8); + const int grid1 = iq_grid_signed(grid_pos.y, s8 >> 4); +#else const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2)); const int signs0 = __vcmpne4(signs & 0x08040201, 0); const int grid0 = __vsub4(grid_pos.x ^ signs0, signs0); - const int u0 = get_int_b4(bq8_1[iqs/2].qs, k0 + 0); - sumi = ggml_cuda_dp4a(grid0, u0, sumi); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); const int grid1 = __vsub4(grid_pos.y ^ signs1, signs1); +#endif // defined(GGML_USE_HIP) + const int u0 = get_int_b4(bq8_1[iqs/2].qs, k0 + 0); + sumi = ggml_cuda_dp4a(grid0, u0, sumi); const int u1 = get_int_b4(bq8_1[iqs/2].qs, k0 + 1); sumi = ggml_cuda_dp4a(grid1, u1, sumi); } @@ -1158,14 +1175,20 @@ static __device__ __forceinline__ float vec_dot_iq2_xs_q8_1( #pragma unroll for (int l0 = 0; l0 < 8; l0 += 2) { const uint2 grid_pos = ((const uint2*)iq2xs_grid)[q2[l0/2] & 0x1FF]; +#if defined(GGML_USE_HIP) + const uint8_t v = q2[l0/2] >> 9; + const uint32_t s8 = v ^ (__popc(v) & 1) << 7; + const int grid_l = iq_grid_signed(grid_pos.x, s8); + const int grid_h = iq_grid_signed(grid_pos.y, s8 >> 4); +#else const uint32_t signs = unpack_ksigns(q2[l0/2] >> 9); const int signs0 = __vcmpne4(signs & 0x08040201, 0); const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); - const int u0 = get_int_b4(bq8_1[iqs/2].qs, l0 + 0); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); +#endif // defined(GGML_USE_HIP) + const int u0 = get_int_b4(bq8_1[iqs/2].qs, l0 + 0); const int u1 = get_int_b4(bq8_1[iqs/2].qs, l0 + 1); if (l0 < 4) { @@ -1206,11 +1229,16 @@ static __device__ __forceinline__ float vec_dot_iq2_s_q8_1( for (int l0 = 0; l0 < 8; l0 += 2) { const int * grid_pos = (const int *)(iq2s_grid + (qs[l0/2] | ((qh << (8-l0)) & 0x300))); +#if defined(GGML_USE_HIP) + const int grid_l = iq_grid_signed(grid_pos[0], signs_packed_8[l0/2]); + const int grid_h = iq_grid_signed(grid_pos[1], signs_packed_8[l0/2] >> 4); +#else const int signs0 = __vcmpne4(((signs_packed_8[l0/2] & 0x03) << 7) | ((signs_packed_8[l0/2] & 0x0C) << 21), 0x00000000); const int signs1 = __vcmpne4(((signs_packed_8[l0/2] & 0x30) << 3) | ((signs_packed_8[l0/2] & 0xC0) << 17), 0x00000000); const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0); const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1); +#endif // defined(GGML_USE_HIP) const int u0 = get_int_b4(bq8_1[iqs/2].qs, l0 + 0); const int u1 = get_int_b4(bq8_1[iqs/2].qs, l0 + 1); @@ -1245,6 +1273,15 @@ static __device__ __forceinline__ float vec_dot_iq3_xxs_q8_1( #pragma unroll for (int l0 = 0; l0 < 8; l0 += 2) { const int2 grid_pos = make_int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); +#if defined(GGML_USE_HIP) + const uint8_t v = aux32 >> (7*l0/2); + const uint32_t s8 = v ^ (__popc(v) & 1) << 7; + const int grid_l = iq_grid_signed(grid_pos.x, s8); + const int grid_h = iq_grid_signed(grid_pos.y, s8 >> 4); + + const int u0 = get_int_b4(bq8_1[iqs/2].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs/2].qs, l0 + 1); +#else const uint32_t signs = unpack_ksigns(aux32 >> (7*l0/2)); const int signs0 = __vcmpne4(signs & 0x08040201, 0); @@ -1256,6 +1293,7 @@ static __device__ __forceinline__ float vec_dot_iq3_xxs_q8_1( const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); const int u1 = get_int_b4(bq8_1[iqs/2].qs, l0 + 1); +#endif // defined(GGML_USE_HIP) sumi = ggml_cuda_dp4a(grid_l, u0, sumi); sumi = ggml_cuda_dp4a(grid_h, u1, sumi); @@ -1291,11 +1329,16 @@ static __device__ __forceinline__ float vec_dot_iq3_s_q8_1( iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); +#if defined(GGML_USE_HIP) + const int grid_l = iq_grid_signed(grid_pos.x, signs_packed_8[l0/2]); + const int grid_h = iq_grid_signed(grid_pos.y, signs_packed_8[l0/2] >> 4); +#else const int signs0 = __vcmpne4(((signs_packed_8[l0/2] & 0x03) << 7) | ((signs_packed_8[l0/2] & 0x0C) << 21), 0x00000000); const int signs1 = __vcmpne4(((signs_packed_8[l0/2] & 0x30) << 3) | ((signs_packed_8[l0/2] & 0xC0) << 17), 0x00000000); const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); +#endif // defined(GGML_USE_HIP) const int u0 = get_int_b4(bq8_1[iqs/2].qs, l0 + 0); const int u1 = get_int_b4(bq8_1[iqs/2].qs, l0 + 1); diff --git a/include/llama.h b/include/llama.h index 181d840a6c88..5a5c1a8403e9 100644 --- a/include/llama.h +++ b/include/llama.h @@ -228,6 +228,13 @@ extern "C" { LLAMA_CONTEXT_TYPE_MTP = 1, }; + // sparse attention (QSA) of an MTP block whose GGUF says dense attention (e.g. the qwen4exp "shared" MTP files) + enum llama_mtp_qsa_type { + LLAMA_MTP_QSA_AUTO = 0, // dense while the KV cache is short, QSA beyond a model specific length + LLAMA_MTP_QSA_OFF = 1, // always dense + LLAMA_MTP_QSA_ON = 2, // always QSA + }; + // TODO: simplify (https://github.com/ggml-org/llama.cpp/pull/9294#pullrequestreview-2286561979) typedef struct llama_token_data { llama_token id; // token id @@ -381,6 +388,9 @@ extern "C" { enum llama_attention_type attention_type; // attention type to use for embeddings enum llama_flash_attn_type flash_attn_type; // when to enable Flash Attention + // MTP draft head options, only read by the qwen4exp MTP context (ctx_type MTP), ignored elsewhere + enum llama_mtp_qsa_type mtp_qsa; // sparse attention of a dense MTP block + // ref: https://github.com/ggml-org/llama.cpp/pull/2054 float rope_freq_base; // RoPE base frequency, 0 = from model float rope_freq_scale; // RoPE frequency scaling factor, 0 = from model diff --git a/src/llama-context.cpp b/src/llama-context.cpp index ee6a03253586..56c0d3b35598 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -216,6 +216,7 @@ llama_context::llama_context( embd_layer_inp.resize(hparams.n_layer() + 1); cparams.ctx_type = params.ctx_type; + cparams.mtp_qsa = params.mtp_qsa; cparams.rope_scaling_type = params.rope_scaling_type; cparams.pooling_type = params.pooling_type; @@ -254,6 +255,22 @@ llama_context::llama_context( } } + // an MTP draft head that leaves out token_embd and output borrows both from its target model + if (model.arch == LLM_ARCH_QWEN4EXP && (model.tok_embd == nullptr || model.output == nullptr)) { + if (params.ctx_other == nullptr) { + throw std::runtime_error(model.arch_name() + " has no token_embd/output of its own and requires ctx_other to be set " + "(load it as the draft model of its target, not on its own)"); + } + + const llama_model & model_tgt = params.ctx_other->get_model(); + if (model_tgt.arch != model.arch || model_tgt.tok_embd == nullptr || model_tgt.output == nullptr || + model_tgt.hparams.n_embd != hparams.n_embd || model_tgt.vocab.n_tokens() != model.vocab.n_tokens()) { + throw std::runtime_error(model.arch_name() + ": the target model cannot provide token_embd/output for this draft head"); + } + + cparams.ctx_other = params.ctx_other; + } + if (cparams.rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) { cparams.rope_scaling_type = hparams.rope_scaling_type_train; } @@ -529,6 +546,11 @@ llama_context::llama_context( } } + // a dense qwen4exp MTP block that the cache can never take to the QSA length stays dense and keeps no indexer state + if (cparams.mtp_qsa == LLAMA_MTP_QSA_AUTO && cparams.n_ctx_seq < LLAMA_MTP_QSA_MIN_KV) { + cparams.mtp_qsa = LLAMA_MTP_QSA_OFF; + } + // init the memory module if (!hparams.vocab_only) { llama_memory_params params_mem = { @@ -4429,6 +4451,7 @@ llama_context_params llama_context_default_params() { /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED, /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED, /*.flash_attn_type =*/ LLAMA_FLASH_ATTN_TYPE_AUTO, + /*.mtp_qsa =*/ LLAMA_MTP_QSA_AUTO, /*.rope_freq_base =*/ 0.0f, /*.rope_freq_scale =*/ 0.0f, /*.yarn_ext_factor =*/ -1.0f, diff --git a/src/llama-cparams.h b/src/llama-cparams.h index 52c85bdd2bf7..75f2195f9059 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -7,6 +7,10 @@ #define LLAMA_MAX_SEQ 256 +// qwen4exp: an MTP block that the GGUF stores with dense attention (the shared MTP files) attends densely while the cache holds +// fewer cells than this, and through QSA from there on (--spec-draft-qsa auto) +static constexpr uint32_t LLAMA_MTP_QSA_MIN_KV = 40960; + struct llama_cparams { uint32_t n_ctx; // context size used during inference uint32_t n_ctx_seq; // context for a single sequence @@ -63,6 +67,7 @@ struct llama_cparams { bool embeddings_nextn_dev; // write the unmasked h_nextn rows to a device buffer instead of host, see llama_set_embeddings_nextn_dev() enum llama_context_type ctx_type; + enum llama_mtp_qsa_type mtp_qsa; enum llama_rope_scaling_type rope_scaling_type; enum llama_pooling_type pooling_type; diff --git a/src/llama-memory-hybrid-idx.cpp b/src/llama-memory-hybrid-idx.cpp index da17476494ef..42406dc4804e 100644 --- a/src/llama-memory-hybrid-idx.cpp +++ b/src/llama-memory-hybrid-idx.cpp @@ -349,8 +349,7 @@ struct llama_memory_hybrid_idx::kpool_layout { // Which pools of the layout the current ubatch must re-pool, in the layout's pool order. struct llama_memory_hybrid_idx_context::kpool_state { std::vector is_new; - std::vector rep_gen; // per global cell, the generation that last marked a pool with that rep - uint32_t generation = 0; + uint32_t generation = 0; // see llama_memory_hybrid_idx::kpool_marks uint32_t n_pool_real = 0; uint32_t n_new = 0; @@ -412,16 +411,28 @@ const llama_memory_hybrid_idx::kpool_layout & llama_memory_hybrid_idx::kpool_lay sq.strm = unified ? 0 : mem_idx->get_stream(s); - if (mem_idx_stale[s] == POS_CLEAN && !sq.cells.empty() && !sp.empty() && - sq.pos_min == sp.begin()->first) { + // an edit after the first position leaves the cells before it as they are, and so the pools made of them only + // (a speculative decoding round drops the rejected drafts this way), only the rest of the sequence is regrouped + const llama_pos stale = mem_idx_stale[s]; + const bool keep_head = !sq.cells.empty() && !sp.empty() && sq.pos_min == sp.begin()->first && stale > sq.pos_min; + + if (keep_head && stale != POS_CLEAN) { + sq.cells.erase(std::lower_bound(sq.cells.begin(), sq.cells.end(), std::make_pair(stale, 0u)), sq.cells.end()); + while (!sq.pools.empty() && sq.pools.back() + kpool > sq.cells.size()) { + sq.pools.pop_back(); + } + sq.j_next = sq.pools.empty() ? 0 : sq.pools.back() + kpool; + } + + if (keep_head) { for (auto it = sp.upper_bound(sq.cells.back()); it != sp.end(); ++it) { sq.cells.push_back(*it); } } // the appended tail accounts for every cell only if nothing before it was dropped, but an edit can - // regroup a sequence without changing its cell count, so a stale sequence must rebuild regardless - if (sq.cells.size() != sp.size() || mem_idx_stale[s] != POS_CLEAN) { + // regroup a sequence without changing its cell count, so a sequence stale from its start must rebuild regardless + if (sq.cells.size() != sp.size() || !keep_head) { sq.cells.assign(sp.begin(), sp.end()); sq.pools.clear(); sq.j_next = 0; @@ -630,15 +641,18 @@ void llama_memory_hybrid_idx_context::kpool_build_state(const llama_ubatch & uba const uint32_t kv_size = idx->get_size(); const uint32_t kpool = mem->get_kpool(); + auto & mk = mem->kpool_marks_get(); + st.n_pool_real = lay.n_pool_real; st.n_new = 0; - if (++st.generation == 0) { + if (++mk.generation == 0) { std::fill(st.is_new.begin(), st.is_new.end(), 0); - std::fill(st.rep_gen.begin(), st.rep_gen.end(), 0); - st.generation = 1; + std::fill(mk.rep_gen.begin(), mk.rep_gen.end(), 0); + mk.generation = 1; } + st.generation = mk.generation; st.is_new.resize(lay.n_pool_real, 0); - st.rep_gen.resize((size_t) kv_size*idx->get_n_stream(), 0); + mk.rep_gen.resize((size_t) kv_size*idx->get_n_stream(), 0); std::array pool_start; @@ -647,8 +661,8 @@ void llama_memory_hybrid_idx_context::kpool_build_state(const llama_ubatch & uba auto mark = [&](llama_seq_id s, size_t k) { const auto & sq = lay.seqs[s]; const size_t rep = (size_t) sq.strm*kv_size + sq.cells[sq.pools[k] + kpool - 1].second; - if (st.rep_gen[rep] != st.generation) { - st.rep_gen[rep] = st.generation; + if (mk.rep_gen[rep] != st.generation) { + mk.rep_gen[rep] = st.generation; st.is_new[pool_start[s] + k] = st.generation; ++st.n_new; } @@ -730,10 +744,15 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, ggml_tensor * sel_mask, ggml_tensor * new_pool_idxs, ggml_tensor * new_pool_rep, const llama_ubatch * ubatch, ggml_tensor * new_pool_pos) const { GGML_ASSERT(mem != nullptr && mem->get_mem_idx() != nullptr); - GGML_ASSERT(ggml_backend_buffer_is_host(pool_cells->buffer)); - GGML_ASSERT(ggml_backend_buffer_is_host(pool_idxs->buffer)); - GGML_ASSERT(ggml_backend_buffer_is_host(pool_mask->buffer)); - GGML_ASSERT(ggml_backend_buffer_is_host(tail_idxs->buffer)); + + // a graph that only keeps the pooled keys up to date (a dense step of a block that may switch to QSA) has no pool inputs + const bool select = pool_cells != nullptr; + if (select) { + GGML_ASSERT(ggml_backend_buffer_is_host(pool_cells->buffer)); + GGML_ASSERT(ggml_backend_buffer_is_host(pool_idxs->buffer)); + GGML_ASSERT(ggml_backend_buffer_is_host(pool_mask->buffer)); + GGML_ASSERT(ggml_backend_buffer_is_host(tail_idxs->buffer)); + } const uint32_t kpool = mem->get_kpool(); const uint32_t n_kv = get_idx()->get_n_kv(); @@ -742,7 +761,7 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, const auto & lay = mem->kpool_layout_get(); const uint32_t n_tokens = ubatch->n_tokens; - const uint32_t n_pool = (uint32_t) pool_cells->ne[0]; + const uint32_t n_pool = select ? (uint32_t) pool_cells->ne[0] : kpool_pad(st.n_pool_real); const uint32_t n_new = st.n_new; // the graph always pools at least one entry, padded to a stable bound, see kpool_build_state const uint32_t n_new_g = st.n_new_g; @@ -751,9 +770,11 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, GGML_ASSERT(n_pool == kpool_pad(st.n_pool_real)); GGML_ASSERT(st.is_new.size() == st.n_pool_real); - GGML_ASSERT(pool_mask->ne[0] == (int64_t) n_pool && pool_mask->ne[1] == (int64_t) n_tokens); - GGML_ASSERT(tail_idxs->ne[0] == (int64_t) kpool - 1 && tail_idxs->ne[1] == (int64_t) n_tokens); - GGML_ASSERT(pool_idxs->ne[0] == (int64_t) kpool && pool_idxs->ne[1] == (int64_t) n_pool); + if (select) { + GGML_ASSERT(pool_mask->ne[0] == (int64_t) n_pool && pool_mask->ne[1] == (int64_t) n_tokens); + GGML_ASSERT(tail_idxs->ne[0] == (int64_t) kpool - 1 && tail_idxs->ne[1] == (int64_t) n_tokens); + GGML_ASSERT(pool_idxs->ne[0] == (int64_t) kpool && pool_idxs->ne[1] == (int64_t) n_pool); + } GGML_ASSERT(ggml_backend_buffer_is_host(new_pool_idxs->buffer)); GGML_ASSERT(ggml_nelements(new_pool_idxs) == (int64_t) kpool*n_new_g); // the graph always scatters the fresh pooled keys back into the cache, see build_qsa_sel @@ -791,7 +812,7 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, // in order mode a token sees the pools and the tail up to its own rank in the sequence, which its cell pins down std::vector rank; - if (by_order) { + if (by_order && select) { const auto & sinfo = sinfos_kpool[i_cur]; const uint32_t n_tps = (uint32_t) sinfo.size(); @@ -824,8 +845,16 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, std::vector pool_end; pool_end.reserve(n_pool); - int32_t * pcell = (int32_t *) pool_cells->data; - int32_t * pidx = (int32_t *) pool_idxs->data; + // the pool cells and members are also what the padded entries below are placed around: keep them locally without the inputs + std::vector pcell_loc; + std::vector pidx_loc; + if (!select) { + pcell_loc.resize(n_pool); + pidx_loc.resize((size_t) n_pool*kpool); + } + + int32_t * pcell = select ? (int32_t *) pool_cells->data : pcell_loc.data(); + int32_t * pidx = select ? (int32_t *) pool_idxs->data : pidx_loc.data(); int32_t * nidx = (int32_t *) new_pool_idxs->data; int64_t * nrep = (int64_t *) new_pool_rep->data; int32_t * npos = new_pool_pos != nullptr ? (int32_t *) new_pool_pos->data : nullptr; @@ -932,6 +961,10 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, } } }; + if (!select) { + return; + } + if (pool_mask->type == GGML_TYPE_F16) { fill_mask((ggml_fp16_t *) pool_mask->data); } else { diff --git a/src/llama-memory-hybrid-idx.h b/src/llama-memory-hybrid-idx.h index 59940dbb841f..09bdafc40289 100644 --- a/src/llama-memory-hybrid-idx.h +++ b/src/llama-memory-hybrid-idx.h @@ -107,6 +107,15 @@ class llama_memory_hybrid_idx : public llama_memory_hybrid { const stale_pos_t & mem_idx_stale_get() const { return mem_idx_stale; } void mem_idx_stale_clear() { mem_idx_stale.fill(POS_CLEAN); } + // The pool marks of a batch, per global cell the generation that last marked a pool with that rep. + // Kept here because a context lives for one batch only and the array spans the whole cache. + struct kpool_marks { + std::vector rep_gen; + uint32_t generation = 0; + }; + + kpool_marks & kpool_marks_get() { return kpool_mk; } + private: // forget seq_id (all of it if seq_id < 0) in every cache at once, so a failed restore cannot leave the caches out of step // seq_id < 0 drops the whole context, as the caches themselves do on a failed restore @@ -121,6 +130,8 @@ class llama_memory_hybrid_idx : public llama_memory_hybrid { // unique_ptr because kpool_layout is incomplete here std::unique_ptr kpool_lay; + kpool_marks kpool_mk; + // seq_id < 0 stales every sequence, p0 < 0 stales the sequence from its first position void mem_idx_stale_set(llama_seq_id seq_id, llama_pos p0); diff --git a/src/llama-mmap.cpp b/src/llama-mmap.cpp index 9688a7ed4e92..f17d8ccd4471 100644 --- a/src/llama-mmap.cpp +++ b/src/llama-mmap.cpp @@ -806,6 +806,11 @@ struct llama_mmap::impl { mapped_fragments = std::move(new_mapped_fragments); } + void evict(size_t first, size_t last) { + GGML_UNUSED(first); + GGML_UNUSED(last); + } + ~impl() { for (const auto & frag : mapped_fragments) { if (munmap((char *) addr + frag.first, frag.second - frag.first)) { @@ -865,9 +870,30 @@ struct llama_mmap::impl { } } + // a view cannot be unmapped in parts, so drop the pages of the range from the working set instead void unmap_fragment(size_t first, size_t last) { - GGML_UNUSED(first); - GGML_UNUSED(last); + evict(first, last); + } + + // the pages are clean file pages: they go to the standby list, and fault back in if the range is read again + void evict(size_t first, size_t last) { + SYSTEM_INFO si; + GetSystemInfo(&si); + const size_t page_size = si.dwPageSize; + + first = (first + page_size - 1) & ~(page_size - 1); + last = std::min(last, size) & ~(page_size - 1); + if (last <= first) { + return; + } + + // VirtualUnlock on pages that are not locked removes them from the working set and fails with ERROR_NOT_LOCKED + if (!VirtualUnlock((char *) addr + first, last - first)) { + const DWORD error = GetLastError(); + if (error != ERROR_NOT_LOCKED) { + LLAMA_LOG_DEBUG("%s: VirtualUnlock failed: %s\n", __func__, llama_format_win_err(error).c_str()); + } + } } ~impl() { @@ -900,6 +926,11 @@ struct llama_mmap::impl { throw std::runtime_error("mmap not supported"); } + + void evict(size_t first, size_t last) { + GGML_UNUSED(first); + GGML_UNUSED(last); + } #endif void * addr; @@ -914,6 +945,7 @@ size_t llama_mmap::size() const { return pimpl->size; } void * llama_mmap::addr() const { return pimpl->addr; } void llama_mmap::unmap_fragment(size_t first, size_t last) { pimpl->unmap_fragment(first, last); } +void llama_mmap::evict(size_t first, size_t last) { pimpl->evict(first, last); } #if defined(_POSIX_MEMLOCK_RANGE) || defined(_WIN32) const bool llama_mmap::SUPPORTED = true; diff --git a/src/llama-mmap.h b/src/llama-mmap.h index 6c6393d5734d..89ec593dc550 100644 --- a/src/llama-mmap.h +++ b/src/llama-mmap.h @@ -58,6 +58,9 @@ struct llama_mmap { void unmap_fragment(size_t first, size_t last); + // drop the pages of [first, last) from the working set, the range stays mapped (no-op except on Windows) + void evict(size_t first, size_t last); + static const bool SUPPORTED; private: diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp index 2cbee61d4a69..54c03531e3c2 100644 --- a/src/llama-model-loader.cpp +++ b/src/llama-model-loader.cpp @@ -1186,7 +1186,6 @@ bool llama_model_loader::lazy_read::add(const std::string & name, const ggml_ten } // do not lazy-read small tensors, it has significant overhead and is not worth it - constexpr size_t auto_min_size = 4ull * 1024 * 1024 * 1024; if (mode != LLAMA_LAZY_MODE_ON && ggml_nbytes(t) <= auto_min_size) { return false; } @@ -1829,6 +1828,10 @@ bool llama_model_loader::load_all_data( mmap_used.second = std::max(mmap_used.second, weight->offs + n_size); } else { ggml_backend_tensor_set(cur, data, 0, n_size); + // the mapped pages were only read for the copy, do not let them accumulate until the end of the load + if (!lazy.has(cur)) { + mapping->evict(weight->offs, weight->offs + n_size); + } } } else { const auto & file = files.at(weight->idx); diff --git a/src/llama-model-loader.h b/src/llama-model-loader.h index ed59079a4ead..1c4524017354 100644 --- a/src/llama-model-loader.h +++ b/src/llama-model-loader.h @@ -88,6 +88,9 @@ struct llama_model_loader { // set by the caller before the create_tensor() calls enum llama_lazy_mode mode = LLAMA_LAZY_MODE_OFF; + // in AUTO mode, only tensors larger than this are read lazily + size_t auto_min_size = 4ull * 1024 * 1024 * 1024; + // decide whether this tensor is read lazily // pass w to also record it, or nullptr to only ask bool add(const std::string & name, const ggml_tensor * t, const llama_tensor_weight * w); diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 7c75ab55ef30..6082461d2e37 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -1709,13 +1709,24 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { } } - // resolve AUTO on systems without mmap support (e.g. iGPUs): fall back to OFF unless mmap is in use; see #28160, #31943 + // resolve AUTO on systems without mmap support (e.g. iGPUs): keep the tensors resident unless mmap is in use; see #28160, #31943 + // a tensor that takes more than a quarter of the host memory is still read lazily, keeping it resident would page if (ml.lazy.mode == LLAMA_LAZY_MODE_AUTO && !ml.use_mmap) { for (const auto & dev : devices) { ggml_backend_dev_props props; ggml_backend_dev_get_props(dev.dev, &props); if (!props.caps.mmap_support) { - ml.lazy.mode = LLAMA_LAZY_MODE_OFF; + size_t host_free = 0; + size_t host_total = 0; + ggml_backend_dev_t host_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); + if (host_dev) { + ggml_backend_dev_memory(host_dev, &host_free, &host_total); + } + if (host_total == 0) { + ml.lazy.mode = LLAMA_LAZY_MODE_OFF; + } else { + ml.lazy.auto_min_size = std::max(ml.lazy.auto_min_size, host_total / 4); + } break; } } @@ -3351,6 +3362,11 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, if (filter_idx) { filter_idx = [&](uint32_t il) { return il >= hparams.n_layer(); }; } + // a dense MTP block (compress ratio 0, e.g. the shared MTP files) caches the indexer keys only + // when its context may run QSA (mtp_qsa auto or on) + if (filter_idx && hparams.dsv4_compress_ratios[hparams.n_layer()] == 0 && cparams.mtp_qsa == LLAMA_MTP_QSA_OFF) { + filter_idx = nullptr; + } } } diff --git a/src/models/models.h b/src/models/models.h index cfef363b6a10..3124629d32be 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2741,9 +2741,11 @@ struct llama_model_qwen4exp : public llama_model_base { int il); // the QSA layers share one set of k-pool inputs, see llama_memory_hybrid_idx - llm_graph_input_kpool * build_inp_kpool(const llama_memory_hybrid_idx_context * mctx_hyb); + // select = false is the light set of a dense step that only keeps the pooled keys up to date: no pool inputs + llm_graph_input_kpool * build_inp_kpool(const llama_memory_hybrid_idx_context * mctx_hyb, bool select = true); // QSA: the additive mask [n_kv, n_tokens] of the top blocks and the tail + // a light k-pool input (inp_kpool->select == false) only writes the indexer keys and the pooled keys of the new blocks, and returns null ggml_tensor * build_qsa_sel( const llama_memory_hybrid_idx_context * mctx_hyb, llm_graph_input_kpool * inp_kpool, @@ -2770,13 +2772,19 @@ struct llama_model_qwen4exp : public llama_model_base { std::map rs_rows; // one conv history per cache tensor: delta-net and PLE each have their own + // split_tail: the state is written back from a separate concat of the last columns only, + // so that the full conv input feeds the convolution alone (backends may fuse the two) + // tail: when not null, the state is not written back here: *tail receives the columns to write back with + // build_conv_state_store later (so that x stays alive until then) ggml_tensor * build_conv_state_at( llm_graph_input_rs * inp, ggml_tensor * conv_states_all, ggml_tensor * x, int64_t state_cols, int64_t channels, - int il); + int il, + bool split_tail = false, + ggml_tensor ** tail = nullptr); ggml_tensor * build_inp_ple( const llama_memory_hybrid_idx_context * mctx_hyb); diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp index 181e4dca4047..144b5fe9e251 100644 --- a/src/models/qwen4exp.cpp +++ b/src/models/qwen4exp.cpp @@ -5,6 +5,16 @@ #include #include +#include + +// from this many tokens on, the PLE gather (a CPU split over the lazily read table) is ordered after the layers +// before the PLE layer, so the CPU reads the rows while the GPU computes those layers +static constexpr int64_t QWEN4EXP_PLE_OVERLAP_MIN_TOKENS = 64; + +// QSA or dense attention for the MTP block of a dense file, for a cache of n_kv cells +static bool qwen4exp_mtp_use_qsa(llama_mtp_qsa_type mode, uint32_t n_kv) { + return mode == LLAMA_MTP_QSA_ON || (mode == LLAMA_MTP_QSA_AUTO && n_kv >= LLAMA_MTP_QSA_MIN_KV); +} // bad metadata must be catchable: GGML_ASSERT aborts the whole process static void qwen4exp_require_nonzero(const llama_model_loader & ml, llm_kv kid, uint32_t value) { @@ -182,7 +192,9 @@ void llama_model_qwen4exp::load_arch_tensors(llama_model_loader & ml) { const int trunk_flags = nf.trunk; const int mtp_flags = nf.mtp; - tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, 0); + // a draft head file without the trunk can leave out token_embd and output (the "shared" MTP files, + // nextn_shared_target_tensors): the draft context then borrows both from its target model + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, trunk_flags); // there is no output_norm: the final hyper-connection mixer carries it // the gammas load as [n_embd, hc] so the grouped norm multiplies them without a graph reshape @@ -191,7 +203,7 @@ void llama_model_qwen4exp::load_arch_tensors(llama_model_loader & ml) { hc_head_up = create_tensor(tn(LLM_TENSOR_HC_HEAD_UP, "weight"), { hc_lr, hc_dim }, trunk_flags); output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED); - if (output == NULL) { + if (output == NULL && tok_embd != NULL) { output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, TENSOR_DUPLICATED); } @@ -365,6 +377,12 @@ llama_model_qwen4exp::graph::build_hc_mix( ggml_tensor * lo = nullptr; ggml_tensor * inject = nullptr; + if (!w_down_inject && w_inject && nt >= 32) { + // prompt batches: the inject sits right after the norm, where the CUDA HC mix kernel looks for it + inject = ggml_scale(ctx0, build_lora_mm(w_inject, xn), 1.0f / (float) hc); + cb(inject, "hc_inject", il); + ggml_build_forward_expand(gf, inject); + } if (w_down_inject) { // one matmul for both: the hc_down rows, then the hc_inject rows const int64_t n_lo = w_down_inject->ne[1] - hc; @@ -406,7 +424,7 @@ llama_model_qwen4exp::graph::build_hc_mix( } cb(mixed, "hc_mixed", il); - if (!w_down_inject && w_inject) { + if (!w_down_inject && w_inject && !inject) { inject = ggml_scale(ctx0, build_lora_mm(w_inject, xn), 1.0f / (float) hc); cb(inject, "hc_inject", il); } @@ -463,10 +481,13 @@ llama_model_qwen4exp::graph::graph(const llm_graph_params & params) : } ggml_tensor * ple_emb = nullptr; + const bool ple_late = n_tokens >= QWEN4EXP_PLE_OVERLAP_MIN_TOKENS; if (hparams.ple_n_heads > 0) { ple_emb = build_inp_ple(mctx_hyb); - // make sure ple_emb and build_inp_embd are in the same graph split - ggml_build_forward_expand(gf, ple_emb); + if (!ple_late) { + // make sure ple_emb and build_inp_embd are in the same graph split + ggml_build_forward_expand(gf, ple_emb); + } } ggml_tensor * inpL = build_inp_embd(model.tok_embd); @@ -499,6 +520,10 @@ llama_model_qwen4exp::graph::graph(const llm_graph_params & params) : } if (hparams.is_ple(il)) { + if (ple_late) { + // the earlier layers come first in the graph, so they do not wait for the gather on the CPU + ggml_build_forward_expand(gf, res_hc); + } res_hc = build_ple(inp->get_recr(), ple_emb, res_hc, il); } @@ -598,9 +623,14 @@ llama_model_qwen4exp::graph_mtp::graph_mtp(const llm_graph_params & params) : inp->h = build_inp_embd_state(inp.get(), hparams.n_embd_out()); + // a draft head without token_embd and output (shared MTP file) borrows them from its target model + const llama_model * model_tgt = cparams.ctx_other ? llama_get_model(cparams.ctx_other) : nullptr; + ggml_tensor * tok_embd; if (ubatch.token) { - tok_embd = ggml_get_rows(ctx0, model.tok_embd, inp->tokens); + ggml_tensor * tok_embd_w = model.tok_embd ? model.tok_embd : model_tgt ? model_tgt->tok_embd : nullptr; + GGML_ASSERT(tok_embd_w && "qwen4exp MTP has no token embeddings, neither its own nor its target's"); + tok_embd = ggml_get_rows(ctx0, tok_embd_w, inp->tokens); } else { tok_embd = inp->embd; } @@ -616,11 +646,17 @@ llama_model_qwen4exp::graph_mtp::graph_mtp(const llm_graph_params & params) : // the draft memory has no recurrent layer, but its input still has to be allocated ggml_build_forward_expand(gf, inp_hyb->get_recr()->s_copy); + // a block with a compress ratio of 0 attends densely (the shared MTP files): it keeps the indexer state (keys and pooled + // keys) only when the draft context may switch to QSA (mtp_qsa auto or on), otherwise there is no indexer cache and no + // k-pool input, or their indexer key indexes would stay unallocated while set_input() fills them llm_graph_input_kpool * inp_kpool = nullptr; - if (mctx_hyb->get_idx() && hparams.indexer_kpool > 0) { + if (mctx_hyb->get_idx() && hparams.indexer_kpool > 0 && (hparams.dsv4_compress_ratios[il] > 0 || cparams.mtp_qsa != LLAMA_MTP_QSA_OFF)) { GGML_ASSERT(mctx_hyb->get_idx()->get_n_kv() == mctx_hyb->get_attn()->get_n_kv() && "the indexer cache must track the attention cache cell for cell"); - inp_kpool = build_inp_kpool(mctx_hyb); + // a dense block picks QSA or dense attention for the cache length of this graph: the k-pool input of a dense step is + // the light one + const bool select = hparams.dsv4_compress_ratios[il] > 0 || qwen4exp_mtp_use_qsa(cparams.mtp_qsa, mctx_hyb->get_idx()->get_n_kv()); + inp_kpool = build_inp_kpool(mctx_hyb, select); } ggml_tensor * inp_pos = build_inp_pos(); @@ -660,7 +696,10 @@ llama_model_qwen4exp::graph_mtp::graph_mtp(const llm_graph_params & params) : cb(cur, "result_norm", -1); res->t_embd = cur; - cur = build_lora_mm(model.output, cur, model.output_s); + const llama_model & model_head = model.output || !model_tgt ? model : *model_tgt; + GGML_ASSERT(model_head.output && "qwen4exp MTP has no output head, neither its own nor its target's"); + + cur = build_lora_mm(model_head.output, cur, model_head.output_s); cb(cur, "result_output", -1); res->t_logits = cur; } @@ -733,9 +772,11 @@ class llama_model_qwen4exp::llm_graph_input_kpool : public llm_graph_input_i { bool res = true; res &= k_idxs->ne[0] == params.ubatch.n_tokens; - res &= pool_cells->ne[0] == mctx->get_n_kpool(); - res &= pool_mask->ne[1] == params.ubatch.n_tokens; - res &= tail_idxs->ne[1] == params.ubatch.n_tokens; + if (select) { + res &= pool_cells->ne[0] == mctx->get_n_kpool(); + res &= pool_mask->ne[1] == params.ubatch.n_tokens; + res &= tail_idxs->ne[1] == params.ubatch.n_tokens; + } // the scatter mask shape follows n_kv res &= n_kv == idx->get_n_kv(); res &= n_new == mctx->get_n_kpool_new(); @@ -744,6 +785,7 @@ class llama_model_qwen4exp::llm_graph_input_kpool : public llm_graph_input_i { } ggml_tensor * k_idxs = nullptr; // I64 [n_tokens] + // null for a dense step that only keeps the pooled keys up to date (select == false): nothing reads them ggml_tensor * pool_cells = nullptr; // I32 [n_pool] cell caching each block's pooled key ggml_tensor * pool_idxs = nullptr; // I32 [kpool, n_pool] member cells per block, n_kv sentinel for the padded blocks ggml_tensor * pool_mask = nullptr; // F16 [n_pool, n_tokens] @@ -755,12 +797,13 @@ class llama_model_qwen4exp::llm_graph_input_kpool : public llm_graph_input_i { const llama_memory_hybrid_idx_context * mctx; const uint32_t kpool; + bool select = true; // the layers attend through QSA, else the step only keeps the pooled keys up to date uint32_t n_new = 0; // padded to a stable bound, never below 1 uint32_t n_sel = 0; uint32_t n_kv = 0; }; -llama_model_qwen4exp::llm_graph_input_kpool * llama_model_qwen4exp::graph::build_inp_kpool(const llama_memory_hybrid_idx_context * mctx_hyb) { +llama_model_qwen4exp::llm_graph_input_kpool * llama_model_qwen4exp::graph::build_inp_kpool(const llama_memory_hybrid_idx_context * mctx_hyb, bool select) { const auto * mctx_idx = mctx_hyb->get_idx(); GGML_ASSERT(mctx_idx != nullptr); @@ -769,21 +812,24 @@ llama_model_qwen4exp::llm_graph_input_kpool * llama_model_qwen4exp::graph::build auto inp = std::make_unique(mctx_hyb, kpool); + inp->select = select; inp->k_idxs = mctx_idx->build_input_k_idxs(ctx0, ubatch); - inp->pool_cells = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_pool); - inp->pool_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool, n_pool); - inp->pool_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F16, n_pool, n_tokens); - inp->tail_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool - 1, n_tokens); - ggml_set_input(inp->pool_cells); - ggml_set_input(inp->pool_idxs); - ggml_set_input(inp->pool_mask); - ggml_set_input(inp->tail_idxs); - - // set_input fills them all, so keep them allocated even when no op reads them - ggml_build_forward_expand(gf, inp->pool_cells); - ggml_build_forward_expand(gf, inp->pool_idxs); - ggml_build_forward_expand(gf, inp->pool_mask); - ggml_build_forward_expand(gf, inp->tail_idxs); + if (select) { + inp->pool_cells = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_pool); + inp->pool_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool, n_pool); + inp->pool_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F16, n_pool, n_tokens); + inp->tail_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool - 1, n_tokens); + ggml_set_input(inp->pool_cells); + ggml_set_input(inp->pool_idxs); + ggml_set_input(inp->pool_mask); + ggml_set_input(inp->tail_idxs); + + // set_input fills them all, so keep them allocated even when no op reads them + ggml_build_forward_expand(gf, inp->pool_cells); + ggml_build_forward_expand(gf, inp->pool_idxs); + ggml_build_forward_expand(gf, inp->pool_mask); + ggml_build_forward_expand(gf, inp->tail_idxs); + } inp->n_kv = mctx_idx->get_n_kv(); inp->n_new = mctx_hyb->get_n_kpool_new(); @@ -816,10 +862,10 @@ ggml_tensor * llama_model_qwen4exp::graph::build_qsa_sel( const int64_t idx_dim = hparams.indexer_head_size; const int64_t n_idx_h = hparams.indexer_n_head; const int64_t kpool = inp_kpool->kpool; - const int64_t n_pool = inp_kpool->pool_cells->ne[0]; + const int64_t n_pool = inp_kpool->select ? inp_kpool->pool_cells->ne[0] : 0; // the light input has no pool tensors const int64_t n_new = inp_kpool->n_new; - GGML_ASSERT(hparams.dsv4_compress_ratios[il] == kpool); + GGML_ASSERT(kpool == hparams.indexer_kpool); // cache rows store raw key | pooled key: pooling precedes norm and rotation, so the raw key gets neither ggml_tensor * k_raw = build_lora_mm(model.layers[il].index_k_proj, cur); @@ -853,6 +899,13 @@ ggml_tensor * llama_model_qwen4exp::graph::build_qsa_sel( // scatter the fresh pooled keys into their rep rows, then gather all n_pool of them by cell: // the older pools come from the rows earlier ubatches wrote ggml_build_forward_expand(gf, kpool_cache.scatter_pooled(pooled_new, inp_kpool->new_pool_rep)); + + // a dense step of a block that may switch to QSA only keeps the state up to date: every ubatch writes its keys and + // re-pools the blocks it completes, so that a later QSA step finds the pooled keys of the whole context + if (!inp_kpool->select) { + return nullptr; + } + ggml_tensor * pooled = kpool_cache.gather_pooled(inp_kpool->pool_cells); pooled = ggml_reshape_3d(ctx0, pooled, idx_dim, 1, n_pool); cb(pooled, "indexer_k", il); @@ -1014,9 +1067,19 @@ ggml_tensor * llama_model_qwen4exp::graph::build_layer_attn( GGML_ASSERT(n_embd_head == hparams.n_embd_head_k()); // indexer reads the same block input as q/k/v; no cache or no ratio means dense - const bool qsa = inp_kpool != nullptr && hparams.dsv4_compress_ratios[il] > 0; + bool qsa = inp_kpool != nullptr && hparams.dsv4_compress_ratios[il] > 0; - ggml_tensor * sel = qsa ? build_qsa_sel(mctx_hyb, inp_kpool, cur, inp_pos, il) : nullptr; + // the MTP block of a dense file keeps the indexer state (see graph_mtp), QSA or dense attention is picked per graph + const bool dense_mtp_state = inp_kpool != nullptr && !qsa && cparams.ctx_type == LLAMA_CONTEXT_TYPE_MTP && il >= (int) hparams.n_layer(); + if (dense_mtp_state) { + qsa = inp_kpool->select; + } + + // a dense step builds no selection, it only keeps the indexer keys and the pooled keys up to date + ggml_tensor * sel = nullptr; + if (qsa || dense_mtp_state) { + sel = build_qsa_sel(mctx_hyb, inp_kpool, cur, inp_pos, il); + } // Qwen3Next uses a single Q projection that outputs query + gate ggml_tensor * Qcur_full = build_lora_mm(model.layers[il].wq, cur, model.layers[il].wq_s); // [ (n_embd_head * 2) * n_head, n_tokens ] @@ -1120,6 +1183,11 @@ ggml_tensor * llama_model_qwen4exp::graph::build_layer_attn_linear( alpha = build_lora_mm(model.layers[il].ssm_alpha, cur, model.layers[il].ssm_alpha_s); alpha = ggml_reshape_3d(ctx0, alpha, num_v_heads, n_seq_tokens, n_seqs); + if (n_seq_tokens >= 64) { + // prompt batches: the two products of the same input next to each other (one launch on CUDA) + ggml_build_forward_expand(gf, beta); + ggml_build_forward_expand(gf, alpha); + } } cb(beta, "beta", il); cb(alpha, "alpha", il); @@ -1145,13 +1213,24 @@ ggml_tensor * llama_model_qwen4exp::graph::build_layer_attn_linear( // the channels must match how load_arch_tensors sizes wqkv, not ssm_d_inner const int64_t conv_channels = head_k_dim * num_k_heads * 2 + head_v_dim * num_v_heads; + // prompt batches: the conv state is written back from the last columns after the GDN, so that the convolution and + // the norms of q and k follow their CONCAT directly (one kernel on CUDA) + ggml_tensor * conv_tail = nullptr; ggml_tensor * conv_input = build_conv_state_at(inp, conv_states_all, qkv_mixed, - conv_kernel_size - 1, conv_channels, il); + conv_kernel_size - 1, conv_channels, il, /*split_tail =*/ true, n_seq_tokens >= 64 ? &conv_tail : nullptr); ggml_tensor * state = build_rs(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); state = ggml_reshape_4d(ctx0, state, head_v_dim, head_v_dim, num_v_heads, n_seqs); cb(state, "state_predelta", il); + if (n_seq_tokens >= 64) { + // prompt batches: the other inputs of the GDN first, so that the convolution, the norms of q and k and the GDN + // follow one another, which the CUDA backend computes in one kernel + ggml_build_forward_expand(gf, gate); + ggml_build_forward_expand(gf, beta); + ggml_build_forward_expand(gf, state); + } + ggml_tensor * conv_output_proper = ggml_ssm_conv(ctx0, conv_input, conv_kernel); cb(conv_output_proper, "conv_output_raw", il); @@ -1196,6 +1275,9 @@ ggml_tensor * llama_model_qwen4exp::graph::build_layer_attn_linear( cb(v_conv, "v_conv_predelta", il); ggml_tensor * output = build_recurrent_attn(inp, ssm_states_all, q_conv, k_conv, v_conv, gate, beta, state, il); + if (conv_tail) { + build_conv_state_store(inp, conv_states_all, conv_tail, conv_kernel_size - 1, 0); + } ggml_tensor * z_2d = ggml_view_4d(ctx0, z, head_v_dim, num_v_heads, n_seq_tokens, n_seqs, ggml_row_size(z->type, head_v_dim), z->nb[1], z->nb[1] * n_seq_tokens, 0); @@ -1270,7 +1352,11 @@ class llm_graph_input_qwen4exp_ple : public llm_graph_input_i { public: llm_graph_input_qwen4exp_ple(const llama_model & model, const llama_kv_cache_context * mctx) : model(model), mctx(mctx) {} - virtual ~llm_graph_input_qwen4exp_ple() = default; + virtual ~llm_graph_input_qwen4exp_ple() { + if (prefetch_thread.joinable()) { + prefetch_thread.join(); + } + } void set_input(const llama_ubatch * ubatch) override; @@ -1288,6 +1374,10 @@ class llm_graph_input_qwen4exp_ple : public llm_graph_input_i { // scratch, reused across set_input() calls std::vector prev; + + // rows being prefetched in the background, owned by the thread until it is joined + std::vector prefetch_idx; + std::thread prefetch_thread; }; void llm_graph_input_qwen4exp_ple::set_input(const llama_ubatch * ubatch) { @@ -1352,11 +1442,21 @@ void llm_graph_input_qwen4exp_ple::set_input(const llama_ubatch * ubatch) { } { - ggml_tensor * ple = model.per_layer_tok_embd; + const ggml_tensor * ple = model.per_layer_tok_embd; - const bool prefetch = model.can_prefetch.count(ple); - if (prefetch) { - llama_prefetch_rows(ple, idx.data(), idx.size()); + if (prefetch_thread.joinable()) { + prefetch_thread.join(); + } + if (model.can_prefetch.count(ple)) { + if (n_tokens >= QWEN4EXP_PLE_OVERLAP_MIN_TOKENS) { + // madvise over tens of thousands of rows takes tens of ms, keep it off the thread that submits the graph + prefetch_idx = idx; + prefetch_thread = std::thread([this, ple]() { + llama_prefetch_rows(ple, prefetch_idx.data(), prefetch_idx.size()); + }); + } else { + llama_prefetch_rows(ple, idx.data(), idx.size()); + } } } @@ -1371,7 +1471,9 @@ ggml_tensor * llama_model_qwen4exp::graph::build_conv_state_at( ggml_tensor * x, int64_t state_cols, int64_t channels, - int il) { + int il, + bool split_tail, + ggml_tensor ** tail) { const int64_t n_seqs = ubatch.n_seqs; const int64_t row_total = conv_states_all->ne[0]; @@ -1387,9 +1489,26 @@ ggml_tensor * llama_model_qwen4exp::graph::build_conv_state_at( ggml_tensor * state = ggml_reshape_3d(ctx0, rows, state_cols, channels, n_seqs); cb(state, "conv_state_at", il); + // the store reads the last state_cols + n_rs_seq columns; with tail_tokens columns of x after the state, + // all of them come from x, so a short concat gives the same values as the full one + const int64_t n_seq_tokens = x->ne[1]; + const int64_t tail_tokens = split_tail ? std::min(n_seq_tokens, state_cols + cparams.n_rs_seq) : n_seq_tokens; + ggml_tensor * conv_input = ggml_concat(ctx0, state, ggml_transpose(ctx0, x), 0); - build_conv_state_store(inp, conv_states_all, conv_input, state_cols, 0); + ggml_tensor * conv_tail = conv_input; + if (tail_tokens < n_seq_tokens) { + ggml_tensor * x_tail = ggml_view_3d(ctx0, x, x->ne[0], tail_tokens, n_seqs, x->nb[1], x->nb[2], + (n_seq_tokens - tail_tokens) * x->nb[1]); + conv_tail = ggml_concat(ctx0, state, ggml_transpose(ctx0, x_tail), 0); + cb(conv_tail, "conv_state_tail", il); + } + + if (tail) { + *tail = conv_tail; + } else { + build_conv_state_store(inp, conv_states_all, conv_tail, state_cols, 0); + } return conv_input; } diff --git a/tests/test-arg-parser.cpp b/tests/test-arg-parser.cpp index 537c333949b1..c8434d80af10 100644 --- a/tests/test-arg-parser.cpp +++ b/tests/test-arg-parser.cpp @@ -284,6 +284,28 @@ static void test(void) { assert(true == common_params_parse(argv.size(), list_str_to_char(argv).data(), params, LLAMA_EXAMPLE_SPECULATIVE)); assert(params.speculative.draft.n_max == 123); + { + // MTP draft head options: auto by default + common_params mtp_params; + assert(mtp_params.speculative.draft.mtp_qsa == LLAMA_MTP_QSA_AUTO); + + argv = {"binary_name", "--spec-draft-qsa", "off"}; + assert(true == common_params_parse(argv.size(), list_str_to_char(argv).data(), mtp_params, LLAMA_EXAMPLE_SERVER)); + assert(mtp_params.speculative.draft.mtp_qsa == LLAMA_MTP_QSA_OFF); + assert(common_context_params_to_llama(mtp_params).mtp_qsa == LLAMA_MTP_QSA_OFF); + + argv = {"binary_name", "--spec-draft-qsa", "on"}; + assert(true == common_params_parse(argv.size(), list_str_to_char(argv).data(), mtp_params, LLAMA_EXAMPLE_SERVER)); + assert(mtp_params.speculative.draft.mtp_qsa == LLAMA_MTP_QSA_ON); + + argv = {"binary_name", "--spec-draft-qsa", "auto"}; + assert(true == common_params_parse(argv.size(), list_str_to_char(argv).data(), mtp_params, LLAMA_EXAMPLE_SERVER)); + assert(mtp_params.speculative.draft.mtp_qsa == LLAMA_MTP_QSA_AUTO); + + argv = {"binary_name", "--spec-draft-qsa", "maybe"}; + assert(false == common_params_parse(argv.size(), list_str_to_char(argv).data(), mtp_params, LLAMA_EXAMPLE_SERVER)); + } + { common_params synth_params; argv = {"binary_name", "--spec-synth-len", "3.4"}; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index dc1d2866e32b..082bb6f631a6 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -244,6 +244,37 @@ static void init_tensor_kq_mask_sparse(ggml_tensor * tensor, int64_t n_kv_max) { ggml_backend_tensor_set(tensor, data_f16.data(), 0, data_f16.size()*sizeof(ggml_fp16_t)); } +// like init_tensor_kq_mask_sparse, but the rows pick their cells in blocks of 4 from a pool of sel_pool_pct% of n_kv_max cells +// shared by all rows, so neighbouring queries overlap like the selections of a Qwen QSA indexer +static void init_tensor_kq_mask_sparse_shared(ggml_tensor * tensor, int64_t n_kv_max, int sel_pool_pct) { + GGML_ASSERT(tensor->type == GGML_TYPE_F16); + GGML_ASSERT(n_kv_max > 0 && n_kv_max <= tensor->ne[0] && sel_pool_pct >= 100); + + const int64_t ne0 = tensor->ne[0]; + const int64_t nrows = ggml_nrows(tensor); + const int64_t n_pool_blocks = std::min(ne0/4, n_kv_max*sel_pool_pct/100/4); + std::vector data_f32(ggml_nelements(tensor), -INFINITY); + std::vector data_f16(ggml_nelements(tensor)); + std::vector order(ne0/4); + for (int64_t i = 0; i < ne0/4; ++i) { + order[i] = i; + } + + std::mt19937 gen(0x5A17); + std::shuffle(order.begin(), order.end(), gen); + std::vector pool(order.begin(), order.begin() + n_pool_blocks); + for (int64_t row = 0; row < nrows; ++row) { + std::shuffle(pool.begin(), pool.end(), gen); + const int64_t count = n_kv_max - row % std::min(n_kv_max, 17); + for (int64_t i = 0; i < count; ++i) { + data_f32[row*ne0 + 4*int64_t(pool[i/4]) + i%4] = -0.03125f * (1 + (i + row) % 7); + } + } + + ggml_fp32_to_fp16_row(data_f32.data(), data_f16.data(), data_f16.size()); + ggml_backend_tensor_set(tensor, data_f16.data(), 0, data_f16.size()*sizeof(ggml_fp16_t)); +} + // generate a lower triangular matrix static void init_tensor_tril(ggml_tensor * tensor, float min = -1.0f, float max = 1.0f) { GGML_ASSERT(tensor->type == GGML_TYPE_F32); @@ -4557,6 +4588,40 @@ struct test_relu_sqr : public test_case { } }; +// GGML_OP_SCALE + GGML_UNARY_OP_SILU (fused operation) +struct test_scale_silu : public test_case { + const std::array ne; + const float scale; + const float bias; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "SCALE_SILU"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR3(ne, scale, bias); + } + + test_scale_silu(std::array ne = {320, 4, 1, 1}, float scale = 0.25f, float bias = 0.0f) + : ne(ne), scale(scale), bias(bias) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_set_name(a, "a"); + + ggml_tensor * s = ggml_scale_bias(ctx, a, scale, bias); + ggml_set_name(s, "scale"); + + ggml_tensor * out = ggml_silu(ctx, s); + ggml_set_name(out, "out"); + + return out; + } +}; + // GGML_OP_UNARY(GELU|SILU|SIGMOID|SOFTPLUS) + GGML_OP_MUL (fused operation). struct test_unary_mul : public test_case { const ggml_unary_op op; @@ -4697,6 +4762,54 @@ struct test_unary_mul : public test_case { } }; +// GGML_OP_UNARY(SIGMOID) + GGML_OP_MUL + GGML_OP_ADD with one gate value per row. +struct test_sigmoid_mul_add : public test_case { + const std::array ne; + const bool swap_mul; + const bool swap_add; + const bool reuse_sigmoid; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "SIGMOID_MUL_ADD"; + } + + bool run_whole_graph() override { return true; } + double max_nmse_err() override { return 1e-7; } + + std::string vars() override { + return VARS_TO_STR4(ne, swap_mul, swap_add, reuse_sigmoid); + } + + test_sigmoid_mul_add(std::array ne, bool swap_mul = false, bool swap_add = false, bool reuse_sigmoid = false) + : ne(ne), swap_mul(swap_mul), swap_add(swap_add), reuse_sigmoid(reuse_sigmoid) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * gate = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, ne[1], ne[2], ne[3]); + ggml_set_name(gate, "gate"); + + ggml_tensor * x = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_set_name(x, "x"); + + ggml_tensor * r = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_set_name(r, "r"); + + ggml_tensor * sigmoid = ggml_sigmoid(ctx, gate); + ggml_set_name(sigmoid, "sigmoid"); + + ggml_tensor * mul = swap_mul ? ggml_mul(ctx, sigmoid, x) : ggml_mul(ctx, x, sigmoid); + ggml_set_name(mul, "mul"); + + ggml_tensor * out = swap_add ? ggml_add(ctx, r, mul) : ggml_add(ctx, mul, r); + if (reuse_sigmoid) { + ggml_set_name(out, "add"); + out = ggml_add(ctx, out, sigmoid); + } + ggml_set_name(out, "out"); + return out; + } +}; + // GGML_OP_ADD + GGML_OP_UNARY(SILU|SIGMOID|SOFTPLUS) + GGML_OP_MUL with the ADD's bias and // the MUL's scale broadcast over dim 0: the delta-net alpha gate, softplus(alpha + dt) * a_coeff. struct test_add_unary_mul : public test_case { @@ -4988,6 +5101,45 @@ struct test_dsv4_hc_pre : public test_dsv4_hc { } }; +// RMSNorm of the Qwen HC activation plus the 4-row F32 inject that reads it. +// check_down also multiplies the q8_0 down matrix and adds its first 4 rows, so a wrong norm fails too. +struct test_hc_inject : public test_case { + const int64_t n_tokens; + const bool check_down; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "HC_INJECT"; + } + std::string vars() override { return VARS_TO_STR2(n_tokens, check_down); } + test_hc_inject(int64_t n_tokens, bool check_down = false) : n_tokens(n_tokens), check_down(check_down) {} + double max_nmse_err() override { return check_down ? 5e-4 : 2e-4; } + // Keep perf from cloning the scale output thousands of times and hiding the fused kernel. + uint64_t op_flops(ggml_tensor * t) override { + GGML_UNUSED(t); + return 1000ULL * 1000 * 1000 * 1000; + } + + ggml_tensor * build_graph(ggml_context * ctx) override { + const int64_t n_embd = 2560; + const int64_t hc = 4; + const int64_t k = n_embd * hc; + ggml_tensor * x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, hc, n_tokens); + ggml_tensor * gamma = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, hc); + ggml_tensor * w_inj = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, k, hc); + ggml_tensor * xn = ggml_mul(ctx, ggml_rms_norm(ctx, x, 1e-6f), gamma); + xn = ggml_reshape_2d(ctx, xn, k, n_tokens); + ggml_tensor * inj = ggml_scale(ctx, ggml_mul_mat(ctx, w_inj, xn), 0.25f); + if (check_down) { + ggml_tensor * w_down = ggml_new_tensor_2d(ctx, GGML_TYPE_Q8_0, k, 320); + ggml_tensor * down = ggml_mul_mat(ctx, w_down, xn); + ggml_tensor * head = ggml_view_2d(ctx, down, hc, n_tokens, down->nb[1], 0); + inj = ggml_add(ctx, inj, head); + } + return inj; + } +}; + struct test_dsv4_hc_post : public test_dsv4_hc { const int64_t n_embd; const int64_t n_tokens; @@ -5102,6 +5254,70 @@ struct test_ssm_conv_bias_silu : public test_case { } }; +// GGML_OP_CONCAT(state, transpose(x)) + GGML_OP_SSM_CONV + optional bias ADD and SILU (fused operation) +// state: [d_conv - 1, d_inner, n_s], x: [d_inner, n_t, n_s] as written by the qkv matmul, so the concat reads x transposed +struct test_ssm_conv_concat : public test_case { + const int64_t d_conv; + const int64_t d_inner; + const int64_t n_t; + const int64_t n_s; + const bool fuse_bias; + const bool fuse_silu; + const bool x_view; // x is a view of a wider tensor, as qkv inside a fused qkvz output + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "SSM_CONV_CONCAT"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR7(d_conv, d_inner, n_t, n_s, fuse_bias, fuse_silu, x_view); + } + + test_ssm_conv_concat(int64_t d_conv = 4, int64_t d_inner = 1024, int64_t n_t = 64, int64_t n_s = 1, + bool fuse_bias = false, bool fuse_silu = true, bool x_view = false) + : d_conv(d_conv), d_inner(d_inner), n_t(n_t), n_s(n_s), fuse_bias(fuse_bias), fuse_silu(fuse_silu), x_view(x_view) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * state = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_conv - 1, d_inner, n_s); + ggml_set_name(state, "state"); + + ggml_tensor * x; + if (x_view) { + x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner + 96, n_t, n_s); + ggml_set_name(x, "x_wide"); + x = ggml_view_3d(ctx, x, d_inner, n_t, n_s, x->nb[1], x->nb[2], 32 * x->nb[0]); + ggml_set_name(x, "x"); + } else { + x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_t, n_s); + ggml_set_name(x, "x"); + } + + ggml_tensor * w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, d_conv, d_inner); + ggml_set_name(w, "w"); + + ggml_tensor * conv_x = ggml_concat(ctx, state, ggml_transpose(ctx, x), 0); + ggml_set_name(conv_x, "conv_x"); + + ggml_tensor * out = ggml_ssm_conv(ctx, conv_x, w); + + if (fuse_bias) { + ggml_tensor * bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, out->ne[0]); + ggml_set_name(bias, "bias"); + out = ggml_add(ctx, out, bias); + } + + if (fuse_silu) { + out = ggml_silu(ctx, out); + } + + ggml_set_name(out, "out"); + return out; + } +}; + // GGML_OP_SSM_SCAN struct test_ssm_scan : public test_case { const ggml_type type; @@ -9444,6 +9660,29 @@ struct test_flash_attn_ext_large_logits : public test_flash_attn_ext { } }; +// Qwen QSA attention (256/256, gqa 12, f16 cache) with queries that select from a shared pool of cells +struct test_flash_attn_ext_qsa : public test_flash_attn_ext { + const int sel_pool_pct; + + test_flash_attn_ext_qsa(int64_t kv, int64_t nb, int64_t n_kv_max, int sel_pool_pct) + : test_flash_attn_ext(256, 256, 2, {12, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, + {0, 1, 2, 3}, true, false, n_kv_max), sel_pool_pct(sel_pool_pct) {} + + std::string vars() override { + return test_flash_attn_ext::vars() + ",sel_pool_pct=" + std::to_string(sel_pool_pct); + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "m") == 0) { + init_tensor_kq_mask_sparse_shared(t, n_kv_max, sel_pool_pct); + } else { + init_tensor_uniform(t); + } + } + } +}; + // GGML_OP_FLASH_ATTN_EXT with kv_rows: each q slice attends to its own list of K/V cache rows struct test_flash_attn_ext_kv_rows : public test_case { const int64_t hs; @@ -10882,6 +11121,10 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_relu_sqr(type, { 5, 7, 11, 13 })); } + // fused scale + silu + test_cases.emplace_back(new test_scale_silu({ 320, 4, 1, 1 }, 0.25f, 0.0f)); + test_cases.emplace_back(new test_scale_silu({ 5, 7, 11, 13 }, -1.5f, 0.5f)); + // fused unary + mul (gated activations that are not expressed as GGML_OP_GLU) for (ggml_unary_op op : { GGML_UNARY_OP_GELU, GGML_UNARY_OP_SILU, GGML_UNARY_OP_RELU, GGML_UNARY_OP_SIGMOID, GGML_UNARY_OP_SOFTPLUS }) { for (ggml_type type : { GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_BF16 }) { @@ -10904,6 +11147,14 @@ static std::vector> make_test_cases_eval() { } } + // fused sigmoid + mul + add: the shared expert gate, one value per row + test_cases.emplace_back(new test_sigmoid_mul_add({ 2560, 1, 1, 1 })); + test_cases.emplace_back(new test_sigmoid_mul_add({ 2560, 4, 1, 1 })); + test_cases.emplace_back(new test_sigmoid_mul_add({ 5, 7, 11, 13 }, false, true)); + test_cases.emplace_back(new test_sigmoid_mul_add({ 1, 4, 1, 1 }, true, false)); + // must not fuse + test_cases.emplace_back(new test_sigmoid_mul_add({ 2560, 4, 1, 1 }, false, false, true)); + // fused add + unary + mul: the delta-net alpha gate, bias and scale broadcast over dim 0 for (ggml_unary_op op : { GGML_UNARY_OP_SILU, GGML_UNARY_OP_SIGMOID, GGML_UNARY_OP_SOFTPLUS }) { test_cases.emplace_back(new test_add_unary_mul(op, GGML_TYPE_F32, { 32, 7, 1, 1 })); @@ -10951,6 +11202,10 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_dsv4_hc_pre(4096, 4, 21)); test_cases.emplace_back(new test_dsv4_hc_pre(31, 4, 17, true)); test_cases.emplace_back(new test_dsv4_hc_pre(4096, 4, 21, true)); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_F32, 320, 64, 10240, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_hc_inject(1)); + test_cases.emplace_back(new test_hc_inject(32)); + test_cases.emplace_back(new test_hc_inject(37, true)); for (int64_t n_hc : {1, 2, 3, 5, 8, 65}) { test_cases.emplace_back(new test_dsv4_hc_pre(128, n_hc, 17)); test_cases.emplace_back(new test_dsv4_hc_pre(128, n_hc, 17, true)); @@ -12028,6 +12283,23 @@ static std::vector> make_test_cases_eval() { } } + // concat(state, transpose(x)) + ssm_conv (+ bias) (+ silu), with the concat fused into the conv + for (int64_t d_conv : {3, 4, 9}) { + for (int64_t n_t : {1, 2, 3, 5, 32, 33, 100}) { + for (int64_t n_s : {1, 3}) { + test_cases.emplace_back(new test_ssm_conv_concat(d_conv, 1536, n_t, n_s, false, true, false)); + test_cases.emplace_back(new test_ssm_conv_concat(d_conv, 1536, n_t, n_s, true, true, false)); + test_cases.emplace_back(new test_ssm_conv_concat(d_conv, 1536, n_t, n_s, false, false, true)); + test_cases.emplace_back(new test_ssm_conv_concat(d_conv, 1536, n_t, n_s, true, false, true)); + } + } + } + test_cases.emplace_back(new test_ssm_conv_concat(4, 1152, 37, 2, true, true, true)); // d_inner not a multiple of 256 + // Qwen3.8-Flash-Next linear attention: 10240 channels, prefill ubatch, MTP verify, decode + for (int64_t n_t : {1, 3, 2048}) { + test_cases.emplace_back(new test_ssm_conv_concat(4, 10240, n_t, 1, false, true, false)); + } + test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 16, 1, 1024, 1, 32, 4)); // Mamba-1 test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 64, 64, 112, 2, 32, 4)); // Zamba2 (real hparams: d_inner=7168, dt_rank=112, n_group=2 -> head_dim=7168/112=64) test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 64, 64, 112, 2, 1, 1)); // Zamba2 decode (single-token, matches real per-token decode workload) @@ -12966,6 +13238,10 @@ static std::vector> make_test_cases_eval() { } } + // short rows of many columns, as the conv state + transposed input of a recurrent layer + test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {3, 10240, 1, 1}, 4, 0, 16)); + test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {9, 10240, 2, 1}, 4, 0, 16)); + // few long rows, which backends may split across workgroups for (int dim : { 0, 1 }) { test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {98304, 8, 1, 1}, dim == 0 ? 288 : 2, dim, 0)); @@ -12979,6 +13255,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {1, 37, 1, 1}, ne_b_d, 0, 16)); } test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {64, 37, 1, 1}, 32, 0, 16)); + test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {9, 10240, 1, 1}, 2048, 0, 16)); // Empty src0 test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {0, 64, 1, 1}, 33, 0, 16)); @@ -13011,6 +13288,15 @@ static std::vector> make_test_cases_eval() { } // a selection of the indexer of sparse attention, with more ties at the threshold than slots test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {1088, 2048, 1, 1}, 512, true)); + // Qwen QSA pools: 512 of a few thousand pools per token, scores with ties and many -inf (invisible pools) + for (int64_t n_pool : {1500, 4224, 8768, 16960, 32768}) { + for (int64_t nrows : {1, 3, 20}) { + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {n_pool, nrows, 1, 1}, 512)); + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {n_pool, nrows, 1, 1}, 512, true)); + test_cases.emplace_back(new test_top_k_inf({n_pool, nrows, 1, 1}, 512)); + } + } + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {16961, 2, 2, 2}, 512, true)); for (int i = 0; i < 20; ++i) { for (int k : {1, 2, 3, 7, 15, 100, 500, 1023, 9999}) { @@ -13457,6 +13743,18 @@ static std::vector> make_test_cases_eval() { // Qwen QSA: 256/256, gqa 12, budget 2048. test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, 8192, 1, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048)); + // MTP verify and draft blocks + for (int nb : {2, 3, 4, 8}) { + test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, nb == 8 ? 32768 : 16384, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048)); + } + // prompt batches: partial tiles, independent and shared selections + for (int64_t nb : {9, 64, 130, 512}) { + test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, nb == 130 ? 32768 : 16384, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048)); + test_cases.emplace_back(new test_flash_attn_ext_qsa(nb == 130 ? 32768 : 16384, nb, 2048, 150)); + } + test_cases.emplace_back(new test_flash_attn_ext_qsa(16384, 2048, 2048, 150)); + test_cases.emplace_back(new test_flash_attn_ext_qsa(10240, 512, 2048, 400)); + test_cases.emplace_back(new test_flash_attn_ext_qsa(65536, 130, 2048, 500)); // quantized cache, deep enough to take the sparse path test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, 32768, 1, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q8_0, {0, 1, 2, 3}, true, false, 2048)); test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, 32768, 1, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q4_0, GGML_TYPE_Q4_0, {0, 1, 2, 3}, true, false, 2048)); @@ -13599,6 +13897,19 @@ static std::vector> make_test_cases_eval() { true, 16, 8, b, false, true, false)); } + // MoE gate/up + GLU and down shapes of the BF16 WMMA kernels on repacked experts (HIP, GGML_CUDA_MOE_WMMA=2) + for (ggml_type type : {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_XS, GGML_TYPE_IQ2_S}) { + for (int64_t n_tokens : {1, 3, 17, 200, 300}) { + test_cases.emplace_back(new test_mul_mat_fusion(type, GGML_GLU_OP_SWIGLU, n_tokens, 640, 2560, + true, 32, 8, true, false, true, false, {1, 1})); + } + } + for (ggml_type type : {GGML_TYPE_Q5_0, GGML_TYPE_IQ4_NL, GGML_TYPE_Q2_0}) { + for (int64_t n_tokens : {1, 3, 17, 200, 300}) { + test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 32, 8, false, 2560, n_tokens, 640)); + } + } + // Gate and up on the SYCL XMX kernels: rows long enough for 2D block loads, a last tile of 8 rows, and // columns on both sides of the 8 and 16 column tiles for (ggml_type type : {GGML_TYPE_Q2_K, GGML_TYPE_Q3_K, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, @@ -13729,6 +14040,27 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_moe_reduce(2048, 15, 40, false, true)); test_cases.emplace_back(new test_moe_reduce(2048, 16, 32, false, true)); + // Qwen3.8-Flash-Next: 10 experts of 2560 columns at decode, MTP verify and prompt batches (odd counts, unaligned experts) + for (int64_t n_tokens : { 1, 3, 17, 2048, 2051 }) { + test_cases.emplace_back(new test_moe_reduce(2560, 10, n_tokens)); + } + test_cases.emplace_back(new test_moe_reduce(2560, 10, 37, true)); + test_cases.emplace_back(new test_moe_reduce(2560, 10, 37, true, true, true)); + test_cases.emplace_back(new test_moe_reduce_mul_mat_vec(2560, 10, 1)); + // the router of the same model: F32 512x2560 at decode, MTP verify, a small and a full prompt batch + for (int64_t n_tokens : { 1, 3, 17, 130, 2048, 2051 }) { + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 512, n_tokens, 2560, {1, 1}, {1, 1})); + } + // other row counts and depths of F32 prompt products (SSM alpha/beta have 48 rows), batched and permuted ones + for (int64_t m : { 16, 48, 80, 511, 1000, 1024, 1040 }) { + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, m, 130, 2560, {1, 1}, {1, 1})); + } + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 512, 300, 64, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 512, 300, 96, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 512, 130, 2560, {2, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 512, 130, 2560, {1, 1}, {1, 1}, {0, 2, 1, 3})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 512, 130, 2560, {1, 1}, {1, 1}, {0, 1, 2, 3}, 2624)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1, 1, true, true)); @@ -13817,6 +14149,14 @@ static std::vector> make_test_cases_eval() { } } + // Qwen QSA indexer: 4 heads, prompt batches that are not a multiple of the WMMA token tile, kv that is not a multiple of the key tile + for (auto [kv, nb, ns, nm] : {std::tuple{1001, 37, 1, 1}, std::tuple{8768, 130, 1, 1}, std::tuple{300, 16, 1, 1}, + std::tuple{4224, 2051, 1, 1}, std::tuple{515, 17, 3, 3}, std::tuple{515, 64, 3, 1}}) { + for (ggml_type type_K : {GGML_TYPE_F32, GGML_TYPE_F16}) { + test_cases.emplace_back(new test_lightning_indexer(128, 4, kv, nb, ns, nm, type_K)); + } + } + return test_cases; } #ifdef _MSC_VER @@ -13842,6 +14182,12 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_dsv4_hc_pre(4096, 4, n_tokens, true)); // synthetic, no gated model uses this width test_cases.emplace_back(new test_dsv4_hc_pre(2560, 4, n_tokens, true)); // Qwen4-Exp (Qwen3.8-Flash-Next) } + // Qwen3.8-Flash-Next gated residual prefill: one ubatch row of the HC chain + test_cases.emplace_back(new test_dsv4_hc_pre(2560, 4, 2048, true)); + test_cases.emplace_back(new test_hc_inject(2048)); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_F32, 320, 2048, 10240, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 4, 2048, 10240, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_F32, 10240, 2048, 320, {1, 1}, {1, 1})); // DSV4_HC_POST: n_tokens 1 is decode, 128 and 512 are prompt batches for (int64_t n_tokens : {1, 128, 512}) { @@ -13854,6 +14200,16 @@ static std::vector> make_test_cases_perf() { // Qwen3.8-Flash-Next pooled indexer prefill. test_cases.emplace_back(new test_lightning_indexer(128, 4, 1088, 1024, 1, 1, GGML_TYPE_F32)); test_cases.emplace_back(new test_lightning_indexer(128, 4, 1088, 1024, 1, 1, GGML_TYPE_Q4_0)); + // the same at 8K / 32K / 64K context (4 cells per pool), and a 3 token verify batch + for (int kv : {2560, 8768, 16960}) { + test_cases.emplace_back(new test_lightning_indexer(128, 4, kv, 2048, 1, 1, GGML_TYPE_F32)); + } + test_cases.emplace_back(new test_lightning_indexer(128, 4, 8768, 3, 1, 1, GGML_TYPE_F32)); + // Qwen3.8-Flash-Next MoE: the weighted sum of 10 experts and the F32 router + for (int64_t n_tokens : { 1, 3, 512, 2048 }) { + test_cases.emplace_back(new test_moe_reduce(2560, 10, n_tokens)); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 512, n_tokens, 2560, {1, 1}, {1, 1})); + } // SWIGLU at a 27B-class FFN width, fused [gate|up] vs split operands // note: same bytes either way, so a backend that indexes them differently shows it here for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_BF16}) { @@ -13869,6 +14225,12 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {3, channels, 1, 1}, n_tokens, 0, 16)); } } + test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {9, 10240, 1, 1}, 2048, 0, 16)); + // the same conv input fused into the conv, and the unfused conv it replaces + for (int64_t n_tokens : {512, 2048}) { + test_cases.emplace_back(new test_ssm_conv_concat(4, 10240, n_tokens, 1, false, true, false)); + test_cases.emplace_back(new test_ssm_conv_bias_silu(GGML_TYPE_F32, {3 + n_tokens, 10240, 1, 1}, {4, 10240, 1, 1}, false)); + } // CONT of a 0<->2 permute at DeepSeek-V4 lightning-indexer shapes: // indexer_kq is [n_kv, n_tokens, n_head=64] and gets ggml_cont(ggml_permute(.., 2,1,0,3)). @@ -14179,6 +14541,21 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_flash_attn_ext(576, 512, 1, {16, 1}, 49152, 1, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, true, 0)); test_cases.emplace_back(new test_flash_attn_ext(576, 512, 1, {16, 1}, 49152, 1, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, true, 2048)); + // Qwen QSA MTP verify and draft blocks + for (int64_t nb : {3, 8}) { + test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, 32768, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048)); + } + // Qwen QSA prompt batches: independent random selections (the worst case for the union of a query tile) + // and selections from a shared pool of cells, 400-500% is close to the real indexer at 32K-64K + for (int64_t kv : {4096, 6144, 8192, 10240, 12288, 16384, 32768, 65536}) { + for (int64_t nb : {64, 512, 2048}) { + test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048)); + for (int pool_pct : {110, 400, 500}) { + test_cases.emplace_back(new test_flash_attn_ext_qsa(kv, nb, 2048, pool_pct)); + } + } + } + // GQA 6 at long context: decode, verify (4), draft block (8) and a prompt ubatch for (int kv : { 32768, 131072 }) { for (int nb : { 1, 4, 8 }) { @@ -14333,6 +14710,13 @@ static std::vector> make_test_cases_perf() { } } + // Qwen QSA: 512 of the pools of an 8K / 32K / 64K context for a prompt batch, a verify batch and a single token + for (auto cols : {2560, 8768, 16960}) { + for (auto nrows : {1, 3, 2048}) { + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {cols, nrows, 1, 1}, 512)); + } + } + // qwen4exp sparse-attention indexer: nrows = n_tokens/n_stream, so tg gives nrows==1. // Sweep nrows to expose how much of the device a single row leaves idle. for (auto cols : {8192, 32768, 131072}) { diff --git a/tools/cli/README.md b/tools/cli/README.md index 475becd2edfc..5ec9af806c19 100644 --- a/tools/cli/README.md +++ b/tools/cli/README.md @@ -202,6 +202,7 @@ | `--spec-draft-n-max N` | number of tokens to draft for speculative decoding (default: 3)
(env: LLAMA_ARG_SPEC_DRAFT_N_MAX) | | `--spec-draft-n-min N` | minimum number of draft tokens to use for speculative decoding (default: 0)
(env: LLAMA_ARG_SPEC_DRAFT_N_MIN) | | `--spec-draft-n-ubatch N` | physical maximum batch size of the draft context, use a smaller value to spare VRAM (default: 0 - same as --n-ubatch)
(env: LLAMA_ARG_SPEC_DRAFT_N_UBATCH) | +| `--spec-draft-qsa {auto,on,off}` | sparse attention (QSA) of an MTP block whose GGUF stores dense attention (qwen4exp only): auto uses dense attention while the context is short and QSA beyond a model specific length (default: auto)
(env: LLAMA_ARG_SPEC_DRAFT_QSA) | | `--spec-synth-len L` | target mean synthetic acceptance length, including the target token (benchmarking only)
(env: LLAMA_ARG_SPEC_SYNTH_LEN) | | `--spec-synth-rates P0,P1,...` | comma-separated unconditional per-position synthetic acceptance probabilities (benchmarking only)
(env: LLAMA_ARG_SPEC_SYNTH_RATES) | | `--spec-draft-p-split, --draft-p-split P` | speculative decoding split probability (default: 0.10)
(env: LLAMA_ARG_SPEC_DRAFT_P_SPLIT) | diff --git a/tools/server/README.md b/tools/server/README.md index 27d1417518f4..183d231cef2c 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -268,6 +268,7 @@ For the full list of features, please refer to [server's changelog](https://gith | `--spec-draft-n-max N` | number of tokens to draft for speculative decoding (default: 3)
(env: LLAMA_ARG_SPEC_DRAFT_N_MAX) | | `--spec-draft-n-min N` | minimum number of draft tokens to use for speculative decoding (default: 0)
(env: LLAMA_ARG_SPEC_DRAFT_N_MIN) | | `--spec-draft-n-ubatch N` | physical maximum batch size of the draft context, use a smaller value to spare VRAM (default: 0 - same as --n-ubatch)
(env: LLAMA_ARG_SPEC_DRAFT_N_UBATCH) | +| `--spec-draft-qsa {auto,on,off}` | sparse attention (QSA) of an MTP block whose GGUF stores dense attention (qwen4exp only): auto uses dense attention while the context is short and QSA beyond a model specific length (default: auto)
(env: LLAMA_ARG_SPEC_DRAFT_QSA) | | `--spec-synth-len L` | target mean synthetic acceptance length, including the target token (benchmarking only)
(env: LLAMA_ARG_SPEC_SYNTH_LEN) | | `--spec-synth-rates P0,P1,...` | comma-separated unconditional per-position synthetic acceptance probabilities (benchmarking only)
(env: LLAMA_ARG_SPEC_SYNTH_RATES) | | `--spec-draft-p-split, --draft-p-split P` | speculative decoding split probability (default: 0.10)
(env: LLAMA_ARG_SPEC_DRAFT_P_SPLIT) | diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index a6059ab38050..92f5117048a6 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -3940,7 +3940,9 @@ struct server_context_impl { slot.stats.n_draft_tokens += draft.size(); - // TODO: avoid restoring the draft context and re-evaluating the drafted tokens when not needed [TAG_SPEC_AVOID_DRAFT_REEVAL] + // Drop the speculative tail. The committed prefix stays: an MTP verify catch-up is + // fused into draft() and lands at positions below pos_next, after this checkpoint + // was taken. [TAG_SPEC_AVOID_DRAFT_REEVAL] const bool use_ckpt_dft = ctx_dft_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_FULL; if (ctx_dft) { @@ -3948,7 +3950,8 @@ struct server_context_impl { GGML_ASSERT(ckpt.load_dft(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); } - if (!llama_memory_seq_rm(llama_get_memory(ctx_dft), slot.id, ckpt.pos_max + 1, -1)) { + const llama_pos pos_spec = slot.prompt.tokens.pos_next(); + if (!llama_memory_seq_rm(llama_get_memory(ctx_dft), slot.id, pos_spec, -1)) { GGML_ABORT("failed to remove sequence %d\n", slot.id); } } @@ -4773,9 +4776,9 @@ struct server_context_impl { metrics_post_decode(off, batch.view.size(), has_output); } - // 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 + // Stash target h for the draft. A qwen MTP verify batch does not decode here: draft() + // catches up the accepted rows together with the new token. [TAG_SPEC_AVOID_DRAFT_REEVAL] + // ref: https://github.com/ggml-org/llama.cpp/pull/22728#issuecomment-4400925384 if (spec) { bool ok = true; queue_tasks.yield_to_queue([&]() {