From c37f47cc78daacd8ac7c9dbe1e1e4de6e18db5c6 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 09:16:48 -0500 Subject: [PATCH 01/24] libref, libavx: logit_softcap calls std::tanh on a float, not std::tanhf std::tanhf is in only from libstdc++ 14; against 13 (Ubuntu 24.04's) the host build stops at libref and all four libavx levels. std::tanh's float overload is tanhf, so the arithmetic is the same to the bit. Co-Authored-By: Claude Opus 5.5 --- libavx/avx_elementwise.cpp | 4 ++-- libref/ref_elementwise.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libavx/avx_elementwise.cpp b/libavx/avx_elementwise.cpp index a5ef8b97..2d2540c5 100644 --- a/libavx/avx_elementwise.cpp +++ b/libavx/avx_elementwise.cpp @@ -692,7 +692,7 @@ AVX_KERNEL(logit_softcap) { AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN) for (int64_t i = 0; i < nel; ++i) { const float v = ldt(x, offlin(x, i)); - stt(y, offlin(y, i), cap * std::tanhf(v / cap)); + stt(y, offlin(y, i), cap * std::tanh(v / cap)); } return RAD_OK; } @@ -713,7 +713,7 @@ AVX_KERNEL(logit_softcap) { for (; i + VF_N <= m; i += VF_N) vf_storeu(so + i, vf_fma(c2, vf_sigmoid(vf_mul(vf_loadu(v + i), z)), c1)); for (; i < m; ++i) - so[i] = cap * std::tanhf(v[i] / cap); + so[i] = cap * std::tanh(v[i] / cap); out_row(y, off, m, so); } return RAD_OK; diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index 830ace9a..4f3daf9d 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -708,7 +708,7 @@ int ref_logit_softcap(const RadArgs* a, RadStream) { #pragma omp parallel for schedule(static) for (int64_t i = 0; i < nel; ++i) { const float v = ldt(x, offlin(x, i)); - stt(y, offlin(y, i), cap * std::tanhf(v / cap)); + stt(y, offlin(y, i), cap * std::tanh(v / cap)); } return RAD_OK; } From 238159182380abf0455e68e68ac309650bfca723 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 09:17:46 -0500 Subject: [PATCH 02/24] tokenizer: end a Gemma 4 generation on and <|tool_response> Gemma 4 declares as its eos but ends a turn on , and a tool-calling turn on <|tool_response> (the opener of the result the caller supplies, written after the model's last ). Neither was in kEogNames, so every Gemma 4 reply ran to max_tokens. llama.cpp's loader lists both for this vocabulary. A vocabulary that has <|tool_response> as a control token also has as ordinary text (llama.cpp concludes the same); ending on it would cut a reply that writes the HTML tag, so is not an end-of-generation token there. This branch already ends a generation on every id generation_config.json names (c65fabe), which covers both tokens for a container that carries `generation.eos_token_id`. The spellings here cover one that does not, and the rule is new either way: the eos list never names for Gemma 4, but kEogNames did. Co-Authored-By: Claude Opus 5.5 --- core/text/tokenizer.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index 300b4ae1..91bf6137 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -603,16 +603,27 @@ int Vocab::load(VocabBuild b) { if (b_.eos >= 0) eog_.push_back(b_.eos); if (b_.eot >= 0 && b_.eot != b_.eos) eog_.push_back(b_.eot); { + /* Gemma 4 ends a turn on `` and a tool-calling turn on `<|tool_response>` -- the + * opener of the result the CALLER supplies, which the model writes after its last + * `` -- and declares neither: its eos is ``. llama.cpp's loader lists + * both for it, and both are control tokens nothing else spells. */ static const char* const kEogNames[] = { "<|endoftext|>", "<|im_end|>", "<|eot_id|>", "<|end_of_text|>", "", "<|end|>", "<|EOT|>", "<|eom_id|>", "<|return|>", "", "", + "", "<|tool_response>", }; + /* A vocabulary with `<|tool_response>` (Gemma 4) has `` as ordinary text, as + * llama.cpp also concludes; ending on it would end a reply that writes the HTML tag. */ + bool gemma4 = false; + for (int32_t id : special_) + if (b_.types[id] == RAD_TT_CONTROL && b_.tokens[id] == "<|tool_response>") gemma4 = true; std::string added; for (int32_t id : special_) { if (b_.types[id] != RAD_TT_CONTROL) continue; if (std::find(eog_.begin(), eog_.end(), id) != eog_.end()) continue; bool known = false; for (const char* n : kEogNames) if (b_.tokens[id] == n) { known = true; break; } + if (gemma4 && b_.tokens[id] == "") known = false; if (!known) continue; eog_.push_back(id); added += (added.empty() ? "" : " ") + b_.tokens[id] + "=" + std::to_string(id); From fb716830c2a0c958d12d35b64eb51520209e0479 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 09:17:46 -0500 Subject: [PATCH 03/24] oai: preserved_tokens on /v1/completions; find a text-tailed reasoning opener by its token /v1/completions accepts llama-server's preserved_tokens: control tokens the completion's text keeps rather than drops. A client that renders its own template and parses its own reply (a tool-call sidecar) has no other way to see a reply format built of control tokens. Bounded like the stop strings. A thinking budget needs the reasoning block found by token. Gemma 4's opener <|channel>thought is one control token followed by text; it is now found by that first token (what a reply opening its own block writes first, and no text can spell), with the text after it counted as reasoning. An opener with a second control token in it is still refused, since its first token may open something other than the reasoning. The refusal message says why. Co-Authored-By: Claude Opus 5.5 --- core/server/oai.cpp | 46 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 9277042e..1ea83487 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -245,7 +245,11 @@ const char* kAcceptedChat[] = { "functions", "function_call", }; -const char* kAcceptedCompletion[] = { "prompt", "echo" }; +/* `preserved_tokens` is llama-server's: control tokens a raw completion's text keeps. On chat the + * reply format decides them (the guarded entry below); a raw completion has no format, and a + * client that renders its own template and parses its own reply -- a tool-call sidecar -- has no + * other way to see a format built of control tokens. */ +const char* kAcceptedCompletion[] = { "prompt", "echo", "preserved_tokens" }; const char* kAcceptedEmbedding[] = { "model", "input", "messages", "encoding_format", "dimensions", "image_tokens", "prompt_name" }; @@ -1613,9 +1617,18 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit if (!render.think_open.empty()) o = d.tok->encode(render.think_open, false, true); n_close = c.size(); n_open = o.size(); - if (c.size() == 1 && (render.think_starts_open || o.size() == 1)) { + /* AN OPENER THAT IS ONE CONTROL TOKEN AND THEN TEXT -- Gemma 4's `<|channel>thought` -- + * is found by that first token: it is what a reply opening its own block writes first, + * and no text can be. The text after it counts as reasoning, as the markers do. An opener + * with a second control token in it (a channel and a message marker) is not read this + * way, since its first token may open something other than the reasoning. */ + bool open_first = o.size() > 1 && d.tok->reply_bytes(o[0]).empty() && + !d.tok->token_bytes(o[0]).empty(); + for (size_t i = 1; open_first && i < o.size(); ++i) + if (d.tok->reply_bytes(o[i]).empty()) open_first = false; + if (c.size() == 1 && (render.think_starts_open || o.size() == 1 || open_first)) { span.close = c[0]; - span.open = o.size() == 1 ? o[0] : -1; + span.open = (o.size() == 1 || open_first) ? o[0] : -1; span.starts_open = render.think_starts_open; } } @@ -1654,8 +1667,8 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit "as one token"; else why = "this reply has to open its own reasoning block, and the opener `" + - render.think_open + "` is " + std::to_string(n_open) + " tokens, so the block " - "cannot be found by token"; + render.think_open + "` is " + std::to_string(n_open) + " tokens and does not " + "start with a lone control token, so the block cannot be found by token"; *err = err_unsupported(named, why); return RAD_E_UNSUPPORTED; } @@ -2135,6 +2148,29 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa if (!get_bool(b, "echo", &out->echo, err)) return RAD_E_INVAL; + /* The control tokens this completion's text keeps (llama-server's field): each string is + * tokenised by the decoder and every control token in it is rendered rather than dropped. + * Bounded as the stop strings are, since the decoder looks each one up per token. */ + { + auto pt = b.find("preserved_tokens"); + if (pt != b.end() && !pt->is_null()) { + if (!pt->is_array() || pt->size() > (size_t)lim.max_stops) { + *err = err_bad("preserved_tokens", "expected an array of at most " + + std::to_string(lim.max_stops) + " strings"); + return RAD_E_INVAL; + } + for (const auto& s : *pt) { + if (!s.is_string() || s.get().size() > (size_t)lim.max_stop_bytes) { + *err = err_bad("preserved_tokens", "expected strings of at most " + + std::to_string(lim.max_stop_bytes) + + " bytes"); + return RAD_E_INVAL; + } + out->preserved_tokens.push_back(s.get()); + } + } + } + RAD_TRY(parse_logprobs(b, lim, Endpoint::Completion, out, err)); /* `echo` with logprobs asks for the PROMPT's logprobs too, which are not computed: a prompt * position's distribution never leaves the card. */ From 29bfe8f00c731a73a2a7a136e89e427a25eac2e0 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 09:17:46 -0500 Subject: [PATCH 04/24] sched: --draft-window adaptive applies to block drafters The adaptive window priced only a serial head's rounds and was refused for a block drafter, on the grounds that the block is proposed in one pass. But every verified draft is still a verify row, and on a MoE whose verify reads the experts each row routes to, rows are not free (16 rows read ~10x the experts one does). A block drafter now takes the same policy with its rounds fixed: each sequence verifies the first min(D, its stop) of the block, its stop from its own measured acceptance and D from the measured step times. Prompt lookup alone keeps the fixed window and says so. Speculation stays lossless: what is verified is a prefix of the proposal. Measured on gemma-4-26B-A4B-it + z-lab DFlash (block 15), 4x R9700, TP4, together with gemma4k's split-KV merge rewrite (landed in the same build, so the two are not separated): story at T=1 95 -> 177 tok/s, greedy thinking ~360 -> 572 tok/s; code at T=0 319-334 tok/s (it verifies deep either way). tests/sched_test.cpp: the block-drafter case now expects the policy on (4 drafts verified while the estimate is the prior, 1 after 64 rejected steps, draft_verify_depth[4] and [1] both counted); the prompt-lookup-only and no-speculation cases are unchanged. Co-Authored-By: Claude Opus 5.5 --- core/sched/scheduler.cpp | 35 +++++++++++++++++----------- tests/sched_test.cpp | 50 ++++++++++++++++++++++++++++++++-------- 2 files changed, 63 insertions(+), 22 deletions(-) diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index f719011a..11d1f8c5 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -112,25 +112,34 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac DraftController::Params dp; dp.max_depth = cfg.n_spec; - /* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more - * round of the head. A block drafter proposes its block in one pass and prompt lookup runs no - * pass at all, so for either the window stays fixed -- decided here, once, before any step - * has counted an acceptance, and said, because a flag that changes nothing reads exactly - * like a flag that made no difference. */ + /* THE ADAPTIVE WINDOW (draft.h) prices a draft by what the step it adds to costs, measured. + * For a serial head that is a round of the head and a verify row. For a BLOCK drafter the + * block is proposed in one pass whatever is verified, but each verified draft is still a + * verify row -- and on a model whose verify streams weights per row, a MoE that reads the + * experts every row routes to, a row is not free: sixteen rows read ten times the experts one + * does. So a block drafter takes the same policy with its rounds fixed: each sequence verifies + * the first min(D, its stop) of the block, its stop from its own measured acceptance, and D + * from the measured step times. Deep where the text is predictable (code, JSON, greedy), a few + * drafts where it is not (prose at temperature 1, where a point-mass draft survives a position + * with probability p(x) and a fifteen-token chain dies after one or two). Prompt lookup runs + * no pass and keeps the fixed window, decided here, once, and said, because a flag that + * changes nothing reads exactly like a flag that made no difference. */ if (cfg.draft_window == DraftWindow::Adaptive) { const RadDrafterDecl& dd = prog.drafter; if (cfg.n_spec <= 0) RAD_WARN("--draft-window adaptive: this deployment does not speculate " "(--num-speculative-tokens %d), so there is no window to adapt", cfg.n_spec); - else if (dd.kind != RAD_DRAFT_SERIAL || dd.depth <= 0) - RAD_WARN("--draft-window adaptive: the window is fixed at %d with %s -- the adaptive " - "window prices the rounds of a serial draft head, which this deployment does " - "not run", cfg.n_spec, - dd.kind == RAD_DRAFT_BLOCK ? "a block drafter, which proposes its block in one " - "pass" - : "prompt lookup only"); - else + else if ((dd.kind != RAD_DRAFT_SERIAL && dd.kind != RAD_DRAFT_BLOCK) || dd.depth <= 0) + RAD_WARN("--draft-window adaptive: the window is fixed at %d with prompt lookup only " + "-- the adaptive window prices draft passes and verify rows, and prompt " + "lookup runs no pass", cfg.n_spec); + else { dp.adapt = true; + if (dd.kind == RAD_DRAFT_BLOCK) + RAD_INFO("--draft-window adaptive with a block drafter: the block of %d is " + "proposed whole, and each sequence verifies the first min(D, its stop) " + "of it", dd.depth); + } } RAD_TRY(draft_.configure(dp)); draft_est_.clear(); diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 71abc150..b0b966f6 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -2170,10 +2170,10 @@ TEST(the_adaptive_window_chooses_the_head_depth_over_the_whole_batch) { CHECK_EQ(h.plan_step(hone, 0, 3), 2); } -/* THE FLAG, AND ONLY FOR A SERIAL HEAD. --draft-window adaptive with a block drafter, with prompt - * lookup alone, or with no speculation keeps the configured depth and says so at startup; the - * proposal then reaches the step uncut. The default is the fixed window. */ -TEST(the_adaptive_window_is_a_flag_for_a_serial_drafter_and_said_when_it_is_not) { +/* THE FLAG, FOR A DRAFTING HEAD -- SERIAL OR BLOCK. --draft-window adaptive with prompt lookup + * alone, or with no speculation, keeps the configured depth and says so at startup; the proposal + * then reaches the step uncut. The default is the fixed window. */ +TEST(the_adaptive_window_is_a_flag_for_a_drafting_head_and_said_when_there_is_none) { { Fixture f; adaptive_fixture(f, 4); @@ -2192,18 +2192,50 @@ TEST(the_adaptive_window_is_a_flag_for_a_serial_drafter_and_said_when_it_is_not) Config d; CHECK(d.draft_window == kDraftWindowDefault); /* the default */ } - for (int kind : { (int)RAD_DRAFT_BLOCK, (int)RAD_DRAFT_NONE }) { + /* A BLOCK DRAFTER TAKES THE POLICY WITH ITS ROUNDS FIXED. It proposes its whole block in one + * pass, and each sequence verifies the first of it up to its own window: the whole block while + * its estimate is the prior, one draft once its drafts stop being taken. Startup says so. */ + { Fixture f; adaptive_fixture(f, 4); - f.prog.drafter.kind = (decltype(f.prog.drafter.kind))kind; - if (kind == RAD_DRAFT_NONE) f.prog.drafter.depth = 0; + f.prog.drafter.kind = RAD_DRAFT_BLOCK; + int st = RAD_E_STATE; + const std::string log = stderr_of([&] { st = f.start(); }); + CHECK_OK(st); + CHECK(f.sch.draft().adaptive()); + CHECK(log.find("ADAPTIVE") != std::string::npos); + CHECK(log.find("with a block drafter") != std::string::npos); + CHECK(log.find("the window is fixed") == std::string::npos); + + const uint64_t a = f.submit(160, 2000); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + int32_t draft[4] = { 21, 22, 23, 24 }; + CHECK_OK(f.sch.set_draft(a, draft, 4)); + CHECK_EQ(f.sch.find(a)->n_draft, 4); + for (int t = 0; t < 64; ++t) { /* no draft is ever taken */ + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(9); + CHECK_OK(f.sch.set_draft(a, draft, 4)); + } + CHECK_EQ(f.sch.find(a)->n_draft, 1); + REQUIRE(f.sch.step() != nullptr); + for (const StepEntry& e : f.sch.plan().e) CHECK_EQ(e.n_spec, 1); + CHECK(f.sch.metrics().draft_adaptive); + CHECK(f.sch.metrics().draft_verify_depth[4] > 0); + CHECK(f.sch.metrics().draft_verify_depth[1] > 0); + } + { + Fixture f; + adaptive_fixture(f, 4); + f.prog.drafter.kind = RAD_DRAFT_NONE; + f.prog.drafter.depth = 0; int st = RAD_E_STATE; const std::string log = stderr_of([&] { st = f.start(); }); CHECK_OK(st); CHECK(!f.sch.draft().adaptive()); CHECK(log.find("--draft-window adaptive: the window is fixed at 4") != std::string::npos); - CHECK(log.find(kind == RAD_DRAFT_BLOCK ? "a block drafter" : "prompt lookup only") != - std::string::npos); + CHECK(log.find("prompt lookup only") != std::string::npos); const uint64_t a = f.submit(160, 64); CHECK(f.sch.step() != nullptr); From d0f6f332ff62fa72fda549ec127e889ea2f610fc Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 09:57:17 -0500 Subject: [PATCH 05/24] ops: pair_argmax in libref and libavx -- the sharded draft head's top-1, one id a row A vocab-sharded draft head proposes each position's argmax: every rank takes its slice's top-R as (id, value) pairs, an all_gather puts them side by side, and something picks the winner. row_topk_merge does that with an R-wide answer; a block drafter wants ONE id a row, written contiguously into the token buffer it verifies, and a rank cannot send R = 1 -- a row-interleaved all_gather moves whole 16-byte words and a pair is 8 bytes. pair_argmax is the merge at R = 1 over world_size * R pairs: largest value, ties to the lower id, a negative id a pad, -1 and -inf for a row with nothing valid, `val` optional. The Gemma 4 DFlash head is its caller (arch/gemma4, later in this series) and gemma4k its device kernel. libref is the oracle and the schema's first declarer; libavx carries the host row, because an op the placement puts on the host cannot run on a reference (avx_check holds libavx to libref's vocabulary). Both scalar: n is sixteen pairs at TP8. docs/OPS.md: the row and a paragraph beside row_topk_merge's. ref_test: ties to the lower id in any slot, a pad carrying the row's largest value dropped, an all-pad row, all-negative values, `idx` at a pitch of two with the slots between untouched, and `val` absent. Co-Authored-By: Claude Opus 5.5 --- docs/OPS.md | 9 +++++++++ libavx/avx_cases.cpp | 1 + libavx/avx_isa.h | 2 +- libavx/avx_moe.cpp | 34 ++++++++++++++++++++++++++++++++++ libavx/avx_registry.cpp | 7 +++++++ libref/ref_moe.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ libref/ref_ops.h | 2 ++ libref/ref_registry.cpp | 8 ++++++++ libref/ref_shapes.cpp | 13 +++++++++++++ tests/ref_test.cpp | 39 ++++++++++++++++++++++++++++++++++++++- 10 files changed, 154 insertions(+), 2 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index e923f0af..dcbefa00 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -595,6 +595,7 @@ and adding 0.0f is exact, so a block sum over 8 wave partials and over 32 are th | `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` | | `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? | | `row_topk_merge` | `M` `R` `world_size` `dtype` | `gathered` → `idx`, `val` | +| `pair_argmax` | `M`(range) `n` `dtype` | `pairs` → `idx`, `val`? | | `logit_rerank` | `M`(range) `R` `n_vocab` `n_embd` `vocab_off`/opt `dtype` | `x`, `head`w, `idx_in` → `idx`, `val`, `pairs`? | `row_topk` and `row_topk_merge` are a pair, and the second only means anything with the first's @@ -610,6 +611,14 @@ over the unsharded plane element for element. A slot a shard could not fill carr `pairs` and is dropped -- a sentinel rather than a -inf value, because a masked logit takes that value legitimately. +`pair_argmax` is the merge at R = 1, for a vocab-sharded draft head that wants each position's +winner as a proposal: `idx` gets the id of the largest value among a row's `n` gathered pairs, +ties to the lower id, a negative id skipped, -1 (and -inf in `val`) when nothing is valid -- +written one element a row at the output's own pitch, which is what a block drafter's contiguous +proposal needs. It is not `row_topk_merge` with R = 1 because a rank still sends R >= 2 pairs: a +row-interleaved `all_gather` moves whole 16-byte words and one pair is 8 bytes, so `n` is +`world_size * R` and the op takes the top-1 of all of them. + `logit_rerank` is the second half of a COARSE top-R. A speculative step can afford a cheap draft head -- the target verifies every proposal, so a worse draft costs acceptance and never a token -- but a head quantised hard enough to be cheap also picks a different top-1 often enough to matter. diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index e35bd33f..ffc36152 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -344,6 +344,7 @@ std::vector build_cases() { add("row_topk", { HI("M", 5), HI("N", 97), HI("R", 4), HI("vocab_off", 0), HS("dtype", dt) }); add("row_topk_merge", { HI("M", 5), HI("R", 4), HI("world_size", 2), HS("dtype", dt) }); + add("pair_argmax", { HI("M", 5), HI("n", 8), HS("dtype", dt) }); /* "sorted" and not "slot": libref refuses any other spelling with RAD_E_UNSUPPORTED, and a case at a spelling both plugins decline is a case that proves nothing. */ for (const char* order : { "token", "sorted" }) { diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index a04ac88e..74ec5f7f 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -107,7 +107,7 @@ int avx_isa_force(int level); /* ---- mixture of experts */ \ X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \ X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \ - X(moe_gemm_q_mod4) \ + X(moe_gemm_q_mod4) X(pair_argmax) \ /* ---- gated delta net */ \ X(gdn_conv_prep) X(gdn_conv_update) X(gdn_kkt_solve) X(gdn_chunk_scan) \ X(gdn_recurrent_update) X(gdn_conv_recurrent_update) X(gdn_gated_rmsnorm) \ diff --git a/libavx/avx_moe.cpp b/libavx/avx_moe.cpp index aad45cbc..bbbe0c38 100644 --- a/libavx/avx_moe.cpp +++ b/libavx/avx_moe.cpp @@ -740,3 +740,37 @@ AVX_KERNEL(row_topk_merge) { } return RAD_OK; } + +/* ------------------------------------------------------------------ pair_argmax */ +/* row_topk_merge at R = 1, one id a row at the output's own pitch: the vocab-sharded draft head's + * proposal. Same pads, same tie rule, -1 and -inf for a row with nothing valid; `val` optional. + * + * LEFT SCALAR for the merge's reason, more so: `n` is world_size * R -- sixteen pairs at TP8 and + * R 2 -- and the whole op is one pass over them a row. */ +AVX_KERNEL(pair_argmax) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *p = &a->t[0], *idx = &a->t[1]; + const RadTensor* val = rad_arg_in(a, 2); + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + if (p->dtype != RAD_F32) return RAD_E_DTYPE; /* the id is carried by bit pattern */ + const int64_t M = numel(p) / (n * 2); + if (M <= 0 || numel(idx) < M || (val && numel(val) < M)) return RAD_E_SHAPE; + const float* const pf = (const float*)p->data; + + AVX_PARALLEL_FOR_IF(M * n >= 4096) + for (int64_t m = 0; m < M; ++m) { + int32_t bid = -1; + float bv = -INFINITY; + for (int64_t j = 0; j < n; ++j) { + int32_t id; + std::memcpy(&id, pf + offlin(p, (m * n + j) * 2), sizeof id); + if (id < 0) continue; /* a pad, not a candidate */ + const float v = pf[offlin(p, (m * n + j) * 2 + 1)]; + if (bid < 0 || v > bv || (v == bv && id < bid)) { bid = id; bv = v; } + } + st_int_dt(idx->dtype, idx->data, offlin(idx, m), bid); + if (val) stt(val, offlin(val, m), bv); + } + return RAD_OK; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 5d186896..443c6b97 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -348,6 +348,8 @@ static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"), P_STR("dtype") }; static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT("val") }; +static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("val") }; /* Mirrors libref's row exactly: R candidates rescored against the full-precision head, ties to the * lower id, pads sort last. libref's shape hook declines to describe this op, so the checker skips @@ -610,6 +612,8 @@ static const RadOpSchema kSchemas[] = { { "row_topk", ARR(pRowTopk), ARR(oRowTopk), "exact per-row top-R." }, { "row_topk_merge", ARR(pRowTopkMerge), ARR(oRowTopkMerge), "the global top-R of the gathered per-rank candidate sets." }, +{ "pair_argmax", ARR(pPairArgmax), ARR(oPairArgmax), + "the global top-1 of a row of gathered (id, value) pairs, one id a row." }, { "logit_rerank", ARR(pLogitRerank), ARR(oLogitRerank), "R candidates a row rescored exactly against the full-precision head." }, { "gdn_conv_prep", ARR(pConvPrep), ARR(oConvPrep), @@ -832,6 +836,9 @@ SIMPLE("avx_moe_gather", "moe_gather", "moe", "weighted scatter back to token or SIMPLE("avx_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, L(row_topk)), SIMPLE("avx_row_topk_merge", "row_topk_merge", "moe", "the global top-R of the gathered per-rank candidate sets", DT_FLOAT, L(row_topk_merge)), +SIMPLE("avx_pair_argmax", "pair_argmax", "moe", + "the global top-1 of a row of gathered (id, value) pairs, one id a row", DT_FLOAT, + L(pair_argmax)), SIMPLE("avx_logit_rerank", "logit_rerank", "moe", "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, L(logit_rerank)), diff --git a/libref/ref_moe.cpp b/libref/ref_moe.cpp index c130799f..18af48d2 100644 --- a/libref/ref_moe.cpp +++ b/libref/ref_moe.cpp @@ -488,6 +488,47 @@ int ref_row_topk_merge(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ pair_argmax */ +/* row_topk_merge at R = 1, for a caller that wants the winner's id as a PROPOSAL rather than as + * a candidate list: one element a row, at the output's own pitch, so a block drafter's per-position + * picks land contiguous in the token buffer it verifies. `pairs` is the same gathered plane -- + * `n` (int32 id, f32 value) pairs a row, a negative id a pad -- and the rule is the same: the + * largest value, ties to the LOWER id, so the pick equals an argmax over the unsharded row. + * + * Its own op rather than row_topk_merge with R = 1 because the shapes differ where it matters: + * row_topk_merge's `gathered` is world_size * R pairs a row, and a rank that sends R = 1 sends 8 + * bytes, which a row-interleaved all_gather moving whole 16-byte words cannot carry. So a rank + * sends R >= 2 and this takes the top-1 of all of them, whatever `n` that makes. A row with no + * valid pair writes -1 and -inf, as the merge does for a slot it cannot fill. `val` is optional. */ +int ref_pair_argmax(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *p = &a->t[0], *idx = &a->t[1]; + const RadTensor* val = t_in(a, 2); + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + if (p->dtype != RAD_F32) return RAD_E_DTYPE; /* the id is carried by bit pattern */ + /* The rows are the operand's, as on row_topk_merge: `M` is a band ceiling. */ + const int64_t M = numel(p) / (n * 2); + if (M <= 0 || numel(idx) < M || (val && numel(val) < M)) return RAD_E_SHAPE; + const float* const pf = (const float*)p->data; + + #pragma omp parallel for schedule(static) + for (int64_t m = 0; m < M; ++m) { + int32_t bid = -1; + float bv = -INFINITY; + for (int64_t j = 0; j < n; ++j) { + int32_t id; + std::memcpy(&id, pf + offlin(p, (m * n + j) * 2), sizeof id); + if (id < 0) continue; /* a pad, not a candidate */ + const float v = pf[offlin(p, (m * n + j) * 2 + 1)]; + if (bid < 0 || v > bv || (v == bv && id < bid)) { bid = id; bv = v; } + } + st_int(idx->dtype, idx->data, offlin(idx, m), bid); + if (val) stt(val, offlin(val, m), bv); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ logit_rerank */ /* EXACTLY RESCORE R CANDIDATES A ROW AGAINST THE FULL-PRECISION HEAD. * diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 083482bf..4df8f840 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -141,6 +141,7 @@ int ref_scale_rows (const RadArgs*, RadStream); int ref_moe_gather (const RadArgs*, RadStream); int ref_row_topk (const RadArgs*, RadStream); int ref_row_topk_merge (const RadArgs*, RadStream); +int ref_pair_argmax (const RadArgs*, RadStream); int ref_logit_rerank (const RadArgs*, RadStream); /* ---- gated delta net */ @@ -270,6 +271,7 @@ REF_SHAPE_FN(ref_scale_rows); REF_SHAPE_FN(ref_moe_gather); REF_SHAPE_FN(ref_row_topk); REF_SHAPE_FN(ref_row_topk_merge); +REF_SHAPE_FN(ref_pair_argmax); REF_SHAPE_FN(ref_logit_rerank); REF_SHAPE_FN(ref_gdn_conv_prep); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 470a8e88..b75ad818 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -444,6 +444,8 @@ static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"), P_STR("dtype") }; static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT("val") }; +static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("val") }; static const RadParamSpec pLogitRerank[] = { P_INT("M"), P_INT("R"), P_INT("n_vocab"), P_INT("n_embd"), P_INTO("vocab_off"), P_STR("dtype") }; @@ -935,6 +937,11 @@ static const RadOpSchema kSchemas[] = { "(idx, val) form the single-rank top-R produces. `gathered` is [M, world_size * R, 2] pairs, " "rank r's at [r*R, (r+1)*R); id -1 is a pad and is dropped. Ties break on the LOWER id, which is " "what makes the merged answer agree with a top-R over the unsharded plane." }, +{ "pair_argmax", ARR(pPairArgmax), ARR(oPairArgmax), + "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in the first " + "f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties to the lower " + "id, a negative id skipped, -1 and -inf where nothing is valid. row_topk_merge at R = 1, " + "written one element a row at the output's own pitch." }, { "logit_rerank", ARR(pLogitRerank), ARR(oLogitRerank), "Rescore R candidate ids a row EXACTLY against the full-precision head and re-sort on those " @@ -1244,6 +1251,7 @@ SIMPLE("ref_qsa_block_key", "qsa_block_key", "attn", ref_qsa_block_key), SIMPLE("ref_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, ref_row_topk), SIMPLE("ref_row_topk_merge", "row_topk_merge", "moe", "the global top-R of the gathered per-rank candidate sets", DT_FLOAT, ref_row_topk_merge), +SIMPLE("ref_pair_argmax", "pair_argmax", "moe", "the global top-1 of a row of gathered (id, value) pairs, one id a row", DT_FLOAT, ref_pair_argmax), SIMPLE("ref_logit_rerank", "logit_rerank", "moe", "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, ref_logit_rerank), SIMPLE("ref_gdn_conv_prep", "gdn_conv_prep", "gdn", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 44456a1e..b3535f7f 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1476,6 +1476,19 @@ int ref_row_topk_merge_shape(const RadParam* p, int n_p, int operand, RadOpdDesc return o.finish("row_topk_merge", operand, out); } +/* The same plane at R = 1 a row, and fillable for the same reason the merge's is: the value lane + * draws proper floats and the id lane their bit patterns, so pads are dropped, ids compared and + * copied, and ties do not occur. */ +int ref_pair_argmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t((uint32_t)RAD_F32, { M, n, 2 }); /* pairs */ + o.t((uint32_t)RAD_I32, { M }); /* idx */ + o.t((uint32_t)RAD_F32, { M }); /* val */ + return o.finish("pair_argmax", operand, out); +} + /* logit_rerank DESCRIBES ITSELF, AND THE READER THAT NEEDS IT INVERTS FIRST. diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index d6d60278..a2975f8e 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -273,7 +273,7 @@ TEST(op_vocabulary) { "attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key", "router_topk", "moe_scatter", "moe_gemm", "moe_gemm_q", "moe_gemm_q_mod4", "moe_gather", "row_topk", - "row_topk_merge", "logit_rerank", + "row_topk_merge", "pair_argmax", "logit_rerank", "gdn_conv_prep", "gdn_conv_update", "gdn_kkt_solve", "gdn_chunk_scan", "gdn_recurrent_update", "gdn_conv_recurrent_update", "gdn_gated_rmsnorm", "all_reduce", "all_gather", @@ -604,6 +604,43 @@ TEST(op_scale) { CHECK(run("scale", b) != RAD_OK); } +/* The sharded draft head's merge at R = 1, on paper: three rows of four gathered pairs, each case + * one rule. Row 0 ties on 2.0 between ids 9 and 3 (the lower id wins, whatever slot it sits in) + * beside a pad carrying the row's largest value (dropped: a pad is a negative id, not a value); + * row 1 is all pads (-1 and -inf, nothing invented); row 2 is all negative values (the largest is + * still the answer). `idx` is written at a pitch of two, as a proposal lands in a token buffer laid + * out for something else, and the slots between are left alone. */ +TEST(op_pair_argmax) { + struct P { int32_t id; float v; }; + const P rows[3][4] = { + { { 5, 1.0f }, { 9, 2.0f }, { 3, 2.0f }, { -1, 7.0f } }, + { { -1, 9.0f }, { -1, 9.0f }, { -1, 9.0f }, { -1, 9.0f } }, + { { 7, -3.0f }, { 2, -4.0f }, { 11, -1.0f }, { 4, -1.5f } }, + }; + T pairs(RAD_F32, {3, 4, 2}); + float* pf = (float*)pairs.t.data; + for (int m = 0; m < 3; ++m) + for (int j = 0; j < 4; ++j) { + std::memcpy(&pf[(m * 4 + j) * 2], &rows[m][j].id, 4); + pf[(m * 4 + j) * 2 + 1] = rows[m][j].v; + } + T idx(RAD_I32, {3, 2}); idx.n({ 100, 100, 100, 100, 100, 100 }); + idx.t.shape[1] = 1; /* [3, 1] at a row pitch of 2 */ + T val(RAD_F32, {3}); + A a; a.t(pairs).t(idx).t(val).i("M", 3).i("n", 4).s("dtype", "f32"); + CHECK_OK(run("pair_argmax", a)); + CHECK_EQ(idx.iat(0), 3); CHECK_EQ(val.at(0), 2.0f); + CHECK_EQ(idx.iat(2), -1); CHECK(std::isinf(val.at(1)) && val.at(1) < 0); + CHECK_EQ(idx.iat(4), 11); CHECK_EQ(val.at(2), -1.0f); + CHECK_EQ(idx.iat(1), 100); CHECK_EQ(idx.iat(3), 100); + + /* `val` is optional, and the ids do not depend on it. */ + T idx2(RAD_I32, {3}); + A b; b.t(pairs).t(idx2).tnull().i("M", 3).i("n", 4).s("dtype", "f32"); + CHECK_OK(run("pair_argmax", b)); + CHECK_EQ(idx2.iat(0), 3); CHECK_EQ(idx2.iat(1), -1); CHECK_EQ(idx2.iat(2), 11); +} + /* The quantised gather. Three things, and the scale is the least interesting of them. * * The E4M3 codes are chosen so their VALUES are exact and writable as literals: 0x38 is 1.0, From 833173cc049a48d7311ffbde2670069a5a79ba0a Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 09:58:28 -0500 Subject: [PATCH 06/24] gemma4k: Gemma 4's kernels beyond libr4d -- paged attention, pair_argmax, the sandwich joins A kernel library beside libr4d, gfx12 only, and AHEAD of it for Gemma 4: `--kernels gemma4k,libr4d,...`. Its own library rather than rows in libr4d: a smaller change, its own gfx12 gating, and no churn in libr4d's row table; folding it in can follow. - attn_paged at head_dim 256 and 512, gqa 1/2/4/8, bf16 or fp8 cache, any window, causal or not. One scalar kernel serves decode, verify and prefill, with a split-KV path whose merge is one wave a row (live pieces found by ballot, four at a time; a piece that saw no key writes only its max and sum); a WMMA prefill kernel takes a query of at least 64 rows and 32 a sequence on average -- Q and K bf16, P and V f16 (bf16 P measured 0.25% of the V range in error), the denominator summed from the rounded P. RADIANCE_G4K_WMMA=0 keeps every launch on the scalar kernel. - pair_argmax, device and host, described as libref describes it so rad-kbench checks both. - norm_add_norm and join_add_scale, ops of its own (docs/OPS.md, a new subsection): each one kernel for a post-norm / residual add / pre-norm chain, rounding where the chain rounds. libref has no row for them on purpose -- a reference row would resolve them where gemma4k is not loaded and the architecture would never fall back to the chain -- and no row declares `replaces`, since rad-kbench assembles a replaced chain from the fusing library's own rows. WHY FIRST. libr4d on this tree also has rows at h256/gqa2 and h512/gqa8, Gemma 4's own geometries, written for the dense 31B (which has no drafter) and not measured on the 26B-A4B or under a DFlash verify; the hierarchy is absolute, so the first library takes them. These rows are the ones every Gemma 4 number below was measured with. No other row overlaps libr4d's (the h256 gqa4/gqa8 rows take a window only), so putting this library first takes nothing else from it. The softcap is libr4d's and libavx's `logit_softcap`. Measured on 4x R9700, gemma-4-26B-A4B-it + z-lab DFlash, TP4: decode attention 3.234 -> 0.104 ms a step on the full layers and 1.906 -> 0.722 on the sliding ones (the split-KV merge); a 20,489-token prefill 4.01 -> 2.83 s (the WMMA kernel); rad-kbench against libref 176/176. Not yet run on the cards: the joins. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 6 + docs/OPS.md | 25 + gemma4k/CMakeLists.txt | 34 ++ gemma4k/g4k.h | 38 ++ gemma4k/g4k_attn.hip | 1146 ++++++++++++++++++++++++++++++++++++++++ gemma4k/g4k_launch.h | 14 + gemma4k/g4k_norm.hip | 252 +++++++++ gemma4k/g4k_pick.hip | 105 ++++ gemma4k/g4k_rows.cpp | 436 +++++++++++++++ tests/CMakeLists.txt | 5 + 10 files changed, 2061 insertions(+) create mode 100644 gemma4k/CMakeLists.txt create mode 100644 gemma4k/g4k.h create mode 100644 gemma4k/g4k_attn.hip create mode 100644 gemma4k/g4k_launch.h create mode 100644 gemma4k/g4k_norm.hip create mode 100644 gemma4k/g4k_pick.hip create mode 100644 gemma4k/g4k_rows.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0d4b60dd..d188d488 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -358,6 +358,12 @@ add_subdirectory(libquant) if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt) add_subdirectory(libr4d) endif() +# gemma4k: Gemma 4's kernels beyond libr4d -- paged attention at head_dim 256/512, pair_argmax, +# and the two sandwich-norm joins (docs/OPS.md). gfx12 only, and ahead of libr4d for Gemma 4: +# `--kernels gemma4k,libr4d,...` (gemma4k/g4k_rows.cpp says why). +if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/gemma4k/CMakeLists.txt) + add_subdirectory(gemma4k) +endif() # libavx: the conventional op vocabulary in hand-written x86 SIMD, runtime-dispatched by CPU # feature -- the production HOST kernels, built wherever libref is, on x86-64. An op the placement # puts on the host needs a host kernel that is not the oracle (rad_gate_reference_kernels refuses diff --git a/docs/OPS.md b/docs/OPS.md index dcbefa00..cbb4451d 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -294,6 +294,31 @@ rounding. -log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's torch expressions are, then rounded. +### The sandwich-norm joins — no reference row + +| op | params | operands | +|---|---|---| +| `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` | +| `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w | + +Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add` and `mul_weight`. +`norm_add_norm` is `t = rmsnorm(a) * w_a; x += t; y = rmsnorm(x) * w_y` -- a post-norm, the +residual add, the next pre-norm. `join_add_scale` is `x = (x + rmsnorm(rmsnorm(d) * w_d + +rmsnorm(r) * w_r) * w_j) * s` -- two arms' post-norms, their sum, its norm, the residual add and a +one-element layer scalar (Gemma 4's MoE feed-forward). Every value the chain stores is rounded to +the activation dtype at the same point, so the two differ from the chain only in the order a sum +of squares is added in: with the same order they are bit-identical to it, and against a chain +summed in another block width a norm factor can differ in its last bit. + +**libref has no row for either, on purpose.** An architecture asks for a join and declares the +chain where it does not resolve (`rad_op_resolved`), and a reference row would resolve it +everywhere -- so a model loaded without the library that serves the join would resolve it to the +reference and be refused at serve, instead of running the chain on libr4d or libavx. The +`gemma4k` kernel library declares both (device and host rows); with no oracle, its kernels are held +to the chain bit for bit by `tests/g4k_emu`, and no row declares `replaces`, because rad-kbench +assembles a replaced chain from the fusing library's own rows and gemma4k has none of the chain's +ops. + ## Quantisation and rotation | op | params | operands | diff --git a/gemma4k/CMakeLists.txt b/gemma4k/CMakeLists.txt new file mode 100644 index 00000000..6fa5692a --- /dev/null +++ b/gemma4k/CMakeLists.txt @@ -0,0 +1,34 @@ +# gemma4k -- Gemma 4's kernels beyond libr4d: paged attention at head_dim 256/512 (gqa 1/2/4/8, any +# window), pair_argmax (the sharded draft head's cross-rank top-1), and the two sandwich-norm +# joins, which are ops of its own (docs/OPS.md). Ahead of libr4d for Gemma 4 (g4k_rows.cpp). +# +# Built inside radiance's tree (add_subdirectory(gemma4k) beside libr4d) or on its own against an +# installed radiance -- the same rad_add_plugin either way: +# cmake -S gemma4k -B build-g4k -DCMAKE_PREFIX_PATH=/opt/radiance && cmake --build build-g4k +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(gemma4k LANGUAGES CXX HIP) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +if(NOT RAD_HIP_FOUND) + message(STATUS "gemma4k: this radiance has no device build (RAD_HIP_FOUND is OFF) -- skipped") + return() +endif() +# gfx12 only, as libr4d: the kernels are wave32 and read an fp8 cache with RDNA4's hardware +# conversion; the software fallback compiles elsewhere but spills. +rad_plugin_gpu_targets(_g4k_targets "^gfx12") +if(NOT _g4k_targets) + message(STATUS "gemma4k: no gfx12 target in RAD_GPU_TARGETS (${RAD_GPU_TARGETS}) -- skipped") + return() +endif() + +rad_add_plugin(gemma4k kernels + SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/g4k_rows.cpp + HIP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/g4k_attn.hip ${CMAKE_CURRENT_SOURCE_DIR}/g4k_pick.hip + ${CMAKE_CURRENT_SOURCE_DIR}/g4k_norm.hip + GPU_TARGETS ${_g4k_targets}) +string(REPLACE ";" " " _g4k_desc "${_g4k_targets}") +target_compile_definitions(gemma4k PRIVATE "G4K_BUILD_TARGET=\"${_g4k_desc}\"") +set_target_properties(gemma4k PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON) diff --git a/gemma4k/g4k.h b/gemma4k/g4k.h new file mode 100644 index 00000000..d6e109c1 --- /dev/null +++ b/gemma4k/g4k.h @@ -0,0 +1,38 @@ +/* g4k.h -- what gemma4k's row table (g4k_rows.cpp, host C++) needs from its device units + * (g4k_attn.hip, g4k_pick.hip, g4k_norm.hip). Plain C declarations: the row table compiles + * without HIP. */ +#ifndef G4K_H +#define G4K_H + +#include "rad_abi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* attn_paged at (head_dim, gqa, kv dtype). One entry point per instantiation, named for its + * geometry, refusing anything else at launch. */ +#define G4K_ATTN_DECL(HD, G) \ + int g4k_attn_h##HD##_gqa##G##_bf16kv(const RadArgs* a, RadStream s); \ + int g4k_attn_h##HD##_gqa##G##_fp8kv(const RadArgs* a, RadStream s); +G4K_ATTN_DECL(256, 1) G4K_ATTN_DECL(256, 2) G4K_ATTN_DECL(256, 4) G4K_ATTN_DECL(256, 8) +G4K_ATTN_DECL(512, 1) G4K_ATTN_DECL(512, 2) G4K_ATTN_DECL(512, 4) G4K_ATTN_DECL(512, 8) +#undef G4K_ATTN_DECL + +/* The split-KV partials one launch can need, at declare (rad_abi.h RadScratchFn). */ +int64_t g4k_attn_h256_scratch(const RadArgs* a); +int64_t g4k_attn_h512_scratch(const RadArgs* a); + +/* pair_argmax on the device: the top-1 of a row of gathered (id, value) pairs, as one i32 a row. */ +int g4k_pair_argmax_f32(const RadArgs* a, RadStream s); + +/* Gemma 4's sandwich-norm joins, one kernel each (g4k_norm.hip): + * norm_add_norm operands a, w_a, x (inout), w_y, y + * join_add_scale operands d, w_d, r, w_r, w_j, x (inout), s */ +int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream s); +int g4k_join_add_scale_bf16(const RadArgs* a, RadStream s); + +#ifdef __cplusplus +} +#endif +#endif /* G4K_H */ diff --git a/gemma4k/g4k_attn.hip b/gemma4k/g4k_attn.hip new file mode 100644 index 00000000..6ffebce9 --- /dev/null +++ b/gemma4k/g4k_attn.hip @@ -0,0 +1,1146 @@ +/* g4k_attn.hip -- paged attention at the head geometries libr4d does not compile: head_dim 256 and + * 512, 1/2/4/8 queries per KV head, ANY sliding window, causal or not, bf16 or fp8-e4m3 cache. + * + * Gemma 4's text layers need two of them and libr4d has neither: its sliding layers are 16 query + * heads over 8 KV heads at head_dim 256 with a 1024-token window (gqa 2 at every TP), and its full + * layers 16 over 2 at head_dim 512 (gqa 8 at TP1/TP2, 4 at TP4, 2 at TP8). libr4d's h256 rows are + * gqa 4/6/8/12 and all of them `window == 0`. + * + * WHAT THIS IS. Two kernels behind one entry point. The scalar one, for decode and verify steps: one + * workgroup owns one (sequence, KV head, slice of BQ query positions, split of the key range); each + * wave owns RW of the tile's R = BQ*gqa query rows; K and V come through LDS one paged block (or + * two) at a time, prefetched into registers while the previous tile is being consumed; the dot + * products are scalar FMAs with a butterfly reduce-scatter that leaves key j's score in lane j; the + * softmax is online, in the log2 domain. It is memory-bound at decode, where that is the only thing + * that matters. A prefill-shaped launch takes the WMMA kernel further down instead (its own header + * says how), which feeds RDNA4's matrix cores. + * + * WHAT IT COMPUTES is libref's ref_attn_paged, predicate for predicate: + * pos = seqused[s] - q_len(s) + i (seqused INCLUDES this step's queries) + * causal key j visible when j <= pos; non-causal when j < seqused[s] + * window causal: pos - j < window; non-causal: |pos - j| < window; 0 = none + * a block-table entry < 0 is a missing block: its keys are not visible + * no visible key at all -> a zero row + * k_descale / v_descale per (sequence, kv head), absent = 1 + * + * THE PAGED LAYOUT is kv_cache[n_blocks, kv_heads, 16, 2*head_dim], K then V inside a slot, which + * makes one block of one KV head ONE contiguous run of 16 * 2 * head_dim elements: a key tile is + * one or two such runs, fetched as 16-byte loads. + * + * SPLIT-KV. A launch with few (tile, kv head) pairs -- a decode step, a short verify -- would leave + * most of the card idle, so the key range of each tile is cut into `n_split` pieces, each written + * as an unnormalised partial (acc, max, sum) into the op's scratch, and a second kernel merges + * them. The split count is chosen at launch from host-side numbers only (rows, sequences, the + * window or max_ctx); each workgroup divides ITS OWN key range by it, so a split that receives no + * keys writes (0, -inf, 0) and the merge needs no host knowledge of the device-side context. + * + * Nothing here allocates, synchronises, or uses anything but hipLaunchKernel (docs/PLUGIN.md §5). + * Wave32 (RDNA): the shuffles and the reduce-scatter are written for 32 lanes. + */ +#include + +#include +#include + +#include "g4k.h" +#include "g4k_launch.h" +#include "rad_plugin.h" + +#if defined(__HIP_DEVICE_COMPILE__) && defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32 +#error "gemma4k's attention is written for wave32 (RDNA): build without -mwavefrontsize64" +#endif + +namespace g4k { + +constexpr int kThreads = 256; +constexpr int kWaves = kThreads / 32; + +/* split-KV bookkeeping: at most this many (tile, kv head, split) triples carry partials, and the + * tile table behind them holds at most kTinfoMax tiles. The launch keeps under both by + * construction; the scratch hook sizes for exactly these. */ +constexpr int kPartBudget = 192; +constexpr int kTinfoMax = 128; +constexpr int kMaxSplit = 64; + +template struct Geo; +/* R query rows a workgroup (R / 8 a wave), BK keys a tile. BK * 2 * HD bf16 = 32 KiB of LDS either + * way: two paged blocks at 256, one at 512. */ +template <> struct Geo<256> { static constexpr int R = 32, BK = 32; }; +template <> struct Geo<512> { static constexpr int R = 16, BK = 16; }; + +/* ------------------------------------------------------------------ device helpers */ +__device__ __forceinline__ int lane_id() { return (int)(threadIdx.x & 31u); } + +__device__ __forceinline__ float shfl_xor(float v, int m) { + return __int_as_float(__builtin_amdgcn_ds_bpermute((lane_id() ^ m) << 2, __float_as_int(v))); +} +__device__ __forceinline__ int shfl_up(int v, int d) { + const int l = lane_id(); + return __builtin_amdgcn_ds_bpermute((l >= d ? l - d : l) << 2, v); +} +__device__ __forceinline__ float readlane(float v, int l) { + return __int_as_float(__builtin_amdgcn_readlane(__float_as_int(v), l)); +} +__device__ __forceinline__ float wave_max(float v) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) v = __builtin_fmaxf(v, shfl_xor(v, d)); + return v; +} +__device__ __forceinline__ float wave_sum(float v) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) v += shfl_xor(v, d); + return v; +} +__device__ __forceinline__ float ex2(float x) { +#if __has_builtin(__builtin_amdgcn_exp2f) + return __builtin_amdgcn_exp2f(x); /* v_exp_f32: exp2(-inf) = 0 */ +#else + return exp2f(x); +#endif +} +__device__ __forceinline__ int imin(int a, int b) { return a < b ? a : b; } +__device__ __forceinline__ int imax(int a, int b) { return a > b ? a : b; } + +/* f(Ic<0>{}), ..., f(Ic{}): a loop whose index is a CONSTANT in every body, unconditionally. + * `#pragma unroll` is a request the unroller drops past a size threshold -- the fp8 legs of the + * row loop crossed it -- and a register array indexed by a loop variable that survives is demoted + * to scratch memory. This cannot be dropped. */ +template struct Ic { static constexpr int value = I; }; +template struct StaticFor { + template __device__ __forceinline__ static void run(F& f) { + if constexpr (I < N) { + f(Ic{}); + StaticFor::run(f); + } + } +}; + +__device__ __forceinline__ void bf16x4(uint2 w, float (&f)[4]) { + f[0] = __uint_as_float(w.x << 16); + f[1] = __uint_as_float(w.x & 0xffff0000u); + f[2] = __uint_as_float(w.y << 16); + f[3] = __uint_as_float(w.y & 0xffff0000u); +} +/* OCP E4M3 (e4m3fn, bias 7, 0x7f/0xff NaN, no infinity) -- the KV cache's bytes at + * --kv-cache-dtype fp8 (docs/PLUGIN.md §10). Exact; subnormals kept. */ +__device__ __forceinline__ float fp8e4m3(unsigned b) { + const unsigned e = (b >> 3) & 15u, m = b & 7u; + float v = e ? __uint_as_float(((e + 120u) << 23) | (m << 20)) : (float)m * 0.001953125f; + if (e == 15u && m == 7u) v = __uint_as_float(0x7fc00000u); + return __uint_as_float(__float_as_uint(v) | ((b & 0x80u) << 24)); +} +__device__ __forceinline__ void fp8x4(unsigned w, float (&f)[4]) { +#if defined(__GFX12__) + /* v_cvt_pk_f32_fp8: RDNA4 converts OCP E4M3 in hardware, two bytes an instruction -- the same + * instruction libr4d reads its fp8 cache with. */ + const auto a = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, false); + const auto b = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, true); + f[0] = a[0]; f[1] = a[1]; f[2] = b[0]; f[3] = b[1]; +#else + f[0] = fp8e4m3(w & 0xffu); + f[1] = fp8e4m3((w >> 8) & 0xffu); + f[2] = fp8e4m3((w >> 16) & 0xffu); + f[3] = fp8e4m3(w >> 24); +#endif +} +/* f32 -> bf16, round to nearest even, NaN kept quiet (rad_plugin.h's rad_f32_to_bf16). */ +__device__ __forceinline__ unsigned bf16_rtne(float f) { + unsigned u = __float_as_uint(f); + if ((u & 0x7fffffffu) > 0x7f800000u) return (u >> 16) | 0x40u; + u += 0x7fffu + ((u >> 16) & 1u); + return u >> 16; +} +__device__ __forceinline__ unsigned pack2(float a, float b) { return bf16_rtne(a) | (bf16_rtne(b) << 16); } + +/* Four elements of one slot row, at element offset `e`, out of the LDS tile. */ +template +__device__ __forceinline__ void lds4(const unsigned char* row, int e, float (&f)[4]) { + if constexpr (KV8) fp8x4(*(const unsigned*)(row + e), f); + else bf16x4(*(const uint2*)(row + 2 * e), f); +} + +/* THE REDUCE-SCATTER. Each lane holds a partial dot for every key of the tile; after it, lane l + * holds key l's full sum. Each step keeps the half of the vector its lane bit selects and adds the + * partner's copy of that half: 16 + 8 + 4 + 2 + 1 = 31 shuffles for 32 keys, against 32 * 5 for 32 + * separate reductions. */ +template +__device__ __forceinline__ void reduce_scatter(float (&v)[N], int lane) { + if constexpr (H >= 1) { + const bool up = (lane & H) != 0; +#pragma unroll + for (int i = 0; i < H; ++i) { + /* VALUES, not lvalues: `up ? v[i + H] : v[i]` selects between two ADDRESSES, and an + * array addressed by a lane-dependent pointer is demoted to scratch memory. */ + const float lo = v[i], hi = v[i + H]; + const float keep = up ? hi : lo; + const float send = up ? lo : hi; + v[i] = keep + shfl_xor(send, H); + } + reduce_scatter(v, lane); + } +} + +/* ------------------------------------------------------------------ the launch's arguments */ +struct AttnArgs { + const uint16_t* q; long long q_rs, q_hs; /* elements */ + const unsigned char* kv; long long kv_sb, kv_sh; /* elements of the cache's dtype */ + const int* bt; long long bt_rs; + const int* seqused; + const int* cu; /* null: uniform q_len */ + const float* kdes; + const float* vdes; + uint16_t* out; long long o_rs, o_hs; + float* part; /* split-KV partials, or null */ + int* tinfo; /* [tile] = (first row, positions) */ + float qscale; /* softmax scale * log2(e) */ + int max_blocks, n_seq, q_len, tps, kv_heads, causal, window, n_split; +}; + +/* Tile `tile` of a ragged batch: the sequence it belongs to and which BQ-position slice of that + * sequence's query it is. Tiles are numbered sequence by sequence, ceil(q_len(s) / BQ) each, so the + * answer is a prefix sum over cu_seqlens -- done by the whole block, 256 sequences a pass. Every + * thread returns the same answer: it is read back out of LDS after a barrier. */ +template +__device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int* s_res, int& s_out, + int& lt_out) { + constexpr int NW = NT / 32; + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + if (tid == 0) { s_res[0] = -1; s_res[1] = 0; } + __syncthreads(); + int base = 0; + for (int c0 = 0; c0 < n_seq; c0 += NT) { + const int s = c0 + tid; + int nt = 0; + if (s < n_seq) { + const int ql = cu[s + 1] - cu[s]; + nt = ql > 0 ? (ql + BQ - 1) / BQ : 0; + } + int x = nt; + for (int d = 1; d < 32; d <<= 1) { + const int y = shfl_up(x, d); + if (lane >= d) x += y; + } + if (lane == 31) s_scan[wave] = x; + __syncthreads(); + int before = 0, total = 0; + for (int w = 0; w < NW; ++w) { + const int v = s_scan[w]; + before += (w < wave) ? v : 0; + total += v; + } + const int incl = base + before + x; + if (nt > 0 && tile >= incl - nt && tile < incl) { s_res[0] = s; s_res[1] = tile - (incl - nt); } + base += total; + __syncthreads(); + if (s_res[0] >= 0 || base > tile) break; + } + s_out = s_res[0]; + lt_out = s_res[1]; +} + +/* ------------------------------------------------------------------ the attention kernel */ +template +__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { + constexpr int R = Geo::R, BK = Geo::BK, RW = R / kWaves, BQ = R / GQA; + constexpr int NC = HD / 128; /* 4-element chunks a lane holds of a row */ + constexpr int ESZ = KV8 ? 1 : 2; + constexpr int KEY_BYTES = 2 * HD * ESZ; /* one slot: K then V */ + constexpr int TILE_U4 = BK * KEY_BYTES / 16; + constexpr int NPT = TILE_U4 / kThreads; /* 16-byte loads a thread, per tile */ + constexpr int BLK_U4 = 16 * KEY_BYTES / 16; /* one paged block of one kv head */ + constexpr int NB = BK / 16; /* paged blocks a key tile spans */ + static_assert(R % kWaves == 0 && R % GQA == 0, "rows must split over waves and heads"); + static_assert(TILE_U4 % kThreads == 0 && BLK_U4 % kThreads == 0, "tile must split over threads"); + static_assert(BK == 32 || BK == 16, "the reduce-scatter is written for 16 or 32 keys"); + + __shared__ uint4 s_kv[TILE_U4]; + __shared__ int s_scan[kWaves]; + __shared__ int s_res[2]; + + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int tile = (int)blockIdx.x, kh = (int)blockIdx.y, z = (int)blockIdx.z; + + /* ---- which sequence, and which slice of its query */ + int s = -1, lt = 0; + if (A.cu) { + find_tile(A.cu, A.n_seq, tile, s_scan, s_res, s, lt); + } else { + s = tile / A.tps; + lt = tile - s * A.tps; + if (s >= A.n_seq) s = -1; + } + int qlen = 0, tokb = 0, ctx = 0; + if (s >= 0) { + if (A.cu) { tokb = A.cu[s]; qlen = A.cu[s + 1] - tokb; } + else { tokb = s * A.q_len; qlen = A.q_len; } + ctx = A.seqused[s]; + } + const int pfirst = lt * BQ; + const int npos = s >= 0 ? imax(0, imin(BQ, qlen - pfirst)) : 0; + if (A.n_split > 1 && kh == 0 && z == 0 && tid == 0) { + A.tinfo[2 * tile] = tokb + pfirst; + A.tinfo[2 * tile + 1] = npos; + } + if (npos <= 0) return; /* uniform across the block */ + + const int tok0 = tokb + pfirst; + const int qbase = ctx - qlen + pfirst; /* absolute position of the tile's first query */ + const int plast = qbase + npos - 1; + const int causal = A.causal, window = A.window; + + /* ---- the tile's key range, and this split's share of it */ + int hi = causal ? plast + 1 : ctx; + if (!causal && window > 0) hi = imin(hi, plast + window); + hi = imin(imin(hi, ctx), A.max_blocks * 16); + const int lo = window > 0 ? imax(0, qbase - window + 1) : 0; + const int lo_a = lo & ~(BK - 1); + const int nkt = hi > lo_a ? (hi - lo_a + BK - 1) / BK : 0; + const int per = (nkt + A.n_split - 1) / A.n_split; + const int kt_lo = imin(nkt, z * per), kt_hi = imin(nkt, kt_lo + per); + + const float kds = A.kdes ? A.kdes[(long long)s * A.kv_heads + kh] : 1.0f; + const float vds = A.vdes ? A.vdes[(long long)s * A.kv_heads + kh] : 1.0f; + + /* ---- this wave's query rows: row r is position r / GQA, head kh * GQA + r % GQA */ + float qf[RW][NC][4], o[RW][NC][4], m[RW], l[RW]; + int pos[RW]; + bool val[RW]; +#pragma unroll + for (int i = 0; i < RW; ++i) { + const int r = wave * RW + i, p = r / GQA, g = r - p * GQA; + val[i] = p < npos; + pos[i] = qbase + p; + m[i] = -__builtin_inff(); + l[i] = 0.0f; + const uint16_t* qp = A.q + (long long)(tok0 + p) * A.q_rs + (long long)(kh * GQA + g) * A.q_hs; + const float qs = A.qscale * kds; /* k_descale folds into the query */ +#pragma unroll + for (int c = 0; c < NC; ++c) { + float f[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + if (val[i]) bf16x4(*(const uint2*)(qp + c * 128 + lane * 4), f); +#pragma unroll + for (int e = 0; e < 4; ++e) { qf[i][c][e] = f[e] * qs; o[i][c][e] = 0.0f; } + } + } + + /* ---- the key tiles, prefetched one ahead through registers */ + uint4 pre[NPT]; + bool pre_ok[NB]; + auto fetch = [&](int kt) __attribute__((always_inline)) { + const int k0 = lo_a + kt * BK; + const unsigned char* src[NB]; +#pragma unroll + for (int b = 0; b < NB; ++b) { + const int lb = (k0 >> 4) + b; + int blk = -1; + if (lb < A.max_blocks && (lb << 4) < hi) blk = A.bt[(long long)s * A.bt_rs + lb]; + pre_ok[b] = blk >= 0; + /* never a null: a select against null makes the pointer FLAT rather than global, and + * every tile load a flat_load. A missing block points at the cache's base and its + * value is replaced by zeros below. */ + src[b] = A.kv + ((long long)(blk >= 0 ? blk : 0) * A.kv_sb + (long long)kh * A.kv_sh) * ESZ; + } +#pragma unroll + for (int i = 0; i < NPT; ++i) { + const int b = (i * kThreads) / BLK_U4; /* constant: BLK_U4 is a multiple of 256 */ + const int off = tid + i * kThreads - b * BLK_U4; + if (pre_ok[b]) pre[i] = ((const uint4*)src[b])[off]; + else pre[i] = make_uint4(0u, 0u, 0u, 0u); + } + }; + + const unsigned char* sb = (const unsigned char*)s_kv; + if (kt_lo < kt_hi) fetch(kt_lo); + for (int kt = kt_lo; kt < kt_hi; ++kt) { + __syncthreads(); /* the previous tile is consumed */ +#pragma unroll + for (int i = 0; i < NPT; ++i) s_kv[tid + i * kThreads] = pre[i]; + const bool ok0 = pre_ok[0], ok1 = pre_ok[NB - 1]; /* values: see reduce_scatter */ + __syncthreads(); + const int k0 = lo_a + kt * BK; + if (kt + 1 < kt_hi) fetch(kt + 1); + + const int jl = lane & (BK - 1); /* the key this lane scores */ + const int kk = k0 + jl; + const bool kok = (jl < 16 ? ok0 : ok1) && kk >= lo && kk < hi; + + auto row_step = [&](auto ic) __attribute__((always_inline)) { + constexpr int i = decltype(ic)::value; + if (!val[i]) return; /* uniform: one row, all lanes */ + float sc[BK]; +#pragma unroll + for (int j = 0; j < BK; ++j) { + const unsigned char* row = sb + j * KEY_BYTES; + float acc = 0.0f; +#pragma unroll + for (int c = 0; c < NC; ++c) { + float k[4]; + lds4(row, c * 128 + lane * 4, k); +#pragma unroll + for (int e = 0; e < 4; ++e) acc = __builtin_fmaf(qf[i][c][e], k[e], acc); + } + sc[j] = acc; + } + if constexpr (BK == 32) { + reduce_scatter<16, BK>(sc, lane); + } else { +#pragma unroll + for (int j = 0; j < BK; ++j) sc[j] += shfl_xor(sc[j], 16); + reduce_scatter<8, BK>(sc, lane); + } + const int pq = pos[i]; + bool vis = kok && (causal ? kk <= pq : true); + if (window > 0) vis = vis && (pq - kk < window) && (causal || kk - pq < window); + const float sv = vis ? sc[0] : -__builtin_inff(); + const float mn = __builtin_fmaxf(m[i], wave_max(sv)); + if (mn == -__builtin_inff()) return; /* nothing visible yet: uniform */ + const float corr = ex2(m[i] - mn); + const float p = vis ? ex2(sv - mn) : 0.0f; + l[i] = l[i] * corr + wave_sum((BK == 16 && lane >= 16) ? 0.0f : p); +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int e = 0; e < 4; ++e) o[i][c][e] *= corr; +#pragma unroll + for (int j = 0; j < BK; ++j) { + const float pj = readlane(p, j); /* uniform; a masked key's V is never read */ + if (pj != 0.0f) { + const unsigned char* row = sb + j * KEY_BYTES; +#pragma unroll + for (int c = 0; c < NC; ++c) { + float v[4]; + lds4(row, HD + c * 128 + lane * 4, v); +#pragma unroll + for (int e = 0; e < 4; ++e) o[i][c][e] = __builtin_fmaf(pj, v[e], o[i][c][e]); + } + } + } + m[i] = mn; + }; + StaticFor<0, RW>::run(row_step); + } + + /* ---- out: normalised bf16 rows, or this split's partials */ +#pragma unroll + for (int i = 0; i < RW; ++i) { + if (!val[i]) continue; + const int r = wave * RW + i, p = r / GQA, g = r - p * GQA; + if (A.n_split == 1) { + const float inv = l[i] > 0.0f ? vds / l[i] : 0.0f; + uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs; +#pragma unroll + for (int c = 0; c < NC; ++c) + *(uint2*)(op + c * 128 + lane * 4) = + make_uint2(pack2(o[i][c][0] * inv, o[i][c][1] * inv), + pack2(o[i][c][2] * inv, o[i][c][3] * inv)); + } else { + const long long slot = (((long long)tile * A.kv_heads + kh) * A.n_split + z) * R + r; + float* pp = A.part + slot * (HD + 4); + if (lane == 0) { pp[HD] = m[i]; pp[HD + 1] = l[i]; } + /* no key visible to this row in this split: the merge weighs it 0 and never reads its + * accumulator, so it is not written (uniform: m is the wave's) */ + if (m[i] == -__builtin_inff()) continue; +#pragma unroll + for (int c = 0; c < NC; ++c) + *(float4*)(pp + c * 128 + lane * 4) = + make_float4(o[i][c][0] * vds, o[i][c][1] * vds, o[i][c][2] * vds, o[i][c][3] * vds); + } + } +} + +/* ================================================================== the WMMA prefill kernel + * + * WHY A SECOND KERNEL. The kernel above is scalar FMAs: right for decode, where a step is a few + * rows and the cache read is the whole cost, and about 8 TFLOP/s a card on a long prefill, where + * the global layers' attention is quadratic in the prompt and 46% of a 48k-token prefill. RDNA4's + * matrix cores do a 16x16x16 bf16 product a WMMA instruction; this kernel feeds them. It is chosen + * at launch for prefill-shaped steps only (a sequence with >= kWmmaMinQ query rows) and computes + * the same function, predicate for predicate. + * + * THE LAYOUTS (RDNA4, wave32, v_wmma_f32_16x16x16_bf16 -- confirmed against llama.cpp's mma.cuh, + * which runs on the card): A[M][K] gives lane L row M = L % 16 and K = 8 * (L / 16) .. + 7; B[K][N] + * gives lane L column N = L % 16 and the same K; the f32 result gives lane L column N = L % 16 and + * rows M = 8 * (L / 16) .. + 7. So the kernel computes S TRANSPOSED: S^T = K * Q^T puts each + * lane's eight values in ONE query row (row L % 16, keys 8h .. 8h + 7), the row's other eight keys + * in lane L ^ 16 -- the softmax statistics are one shuffle -- and those eight values, as bf16, are + * exactly the B operand of O^T = V^T * P^T. O^T's lane L likewise holds only row L % 16, so the + * online-softmax rescale is a per-lane scalar. + * + * THE SPLIT. O^T for 16 rows of a 512-dim head is 256 f32 a lane -- the whole register file. So a + * wave owns 16 rows by a 128-dim slice of the head (kDQ): its Q^T (32 VGPRs) and O^T (64). The + * slices of one row group each compute S^T over their own dims; the partials meet in LDS and every + * slice sums them in the same order, so all of them see bit-identical scores and take identical + * softmax steps. 16 waves: h512 is 4 row groups of 4 slices (64 rows), h256 8 of 2 (128 rows). + * + * THE TILE is one paged block, 16 keys. K goes to LDS as it is ([key][dim] bf16, a 16-byte pad a row + * so the A-fragment reads hit 32 different banks); V goes TRANSPOSED ([dim][key], rows of 48 + * bytes), since the PV product reduces over keys and an operand's eight K-values must be + * contiguous. The transposed write is two keys' dims packed a dword, the dword index rotated per + * lane group so a wave's 32 writes land in 32 banks. An fp8 cache is widened on the way in -- exact, + * e4m3 has 3 mantissa bits. Keys outside the tile's range or in a missing block are written as + * zeros: a probability of 0 times a NaN in a recycled slot is still NaN. + * + * P AND V IN f16, Q AND K IN bf16. The probabilities are rounded for the matrix product, and bf16's + * 8 bits leave 2^-9 of |v| in every output -- measured in the emulator against f64 at up to 0.25% + * of the V range, four times the scalar kernel's error. f16 runs at the same rate with 11 bits. V's + * bf16 values are exact in f16 between 2^-14 and 65504 (clamped beyond, NaN kept); an fp8 cache's + * are exact outright. The denominator sums the probabilities as rounded, so a row is a true + * weighted mean of V: a dominant key keeps weight 1 exactly. + */ +typedef short g4k_v8s __attribute__((ext_vector_type(8))); /* 8 bf16, as the builtin takes them */ +typedef float g4k_v8f __attribute__((ext_vector_type(8))); +typedef _Float16 g4k_v8h __attribute__((ext_vector_type(8))); + +constexpr int kWThreads = 512; +constexpr int kWWaves = kWThreads / 32; +constexpr int kDQ = 128; /* dims of a wave's slice of the head */ +constexpr int kWmmaMinQ = 64; /* a launch whose longest query is shorter stays scalar */ + +template struct WGeo { + static constexpr int NS = HD / kDQ; /* slices: waves sharing one 16-row group */ + static constexpr int RG = kWWaves / NS; /* row groups a workgroup */ + static constexpr int R = RG * 16; /* rows a workgroup */ + static constexpr int KS = HD * 2 + 16; /* bytes a key row of the K tile */ + static constexpr int VS = 48; /* bytes a dim row of the V^T tile: 16 keys + pad */ +}; + +__device__ __forceinline__ g4k_v8f wmma_bf16(g4k_v8s a, g4k_v8s b, g4k_v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); +} +__device__ __forceinline__ g4k_v8f wmma_f16(g4k_v8h a, g4k_v8h b, g4k_v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +} +/* f32 -> f16 bits, round to nearest even; a finite value past f16's range saturates, NaN stays */ +__device__ __forceinline__ unsigned f16_bits(float f) { + if (f == f) f = __builtin_fminf(__builtin_fmaxf(f, -65504.0f), 65504.0f); + return (unsigned)__builtin_bit_cast(unsigned short, (_Float16)f); +} +__device__ __forceinline__ void fp8x16_f16(const uint4 w, unsigned (&h)[16]) { + const unsigned in[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int q = 0; q < 4; ++q) { + float f[4]; + fp8x4(in[q], f); +#pragma unroll + for (int e = 0; e < 4; ++e) h[q * 4 + e] = f16_bits(f[e]); + } +} +__device__ __forceinline__ void bf16x8_f16(const uint4 w, unsigned (&h)[8]) { + const unsigned in[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int q = 0; q < 4; ++q) { + h[2 * q] = f16_bits(__uint_as_float(in[q] << 16)); + h[2 * q + 1] = f16_bits(__uint_as_float(in[q] & 0xffff0000u)); + } +} +/* fp8 e4m3 -> bf16 bits (the K tile), exact: the f32 a byte widens to has nothing below bit 16 */ +__device__ __forceinline__ void fp8x16_bf16(const uint4 w, unsigned (&h)[16]) { + const unsigned in[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int q = 0; q < 4; ++q) { + float f[4]; + fp8x4(in[q], f); +#pragma unroll + for (int e = 0; e < 4; ++e) h[q * 4 + e] = __float_as_uint(f[e]) >> 16; + } +} + +template +__global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { + using G = WGeo; + constexpr int NS = G::NS, R = G::R, BQ = R / GQA, KS = G::KS, VS = G::VS; + constexpr int ESZ = KV8 ? 1 : 2; + constexpr int SLOT = 2 * HD * ESZ; /* bytes of one key's slot: K then V */ + constexpr int CW = 16 / ESZ; /* cache elements one 16-byte load carries */ + constexpr int NCH = HD / CW; /* such chunks a head */ + constexpr int NKI = 16 * NCH; /* K items a tile: (key, chunk) */ + constexpr int NVI = 8 * NCH; /* V items a tile: (key pair, chunk) */ + constexpr int KPT = (NKI + kWThreads - 1) / kWThreads; + constexpr int VPT = (NVI + kWThreads - 1) / kWThreads; + static_assert(R % GQA == 0 && NS * G::RG == kWWaves, "rows must split over heads and waves"); + static_assert(KS % 16 == 0 && VS % 16 == 0, "16-byte LDS rows"); + + __shared__ uint4 s_k[16 * KS / 16]; + __shared__ uint4 s_vt[HD * VS / 16]; + __shared__ float4 s_x[kWWaves * 32 * 2]; + __shared__ int s_scan[kWWaves]; + __shared__ int s_res[2]; + + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int rg = wave / NS, sl = wave - rg * NS; + const int tile = (int)blockIdx.x, kh = (int)blockIdx.y; + + /* ---- which sequence, and which slice of its query: as the scalar kernel, at this BQ */ + int s = -1, lt = 0; + if (A.cu) { + find_tile(A.cu, A.n_seq, tile, s_scan, s_res, s, lt); + } else { + s = tile / A.tps; + lt = tile - s * A.tps; + if (s >= A.n_seq) s = -1; + } + int qlen = 0, tokb = 0, ctx = 0; + if (s >= 0) { + if (A.cu) { tokb = A.cu[s]; qlen = A.cu[s + 1] - tokb; } + else { tokb = s * A.q_len; qlen = A.q_len; } + ctx = A.seqused[s]; + } + const int pfirst = lt * BQ; + const int npos = s >= 0 ? imax(0, imin(BQ, qlen - pfirst)) : 0; + if (npos <= 0) return; /* uniform across the block */ + + const int tok0 = tokb + pfirst; + const int qbase = ctx - qlen + pfirst; + const int plast = qbase + npos - 1; + const int causal = A.causal, window = A.window; + int hi = causal ? plast + 1 : ctx; + if (!causal && window > 0) hi = imin(hi, plast + window); + hi = imin(imin(hi, ctx), A.max_blocks * 16); + const int lo = window > 0 ? imax(0, qbase - window + 1) : 0; + const int lo_a = lo & ~15; + const int nkt = hi > lo_a ? (hi - lo_a + 15) / 16 : 0; + + const float kds = A.kdes ? A.kdes[(long long)s * A.kv_heads + kh] : 1.0f; + const float vds = A.vdes ? A.vdes[(long long)s * A.kv_heads + kh] : 1.0f; + const float sscale = A.qscale * kds; /* log2-domain softmax scale, k_descale in */ + + /* ---- this lane's query row: column n of every S^T and O^T tile */ + const int n = lane & 15, h = lane >> 4; + const int r = rg * 16 + n, p = r / GQA, g = r - p * GQA; + const bool rval = p < npos; + const int pos = qbase + p; + + g4k_v8s qf[kDQ / 16]; + { + const uint16_t* qp = A.q + (long long)(tok0 + (rval ? p : 0)) * A.q_rs + + (long long)(kh * GQA + g) * A.q_hs + sl * kDQ + 8 * h; +#pragma unroll + for (int kc = 0; kc < kDQ / 16; ++kc) { + const uint4 w = rval ? *(const uint4*)(qp + kc * 16) : make_uint4(0u, 0u, 0u, 0u); + qf[kc] = __builtin_bit_cast(g4k_v8s, w); + } + } + g4k_v8f oacc[kDQ / 16]; +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) +#pragma unroll + for (int e = 0; e < 8; ++e) oacc[mc][e] = 0.0f; + float m = -__builtin_inff(), l = 0.0f; + + /* ---- the key tiles, one paged block each, prefetched one ahead through registers */ + uint4 pk[KPT], pv[VPT][2]; + bool pre_ok = false; + auto fetch = [&](int kt) __attribute__((always_inline)) { + const int k0 = lo_a + kt * 16, lb = k0 >> 4; + int blk = -1; + if (lb < A.max_blocks && k0 < hi) blk = A.bt[(long long)s * A.bt_rs + lb]; + pre_ok = blk >= 0; + /* never a null: see the scalar kernel's fetch */ + const unsigned char* base = + A.kv + ((long long)(blk >= 0 ? blk : 0) * A.kv_sb + (long long)kh * A.kv_sh) * ESZ; +#pragma unroll + for (int j = 0; j < KPT; ++j) { + const int idx = tid + j * kWThreads; + pk[j] = make_uint4(0u, 0u, 0u, 0u); + if (pre_ok && idx < NKI) { + const int key = idx / NCH, ch = idx - key * NCH; + pk[j] = *(const uint4*)(base + key * SLOT + ch * 16); + } + } +#pragma unroll + for (int j = 0; j < VPT; ++j) { + const int idx = tid + j * kWThreads; + pv[j][0] = pv[j][1] = make_uint4(0u, 0u, 0u, 0u); + if (pre_ok && idx < NVI) { + const int kp = idx & 7, ch = idx >> 3; + const unsigned char* v0 = base + (2 * kp) * SLOT + HD * ESZ + ch * 16; + pv[j][0] = *(const uint4*)v0; + pv[j][1] = *(const uint4*)(v0 + SLOT); + } + } + }; + + unsigned char* kb = (unsigned char*)s_k; + unsigned char* vb = (unsigned char*)s_vt; + if (nkt > 0) fetch(0); + for (int kt = 0; kt < nkt; ++kt) { + const int k0 = lo_a + kt * 16; + const bool tok = pre_ok; /* this tile's block is present */ + __syncthreads(); /* the previous tile's LDS is consumed */ + + /* ---- K: [key][dim] as bf16 */ +#pragma unroll + for (int j = 0; j < KPT; ++j) { + const int idx = tid + j * kWThreads; + if (idx < NKI) { + const int key = idx / NCH, ch = idx - key * NCH; + const int kk = k0 + key; + const bool keep = tok && kk >= lo && kk < hi; + const uint4 w = keep ? pk[j] : make_uint4(0u, 0u, 0u, 0u); + if constexpr (KV8) { + unsigned hb[16]; + fp8x16_bf16(w, hb); + uint4* dst = (uint4*)(kb + key * KS + ch * 32); + dst[0] = make_uint4(hb[0] | hb[1] << 16, hb[2] | hb[3] << 16, hb[4] | hb[5] << 16, hb[6] | hb[7] << 16); + dst[1] = make_uint4(hb[8] | hb[9] << 16, hb[10] | hb[11] << 16, hb[12] | hb[13] << 16, hb[14] | hb[15] << 16); + } else { + *(uint4*)(kb + key * KS + ch * 16) = w; + } + } + } + /* ---- V: [dim][key] as f16, two keys a dword; the row order rotated by 2 per 8-lane + * group, so the four groups of a wave write four different rows mod 8 -- 32 banks */ +#pragma unroll + for (int j = 0; j < VPT; ++j) { + const int idx = tid + j * kWThreads; + if (idx < NVI) { + const int kp = idx & 7, ch = idx >> 3; + const int ka = k0 + 2 * kp, kb1 = ka + 1; + const uint4 wa = (tok && ka >= lo && ka < hi) ? pv[j][0] : make_uint4(0u, 0u, 0u, 0u); + const uint4 wb = (tok && kb1 >= lo && kb1 < hi) ? pv[j][1] : make_uint4(0u, 0u, 0u, 0u); + unsigned d[CW]; /* f16 pairs: key 2kp low, 2kp + 1 high */ + if constexpr (KV8) { + unsigned ha[16], hb2[16]; + fp8x16_f16(wa, ha); + fp8x16_f16(wb, hb2); +#pragma unroll + for (int e = 0; e < CW; ++e) d[e] = ha[e] | hb2[e] << 16; + } else { + unsigned ha[8], hb2[8]; + bf16x8_f16(wa, ha); + bf16x8_f16(wb, hb2); +#pragma unroll + for (int e = 0; e < CW; ++e) d[e] = ha[e] | hb2[e] << 16; + } + const int rot = 2 * ((lane >> 3) & 3); + unsigned* col = (unsigned*)(vb + (ch * CW) * VS) + kp; +#pragma unroll + for (int t = 0; t < CW; ++t) { + /* element (t + rot) % CW, chosen by value: rot is per lane */ + const unsigned v0 = d[t], v2 = d[(t + 2) % CW], v4 = d[(t + 4) % CW], v6 = d[(t + 6) % CW]; + const unsigned v = rot == 0 ? v0 : rot == 2 ? v2 : rot == 4 ? v4 : v6; + const int e = (t + rot) % CW; + col[e * (VS / 4)] = v; + } + } + } + __syncthreads(); + if (kt + 1 < nkt) fetch(kt + 1); + + /* ---- S^T partial over this wave's slice: A = K rows (key n), B = Q^T (row n) */ + g4k_v8f sacc; +#pragma unroll + for (int e = 0; e < 8; ++e) sacc[e] = 0.0f; + { + /* one accumulator: a second one hides the chain's latency but costs 12 VGPRs, and at + * 187 two 16-wave workgroups share a WGP (8 waves a SIMD, 1536 VGPRs) where at 200 + * one does -- the other waves hide the latency better */ + const unsigned char* ka = kb + n * KS + (sl * kDQ + 8 * h) * 2; +#pragma unroll + for (int kc = 0; kc < kDQ / 16; ++kc) + sacc = wmma_bf16(__builtin_bit_cast(g4k_v8s, *(const uint4*)(ka + kc * 32)), qf[kc], sacc); + } + /* ---- the slices' partials meet: every slice sums them in slice order */ + s_x[(wave * 2 + 0) * 32 + lane] = make_float4(sacc[0], sacc[1], sacc[2], sacc[3]); + s_x[(wave * 2 + 1) * 32 + lane] = make_float4(sacc[4], sacc[5], sacc[6], sacc[7]); + __syncthreads(); + float tot[8]; +#pragma unroll + for (int j = 0; j < NS; ++j) { + float v[8]; + if (j == sl) { /* uniform: the wave's own, as written */ +#pragma unroll + for (int e = 0; e < 8; ++e) v[e] = sacc[e]; + } else { + const float4 a = s_x[((rg * NS + j) * 2 + 0) * 32 + lane]; + const float4 b = s_x[((rg * NS + j) * 2 + 1) * 32 + lane]; + v[0] = a.x; v[1] = a.y; v[2] = a.z; v[3] = a.w; + v[4] = b.x; v[5] = b.y; v[6] = b.z; v[7] = b.w; + } +#pragma unroll + for (int e = 0; e < 8; ++e) tot[e] = j == 0 ? v[e] : tot[e] + v[e]; + } + + /* ---- online softmax, row n: eight keys here, eight in lane ^ 16 */ + float sv[8], mx = -__builtin_inff(); +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int kk = k0 + 8 * h + e; + bool vis = rval && tok && kk >= lo && kk < hi; + if (causal) vis = vis && kk <= pos; + if (window > 0) vis = vis && (pos - kk < window) && (causal || kk - pos < window); + sv[e] = vis ? tot[e] * sscale : -__builtin_inff(); + mx = __builtin_fmaxf(mx, sv[e]); + } + mx = __builtin_fmaxf(mx, shfl_xor(mx, 16)); + const float mn = __builtin_fmaxf(m, mx); + const float corr = mn == -__builtin_inff() ? 1.0f : ex2(m - mn); + /* P in f16, and the denominator summed from P as rounded (see the head of this kernel) */ + float ps = 0.0f; + g4k_v8h pf; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const float pe = sv[e] == -__builtin_inff() ? 0.0f : ex2(sv[e] - mn); + pf[e] = (_Float16)pe; /* in [0, 1]: no saturation to worry about */ + ps += (float)pf[e]; + } + l = l * corr + ps; + m = mn; + + /* ---- O^T += V^T * P^T in f16: A = V^T rows (dim n of the chunk), keys 8h .. 8h + 7 */ + const unsigned char* va = vb + (sl * kDQ + n) * VS + h * 16; +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) { + oacc[mc] *= corr; + oacc[mc] = wmma_f16(__builtin_bit_cast(g4k_v8h, *(const uint4*)(va + mc * 16 * VS)), pf, oacc[mc]); + } + } + + /* ---- out: the row's denominator is its two lanes' partial sums */ + const float lt2 = l + shfl_xor(l, 16); + if (rval) { + const float inv = lt2 > 0.0f ? vds / lt2 : 0.0f; + uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs + + sl * kDQ + 8 * h; +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) + *(uint4*)(op + mc * 16) = + make_uint4(pack2(oacc[mc][0] * inv, oacc[mc][1] * inv), pack2(oacc[mc][2] * inv, oacc[mc][3] * inv), + pack2(oacc[mc][4] * inv, oacc[mc][5] * inv), pack2(oacc[mc][6] * inv, oacc[mc][7] * inv)); + } +} + +/* ------------------------------------------------------------------ the split-KV merge + * + * ONE WAVE A ROW, THE SPLITS ACROSS ITS LANES. Lane z reads split z's (max, sum) and lane z + 32 + * split z + 32's -- kMaxSplit is 64 -- so the row's max and denominator are one wave reduction + * each; then one sweep over the splits that saw a key, four at a time, every lane accumulating + * its 4 * NC dims. The first version walked the splits three times over, + * serially, in one thread block per tile: at the 64 splits a decode step of a full-attention layer + * gets, that was 750 us a call, a quarter of the step's device time. */ +template +__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { + constexpr int R = Geo::R, NC = HD / 128; + static_assert(kMaxSplit <= 64, "two splits a lane"); + const int tile = (int)blockIdx.x, kh = (int)blockIdx.y; + const int lane = lane_id(), wave = (int)(threadIdx.x >> 5); + const int tok0 = A.tinfo[2 * tile], npos = A.tinfo[2 * tile + 1]; + const int ns = A.n_split; + const float ninf = -__builtin_inff(); + for (int r = wave; r < npos * GQA; r += kWaves) { + const int p = r / GQA, g = r - p * GQA; + const long long base = ((long long)tile * A.kv_heads + kh) * ns * R + r; + uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs; + float m0 = ninf, m1 = ninf, l0 = 0.0f, l1 = 0.0f; + if (lane < ns) { + const float* pp = A.part + (base + (long long)lane * R) * (HD + 4); + m0 = pp[HD]; l0 = pp[HD + 1]; + } + if (lane + 32 < ns) { + const float* pp = A.part + (base + (long long)(lane + 32) * R) * (HD + 4); + m1 = pp[HD]; l1 = pp[HD + 1]; + } + const float mt = wave_max(__builtin_fmaxf(m0, m1)); + if (mt == ninf) { /* no key visible to the row: a zero row */ +#pragma unroll + for (int c = 0; c < NC; ++c) *(uint2*)(op + c * 128 + lane * 4) = make_uint2(0u, 0u); + continue; + } + const float w0 = ex2(m0 - mt), w1 = ex2(m1 - mt); /* an empty split: ex2(-inf) = 0 */ + const float lt = wave_sum(__builtin_fmaf(l0, w0, l1 * w1)); + const float inv = lt > 0.0f ? 1.0f / lt : 0.0f; + float acc[NC][4]; +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int e = 0; e < 4; ++e) acc[c][e] = 0.0f; + /* The splits that carry weight, as a 64-bit set every lane holds the same copy of, taken + * four at a time so 4 * NC loads are in flight before the first FMA waits on one. A short + * group repeats its first split at weight 0: the index is a written one, so the product is + * 0 * finite. An empty split's accumulator was never written and is never read. */ + uint64_t live = (uint64_t)__builtin_amdgcn_ballot_w32(w0 != 0.0f) | + ((uint64_t)__builtin_amdgcn_ballot_w32(w1 != 0.0f) << 32); + while (live) { + int zi[4]; + float wj[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const bool have = live != 0; + zi[j] = have ? __builtin_ctzll(live) : zi[0]; + live &= have ? live - 1 : live; + wj[j] = readlane(zi[j] < 32 ? w0 : w1, zi[j] & 31); + if (!have) wj[j] = 0.0f; + } + float4 v[4][NC]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float* pp = A.part + (base + (long long)zi[j] * R) * (HD + 4); +#pragma unroll + for (int c = 0; c < NC; ++c) v[j][c] = *(const float4*)(pp + c * 128 + lane * 4); + } +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int c = 0; c < NC; ++c) { + acc[c][0] = __builtin_fmaf(wj[j], v[j][c].x, acc[c][0]); + acc[c][1] = __builtin_fmaf(wj[j], v[j][c].y, acc[c][1]); + acc[c][2] = __builtin_fmaf(wj[j], v[j][c].z, acc[c][2]); + acc[c][3] = __builtin_fmaf(wj[j], v[j][c].w, acc[c][3]); + } + } +#pragma unroll + for (int c = 0; c < NC; ++c) + *(uint2*)(op + c * 128 + lane * 4) = + make_uint2(pack2(acc[c][0] * inv, acc[c][1] * inv), pack2(acc[c][2] * inv, acc[c][3] * inv)); + } +} + +/* ------------------------------------------------------------------ host: the launch adapter */ + +/* q and out as [rows, heads, head_dim] at whatever rank they arrived in: rank 3 (or more, leading + * axes dense), or rank 2 [rows, heads * head_dim] with its own row pitch -- a column slice of a + * fused projection. The last axis must be dense. */ +static bool head_view(const RadTensor* t, int64_t heads, int64_t hd, int64_t* rows, int64_t* rs, + int64_t* hs) { + if (t->rank >= 3) { + const uint32_t k = t->rank; + if (t->shape[k - 1] != hd || t->shape[k - 2] != heads || t->stride[k - 1] != 1) return false; + int64_t n = 1; + for (uint32_t i = 0; i + 2 < k; ++i) n *= t->shape[i]; + for (uint32_t i = 0; i + 3 < k; ++i) + if (t->shape[i] > 1 && t->stride[i] != t->stride[i + 1] * t->shape[i + 1]) return false; + *rows = n; *rs = t->stride[k - 3]; *hs = t->stride[k - 2]; + return true; + } + if (t->rank == 2) { + if (t->shape[1] != heads * hd || t->stride[1] != 1) return false; + *rows = t->shape[0]; *rs = t->stride[0]; *hs = hd; + return true; + } + if (t->rank == 1) { + if (t->shape[0] % (heads * hd)) return false; + *rows = t->shape[0] / (heads * hd); *rs = heads * hd; *hs = hd; + return true; + } + return false; +} + +template +static constexpr int64_t part_bytes() { + return (int64_t)kPartBudget * Geo::R * (HD + 4) * (int64_t)sizeof(float); +} +template +static constexpr int64_t scratch_need() { + return part_bytes() + (int64_t)kTinfoMax * 2 * (int64_t)sizeof(int); +} + +/* RADIANCE_G4K_WMMA=0 in the environment keeps every launch on the scalar kernel: an A/B switch, + * and a way out if the matrix path misbehaves on a card. Read once. */ +static bool wmma_enabled() { + static const bool on = [] { + const char* v = getenv("RADIANCE_G4K_WMMA"); + return !(v && v[0] == '0'); + }(); + return on; +} + +template +static int launch_attn(const RadArgs* a, RadStream stream) { + constexpr int R = Geo::R, BK = Geo::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2; + if (!a || a->n_t < 8) return RAD_E_INVAL; + const RadTensor* q = rad_arg_in(a, 0); + const RadTensor* kv = rad_arg_in(a, 1); + const RadTensor* bt = rad_arg_in(a, 2); + const RadTensor* su = rad_arg_in(a, 3); + const RadTensor* kd = rad_arg_in(a, 4); + const RadTensor* vd = rad_arg_in(a, 5); + const RadTensor* cu = rad_arg_in(a, 6); + const RadTensor* o = rad_arg_in(a, 7); + if (!q || !kv || !bt || !su || !o) return RAD_E_INVAL; + + if (rad_args_geti_or(a, "head_dim", HD) != HD || rad_args_geti_or(a, "gqa", GQA) != GQA || + rad_args_geti_or(a, "block_size", 16) != 16) + return RAD_E_SHAPE; + const long long causal = rad_args_geti_or(a, "causal", 1); + const long long window = rad_args_geti_or(a, "window", 0); + if ((causal != 0 && causal != 1) || window < 0 || window > (1ll << 30)) return RAD_E_SHAPE; + + if (q->dtype != RAD_BF16 || o->dtype != RAD_BF16) return RAD_E_DTYPE; + if (kv->dtype != (uint32_t)(KV8 ? RAD_F8E4M3 : RAD_BF16)) return RAD_E_DTYPE; + if (bt->dtype != RAD_I32 || su->dtype != RAD_I32 || (cu && cu->dtype != RAD_I32)) return RAD_E_DTYPE; + if ((kd && kd->dtype != RAD_F32) || (vd && vd->dtype != RAD_F32)) return RAD_E_DTYPE; + + /* the cache: [n_blocks, kv_heads, 16, 2 * head_dim], slots dense */ + if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * HD) return RAD_E_SHAPE; + if (kv->stride[3] != 1 || kv->stride[2] != 2 * HD) return RAD_E_STRIDE; + const int64_t kvh = kv->shape[1]; + if (kvh <= 0 || kvh > 65535) return RAD_E_SHAPE; + const int64_t qh = kvh * GQA; + + int64_t rows = 0, q_rs = 0, q_hs = 0, orows = 0, o_rs = 0, o_hs = 0; + if (!head_view(q, qh, HD, &rows, &q_rs, &q_hs) || !head_view(o, qh, HD, &orows, &o_rs, &o_hs)) + return RAD_E_SHAPE; + if (orows < rows) return RAD_E_SHAPE; + const int64_t n_seq = rad_tensor_numel(su); + if (rows == 0) return RAD_OK; + if (n_seq <= 0 || n_seq > (1 << 24)) return RAD_E_SHAPE; + + /* the block table: [n_seq, max_blocks] with a row pitch, or flat */ + int64_t max_blocks = 0, bt_rs = 0; + if (bt->rank >= 2) { + if (bt->stride[bt->rank - 1] != 1) return RAD_E_STRIDE; + max_blocks = bt->shape[bt->rank - 1]; + bt_rs = bt->stride[bt->rank - 2]; + if (rad_tensor_numel(bt) / max_blocks < n_seq) return RAD_E_SHAPE; + } else { + max_blocks = rad_tensor_numel(bt) / n_seq; + bt_rs = max_blocks; + } + if (max_blocks <= 0 || max_blocks > (1 << 26)) return RAD_E_SHAPE; + if ((kd && rad_tensor_numel(kd) < n_seq * kvh) || (vd && rad_tensor_numel(vd) < n_seq * kvh)) + return RAD_E_SHAPE; + + /* 8-byte query/output chunks, 16-byte cache loads */ + if (!rad_ptr_aligned(q->data, 8) || !rad_ptr_aligned(o->data, 8) || (q_rs | q_hs | o_rs | o_hs) % 4) + return RAD_E_ALIGN; + if (!rad_ptr_aligned(kv->data, 16) || (kv->stride[0] * ESZ) % 16 || (kv->stride[1] * ESZ) % 16) + return RAD_E_ALIGN; + + /* the tiles: uniform, or an upper bound over a ragged batch (empty tiles exit at once) */ + int64_t nt = 0, tps = 0, qlen_u = 0; + if (!cu) { + if (rows % n_seq) return RAD_E_SHAPE; + qlen_u = rows / n_seq; + tps = (qlen_u + BQ - 1) / BQ; + nt = n_seq * tps; + } else { + if (rad_tensor_numel(cu) != n_seq + 1) return RAD_E_SHAPE; + int64_t qmax = rad_args_geti_or(a, "q_len", rows); + if (qmax <= 0 || qmax > rows) qmax = rows; + const int64_t b1 = (rows + n_seq * (BQ - 1)) / BQ; + const int64_t b2 = n_seq * ((qmax + BQ - 1) / BQ); + nt = b1 < b2 ? b1 : b2; + } + if (nt <= 0) return RAD_OK; + if (nt > 0x7fffffff) return RAD_E_SHAPE; + + /* THE WMMA PATH, for a prefill-shaped step: the longest query at least kWmmaMinQ rows and the + * mean at least half that -- a decode or verify batch, a few rows a sequence however many + * sequences, keeps the scalar kernel and its split-KV below. 16-byte query and output rows. + * RADIANCE_G4K_WMMA=0 in the server's environment turns it off. */ + { + int64_t qmax_w = qlen_u; + if (cu) { + qmax_w = rad_args_geti_or(a, "q_len", rows); + if (qmax_w <= 0 || qmax_w > rows) qmax_w = rows; + } + const bool shaped = qmax_w >= kWmmaMinQ && rows >= n_seq * (kWmmaMinQ / 2); + const bool aligned = rad_ptr_aligned(q->data, 16) && rad_ptr_aligned(o->data, 16) && + (q_rs | q_hs | o_rs | o_hs) % 8 == 0; + if (shaped && aligned && wmma_enabled()) { + constexpr int BQW = WGeo::R / GQA; + int64_t ntw = 0, tpsw = 0; + if (!cu) { + tpsw = (qlen_u + BQW - 1) / BQW; + ntw = n_seq * tpsw; + } else { + const int64_t b1 = (rows + n_seq * (BQW - 1)) / BQW; + const int64_t b2 = n_seq * ((qmax_w + BQW - 1) / BQW); + ntw = b1 < b2 ? b1 : b2; + } + if (ntw <= 0) return RAD_OK; + if (ntw > 0x7fffffff) return RAD_E_SHAPE; + AttnArgs W{}; + W.q = (const uint16_t*)q->data; W.q_rs = q_rs; W.q_hs = q_hs; + W.kv = (const unsigned char*)kv->data; W.kv_sb = kv->stride[0]; W.kv_sh = kv->stride[1]; + W.bt = (const int*)bt->data; W.bt_rs = bt_rs; + W.seqused = (const int*)su->data; + W.cu = cu ? (const int*)cu->data : nullptr; + W.kdes = kd ? (const float*)kd->data : nullptr; + W.vdes = vd ? (const float*)vd->data : nullptr; + W.out = (uint16_t*)o->data; W.o_rs = o_rs; W.o_hs = o_hs; + const double wscale = rad_args_getf_or(a, "scale", 1.0 / __builtin_sqrt((double)HD)); + W.qscale = (float)(wscale * 1.4426950408889634); + W.max_blocks = (int)max_blocks; + W.n_seq = (int)n_seq; + W.q_len = (int)qlen_u; + W.tps = (int)tpsw; + W.kv_heads = (int)kvh; + W.causal = (int)causal; + W.window = (int)window; + W.n_split = 1; + G4K_LAUNCH(G4K_KNAME(attn_wmma_kernel), dim3((unsigned)ntw, (unsigned)kvh, 1u), + dim3(kWThreads), (hipStream_t)stream, W); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; + } + } + + /* SPLIT-KV: only where (tile, kv head) pairs are too few to fill the card */ + int64_t ns = 1; + const int64_t pairs = nt * kvh; + if (pairs < kTinfoMax) { + ns = kPartBudget / pairs; + if (ns > kMaxSplit) ns = kMaxSplit; + const int64_t span = window > 0 ? window + BQ + : rad_args_geti_or(a, "max_ctx", max_blocks * 16); + const int64_t nkt = (span + BK - 1) / BK + 1; + if (ns > nkt / 2) ns = nkt / 2; + if (ns < 1) ns = 1; + if (ns > 1 && (!a->scratch || a->scratch_bytes < scratch_need() || + !rad_ptr_aligned(a->scratch, 16))) + ns = 1; /* never wrong, only slower: the unsplit kernel writes the rows itself */ + } + + AttnArgs A{}; + A.q = (const uint16_t*)q->data; A.q_rs = q_rs; A.q_hs = q_hs; + A.kv = (const unsigned char*)kv->data; A.kv_sb = kv->stride[0]; A.kv_sh = kv->stride[1]; + A.bt = (const int*)bt->data; A.bt_rs = bt_rs; + A.seqused = (const int*)su->data; + A.cu = cu ? (const int*)cu->data : nullptr; + A.kdes = kd ? (const float*)kd->data : nullptr; + A.vdes = vd ? (const float*)vd->data : nullptr; + A.out = (uint16_t*)o->data; A.o_rs = o_rs; A.o_hs = o_hs; + A.part = ns > 1 ? (float*)a->scratch : nullptr; + A.tinfo = ns > 1 ? (int*)((char*)a->scratch + part_bytes()) : nullptr; + const double scale = rad_args_getf_or(a, "scale", 1.0 / __builtin_sqrt((double)HD)); + A.qscale = (float)(scale * 1.4426950408889634); + A.max_blocks = (int)max_blocks; + A.n_seq = (int)n_seq; + A.q_len = (int)qlen_u; + A.tps = (int)tps; + A.kv_heads = (int)kvh; + A.causal = (int)causal; + A.window = (int)window; + A.n_split = (int)ns; + + hipStream_t s = (hipStream_t)stream; + G4K_LAUNCH(G4K_KNAME(attn_kernel), dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), + dim3(kThreads), s, A); + if (ns > 1) + G4K_LAUNCH(G4K_KNAME(merge_kernel), dim3((unsigned)nt, (unsigned)kvh), dim3(kThreads), + s, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* namespace g4k */ + +/* ------------------------------------------------------------------ the exported entry points */ +extern "C" { + +#define G4K_ATTN_DEF(HD, G) \ + int g4k_attn_h##HD##_gqa##G##_bf16kv(const RadArgs* a, RadStream s) { \ + return g4k::launch_attn(a, s); \ + } \ + int g4k_attn_h##HD##_gqa##G##_fp8kv(const RadArgs* a, RadStream s) { \ + return g4k::launch_attn(a, s); \ + } +G4K_ATTN_DEF(256, 1) G4K_ATTN_DEF(256, 2) G4K_ATTN_DEF(256, 4) G4K_ATTN_DEF(256, 8) +G4K_ATTN_DEF(512, 1) G4K_ATTN_DEF(512, 2) G4K_ATTN_DEF(512, 4) G4K_ATTN_DEF(512, 8) +#undef G4K_ATTN_DEF + +/* Called at declare with the band's bound and no tensors: the split-KV partials are capped at + * kPartBudget (tile, head, split) triples whatever the batch, so the answer is a constant. */ +int64_t g4k_attn_h256_scratch(const RadArgs*) { return g4k::scratch_need<256>(); } +int64_t g4k_attn_h512_scratch(const RadArgs*) { return g4k::scratch_need<512>(); } + +} /* extern "C" */ diff --git a/gemma4k/g4k_launch.h b/gemma4k/g4k_launch.h new file mode 100644 index 00000000..44d8bddd --- /dev/null +++ b/gemma4k/g4k_launch.h @@ -0,0 +1,14 @@ +/* g4k_launch.h -- the one spelling of a kernel launch in gemma4k's device units. + * + * A template kernel's name carries commas, so it goes through G4K_KNAME the way HIP_KERNEL_NAME + * exists for hipLaunchKernelGGL. G4K_LAUNCH is overridable so the same sources can be driven by a + * host-side SIMT emulator in a test -- the kernels are ordinary C++ once the HIP names are + * supplied. A build never defines it, and gets the triple-chevron launch, which the engine answers + * through hipLaunchKernel on its own queues (docs/PLUGIN.md §5). */ +#ifndef G4K_LAUNCH_H +#define G4K_LAUNCH_H +#define G4K_KNAME(...) __VA_ARGS__ +#ifndef G4K_LAUNCH +#define G4K_LAUNCH(kernel, grid, block, stream, ...) kernel<<>>(__VA_ARGS__) +#endif +#endif diff --git a/gemma4k/g4k_norm.hip b/gemma4k/g4k_norm.hip new file mode 100644 index 00000000..dea63fd4 --- /dev/null +++ b/gemma4k/g4k_norm.hip @@ -0,0 +1,252 @@ +/* g4k_norm.hip -- Gemma 4's sandwich-norm joins, each one kernel instead of a chain of small ones. + * + * A decode step of the 26B-A4B launches ~250 rmsnorms and ~90 adds a step, each a few hundred + * bytes of work behind a full launch: --profile-ops measured 2.0 ms and 0.85 ms of a 16.6 ms step. + * Two places in every layer are pure chains of them: + * + * norm_add_norm the attention's join: t = norm(a) * w_a; x += t; y = norm(x) * w_y + * (post_attention_layernorm, the residual add, pre_feedforward_layernorm) + * join_add_scale the feed-forward's: d' = norm(d) * w_d; r' = norm(r) * w_r; + * j = norm(d' + r') * w_j; x = (x + j) * s + * (post_feedforward_layernorm_1 and _2, the arms' sum, post_feedforward_layernorm, + * the residual add, layer_scalar) + * + * THE SAME FUNCTION AS THE CHAIN, ROUNDING FOR ROUNDING. Every value the chain stores as bf16 is + * rounded to bf16 here at the same point, and every element is computed with libr4d's own + * expression: a norm is bf16((v * rsqrtf(mean(v^2) + eps)) * g), an add bf16(u + v), a scale + * bf16(x * s). The one thing that can differ is the ORDER the sum of squares is added in -- libr4d + * picks its block width from a measured table -- which moves the f32 norm factor by an ulp at most + * and, rarely, a bf16 output by one ulp. The arch plugin asks for these first and falls back to + * the chain where nothing serves them (gemma4.cpp). + * + * One 256-thread block a row: a decode step is a handful of rows, so the row is latency-bound and + * a block's three reductions beat seven launches. Values a later stage reuses stay in registers + * (kMaxPer a thread, so n <= 256 * kMaxPer; the row table says so). + */ +#include + +#include + +#include "g4k.h" +#include "g4k_launch.h" +#include "rad_plugin.h" + +namespace g4kn { + +constexpr int kThreads = 256; +constexpr int kWaves = kThreads / 32; +constexpr int kMaxPer = 24; /* elements a thread holds: n <= 6144 */ + +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((unsigned)h << 16); } +/* round to nearest even, as libr4d's f32_to_bf16 */ +__device__ __forceinline__ uint16_t f2bf(float f) { + const unsigned u = __float_as_uint(f); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} +__device__ __forceinline__ float rbf(float f) { return bf2f(f2bf(f)); } +__device__ __forceinline__ int lane_id() { return (int)(threadIdx.x & 31u); } +__device__ __forceinline__ float shfl_xor(float v, int m) { + return __int_as_float(__builtin_amdgcn_ds_bpermute((lane_id() ^ m) << 2, __float_as_int(v))); +} +/* the block's sum, every thread the same value: a wave butterfly, then the waves in order */ +__device__ __forceinline__ float block_sum(float v, float* lds) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) v += shfl_xor(v, d); + const int lane = lane_id(), wave = (int)(threadIdx.x >> 5); + __syncthreads(); /* lds is free: the last read of it is done */ + if (lane == 0) lds[wave] = v; + __syncthreads(); + float s = 0.0f; +#pragma unroll + for (int w = 0; w < kWaves; ++w) s += lds[w]; + return s; +} +__device__ __forceinline__ float norm_factor(float ss, int n, float eps) { + return rsqrtf(ss / (float)n + eps); +} + +struct NormArgs { + const uint16_t* a; long long a_ld; /* norm_add_norm: the block output */ + const uint16_t* d; long long d_ld; /* join_add_scale: the dense partial */ + const uint16_t* r; long long r_ld; /* the routed partial */ + uint16_t* x; long long x_ld; /* the residual stream, read and written */ + uint16_t* y; long long y_ld; /* norm_add_norm: the next norm's output */ + const float* w0; /* w_a, or w_d */ + const float* w1; /* w_y, or w_r */ + const float* w2; /* w_j */ + const uint16_t* s; /* the layer scalar, bf16, one element */ + int n; + float eps; +}; + +/* t = norm(a) * w_a; x += t; y = norm(x) * w_y */ +__global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { + __shared__ float lds[kWaves]; + const int tid = (int)threadIdx.x, n = A.n; + const long long m = (long long)blockIdx.x; + const uint16_t* ar = A.a + m * A.a_ld; + uint16_t* xr = A.x + m * A.x_ld; + uint16_t* yr = A.y + m * A.y_ld; + + float av[kMaxPer], xv[kMaxPer]; + float ss = 0.0f; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + av[k] = i < n ? bf2f(ar[i]) : 0.0f; + ss += av[k] * av[k]; + } + const float sa = norm_factor(block_sum(ss, lds), n, A.eps); + ss = 0.0f; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + const float t = rbf((av[k] * sa) * A.w0[i]); + xv[k] = rbf(bf2f(xr[i]) + t); + xr[i] = f2bf(xv[k]); + } else { + xv[k] = 0.0f; + } + ss += xv[k] * xv[k]; + } + const float sx = norm_factor(block_sum(ss, lds), n, A.eps); +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) yr[i] = f2bf((xv[k] * sx) * A.w1[i]); + } +} + +/* x = (x + norm(norm(d) * w_d + norm(r) * w_r) * w_j) * s */ +__global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { + __shared__ float lds[kWaves]; + const int tid = (int)threadIdx.x, n = A.n; + const long long m = (long long)blockIdx.x; + const uint16_t* dr = A.d + m * A.d_ld; + const uint16_t* rr = A.r + m * A.r_ld; + uint16_t* xr = A.x + m * A.x_ld; + + float dv[kMaxPer], rv[kMaxPer]; + float sd2 = 0.0f, sr2 = 0.0f; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + dv[k] = i < n ? bf2f(dr[i]) : 0.0f; + rv[k] = i < n ? bf2f(rr[i]) : 0.0f; + sd2 += dv[k] * dv[k]; + sr2 += rv[k] * rv[k]; + } + const float sd = norm_factor(block_sum(sd2, lds), n, A.eps); + const float sr = norm_factor(block_sum(sr2, lds), n, A.eps); + /* the join, kept in dv */ + float ss = 0.0f; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + const float u = rbf((dv[k] * sd) * A.w0[i]); + const float v = rbf((rv[k] * sr) * A.w1[i]); + dv[k] = rbf(u + v); + } else { + dv[k] = 0.0f; + } + ss += dv[k] * dv[k]; + } + const float sj = norm_factor(block_sum(ss, lds), n, A.eps); + const float sc = bf2f(*A.s); +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + const float j = rbf((dv[k] * sj) * A.w2[i]); + const float x1 = rbf(bf2f(xr[i]) + j); + xr[i] = f2bf(x1 * sc); + } + } +} + +/* ------------------------------------------------------------------ host: the launch adapters */ + +/* [rows..., n] with a dense last axis: its row count and pitch, or false */ +static bool rows_of(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != RAD_BF16 || t->rank < 1) return false; + if (rad_tensor_lastdim(t) != n || (t->stride[t->rank - 1] != 1)) return false; + *rows = rad_tensor_rows(t); + *ld = rad_tensor_row_pitch(t); + return *ld >= n || *rows <= 1; +} +static bool gain(const RadTensor* w, int64_t n) { + return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n && + (w->rank == 0 || w->stride[w->rank - 1] == 1); +} + +static int params(const RadArgs* a, int64_t* n, float* eps) { + *n = rad_args_geti_or(a, "n", 0); + *eps = (float)rad_args_getf_or(a, "eps", 1e-6); + if (*n <= 0 || *n > (int64_t)kThreads * kMaxPer) return RAD_E_SHAPE; + return RAD_OK; +} + +} /* namespace g4kn */ + +extern "C" { + +/* operands: a, w_a, x (inout), w_y, y */ +int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream stream) { + using namespace g4kn; + if (!a || a->n_t < 5) return RAD_E_INVAL; + int64_t n = 0; + float eps = 0.0f; + if (int rc = params(a, &n, &eps)) return rc; + const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), + *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4); + if (!A_ || !X || !Y) return RAD_E_INVAL; + if (!gain(Wa, n) || !gain(Wy, n)) return RAD_E_DTYPE; + int64_t ra = 0, la = 0, rx = 0, lx = 0, ry = 0, ly = 0; + if (!rows_of(A_, n, &ra, &la) || !rows_of(X, n, &rx, &lx) || !rows_of(Y, n, &ry, &ly)) + return RAD_E_SHAPE; + const int64_t M = rx; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (ra < M || ry < M || M > 0x7fffffff) return RAD_E_SHAPE; + NormArgs P{}; + P.a = (const uint16_t*)A_->data; P.a_ld = la; + P.x = (uint16_t*)X->data; P.x_ld = lx; + P.y = (uint16_t*)Y->data; P.y_ld = ly; + P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data; + P.n = (int)n; P.eps = eps; + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +/* operands: d, w_d, r, w_r, w_j, x (inout), s */ +int g4k_join_add_scale_bf16(const RadArgs* a, RadStream stream) { + using namespace g4kn; + if (!a || a->n_t < 7) return RAD_E_INVAL; + int64_t n = 0; + float eps = 0.0f; + if (int rc = params(a, &n, &eps)) return rc; + const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2), + *Wr = rad_arg_in(a, 3), *Wj = rad_arg_in(a, 4), *X = rad_arg_in(a, 5), + *Sc = rad_arg_in(a, 6); + if (!D || !R || !X || !Sc) return RAD_E_INVAL; + if (!gain(Wd, n) || !gain(Wr, n) || !gain(Wj, n)) return RAD_E_DTYPE; + if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE; + int64_t rd = 0, ld = 0, rr = 0, lr = 0, rx = 0, lx = 0; + if (!rows_of(D, n, &rd, &ld) || !rows_of(R, n, &rr, &lr) || !rows_of(X, n, &rx, &lx)) + return RAD_E_SHAPE; + const int64_t M = rx; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (rd < M || rr < M || M > 0x7fffffff) return RAD_E_SHAPE; + NormArgs P{}; + P.d = (const uint16_t*)D->data; P.d_ld = ld; + P.r = (const uint16_t*)R->data; P.r_ld = lr; + P.x = (uint16_t*)X->data; P.x_ld = lx; + P.w0 = (const float*)Wd->data; P.w1 = (const float*)Wr->data; P.w2 = (const float*)Wj->data; + P.s = (const uint16_t*)Sc->data; + P.n = (int)n; P.eps = eps; + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* extern "C" */ diff --git a/gemma4k/g4k_pick.hip b/gemma4k/g4k_pick.hip new file mode 100644 index 00000000..fff46f3d --- /dev/null +++ b/gemma4k/g4k_pick.hip @@ -0,0 +1,105 @@ +/* g4k_pick.hip -- pair_argmax: the global argmax of a row of gathered (id, value) pairs, written as + * ONE CONTIGUOUS COLUMN of token ids. + * + * WHY THIS OP EXISTS. A vocab-sharded draft head finds each rank's best candidates with `row_topk` + * and moves them with `all_gather`. The gather moves whole 16-byte words a row, and one (int32 id, + * f32 value) pair is 8 bytes, so a rank contributes at least R = 2 (rad_block_mtp_hc.h states the + * same bound). `row_topk_merge` then returns R = 2 columns a row, and a BLOCK drafter's proposal + * is `steps` contiguous ids a sequence -- column 0 of an [S, 2] plane is not that, and nothing in + * libr4d copies a strided i32 column. This reduces the gathered row to its top-1 and writes it + * where the proposal reads it. + * + * It is row_topk_merge at R = 1 with a strided output, rule for rule: the largest value wins, a tie + * goes to the LOWER id, and a pair whose id is negative (a slot a shard could not fill) is skipped. + * A row with no valid pair writes id -1 and value -inf. One wave a row, eight rows a workgroup. + */ +#include + +#include + +#include "g4k.h" +#include "g4k_launch.h" +#include "rad_plugin.h" + +namespace g4k { + +struct PickArgs { + const float* pairs; long long p_rs; /* [M, n, 2]: int32 id bits, then f32 value */ + int* tok; long long t_rs; + float* val; long long v_rs; /* optional */ + long long rows; + int n; +}; + +__device__ __forceinline__ int pk_lane() { return (int)(threadIdx.x & 31u); } +__device__ __forceinline__ int pk_xor_i(int v, int m) { + return __builtin_amdgcn_ds_bpermute((pk_lane() ^ m) << 2, v); +} +__device__ __forceinline__ float pk_xor_f(float v, int m) { + return __int_as_float(pk_xor_i(__float_as_int(v), m)); +} +/* (v, id) beats (bv, bid)? Larger value, then lower id; an invalid id (< 0) never wins. */ +__device__ __forceinline__ bool pk_better(float v, int id, float bv, int bid) { + if (id < 0) return false; + if (bid < 0) return true; + return v > bv || (v == bv && id < bid); +} + +__global__ __launch_bounds__(256) void pick_kernel(PickArgs A) { + const long long r = (long long)blockIdx.x * 8 + (threadIdx.x >> 5); + if (r >= A.rows) return; /* uniform across the wave */ + const int lane = pk_lane(); + const float* row = A.pairs + r * A.p_rs; + float bv = -__builtin_inff(); + int bid = -1; + for (int j = lane; j < A.n; j += 32) { + const int id = __float_as_int(row[2 * j]); + const float v = row[2 * j + 1]; + if (pk_better(v, id, bv, bid)) { bv = v; bid = id; } + } +#pragma unroll + for (int m = 16; m >= 1; m >>= 1) { + const float ov = pk_xor_f(bv, m); + const int oid = pk_xor_i(bid, m); + if (pk_better(ov, oid, bv, bid)) { bv = ov; bid = oid; } + } + if (lane == 0) { + A.tok[r * A.t_rs] = bid; + if (A.val) A.val[r * A.v_rs] = bv; + } +} + +} /* namespace g4k */ + +/* pairs as [M, n, 2] (rank 3) or [M, 2n] (rank 2), last axes dense; the outputs one element a row + * at their own row pitch. */ +extern "C" int g4k_pair_argmax_f32(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const RadTensor* p = rad_arg_in(a, 0); + const RadTensor* t = rad_arg_in(a, 1); + const RadTensor* v = rad_arg_in(a, 2); + if (!p || !t) return RAD_E_INVAL; + if (p->dtype != RAD_F32 || t->dtype != RAD_I32 || (v && v->dtype != RAD_F32)) return RAD_E_DTYPE; + const long long n = rad_args_geti_or(a, "n", 0); + if (n <= 0 || p->rank < 2) return RAD_E_SHAPE; + if (p->rank == 3) { + if (p->shape[1] < n || p->shape[2] != 2 || p->stride[2] != 1 || p->stride[1] != 2) return RAD_E_SHAPE; + } else if (p->rank == 2) { + if (p->shape[1] < 2 * n || p->stride[1] != 1) return RAD_E_SHAPE; + } else { + return RAD_E_SHAPE; + } + const int64_t rows = p->shape[0]; + if (rows == 0) return RAD_OK; + if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE; + g4k::PickArgs A{}; + A.pairs = (const float*)p->data; A.p_rs = p->stride[0]; + A.tok = (int*)t->data; A.t_rs = t->rank >= 2 ? t->stride[0] : 1; + A.val = v ? (float*)v->data : nullptr; + A.v_rs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0; + A.rows = rows; + A.n = (int)n; + G4K_LAUNCH(G4K_KNAME(g4k::pick_kernel), dim3((unsigned)((rows + 7) / 8)), dim3(256), + (hipStream_t)stream, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} diff --git a/gemma4k/g4k_rows.cpp b/gemma4k/g4k_rows.cpp new file mode 100644 index 00000000..7376d9e6 --- /dev/null +++ b/gemma4k/g4k_rows.cpp @@ -0,0 +1,436 @@ +/* g4k_rows.cpp -- gemma4k's row table, the op schemas it defines, and the host arms of those ops. + * + * gemma4k is the kernel library for Gemma 4's text model beyond what libr4d serves it with: + * + * attn_paged at head_dim 256 and 512, gqa 1/2/4/8, ANY window, causal or not, bf16 or fp8 cache. + * Gemma 4's sliding layers are h256/gqa2 with a 1024-token window and its full layers h512 at + * gqa 8 (TP1/TP2), 4 (TP4) or 2 (TP8). + * pair_argmax: the top-1 of a row of all-gathered (id, value) pairs, one i32 a row -- the + * vocab-sharded DFlash head's merge, which needs R >= 2 on the wire (16-byte gather rows) and a + * contiguous proposal out (g4k_pick.hip says why). libref declares it too, and is its oracle. + * norm_add_norm and join_add_scale, ops this library DEFINES: Gemma 4's two sandwich-norm joins, + * each one kernel in place of a chain of rmsnorm / add / mul_weight launches, rounding where the + * chain rounds (g4k_norm.hip). The arch plugin asks for them and falls back to the chain. + * + * Put it AHEAD of libr4d for Gemma 4 (`--kernels gemma4k,libr4d,...`). The hierarchy is absolute, + * and libr4d has rows at h256/gqa2 and h512/gqa8 too -- written for the dense 31B, which has no + * drafter, and not measured on the 26B-A4B or under a DFlash verify. These rows are the ones every + * Gemma 4 number in this tree was measured with. Every other row here is the only one in the tree + * for its geometry, so the order changes nothing else: libr4d keeps the drafter's h128/gqa4 + * attention, say. (Gemma's final logit softcap is libr4d's and libavx's `logit_softcap`; this + * library has no row for it.) + * + * Pure host code: no HIP header. The entry points it names are in g4k_attn.hip, g4k_pick.hip and + * g4k_norm.hip. + */ +#include "g4k.h" +#include "rad_plugin.h" + +#include +#include +#include + +#ifndef G4K_BUILD_TARGET +#define G4K_BUILD_TARGET "gfx12" +#endif + +#define ROW(a) (a), (int)(sizeof(a) / sizeof((a)[0])) +#define NOTUNE nullptr, 0, nullptr +#define C_EQ(k, v) { (k), RAD_C_EQ, (long long)(v), nullptr } +#define C_GE(k, v) { (k), RAD_C_GE, (long long)(v), nullptr } +#define C_LE(k, v) { (k), RAD_C_LE, (long long)(v), nullptr } +#define C_IN(k, s) { (k), RAD_C_IN, 0, (s) } + +namespace { + +/* ==================================================================== the ops this library declares + * + * pair_argmax is libref's schema restated field for field (the first declarer in a hierarchy fixes + * it, and libref is in every hierarchy). The two joins are this library's own: libref has no row + * for them ON PURPOSE, because a reference row would resolve them wherever gemma4k is not loaded, + * and the architecture's fallback to the rmsnorm / add / mul_weight chain -- which libr4d and + * libavx serve -- would never be taken. docs/OPS.md carries all three rows, which is what the + * ops_doc test holds them to. */ +static const RadParamSpec pPick[] = { + { "M", RAD_P_INT, RAD_REQUIRED, 0 }, + { "n", RAD_P_INT, RAD_REQUIRED, 0 }, + { "dtype", RAD_P_STR, RAD_REQUIRED, 0 }, +}; +static const RadOperandSpec oPick[] = { + { "pairs", RAD_OPD_IN, 0 }, + { "idx", RAD_OPD_OUT, 0 }, + { "val", RAD_OPD_OUT, 1 }, +}; +static const RadParamSpec pJoin[] = { + { "M", RAD_P_INT, RAD_REQUIRED, 0 }, + { "n", RAD_P_INT, RAD_REQUIRED, 0 }, + { "eps", RAD_P_F64, RAD_REQUIRED, 0 }, + { "dtype", RAD_P_STR, RAD_REQUIRED, 0 }, +}; +static const RadOperandSpec oNan[] = { + { "a", RAD_OPD_IN, 0 }, + { "w_a", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_INOUT, 0 }, + { "w_y", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec oJas[] = { + { "d", RAD_OPD_IN, 0 }, + { "w_d", RAD_OPD_WEIGHT, 0 }, + { "r", RAD_OPD_IN, 0 }, + { "w_r", RAD_OPD_WEIGHT, 0 }, + { "w_j", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_INOUT, 0 }, + { "s", RAD_OPD_WEIGHT, 0 }, +}; +static const RadOpSchema kSchemas[] = { + { "pair_argmax", ROW(pPick), ROW(oPick), + "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in the first " + "f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties to the lower " + "id, a negative id skipped, -1 and -inf where nothing is valid. row_topk_merge at R = 1, " + "written one element a row at the output's own pitch." }, + { "norm_add_norm", ROW(pJoin), ROW(oNan), + "t = rmsnorm(a) * w_a; x = x + t; y = rmsnorm(x) * w_y, over [M, n] rows; every value the " + "unfused rmsnorm, add, rmsnorm chain stores is rounded to the activation dtype at the same " + "point. A post-norm, the residual add and the next pre-norm (Gemma's sandwich)." }, + { "join_add_scale", ROW(pJoin), ROW(oJas), + "x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s, over [M, n] rows, s one " + "element; rounding where the unfused chain rounds. Two arms' post-norms, their sum, its norm, " + "the residual add and a per-layer scalar (Gemma 4's feed-forward join)." }, +}; + +/* ==================================================================== operand descriptions + * + * So rad-kbench can call these kernels cold and check them against libref (docs/PLUGIN.md §9). + * attn_paged's is libr4d's (r4d_shapes.cpp) restated: ONE sequence whose context is its query, or + * `ctx` deep when a sweep sets it. */ +RadOpdDesc opd(uint32_t dt, int64_t d0, int64_t d1 = 0, int64_t d2 = 0, int64_t d3 = 0) { + RadOpdDesc d{}; + d.dtype = dt; + d.fill = RAD_FILL_NORMAL; + d.idx_const = -1; + const int64_t e[4] = { d0, d1, d2, d3 }; + for (int i = 0; i < 4 && e[i] != 0; ++i) d.shape[d.rank++] = e[i]; + return d; +} +RadOpdDesc opd_idx(int64_t d0, int64_t d1, int64_t idx_max, int64_t konst = -1) { + RadOpdDesc d = opd((uint32_t)RAD_I32, d0, d1); + d.fill = RAD_FILL_INDEX; + d.idx_max = idx_max; + d.idx_const = konst; + return d; +} +RadOpdDesc opd_none() { + RadOpdDesc d{}; + d.idx_const = -1; + d.flags = RAD_OPD_F_ABSENT; + return d; +} +int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) { + if (!out || !list) return RAD_E_INVAL; + for (int i = 0; i < n; ++i) { + if (list[i].flags & RAD_OPD_F_ABSENT) continue; + if (list[i].rank == 0) return RAD_E_UNSUPPORTED; + for (uint32_t d = 0; d < list[i].rank; ++d) + if (list[i].shape[d] <= 0) return RAD_E_UNSUPPORTED; + } + if (operand < 0 || operand >= n) return RAD_E_SHAPE; + *out = list[operand]; + return RAD_OK; +} +#define PICK(l) return pick(out, operand, (l), (int)(sizeof(l) / sizeof((l)[0]))) +int64_t pi(const RadParam* p, int n_p, const char* k, int64_t dflt = 0) { + return (int64_t)rad_param_getdim(p, n_p, k, (long long)dflt); +} +uint32_t dt_act(const RadParam* p, int n_p, const char* k) { + const uint32_t d = rad_param_getdt(p, n_p, k); + return d == RAD_DT_INVALID ? (uint32_t)RAD_BF16 : d; +} + +int shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t q_len = pi(p, n_p, "q_len"), hd = pi(p, n_p, "head_dim"); + const int64_t gqa = pi(p, n_p, "gqa"), bs = pi(p, n_p, "block_size", 16), nh = pi(p, n_p, "n_head"); + if (q_len <= 0 || hd <= 0 || gqa <= 0 || bs <= 0 || nh <= 0 || nh % gqa) return RAD_E_UNSUPPORTED; + int64_t ctx = pi(p, n_p, "ctx", 0); + if (ctx < q_len) ctx = q_len; + const int64_t nblk = (ctx + bs - 1) / bs; + const uint32_t Q = dt_act(p, n_p, "q_dtype"), KV = dt_act(p, n_p, "kv_dtype"); + const RadOpdDesc l[] = { + opd(Q, q_len, nh, hd), + opd(KV, nblk, nh / gqa, bs, 2 * hd), + opd_idx(1, nblk, nblk), + opd_idx(1, 0, 0, ctx), + opd_none(), + opd_none(), + opd_none(), + opd(Q, q_len, nh, hd), + }; + PICK(l); +} + +/* pair_argmax as libref describes it (ref_shapes.cpp): the gathered plane is f32, so the value + * lane draws proper floats and the id lane their bit patterns -- negative ones pads, positive ones + * legal ids -- and ties do not occur. */ +int shape_pick(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd((uint32_t)RAD_F32, M, n, 2), + opd((uint32_t)RAD_I32, M), + opd((uint32_t)RAD_F32, M), + }; + PICK(l); +} + +/* The host arm of pair_argmax, the device kernel's rules in plain C++. Not libref's row: that one + * is a reference, which the engine refuses to serve, and this op has no chain to fall back to. */ +int pick_host(const RadArgs* a, RadStream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const RadTensor* p = rad_arg_in(a, 0); + const RadTensor* t = rad_arg_in(a, 1); + const RadTensor* v = rad_arg_in(a, 2); + if (!p || !t) return RAD_E_INVAL; + if (p->dtype != RAD_F32 || t->dtype != RAD_I32 || (v && v->dtype != RAD_F32)) return RAD_E_DTYPE; + const long long n = rad_args_geti_or(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + if (p->rank == 3) { + if (p->shape[1] < n || p->shape[2] != 2 || p->stride[2] != 1 || p->stride[1] != 2) return RAD_E_SHAPE; + } else if (p->rank == 2) { + if (p->shape[1] < 2 * n || p->stride[1] != 1) return RAD_E_SHAPE; + } else { + return RAD_E_SHAPE; + } + const int64_t rows = p->shape[0]; + if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE; + const int64_t prs = p->stride[0], trs = t->rank >= 2 ? t->stride[0] : 1; + const int64_t vrs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0; + for (int64_t r = 0; r < rows; ++r) { + const float* row = (const float*)p->data + r * prs; + int32_t bid = -1; + float bv = -INFINITY; + for (long long j = 0; j < n; ++j) { + int32_t id; + std::memcpy(&id, &row[2 * j], 4); + const float val = row[2 * j + 1]; + if (id < 0) continue; + if (bid < 0 || val > bv || (val == bv && id < bid)) { bid = id; bv = val; } + } + ((int32_t*)t->data)[r * trs] = bid; + if (v) ((float*)v->data)[r * vrs] = bv; + } + return RAD_OK; +} + +/* ==================================================================== the host arms of the joins + * + * The device kernels' arithmetic in plain C++: each value the unfused chain stores is rounded to + * bf16 where it stores it. Summed in index order, so a ULP from the device's block order. */ +static float hb2f(uint16_t h) { const uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; } +static uint16_t hf2b(float f) { + uint32_t u; std::memcpy(&u, &f, 4); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} +static float hrbf(float f) { return hb2f(hf2b(f)); } +static float hnorm(const float* v, int64_t n, double eps) { + float ss = 0.0f; + for (int64_t i = 0; i < n; ++i) ss += v[i] * v[i]; + return 1.0f / std::sqrt(ss / (float)n + (float)eps); +} +static bool hrows(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != RAD_BF16 || t->rank < 1 || rad_tensor_lastdim(t) != n) return false; + if (t->stride[t->rank - 1] != 1) return false; + *rows = rad_tensor_rows(t); + *ld = rad_tensor_row_pitch(t); + return true; +} +static bool hgain(const RadTensor* w, int64_t n) { + return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n; +} + +int norm_add_norm_host(const RadArgs* a, RadStream) { + if (!a || a->n_t < 5) return RAD_E_INVAL; + const int64_t n = rad_args_geti_or(a, "n", 0); + const double eps = rad_args_getf_or(a, "eps", 1e-6); + const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), + *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4); + if (n <= 0 || !A_ || !X || !Y) return RAD_E_INVAL; + if (!hgain(Wa, n) || !hgain(Wy, n)) return RAD_E_DTYPE; + int64_t ra, la, rx, lx, ry, ly; + if (!hrows(A_, n, &ra, &la) || !hrows(X, n, &rx, &lx) || !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE; + if (ra < rx || ry < rx) return RAD_E_SHAPE; + const float *wa = (const float*)Wa->data, *wy = (const float*)Wy->data; + std::vector v((size_t)n), xv((size_t)n); + for (int64_t m = 0; m < rx; ++m) { + const uint16_t* ar = (const uint16_t*)A_->data + m * la; + uint16_t* xr = (uint16_t*)X->data + m * lx; + uint16_t* yr = (uint16_t*)Y->data + m * ly; + for (int64_t i = 0; i < n; ++i) v[(size_t)i] = hb2f(ar[i]); + const float sa = hnorm(v.data(), n, eps); + for (int64_t i = 0; i < n; ++i) { + const float t = hrbf((v[(size_t)i] * sa) * wa[i]); + xv[(size_t)i] = hrbf(hb2f(xr[i]) + t); + xr[i] = hf2b(xv[(size_t)i]); + } + const float sx = hnorm(xv.data(), n, eps); + for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((xv[(size_t)i] * sx) * wy[i]); + } + return RAD_OK; +} + +int join_add_scale_host(const RadArgs* a, RadStream) { + if (!a || a->n_t < 7) return RAD_E_INVAL; + const int64_t n = rad_args_geti_or(a, "n", 0); + const double eps = rad_args_getf_or(a, "eps", 1e-6); + const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2), + *Wr = rad_arg_in(a, 3), *Wj = rad_arg_in(a, 4), *X = rad_arg_in(a, 5), + *Sc = rad_arg_in(a, 6); + if (n <= 0 || !D || !R || !X || !Sc) return RAD_E_INVAL; + if (!hgain(Wd, n) || !hgain(Wr, n) || !hgain(Wj, n)) return RAD_E_DTYPE; + if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE; + int64_t rd, ld, rr, lr, rx, lx; + if (!hrows(D, n, &rd, &ld) || !hrows(R, n, &rr, &lr) || !hrows(X, n, &rx, &lx)) return RAD_E_SHAPE; + if (rd < rx || rr < rx) return RAD_E_SHAPE; + const float *wd = (const float*)Wd->data, *wr = (const float*)Wr->data, *wj = (const float*)Wj->data; + const float sc = hb2f(*(const uint16_t*)Sc->data); + std::vector dv((size_t)n), rv((size_t)n); + for (int64_t m = 0; m < rx; ++m) { + const uint16_t* dr = (const uint16_t*)D->data + m * ld; + const uint16_t* rrw = (const uint16_t*)R->data + m * lr; + uint16_t* xr = (uint16_t*)X->data + m * lx; + for (int64_t i = 0; i < n; ++i) { dv[(size_t)i] = hb2f(dr[i]); rv[(size_t)i] = hb2f(rrw[i]); } + const float sd = hnorm(dv.data(), n, eps), sr = hnorm(rv.data(), n, eps); + for (int64_t i = 0; i < n; ++i) + dv[(size_t)i] = hrbf(hrbf((dv[(size_t)i] * sd) * wd[i]) + hrbf((rv[(size_t)i] * sr) * wr[i])); + const float sj = hnorm(dv.data(), n, eps); + for (int64_t i = 0; i < n; ++i) { + const float x1 = hrbf(hb2f(xr[i]) + hrbf((dv[(size_t)i] * sj) * wj[i])); + xr[i] = hf2b(x1 * sc); + } + } + return RAD_OK; +} + +/* ==================================================================== constraints + * + * The attention rows serve their (head_dim, gqa) at ANY q_len -- one kernel does decode, verify and + * prefill, splitting the key range when there are too few tiles to fill the card -- so `q_len` + * carries no constraint and cuts no band. `causal` and `window` are runtime fields of the kernel. + * block_size is the kernel's (RAD_DERIVED): 16. + * + * TWO ROWS HERE OVERLAP libr4d's ON PURPOSE: h256/gqa2 (any window) and h512/gqa8, Gemma 4's own + * geometries, which this library serves ahead of libr4d (see the top of this file). Nothing else + * overlaps, so putting this library first cannot take one of libr4d's other geometries: libr4d + * serves h256 at gqa 4/6/8/12 with window 0, so the h256 gqa4 and gqa8 rows below take a window + * only (C_GE 1), and gqa 1 and h512 at gqa 1/2/4, which libr4d does not compile, take anything. */ +#define G4K_ATTN_C(NAME, HD, G, KV, WMIN) \ + static const RadConstraint NAME[] = { \ + C_EQ("head_dim", HD), C_EQ("gqa", G), C_EQ("block_size", 16), C_GE("causal", 0), \ + C_GE("window", WMIN), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", KV), \ + }; +G4K_ATTN_C(cH256x1B, 256, 1, "bf16", 0) G4K_ATTN_C(cH256x1F, 256, 1, "fp8_e4m3", 0) +G4K_ATTN_C(cH256x2B, 256, 2, "bf16", 0) G4K_ATTN_C(cH256x2F, 256, 2, "fp8_e4m3", 0) +G4K_ATTN_C(cH256x4B, 256, 4, "bf16", 1) G4K_ATTN_C(cH256x4F, 256, 4, "fp8_e4m3", 1) +G4K_ATTN_C(cH256x8B, 256, 8, "bf16", 1) G4K_ATTN_C(cH256x8F, 256, 8, "fp8_e4m3", 1) +G4K_ATTN_C(cH512x1B, 512, 1, "bf16", 0) G4K_ATTN_C(cH512x1F, 512, 1, "fp8_e4m3", 0) +G4K_ATTN_C(cH512x2B, 512, 2, "bf16", 0) G4K_ATTN_C(cH512x2F, 512, 2, "fp8_e4m3", 0) +G4K_ATTN_C(cH512x4B, 512, 4, "bf16", 0) G4K_ATTN_C(cH512x4F, 512, 4, "fp8_e4m3", 0) +G4K_ATTN_C(cH512x8B, 512, 8, "bf16", 0) G4K_ATTN_C(cH512x8F, 512, 8, "fp8_e4m3", 0) +#undef G4K_ATTN_C + +/* the device kernels hold 24 elements a thread over a 256-thread block */ +static const RadConstraint cJoin[] = { C_GE("n", 1), C_LE("n", 6144), C_IN("dtype", "bf16") }; +static const RadConstraint cJoinHost[] = { C_GE("n", 1), C_IN("dtype", "bf16") }; +static const RadConstraint cPick[] = { C_GE("n", 1), C_IN("dtype", "f32 fp32") }; + +/* ==================================================================== the rows */ +#define G4K_ATTN_ROW(HD, G, KVN, C, KVDOC) \ + { "attn_paged_h" #HD "_gqa" #G "_" #KVN, "attn_paged", "attn", \ + "paged attention, any window, causal or not; split-KV with a merge where tiles are few", \ + "head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \ + "bf16 query, " KVDOC " kv cache, bf16 out, f32 partials", \ + RAD_DOMAIN_DEVICE, 10, ROW(C), NOTUNE, \ + nullptr, nullptr, g4k_attn_h##HD##_gqa##G##_##KVN, g4k_attn_h##HD##_scratch, nullptr, \ + nullptr, shape_attn_paged, nullptr, nullptr, nullptr }, +#define G4K_ATTN_PAIR(HD, G) \ + G4K_ATTN_ROW(HD, G, bf16kv, cH##HD##x##G##B, "bf16") \ + G4K_ATTN_ROW(HD, G, fp8kv, cH##HD##x##G##F, "fp8-e4m3 (per-(seq,head) descales)") + +static const RadKernelInfo kKernels[] = { + G4K_ATTN_PAIR(256, 1) G4K_ATTN_PAIR(256, 2) G4K_ATTN_PAIR(256, 4) G4K_ATTN_PAIR(256, 8) + G4K_ATTN_PAIR(512, 1) G4K_ATTN_PAIR(512, 2) G4K_ATTN_PAIR(512, 4) G4K_ATTN_PAIR(512, 8) + + /* Described as libref describes it, so rad-kbench runs both arms against the oracle. */ + { "pair_argmax_f32", "pair_argmax", "select", + "the top-1 of a row of (id, value) pairs, ties to the lower id, negative ids skipped", + "any M and n; one wave a row; the outputs one element a row at their own pitch", + "f32 pairs (int32 id bits, f32 value), i32 idx, f32 val", + RAD_DOMAIN_DEVICE, 10, ROW(cPick), NOTUNE, + nullptr, nullptr, g4k_pair_argmax_f32, nullptr, nullptr, nullptr, shape_pick, + nullptr, nullptr, nullptr }, + /* NO opd_shape: libref has no row for these (see the schemas), so there is no oracle to run + * them against. The host arms state the arithmetic, and tests/g4k_emu checks the device + * kernels against them and against the unfused chain, bit for bit. */ + { "norm_add_norm_bf16", "norm_add_norm", "norm", + "post-norm, residual add, next pre-norm: one block a row, rounding where the chain rounds", + "n <= 6144, any M, row pitches honoured", "bf16 activations, f32 gains", + RAD_DOMAIN_DEVICE, 10, ROW(cJoin), NOTUNE, + nullptr, nullptr, g4k_norm_add_norm_bf16, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "norm_add_norm_bf16_host", "norm_add_norm", "norm", + "post-norm, residual add, next pre-norm, rounding where the chain rounds", "any [M, n]", + "bf16 activations, f32 gains", + RAD_DOMAIN_HOST, 10, ROW(cJoinHost), NOTUNE, + nullptr, nullptr, norm_add_norm_host, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "join_add_scale_bf16", "join_add_scale", "norm", + "two arms' post-norms, sum, norm, residual add, layer scalar: one block a row", + "n <= 6144, any M, row pitches honoured", "bf16 activations, f32 gains, bf16 scalar", + RAD_DOMAIN_DEVICE, 10, ROW(cJoin), NOTUNE, + nullptr, nullptr, g4k_join_add_scale_bf16, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "join_add_scale_bf16_host", "join_add_scale", "norm", + "two arms' post-norms, sum, norm, residual add, layer scalar", "any [M, n]", + "bf16 activations, f32 gains, bf16 scalar", + RAD_DOMAIN_HOST, 10, ROW(cJoinHost), NOTUNE, + nullptr, nullptr, join_add_scale_host, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "pair_argmax_f32_host", "pair_argmax", "select", + "the top-1 of a row of (id, value) pairs, ties to the lower id, negative ids skipped", + "any M and n", "f32 pairs (int32 id bits, f32 value), i32 idx, f32 val", + RAD_DOMAIN_HOST, 10, ROW(cPick), NOTUNE, + nullptr, nullptr, pick_host, nullptr, nullptr, nullptr, shape_pick, + nullptr, nullptr, nullptr }, +}; +#undef G4K_ATTN_PAIR +#undef G4K_ATTN_ROW + +} /* namespace */ + +extern "C" { + +uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } + +const RadPluginInfo* rad_plugin_info(void) { + static const RadPluginInfo i = { + RAD_PLUGIN_KERNEL, "gemma4k", "0.1.0", + "Gemma 4 text: paged attention at head_dim 256/512 (gqa 1/2/4/8, any window), the " + "sharded draft head's pair_argmax, and the sandwich-norm joins", + G4K_BUILD_TARGET, + }; + return &i; +} + +int rad_kernel_schema_count(void) { return (int)(sizeof(kSchemas) / sizeof(kSchemas[0])); } +const RadOpSchema* rad_kernel_schema_at(int i) { + return (i >= 0 && i < rad_kernel_schema_count()) ? &kSchemas[i] : nullptr; +} +int rad_kernel_count(void) { return (int)(sizeof(kKernels) / sizeof(kKernels[0])); } +const RadKernelInfo* rad_kernel_at(int i) { + return (i >= 0 && i < rad_kernel_count()) ? &kKernels[i] : nullptr; +} + +/* Every kernel here reads and writes its operands and its scratch, and nothing else: no state + * between launches, no allocation of its own (rad_abi.h, rad_kernel_concurrent). */ +int rad_kernel_concurrent(int) { return 1; } + +} /* extern "C" */ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2e959c40..4ad783d2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -200,6 +200,11 @@ set(RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libref.so) if(RAD_HIP_FOUND AND TARGET libr4d) list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libr4d.so) endif() +# gemma4k declares two ops no other library does (the sandwich joins), so without it their rows +# would be "unchecked" on every machine. +if(RAD_HIP_FOUND AND TARGET gemma4k) + list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/gemma4k.so) +endif() add_test(NAME ops_doc COMMAND ${CMAKE_SOURCE_DIR}/tools/ops_doc_check.sh ${CMAKE_SOURCE_DIR}/docs/OPS.md $ From 846e52148a9e17a36a4f00d585dae27139312d68 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 10:00:42 -0500 Subject: [PATCH 07/24] tests: g4k_emu -- gemma4k's kernel source on the host, every GPU thread a fiber gemma4k builds for gfx12 only and its two joins have no libref oracle, so nothing on a machine without the card, and nothing in rad-kbench, would ever run its kernels. g4k_emu compiles the .hip sources as host C++ against a HIP shim: every GPU thread a fiber, __syncthreads and every cross-lane op a barrier (one not reached uniformly is reported as a deadlock), the WMMA operand layouts gfx12's. Checked against a port of libref's ref_attn_paged (attention, fixed cases and a random sweep over every compiled geometry), against the host rows (pair_argmax), and against the unfused chain bit for bit (the joins). Registered in CTest under the label g4k_emu, on x86-64 with a clang: the kernels use ext_vector_type and the fiber switch is SysV inline assembly. Under a clang C++ compiler they are ordinary targets. The docker image compiles host C++ with g++, so there g4k_emu/run.sh builds the same tests with the HIP compiler, ROCm's own clang++, and runs them as one test -- so wherever gemma4k is built, this runs, the image's host-test stage included. About 40 s at the default 40-case sweep (50 s through run.sh, which compiles too); `g4k_emu_attn sweep 200` is the long run. Co-Authored-By: Claude Opus 5.5 --- tests/CMakeLists.txt | 47 ++++++ tests/g4k_emu/emu/emu.cpp | 198 ++++++++++++++++++++++ tests/g4k_emu/emu/hip/hip_runtime.h | 71 ++++++++ tests/g4k_emu/run.sh | 25 +++ tests/g4k_emu/test_attn.cpp | 249 ++++++++++++++++++++++++++++ tests/g4k_emu/test_norm.cpp | 188 +++++++++++++++++++++ tests/g4k_emu/test_pick.cpp | 62 +++++++ 7 files changed, 840 insertions(+) create mode 100644 tests/g4k_emu/emu/emu.cpp create mode 100644 tests/g4k_emu/emu/hip/hip_runtime.h create mode 100644 tests/g4k_emu/run.sh create mode 100644 tests/g4k_emu/test_attn.cpp create mode 100644 tests/g4k_emu/test_norm.cpp create mode 100644 tests/g4k_emu/test_pick.cpp diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4ad783d2..a8eafe75 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -181,6 +181,53 @@ if(TARGET libavx AND TARGET rad-avx-check) set_tests_properties(avx_check PROPERTIES TIMEOUT 600) endif() +# ================================================================== gemma4k's kernels, on the host +# +# gemma4k builds for gfx12 only, and two of its ops (the sandwich-norm joins) have no libref oracle +# by design (docs/OPS.md), so neither rad-kbench nor a no-card machine would ever run its kernels. +# g4k_emu runs their SOURCE on the host instead: emu/hip/hip_runtime.h supplies the HIP names, every +# GPU thread is a fiber, __syncthreads and every cross-lane op a barrier (one not reached uniformly +# is reported as a deadlock), and the kernels' launch macro is pointed at the emulator. Checked +# against a port of libref's ref_attn_paged, against the host rows, and -- for the joins -- against +# the unfused chain, bit for bit. +# +# CLANG AND x86-64: the kernels use clang's ext_vector_type, and the fiber switch is x86-64 SysV +# inline assembly. Under a clang C++ compiler they are ordinary targets here, the .hip files +# compiled as C++ (`-x c++`, which is what makes them host code; the property is per directory, so +# gemma4k's own HIP build is untouched). Under g++ -- the docker image's -- a build with a card +# still has a clang: its HIP compiler, ROCm's own clang++, and g4k_emu/run.sh builds and runs the +# same tests with that. So wherever gemma4k is built, this runs. +set(G4K_DIR ${CMAKE_SOURCE_DIR}/gemma4k) +set(G4K_EMU ${CMAKE_CURRENT_SOURCE_DIR}/g4k_emu) +if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") + # no fiber switch for this ISA: nothing to register +elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(G4K_HIP ${G4K_DIR}/g4k_attn.hip ${G4K_DIR}/g4k_pick.hip ${G4K_DIR}/g4k_norm.hip) + set_source_files_properties(${G4K_HIP} PROPERTIES LANGUAGE CXX COMPILE_OPTIONS "-x;c++") + add_library(g4k_emu_kernels OBJECT ${G4K_HIP} ${G4K_DIR}/g4k_rows.cpp ${G4K_EMU}/emu/emu.cpp) + target_include_directories(g4k_emu_kernels PUBLIC ${G4K_EMU}/emu ${G4K_DIR}) + target_link_libraries(g4k_emu_kernels PUBLIC rad_abi) + # As libr4d compiles every unit: the joins are held to the chain bit for bit, and a contracted + # multiply-add is a different rounding. + target_compile_options(g4k_emu_kernels PRIVATE -ffp-contract=off -Wno-psabi) + foreach(t attn pick norm) + add_executable(g4k_emu_${t} ${G4K_EMU}/test_${t}.cpp) + target_link_libraries(g4k_emu_${t} PRIVATE g4k_emu_kernels) + target_compile_options(g4k_emu_${t} PRIVATE -ffp-contract=off -Wno-psabi) + set_target_properties(g4k_emu_${t} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests) + add_test(NAME g4k_emu_${t} COMMAND g4k_emu_${t}) + endforeach() + # The random sweep at a size the inner loop can afford; `g4k_emu_attn sweep 200` is the long one. + add_test(NAME g4k_emu_attn_sweep COMMAND g4k_emu_attn sweep 40) + set_tests_properties(g4k_emu_attn g4k_emu_pick g4k_emu_norm g4k_emu_attn_sweep + PROPERTIES LABELS "g4k_emu" TIMEOUT 600) +elseif(RAD_HIP_FOUND AND CMAKE_HIP_COMPILER_ID MATCHES "Clang") + add_test(NAME g4k_emu + COMMAND sh ${G4K_EMU}/run.sh ${CMAKE_HIP_COMPILER} ${CMAKE_SOURCE_DIR}/abi ${G4K_DIR} + ${CMAKE_CURRENT_BINARY_DIR}/g4k_emu 40) + set_tests_properties(g4k_emu PROPERTIES LABELS "g4k_emu" TIMEOUT 900) +endif() + # ================================================================== the document as a test # # docs/OPS.md calls its resolved table "THE AUTHORITY FOR THE OPS IN IT" and says of itself that diff --git a/tests/g4k_emu/emu/emu.cpp b/tests/g4k_emu/emu/emu.cpp new file mode 100644 index 00000000..f3f70c19 --- /dev/null +++ b/tests/g4k_emu/emu/emu.cpp @@ -0,0 +1,198 @@ +#include "hip/hip_runtime.h" +#include +#include + +/* ---- the context switch: callee-saved registers and the stack pointer (x86-64 SysV) */ +extern "C" void emu_switch(void** save_sp, void* new_sp); +asm(R"( +.text +.globl emu_switch +.type emu_switch,@function +emu_switch: + pushq %rbp + pushq %rbx + pushq %r12 + pushq %r13 + pushq %r14 + pushq %r15 + movq %rsp, (%rdi) + movq %rsi, %rsp + popq %r15 + popq %r14 + popq %r13 + popq %r12 + popq %rbx + popq %rbp + ret +)"); + +namespace { +constexpr size_t kStack = 512 * 1024; +struct Fiber { + void* sp = nullptr; + std::vector stack; + EmuIdx tid{}; + bool done = false; + unsigned bar_gen = 0; /* block barrier generation this fiber waits on */ + unsigned wbar_gen = 0; + int waiting = 0; /* 0 run, 1 block barrier, 2 wave barrier */ +}; +struct Sched { + std::vector f; + void* main_sp = nullptr; + int cur = -1, nthreads = 0; + EmuIdx bid{}; + void (*body)(void*) = nullptr; + void* ctx = nullptr; + /* block barrier */ + int arrive = 0; unsigned gen = 0; + /* wave barriers and exchange slots, double-buffered by parity */ + int warrive[64] = {}; unsigned wgen[64] = {}; + int slot[64][2][32] = {}; + unsigned xparity[1024] = {}; +} S; + +void yield() { Fiber& me = S.f[S.cur]; emu_switch(&me.sp, S.main_sp); } + +extern "C" void emu_trampoline() { + S.body(S.ctx); + S.f[S.cur].done = true; + yield(); + std::abort(); +} +/* the entry a fresh stack "returns" into, keeping the SysV alignment at call boundaries */ +asm(R"( +.text +.globl emu_entry +.type emu_entry,@function +emu_entry: + andq $-16, %rsp + call emu_trampoline + ud2 +)"); +extern "C" void emu_entry(); +} // namespace + +EmuIdx& emu_thread_idx() { return S.f[S.cur].tid; } +EmuIdx& emu_block_idx() { return S.bid; } + +void __syncthreads() { + Fiber& me = S.f[S.cur]; + const unsigned g = S.gen; + if (++S.arrive == S.nthreads) { S.arrive = 0; ++S.gen; return; } + me.waiting = 1; + while (S.gen == g) yield(); + me.waiting = 0; +} + +static void wave_barrier(int w) { + Fiber& me = S.f[S.cur]; + const unsigned g = S.wgen[w]; + if (++S.warrive[w] == 32) { S.warrive[w] = 0; ++S.wgen[w]; return; } + me.waiting = 2; + while (S.wgen[w] == g) yield(); + me.waiting = 0; +} + +int emu_bpermute(int addr, int v) { + const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31; + const unsigned par = S.xparity[t]++ & 1u; + S.slot[w][par][l] = v; + wave_barrier(w); + return S.slot[w][par][(addr >> 2) & 31]; +} +int emu_readlane(int v, int lane) { return emu_bpermute(lane << 2, v); } +static short g_wa[64][2][32][8], g_wb[64][2][32][8]; +emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c) { + const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31; + const unsigned par = S.xparity[t]++ & 1u; + for (int e = 0; e < 8; ++e) { g_wa[w][par][l][e] = a[e]; g_wb[w][par][l][e] = b[e]; } + wave_barrier(w); + auto bf = [](short v) { unsigned u = (unsigned)(unsigned short)v << 16; float f; std::memcpy(&f, &u, 4); return f; }; + const int N = l & 15, h = l >> 4; + emu_v8f d; + for (int e = 0; e < 8; ++e) { + const int M = 8 * h + e; + float acc = c[e]; + for (int k = 0; k < 16; ++k) + acc += bf(g_wa[w][par][M + 16 * (k >> 3)][k & 7]) * bf(g_wb[w][par][N + 16 * (k >> 3)][k & 7]); + d[e] = acc; + } + return d; +} +static _Float16 g_ha[64][2][32][8], g_hb[64][2][32][8]; +emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c) { + const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31; + const unsigned par = S.xparity[t]++ & 1u; + for (int e = 0; e < 8; ++e) { g_ha[w][par][l][e] = a[e]; g_hb[w][par][l][e] = b[e]; } + wave_barrier(w); + const int N = l & 15, h = l >> 4; + emu_v8f d; + for (int e = 0; e < 8; ++e) { + const int M = 8 * h + e; + float acc = c[e]; + for (int k = 0; k < 16; ++k) + acc += (float)g_ha[w][par][M + 16 * (k >> 3)][k & 7] * (float)g_hb[w][par][N + 16 * (k >> 3)][k & 7]; + d[e] = acc; + } + return d; +} +unsigned emu_ballot(bool p) { + unsigned m = 0; + for (int l = 0; l < 32; ++l) m |= (unsigned)(emu_readlane(p ? 1 : 0, l) & 1) << l; + return m; +} + +int emu_grids = 0; +int emu_last_block = 0; +void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx) { + ++emu_grids; + const int n = (int)(block.x * block.y * block.z); + emu_last_block = n; + if (block.y != 1 || block.z != 1 || n % 32 || n > 1024) { std::fprintf(stderr, "emu: block shape\n"); std::abort(); } + S.body = body; S.ctx = ctx; S.nthreads = n; + S.f.resize(n); + for (auto& f : S.f) if (f.stack.size() != kStack) f.stack.assign(kStack, 0); + for (unsigned bz = 0; bz < grid.z; ++bz) + for (unsigned by = 0; by < grid.y; ++by) + for (unsigned bx = 0; bx < grid.x; ++bx) { + S.bid = EmuIdx{bx, by, bz}; + S.arrive = 0; S.gen = 0; + for (int w = 0; w < 64; ++w) { S.warrive[w] = 0; S.wgen[w] = 0; } + for (int t = 0; t < n; ++t) { + Fiber& f = S.f[t]; + f.done = false; f.waiting = 0; f.tid = EmuIdx{(unsigned)t, 0, 0}; + S.xparity[t] = 0; + /* a fresh stack: six callee-saved slots, then the entry as the return address */ + void** top = (void**)(f.stack.data() + kStack - 64); + *--top = (void*)&emu_entry; + for (int r = 0; r < 6; ++r) *--top = nullptr; + f.sp = top; + } + int live = n; + while (live > 0) { + int progressed = 0; + const int live_before = live; + const unsigned g0 = S.gen; unsigned wg0[64]; for (int w = 0; w < 64; ++w) wg0[w] = S.wgen[w]; + int arr0 = S.arrive; int warr0[64]; for (int w = 0; w < 64; ++w) warr0[w] = S.warrive[w]; + live = 0; + for (int t = 0; t < n; ++t) { + if (S.f[t].done) continue; + S.cur = t; + emu_switch(&S.main_sp, S.f[t].sp); + S.cur = -1; + if (!S.f[t].done) ++live; + } + progressed = S.gen != g0 || S.arrive != arr0 || live != live_before; + for (int w = 0; w < 64; ++w) progressed |= (S.wgen[w] != wg0[w]) || (S.warrive[w] != warr0[w]); + if (live > 0 && !progressed) { + int done = 0, wb = 0, bb = 0; + for (auto& f : S.f) { done += f.done; wb += f.waiting == 2; bb += f.waiting == 1; } + std::fprintf(stderr, "emu: DEADLOCK in block (%u,%u,%u): %d threads done, %d at a block " + "barrier, %d at a wave barrier -- a barrier not reached uniformly\n", + bx, by, bz, done, bb, wb); + std::abort(); + } + } + } +} diff --git a/tests/g4k_emu/emu/hip/hip_runtime.h b/tests/g4k_emu/emu/hip/hip_runtime.h new file mode 100644 index 00000000..d17a081f --- /dev/null +++ b/tests/g4k_emu/emu/hip/hip_runtime.h @@ -0,0 +1,71 @@ +/* tests/g4k_emu: SIMT EMULATOR SHIM -- runs gemma4k's kernel source on the host. Every GPU thread is a fiber on + * one OS thread; __syncthreads and every cross-lane op are barriers the scheduler enforces, and a + * barrier some threads never reach is reported as a deadlock rather than hung. Test-only. */ +#pragma once +#include +#include +#include +#include +#include + +#define __global__ +#define __device__ +#define __host__ +#define __shared__ static +#define __forceinline__ inline +#define __launch_bounds__(n) + +struct dim3 { + unsigned x, y, z; + constexpr dim3(unsigned a = 1, unsigned b = 1, unsigned c = 1) : x(a), y(b), z(c) {} +}; +typedef void* hipStream_t; +typedef int hipError_t; +enum { hipSuccess = 0 }; +inline hipError_t hipGetLastError() { return 0; } + +struct EmuIdx { unsigned x, y, z; }; +EmuIdx& emu_thread_idx(); +EmuIdx& emu_block_idx(); +#define threadIdx (emu_thread_idx()) +#define blockIdx (emu_block_idx()) +void __syncthreads(); +int emu_bpermute(int addr, int v); +int emu_readlane(int v, int lane); +#define __builtin_amdgcn_ds_bpermute(a, v) emu_bpermute((a), (v)) +#define __builtin_amdgcn_readlane(v, l) emu_readlane((v), (l)) +unsigned emu_ballot(bool p); +#define __builtin_amdgcn_ballot_w32(p) emu_ballot((p)) +/* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N] + * lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */ +typedef short emu_v8s __attribute__((ext_vector_type(8))); +typedef float emu_v8f __attribute__((ext_vector_type(8))); +emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c); +#define __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c) emu_wmma_bf16((a), (b), (c)) +typedef _Float16 emu_v8h __attribute__((ext_vector_type(8))); +emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c); +#define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c)) +extern int emu_last_block; /* threads a block of the last grid had: which kernel ran */ + +struct alignas(8) uint2 { unsigned x, y; }; +struct alignas(16) uint4 { unsigned x, y, z, w; }; +struct alignas(16) float4 { float x, y, z, w; }; +inline uint4 make_uint4(unsigned a, unsigned b, unsigned c, unsigned d) { return uint4{a, b, c, d}; } +inline uint2 make_uint2(unsigned a, unsigned b) { return uint2{a, b}; } +inline float4 make_float4(float a, float b, float c, float d) { return float4{a, b, c, d}; } +inline float __uint_as_float(unsigned u) { float f; std::memcpy(&f, &u, 4); return f; } +inline float rsqrtf(float x) { return 1.0f / std::sqrt(x); } /* v_rsq_f32 is within an ulp of it */ +inline unsigned __float_as_uint(float f) { unsigned u; std::memcpy(&u, &f, 4); return u; } +inline float __int_as_float(int u) { float f; std::memcpy(&f, &u, 4); return f; } +inline int __float_as_int(float f) { int u; std::memcpy(&u, &f, 4); return u; } + +/* one block at a time, every thread a fiber */ +void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx); +template +struct EmuCall { K k; A a; static void run(void* p) { auto* c = (EmuCall*)p; c->k(c->a); } }; +template +void emu_launch(void (*k)(A), dim3 g, dim3 b, A a) { + EmuCall c{k, a}; + emu_run_grid(g, b, &EmuCall::run, &c); +} +#define G4K_LAUNCH(kernel, grid, block, stream, ...) emu_launch(&kernel, grid, block, __VA_ARGS__) diff --git a/tests/g4k_emu/run.sh b/tests/g4k_emu/run.sh new file mode 100644 index 00000000..01659103 --- /dev/null +++ b/tests/g4k_emu/run.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# tests/g4k_emu/run.sh -- build and run g4k_emu with a clang that is not the build's C++ compiler. +# +# A build whose C++ compiler is clang builds these as ordinary targets (tests/CMakeLists.txt). The +# docker image compiles host C++ with g++, which has no ext_vector_type; its HIP compiler is ROCm's +# own clang++, and with `-x c++` that compiles the kernel sources as the host code this test needs. +# +# run.sh [sweep cases] +set -e +CXX=${1:?usage: run.sh [sweep cases]} +ABI=$2; G=$3; B=$4; N=${5:-40} +HERE=$(cd "$(dirname "$0")" && pwd) +mkdir -p "$B" +F="-std=c++20 -O2 -ffp-contract=off -Wno-psabi -I$HERE/emu -I$ABI -I$G" +for u in attn pick norm; do $CXX $F -x c++ -c "$G/g4k_$u.hip" -o "$B/k_$u.o"; done +$CXX $F -c "$G/g4k_rows.cpp" -o "$B/rows.o" +$CXX $F -c "$HERE/emu/emu.cpp" -o "$B/emu.o" +for t in attn pick norm; do + $CXX $F -c "$HERE/test_$t.cpp" -o "$B/test_$t.o" + $CXX "$B/test_$t.o" "$B/k_attn.o" "$B/k_pick.o" "$B/k_norm.o" "$B/rows.o" "$B/emu.o" -o "$B/test_$t" +done +"$B/test_attn" +"$B/test_attn" sweep "$N" +"$B/test_pick" +"$B/test_norm" diff --git a/tests/g4k_emu/test_attn.cpp b/tests/g4k_emu/test_attn.cpp new file mode 100644 index 00000000..5b8a36ba --- /dev/null +++ b/tests/g4k_emu/test_attn.cpp @@ -0,0 +1,249 @@ +/* Drives gemma4k's attn_paged entry points through the SIMT emulator and checks every output + * element against a port of libref's ref_attn_paged (same mask predicates, f64 accumulation). */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "g4k.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +static std::mt19937 rng(1234); +extern int emu_grids; +extern int emu_last_block; /* threads a block of the last grid: 512 is the WMMA kernel */ +static float nrm() { static std::normal_distribution d(0.f, 1.f); return d(rng); } + +static RadTensor tens(void* p, uint32_t dt, std::vector shape) { + RadTensor t{}; t.data = p; t.dtype = dt; t.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { t.shape[i] = shape[i]; t.stride[i] = st; st *= shape[i]; } + return t; +} + +struct Case { + std::string name; + int hd, gqa, kvh; + bool fp8, causal, ragged, descale; + int window; + std::vector qlen, ctx; /* per sequence */ + int missing_block = -1; /* sequence 0's block index to mark -1, or -1 */ + long long max_ctx = 0; /* 0: not passed */ + int64_t scratch = 0; /* 0: no scratch */ + int qpitch_extra = 0; /* q as a column slice of a wider buffer */ + int expect_wmma = -1; /* 1: must take the WMMA kernel, 0: must not, -1: either */ +}; + +using Fn = int (*)(const RadArgs*, RadStream); +static Fn pick(int hd, int gqa, bool fp8) { +#define P(H, G) if (hd == H && gqa == G) return fp8 ? g4k_attn_h##H##_gqa##G##_fp8kv : g4k_attn_h##H##_gqa##G##_bf16kv; + P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8) +#undef P + return nullptr; +} + +static int run(const Case& c) { + const int n_seq = (int)c.qlen.size(), HD = c.hd, kvh = c.kvh, qh = kvh * c.gqa; + int rows = 0; for (int q : c.qlen) rows += q; + /* blocks: each sequence gets ceil(ctx/16) blocks at shuffled ids */ + int maxb = 0; for (int x : c.ctx) maxb = std::max(maxb, (x + 15) / 16); + maxb += 1; /* a spare column: the table is wider than any sequence needs */ + const int nblocks = n_seq * maxb + 3; + std::vector ids(nblocks); for (int i = 0; i < nblocks; ++i) ids[i] = i; + std::shuffle(ids.begin(), ids.end(), rng); + std::vector bt(n_seq * maxb, -1); + int nx = 0; + for (int s = 0; s < n_seq; ++s) for (int b = 0; b < (c.ctx[s] + 15) / 16; ++b) bt[s * maxb + b] = ids[nx++]; + if (c.missing_block >= 0) bt[c.missing_block] = -1; + /* the cache, filled everywhere -- including slots past each context, with NaN in some, so a + * kernel that reads a masked key's V without guarding is caught */ + const int64_t slot = 2 * HD, nel = (int64_t)nblocks * kvh * 16 * slot; + std::vector kvf(nel); + std::vector kvb(nel); std::vector kv8(nel); + for (int64_t i = 0; i < nel; ++i) { + float v = nrm(); + if (c.fp8) { kv8[i] = rad_f32_to_fp8e4m3(v * 4.f); kvf[i] = rad_fp8e4m3_to_f32(kv8[i]); } + else { kvb[i] = rad_f32_to_bf16(v); kvf[i] = rad_bf16_to_f32(kvb[i]); } + } + /* poison: every slot at or past a sequence's context in its last block, and every block no + * table names */ + std::vector named(nblocks, 0); + for (int s = 0; s < n_seq; ++s) for (int b = 0; b < maxb; ++b) if (bt[s * maxb + b] >= 0) named[bt[s * maxb + b]] = 1; + auto poison = [&](int64_t i) { if (c.fp8) { kv8[i] = 0x7f; } else { kvb[i] = 0x7fc0; } kvf[i] = NAN; }; + for (int blk = 0; blk < nblocks; ++blk) if (!named[blk]) for (int64_t i = 0; i < kvh * 16 * slot; ++i) poison((int64_t)blk * kvh * 16 * slot + i); + for (int s = 0; s < n_seq; ++s) { + const int last = (c.ctx[s] - 1) / 16, blk = bt[s * maxb + last]; + if (blk < 0) continue; + for (int o = c.ctx[s] % 16 ? c.ctx[s] % 16 : 16; o < 16; ++o) + for (int h = 0; h < kvh; ++h) for (int d = 0; d < slot; ++d) poison((((int64_t)blk * kvh + h) * 16 + o) * slot + d); + } + const int qcols = qh * HD + c.qpitch_extra; + std::vector qb((size_t)rows * qcols); std::vector qf(qb.size()); + for (size_t i = 0; i < qb.size(); ++i) { qb[i] = rad_f32_to_bf16(nrm()); qf[i] = rad_bf16_to_f32(qb[i]); } + std::vector su(c.ctx), cu(n_seq + 1, 0); + for (int s = 0; s < n_seq; ++s) cu[s + 1] = cu[s] + c.qlen[s]; + std::vector kd(n_seq * kvh, 1.f), vd(n_seq * kvh, 1.f); + if (c.descale) for (auto* v : {&kd, &vd}) for (auto& x : *v) x = 0.5f + (float)(rng() % 100) / 100.f; + std::vector out((size_t)rows * qh * HD, 0xffff); + std::vector scratch(c.scratch + 64); + char* sp = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15); + + RadTensor t[8]; + t[0] = tens(qb.data(), RAD_BF16, {rows, qh * HD}); t[0].stride[0] = qcols; + t[1] = tens(c.fp8 ? (void*)kv8.data() : (void*)kvb.data(), c.fp8 ? RAD_F8E4M3 : RAD_BF16, {nblocks, kvh, 16, slot}); + t[2] = tens(bt.data(), RAD_I32, {n_seq, maxb}); + t[3] = tens(su.data(), RAD_I32, {n_seq}); + t[4] = c.descale ? tens(kd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{}; + t[5] = c.descale ? tens(vd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{}; + t[6] = c.ragged ? tens(cu.data(), RAD_I32, {n_seq + 1}) : RadTensor{}; + t[7] = tens(out.data(), RAD_BF16, {rows, qh, HD}); + int qmax = 0; for (int q : c.qlen) qmax = std::max(qmax, q); + std::vector p; + auto pi = [&](const char* k, long long v) { RadParam x{}; x.key = k; x.kind = RAD_P_INT; x.ival = v; p.push_back(x); }; + auto ps = [&](const char* k, const char* v) { RadParam x{}; x.key = k; x.kind = RAD_P_STR; x.sval = v; p.push_back(x); }; + auto pf = [&](const char* k, double v) { RadParam x{}; x.key = k; x.kind = RAD_P_F64; x.dval = v; p.push_back(x); }; + pi("q_len", qmax + 3); /* the band bound, above the step's max */ + pi("head_dim", HD); pi("gqa", c.gqa); pi("block_size", 16); pi("causal", c.causal); pi("window", c.window); + ps("q_dtype", "bf16"); ps("kv_dtype", c.fp8 ? "fp8_e4m3" : "bf16"); + const double scale = 1.0 / std::sqrt((double)HD) * 1.3; /* not the default: the param must be read */ + pf("scale", scale); pi("n_head", qh); pi("max_seqs", n_seq); + if (c.max_ctx) pi("max_ctx", c.max_ctx); + RadArgs a{}; a.t = t; a.n_t = 8; a.p = p.data(); a.n_p = (int)p.size(); + a.scratch = c.scratch ? sp : nullptr; a.scratch_bytes = c.scratch; + Fn fn = pick(HD, c.gqa, c.fp8); + const int g0 = emu_grids; + const int rc = fn(&a, nullptr); + const int launches = emu_grids - g0; + if (rc != RAD_OK) { std::printf("%-44s launch returned %d\n", c.name.c_str(), rc); return 1; } + + /* the reference */ + double max_err = 0, max_ref = 0, se = 0, sr = 0; long bad = 0, nan_out = 0; + for (int s = 0; s < n_seq; ++s) for (int i = 0; i < c.qlen[s]; ++i) for (int h = 0; h < qh; ++h) { + const int tok = cu[s] + i, kh = h / c.gqa, pos = c.ctx[s] - c.qlen[s] + i; + auto visible = [&](int j) { + if (c.causal ? j > pos : j >= c.ctx[s]) return false; + if (c.window > 0) { const int d = pos - j; if (c.causal ? d >= c.window : (d >= c.window || d <= -c.window)) return false; } + return bt[s * maxb + j / 16] >= 0; + }; + std::vector sc(c.ctx[s], -INFINITY); double mx = -INFINITY; + for (int j = 0; j < c.ctx[s]; ++j) { + if (!visible(j)) continue; + const int64_t kb = (((int64_t)bt[s * maxb + j / 16] * kvh + kh) * 16 + j % 16) * slot; + double dot = 0; for (int d = 0; d < HD; ++d) dot += (double)qf[(size_t)tok * qcols + h * HD + d] * kvf[kb + d] * kd[s * kvh + kh]; + sc[j] = dot * scale; mx = std::max(mx, sc[j]); + } + std::vector acc(HD, 0.0); double sum = 0; + if (mx > -INFINITY) + for (int j = 0; j < c.ctx[s]; ++j) { + if (sc[j] == -INFINITY) continue; + const double w = std::exp(sc[j] - mx); sum += w; + const int64_t kb = (((int64_t)bt[s * maxb + j / 16] * kvh + kh) * 16 + j % 16) * slot; + for (int d = 0; d < HD; ++d) acc[d] += w * kvf[kb + HD + d] * vd[s * kvh + kh]; + } + for (int d = 0; d < HD; ++d) { + const double ref = sum > 0 ? acc[d] / sum : 0.0; + const float got = rad_bf16_to_f32(out[((size_t)tok * qh + h) * HD + d]); + if (std::isnan(got)) { ++nan_out; continue; } + const double e = std::fabs(got - ref); + max_err = std::max(max_err, e); max_ref = std::max(max_ref, std::fabs(ref)); + se += e * e; sr += ref * ref; + if (e > 1e-2 * std::max(1.0, std::fabs(ref)) + 4e-3 * std::fabs(ref)) ++bad; + } + } + const double rel = std::sqrt(se / std::max(sr, 1e-30)); + const bool ok = bad == 0 && nan_out == 0 && rel < 5e-3; + std::printf("%-44s rows %4d %s rel_l2 %.2e max_abs %.2e bad %ld nan %ld %s\n", c.name.c_str(), rows, + launches > 1 ? "split" : emu_last_block == 512 ? "wmma " : " ", rel, max_err, bad, nan_out, + ok ? "PASS" : "FAIL"); + if (c.expect_wmma >= 0 && (emu_last_block == 512) != (c.expect_wmma == 1)) { + std::printf("%-44s took the %s kernel, expected the %s one\n", c.name.c_str(), + emu_last_block == 512 ? "WMMA" : "scalar", c.expect_wmma ? "WMMA" : "scalar"); + return 1; + } + return ok ? 0 : 1; +} + +int main(int argc, char** argv) { + const int64_t s256 = g4k_attn_h256_scratch(nullptr), s512 = g4k_attn_h512_scratch(nullptr); + std::vector cases = { + /* Gemma 4 sliding: h256 gqa2, causal, windowed; a ragged mixed step */ + {"h256 gqa2 swa w64 ragged bf16", 256, 2, 2, false, true, true, false, 64, {1, 5, 40}, {200, 77, 140}}, + {"h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {1, 5, 40}, {200, 77, 140}}, + /* the real window, a context past it, a verify-sized query */ + {"h256 gqa2 swa w1024 verify16", 256, 2, 1, false, true, false, false, 1024, {16}, {1100}}, + /* split-KV decode: one row a sequence, long context, scratch present */ + {"h256 gqa2 swa w1024 decode split", 256, 2, 2, false, true, true, false, 1024, {1, 1}, {1300, 40}, -1, 0, s256}, + /* Gemma 4 full: h512, causal, no window, at the three TP ratios */ + {"h512 gqa8 full ragged bf16", 512, 8, 1, false, true, true, false, 0, {2, 7}, {90, 33}}, + {"h512 gqa8 full decode split fp8", 512, 8, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512}, + {"h512 gqa4 full verify16 split", 512, 4, 1, false, true, false, false, 0, {16}, {300}, -1, 1024, s512}, + /* the serving case: max_ctx 262144 gives a decode step 64 splits, most of them empty */ + {"h512 gqa4 full decode, 64 splits, short ctx", 512, 4, 1, false, true, false, false, 0, {4}, {37}, -1, 262144, s512}, + {"h256 gqa2 swa w1024 verify, ragged, splits", 256, 2, 2, true, true, true, true, 1024, {3, 5}, {20, 900}, -1, 262144, s256}, + {"h512 gqa2 full ragged", 512, 2, 2, false, true, true, false, 0, {3, 1, 9}, {50, 64, 9}}, + /* the coverage the rows claim beyond Gemma: non-causal, two-sided window, a missing block */ + {"h256 gqa4 noncausal w20 missing-block", 256, 4, 1, false, false, true, false, 20, {6, 2}, {70, 30}, 2}, + {"h512 gqa1 noncausal full", 512, 1, 1, false, false, false, false, 0, {4}, {37}}, + {"h256 gqa8 causal q-pitch slice", 256, 8, 1, false, true, false, false, 0, {5}, {21}, -1, 0, 0, 512}, + /* no scratch where a split was wanted: falls back to the unsplit kernel */ + {"h256 gqa2 decode, split wanted, no scratch", 256, 2, 1, false, true, false, false, 0, {1}, {500}}, + /* PREFILL-SHAPED: the WMMA kernel (a 64-row query, or longer) */ + {"wmma h512 gqa4 prefill 200 of 900", 512, 4, 1, false, true, false, false, 0, {200}, {900}, -1, 262144, s512, 0, 1}, + {"wmma h512 gqa8 prefill fp8+descale", 512, 8, 1, true, true, false, true, 0, {130}, {130}, -1, 0, 0, 0, 1}, + {"wmma h512 gqa2 kvh2 ragged + decode rows", 512, 2, 2, false, true, true, false, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1}, + {"wmma h512 gqa1 noncausal", 512, 1, 1, false, false, false, false, 0, {64}, {100}, -1, 0, 0, 0, 1}, + {"wmma h256 gqa2 swa w1024 prefill 300 of 1500", 256, 2, 2, false, true, false, false, 1024, {300}, {1500}, -1, 0, 0, 0, 1}, + {"wmma h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {100, 90}, {250, 90}, -1, 0, 0, 0, 1}, + {"wmma h256 gqa4 noncausal w20 missing-block", 256, 4, 1, false, false, true, false, 20, {80, 70}, {200, 70}, 3, 0, 0, 0, 1}, + {"wmma h256 gqa8 causal q-pitch slice", 256, 8, 1, false, true, false, false, 0, {64}, {64}, -1, 0, 0, 512, 1}, + {"wmma h256 gqa1 causal w5 fp8", 256, 1, 1, true, true, false, false, 5, {96}, {150}, -1, 0, 0, 0, 1}, + /* and what must stay scalar: a verify batch, many sequences, a few rows each */ + {"scalar: 8 x verify16, ragged", 512, 4, 1, false, true, true, false, 0, {16, 16, 16, 16, 16, 16, 16, 16}, + {40, 50, 60, 70, 80, 90, 100, 110}, -1, 262144, s512, 0, 0}, + }; + if (argc > 1 && std::string(argv[1]) == "sweep") { + const int n = argc > 2 ? std::atoi(argv[2]) : 200; + int fails = 0, splits = 0, wmmas = 0; + const int hds[2] = {256, 512}, gqas[4] = {1, 2, 4, 8}; + for (int it = 0; it < n; ++it) { + Case c; + c.hd = hds[rng() % 2]; c.gqa = gqas[rng() % 4]; c.kvh = 1 + rng() % 3; + c.fp8 = rng() % 2; c.causal = rng() % 4 != 0; c.ragged = rng() % 2; c.descale = rng() % 2; + c.window = rng() % 3 == 0 ? 0 : 1 + rng() % 200; + const int ns = 1 + rng() % 4; + const bool pre = rng() % 3 == 0; /* prefill-shaped: the WMMA kernel */ + const int qspan = pre ? 160 : 40, qmin = pre ? 64 : 1; + const int ql = qmin + rng() % qspan; + for (int s = 0; s < ns; ++s) { + int q = c.ragged ? (int)(rng() % 3 == 0 ? 0 : qmin + rng() % qspan) : ql; + if (c.ragged && s == 0 && q == 0) q = 1; + c.qlen.push_back(q); + c.ctx.push_back(q + (int)(rng() % 400)); + } + if (rng() % 2) c.scratch = c.hd == 256 ? s256 : s512; + if (rng() % 2) c.max_ctx = 512; + if (rng() % 5 == 0) c.missing_block = (int)(rng() % ((c.ctx[0] + 15) / 16)); + c.name = "sweep " + std::to_string(it) + " h" + std::to_string(c.hd) + " g" + std::to_string(c.gqa) + + " kvh" + std::to_string(c.kvh) + (c.fp8 ? " fp8" : " bf16") + (c.causal ? " c" : " nc") + + " w" + std::to_string(c.window) + (c.ragged ? " rag" : ""); + const int g0 = emu_grids; + fails += run(c); + splits += emu_grids - g0 > 1; + wmmas += emu_last_block == 512; + } + std::printf("sweep: %d cases, %d took the split path, %d the WMMA kernel, %d failure(s)\n", n, splits, + wmmas, fails); + return fails ? 1 : 0; + } + int fails = 0; + for (auto& c : cases) { + if (argc > 1 && c.name.find(argv[1]) == std::string::npos) continue; + fails += run(c); + } + std::printf("%d failure(s)\n", fails); + return fails ? 1 : 0; +} diff --git a/tests/g4k_emu/test_norm.cpp b/tests/g4k_emu/test_norm.cpp new file mode 100644 index 00000000..32c89094 --- /dev/null +++ b/tests/g4k_emu/test_norm.cpp @@ -0,0 +1,188 @@ +/* tests/g4k_emu: the sandwich-norm joins (g4k_norm.hip) on the host SIMT emulator. + * + * Two references. The CHAIN is the unfused sequence the arch plugin would otherwise issue -- rmsnorm, + * add, rmsnorm (or rmsnorm x2, add, rmsnorm, add, mul_weight) -- in libr4d's per-element arithmetic, + * its sums of squares added in this kernel's block order: the fused kernel must match it BIT FOR + * BIT, which is the claim that fusing changes nothing but the launch count. The HOST ARM sums in + * index order -- what a different libr4d block width does too -- and may differ by a flipped + * rounding, measured against the row's scale (see cmp). Padding columns and rows past M must be + * left alone. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "g4k.h" +#include +#include +#include +#include +#include +#include +extern "C" const RadKernelInfo* rad_kernel_at(int); +extern "C" int rad_kernel_count(void); + +static std::mt19937 rng(11); +static float b2f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; } +static uint16_t f2b(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } +static float rb(float f) { return b2f(f2b(f)); } + +/* the kernel's sum of squares: 256 threads strided over the row, a butterfly a wave, waves in order */ +static float block_factor(const std::vector& v, int n, float eps) { + float part[256]; + for (int t = 0; t < 256; ++t) { + float s = 0.0f; + for (int k = 0; k < 24; ++k) { const int i = t + 256 * k; const float x = i < n ? v[(size_t)i] : 0.0f; s += x * x; } + part[t] = s; + } + float total = 0.0f; + for (int w = 0; w < 8; ++w) { + float l[32]; + for (int i = 0; i < 32; ++i) l[i] = part[w * 32 + i]; + for (int d = 16; d >= 1; d >>= 1) { + float nl[32]; + for (int i = 0; i < 32; ++i) nl[i] = l[i] + l[i ^ d]; + std::memcpy(l, nl, sizeof l); + } + total += l[0]; + } + return 1.0f / std::sqrt(total / (float)n + eps); +} +static std::vector chain_norm(const std::vector& v, const float* g, int n, float eps) { + const float f = block_factor(v, n, eps); + std::vector y((size_t)n); + for (int i = 0; i < n; ++i) y[(size_t)i] = rb((v[(size_t)i] * f) * g[i]); + return y; +} + +static RadTensor rows(void* p, uint32_t dt, int64_t M, int64_t n, int64_t ld) { + RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 2; t.shape[0] = M; t.shape[1] = n; t.stride[0] = ld; t.stride[1] = 1; + return t; +} +static RadTensor vec(void* p, uint32_t dt, int64_t n) { + RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 1; t.shape[0] = n; t.stride[0] = 1; + return t; +} +static const RadKernelInfo* host_row(const char* op) { + for (int i = 0; i < rad_kernel_count(); ++i) + if (rad_kernel_at(i)->domain == RAD_DOMAIN_HOST && !std::strcmp(rad_kernel_at(i)->op, op)) return rad_kernel_at(i); + return nullptr; +} +static std::vector randb(size_t k, float sd) { + std::normal_distribution d(0.f, sd); + std::vector v(k); + for (auto& x : v) x = f2b(d(rng)); + return v; +} +static std::vector gains(int n) { + std::normal_distribution d(1.f, 0.4f); + std::vector g((size_t)n); + for (auto& x : g) x = d(rng); + return g; +} +/* vs the host arm, the difference in units of the row's RMS: a different summation order moves the + * norm factor by an f32 ulp, which flips a bf16 rounding here and there -- and where the residual + * add cancels, a flipped ulp of the addend is many ulps of a small sum, so ulps of the OUTPUT are + * the wrong yardstick and the row's scale is the right one. */ +struct Tally { long chain_bad = 0, host_diff = 0, host_bad = 0, pad = 0; double worst = 0.0; }; +static void cmp(const uint16_t* got, const uint16_t* chain, const uint16_t* host, int n, Tally& t) { + double ss = 0.0; + for (int i = 0; i < n; ++i) ss += (double)b2f(host[i]) * b2f(host[i]); + const double rms = std::sqrt(ss / n) + 1e-30; + for (int i = 0; i < n; ++i) { + if (got[i] != chain[i]) ++t.chain_bad; + if (got[i] == host[i]) continue; + ++t.host_diff; + const double e = std::fabs((double)b2f(got[i]) - b2f(host[i])) / rms; + if (e > t.worst) t.worst = e; + /* one bf16 ulp of an element at 4x the row's rms is up to 3% of it: 1/16 passes a flipped + * rounding of a large element and fails anything a real bug produces */ + if (e > 1.0 / 16) ++t.host_bad; + } +} + +static int case_nan(int M, int n, int pad, int extra_rows) { + const int ld = n + pad, R = M + extra_rows; + const float eps = 1e-6f; + auto a = randb((size_t)R * ld, 3.f), x = randb((size_t)R * ld, 1.f), y0 = randb((size_t)R * ld, 1.f); + auto wa = gains(n), wy = gains(n); + auto xd = x, yd = y0, xh = x, yh = y0; + RadTensor t[5] = { rows(a.data(), RAD_BF16, M, n, ld), vec(wa.data(), RAD_F32, n), + rows(xd.data(), RAD_BF16, M, n, ld), vec(wy.data(), RAD_F32, n), + rows(yd.data(), RAD_BF16, M, n, ld) }; + RadParam p[4]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n}; + p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16"; + RadArgs ar{}; ar.t = t; ar.n_t = 5; ar.p = p; ar.n_p = 4; + if (g4k_norm_add_norm_bf16(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm: device launch failed"); return 1; } + t[2].data = xh.data(); t[4].data = yh.data(); + if (host_row("norm_add_norm")->launch(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm: host launch failed"); return 1; } + Tally tx, ty; + for (int m = 0; m < R; ++m) { + const size_t o = (size_t)m * ld; + if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]); continue; } + for (int i = n; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]); + std::vector av((size_t)n), xv((size_t)n); + for (int i = 0; i < n; ++i) av[(size_t)i] = b2f(a[o + i]); + const auto t1 = chain_norm(av, wa.data(), n, eps); /* rmsnorm */ + std::vector cx((size_t)n), cy((size_t)n); + for (int i = 0; i < n; ++i) { xv[(size_t)i] = rb(b2f(x[o + i]) + t1[(size_t)i]); cx[(size_t)i] = f2b(xv[(size_t)i]); } /* add */ + const auto t2 = chain_norm(xv, wy.data(), n, eps); /* rmsnorm */ + for (int i = 0; i < n; ++i) cy[(size_t)i] = f2b(t2[(size_t)i]); + cmp(&xd[o], cx.data(), &xh[o], n, tx); + cmp(&yd[o], cy.data(), &yh[o], n, ty); + } + const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tx.host_bad == 0 && ty.host_bad == 0 && tx.pad == 0; + std::printf("norm_add_norm M %3d n %4d pitch %4d: vs chain x %ld y %ld differ; vs host arm %ld/%ld differ, worst " + "%.1e of the row rms; padding touched %ld -> %s\n", M, n, ld, tx.chain_bad, ty.chain_bad, tx.host_diff, + ty.host_diff, tx.worst > ty.worst ? tx.worst : ty.worst, tx.pad, ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} + +static int case_jas(int M, int n, int pad, int extra_rows) { + const int ld = n + pad, R = M + extra_rows; + const float eps = 1e-6f; + /* the two arms as one [2M, n] buffer, as the plugin holds them: dense rows, then routed */ + auto ff = randb((size_t)2 * R * ld, 2.f), x = randb((size_t)R * ld, 4.f); + auto wd = gains(n), wr = gains(n), wj = gains(n); + uint16_t sc = f2b(0.4375f + (float)(rng() % 64) / 128.f); + auto xd = x, xh = x; + RadTensor t[7] = { rows(ff.data(), RAD_BF16, M, n, ld), vec(wd.data(), RAD_F32, n), + rows(ff.data() + (size_t)M * ld, RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n), + vec(wj.data(), RAD_F32, n), rows(xd.data(), RAD_BF16, M, n, ld), vec(&sc, RAD_BF16, 1) }; + RadParam p[4]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n}; + p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16"; + RadArgs ar{}; ar.t = t; ar.n_t = 7; ar.p = p; ar.n_p = 4; + if (g4k_join_add_scale_bf16(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: device launch failed"); return 1; } + t[5].data = xh.data(); + if (host_row("join_add_scale")->launch(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: host launch failed"); return 1; } + Tally tx; + for (int m = 0; m < R; ++m) { + const size_t o = (size_t)m * ld; + if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += xd[o + i] != x[o + i]; continue; } + for (int i = n; i < ld; ++i) tx.pad += xd[o + i] != x[o + i]; + std::vector dv((size_t)n), rv((size_t)n), sv((size_t)n); + for (int i = 0; i < n; ++i) { dv[(size_t)i] = b2f(ff[o + i]); rv[(size_t)i] = b2f(ff[(size_t)M * ld + o + i]); } + const auto d1 = chain_norm(dv, wd.data(), n, eps); /* rmsnorm (arm 1) */ + const auto r1 = chain_norm(rv, wr.data(), n, eps); /* rmsnorm (arm 2) */ + for (int i = 0; i < n; ++i) sv[(size_t)i] = rb(d1[(size_t)i] + r1[(size_t)i]); /* add */ + const auto j = chain_norm(sv, wj.data(), n, eps); /* rmsnorm */ + std::vector cx((size_t)n); + for (int i = 0; i < n; ++i) cx[(size_t)i] = f2b(rb(b2f(x[o + i]) + j[(size_t)i]) * b2f(sc)); /* add, mul_weight */ + cmp(&xd[o], cx.data(), &xh[o], n, tx); + } + const bool ok = tx.chain_bad == 0 && tx.host_bad == 0 && tx.pad == 0; + std::printf("join_add_scale M %3d n %4d pitch %4d: vs chain %ld differ; vs host arm %ld differ, worst %.1e of the " + "row rms; padding touched %ld -> %s\n", M, n, ld, tx.chain_bad, tx.host_diff, tx.worst, tx.pad, + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} + +int main() { + int fails = 0; + /* Gemma 4 26B's 2816 at decode and verify heights, a prefill height, odd widths, the limit */ + const int Ms[] = {1, 4, 16, 37}; + for (int M : Ms) fails += case_nan(M, 2816, M % 2 ? 64 : 0, 2); + for (int M : Ms) fails += case_jas(M, 2816, M % 2 ? 0 : 128, 2); + fails += case_nan(3, 1000, 24, 1) + case_jas(3, 1000, 24, 1); + fails += case_nan(2, 6144, 0, 0) + case_jas(2, 6144, 16, 0); + fails += case_nan(5, 256, 8, 1) + case_jas(5, 5376, 0, 1); + std::printf("norm joins: %d failure(s)\n", fails); + return fails ? 1 : 0; +} diff --git a/tests/g4k_emu/test_pick.cpp b/tests/g4k_emu/test_pick.cpp new file mode 100644 index 00000000..2dff13b9 --- /dev/null +++ b/tests/g4k_emu/test_pick.cpp @@ -0,0 +1,62 @@ +/* pair_argmax: device kernel (emulated) vs the host row vs brute force, over the row-interleaved + * [rows][world][R][2] layout the all_gather produces -- ties, negative (unfilled) ids, -inf, empty rows. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "g4k.h" +#include +#include +#include +#include +#include +extern "C" const RadKernelInfo* rad_kernel_at(int); +extern "C" int rad_kernel_count(void); +int main() { + std::mt19937 rng(11); + const RadKernelInfo* host = nullptr; + for (int i = 0; i < rad_kernel_count(); ++i) + if (!std::strcmp(rad_kernel_at(i)->op, "pair_argmax") && rad_kernel_at(i)->domain == RAD_DOMAIN_HOST) host = rad_kernel_at(i); + int fails = 0, cases = 0; + for (int world : {1, 2, 4, 8}) for (int R : {2, 4}) for (int rows : {1, 7, 16, 33, 240}) for (int rank3 = 0; rank3 < 2; ++rank3) { + const int n = world * R; + std::vector pairs((size_t)rows * n * 2); + std::vector ref(rows), dev(rows, 12345), hst(rows, 12345), pitched(rows * 3, 777); + std::vector dval(rows), hval(rows); + for (int r = 0; r < rows; ++r) { + int32_t bid = -1; float bv = -INFINITY; + const int mode = rng() % 5; /* 0: ties, 1: some unfilled, 2: all unfilled, else random */ + for (int j = 0; j < n; ++j) { + int32_t id = (int32_t)(rng() % 262144); + float v = mode == 0 ? 3.5f : std::ldexp((float)(int)(rng() % 2000) - 1000.f, -4); + if ((mode == 1 && rng() % 3 == 0) || mode == 2) { id = -1; v = -INFINITY; } + std::memcpy(&pairs[((size_t)r * n + j) * 2], &id, 4); + pairs[((size_t)r * n + j) * 2 + 1] = v; + if (id >= 0 && (bid < 0 || v > bv || (v == bv && id < bid))) { bid = id; bv = v; } + } + ref[r] = bid; + } + RadTensor t[3]{}; + t[0].data = pairs.data(); t[0].dtype = RAD_F32; + if (rank3) { t[0].rank = 3; t[0].shape[0] = rows; t[0].shape[1] = n; t[0].shape[2] = 2; t[0].stride[0] = n * 2; t[0].stride[1] = 2; t[0].stride[2] = 1; } + else { t[0].rank = 2; t[0].shape[0] = rows; t[0].shape[1] = 2 * n; t[0].stride[0] = 2 * n; t[0].stride[1] = 1; } + t[1].dtype = RAD_I32; t[1].rank = 2; t[1].shape[0] = rows; t[1].shape[1] = 1; t[1].stride[0] = 1; t[1].stride[1] = 1; + t[2].dtype = RAD_F32; t[2].rank = 2; t[2].shape[0] = rows; t[2].shape[1] = 1; t[2].stride[0] = 1; t[2].stride[1] = 1; + RadParam p[3]{}; p[0] = {"M", RAD_P_INT, rows}; p[1] = {"n", RAD_P_INT, n}; p[2].key = "dtype"; p[2].kind = RAD_P_STR; p[2].sval = "f32"; + RadArgs a{}; a.t = t; a.n_t = 3; a.p = p; a.n_p = 3; + t[1].data = dev.data(); t[2].data = dval.data(); + int rc = g4k_pair_argmax_f32(&a, nullptr); + t[1].data = hst.data(); t[2].data = hval.data(); + int rh = host->launch(&a, nullptr); + /* a pitched output: every third element, the rest must stay untouched */ + RadTensor tp = t[1]; tp.data = pitched.data(); tp.stride[0] = 3; RadTensor t3[3] = {t[0], tp, RadTensor{}}; + RadArgs ap = a; ap.t = t3; + int rp = g4k_pair_argmax_f32(&ap, nullptr); + bool ok = rc == 0 && rh == 0 && rp == 0; + for (int r = 0; r < rows && ok; ++r) { + ok = dev[r] == ref[r] && hst[r] == ref[r] && pitched[3 * r] == ref[r] && pitched[3 * r + 1] == 777 && pitched[3 * r + 2] == 777; + if (ok && ref[r] < 0) ok = std::isinf(dval[r]) && dval[r] < 0; + } + ++cases; if (!ok) { ++fails; std::printf("FAIL world %d R %d rows %d rank%d\n", world, R, rows, rank3 ? 3 : 2); } + } + std::printf("pair_argmax: %d cases, %d failure(s)\n", cases, fails); + return fails != 0; +} From 368d0363eb2666425341fdefac4420728fcbca60 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 10:02:09 -0500 Subject: [PATCH 08/24] arch: Gemma 4's reply format into arch/common, for both Gemma 4 plugins Two plugins are about to serve Gemma 4 -- gemma4_bf16 the CT-INT4 dense release and arch/gemma4 the bf16 / fp8-expert containers -- and the reply format is the model's, not the weights': the thought channel, and calls written as a name and one object in Gemma's dialect of JSON. One declaration in the shared header library (installed as ), so the two cannot drift apart and the reply-format tests read what both export. The declaration moves unchanged, from gemma4_bf16::chat_format_decl() to rad::arch::gemma4_chat_format(); chatparse_gemma4_test follows it. Co-Authored-By: Claude Opus 5.5 --- .../rad_gemma4_chat.h} | 16 +++++++++------ arch/gemma4_bf16/gemma4_bf16.cpp | 7 +++---- tests/chatparse_gemma4_test.cpp | 20 +++++++++---------- 3 files changed, 23 insertions(+), 20 deletions(-) rename arch/{gemma4_bf16/gemma4_chat_format.h => common/rad_gemma4_chat.h} (81%) diff --git a/arch/gemma4_bf16/gemma4_chat_format.h b/arch/common/rad_gemma4_chat.h similarity index 81% rename from arch/gemma4_bf16/gemma4_chat_format.h rename to arch/common/rad_gemma4_chat.h index 7520d298..74dc4ae7 100644 --- a/arch/gemma4_bf16/gemma4_chat_format.h +++ b/arch/common/rad_gemma4_chat.h @@ -1,4 +1,4 @@ -/* gemma4_chat_format.h -- how Gemma 4 spells a turn: its reasoning and its tool calls, as data. +/* rad_gemma4_chat.h -- how Gemma 4 spells a turn: its reasoning and its tool calls, as data. * * The chat template is one llama.cpp reads with a hand-written handler, so the template analysis * finds nothing in it, and the engine would serve the model with no reasoning split and refuse @@ -16,14 +16,17 @@ * the answer, and a lone . `reasoning_anywhere` reads the first as reasoning and drops * the second, so neither reaches the content. * - * Kept in a header of its own so the reply-format tests read the declaration the plugin exports - * rather than a copy of it. */ + * Here rather than in one plugin because two plugins serve Gemma 4 -- arch/gemma4 (bf16 and fp8 + * experts) and arch/gemma4_bf16 (the CT-INT4 dense release) -- and the format is the model's, not + * the weights'. One declaration, so the two cannot drift apart, and so the reply-format tests read + * the declaration the plugins export rather than a copy of it. */ #pragma once #include "rad_builder.h" -namespace gemma4_bf16 { +namespace rad { +namespace arch { -inline const RadChatFormat* chat_format_decl() { +inline const RadChatFormat* gemma4_chat_format() { static const char* const kBreaks[] = { "<|tool_call>" }; static const char* const kTriggers[] = { "<|tool_call>" }; static const RadChatFormat f = [] { @@ -57,4 +60,5 @@ inline const RadChatFormat* chat_format_decl() { return &f; } -} /* namespace gemma4_bf16 */ +} /* namespace arch */ +} /* namespace rad */ diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index a12acb94..f61206cc 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -9,8 +9,7 @@ * cap * tanh(x / cap). */ #include - -#include "gemma4_chat_format.h" +#include #include #include @@ -881,8 +880,8 @@ static void step(RadCtx* c, const RadBatch* batch) { } } -/* The reply format: gemma4_chat_format.h. */ -const RadChatFormat* chat_format(const RadModelMeta*) { return chat_format_decl(); } +/* The reply format: the model's, shared with arch/gemma4 (arch/rad_gemma4_chat.h). */ +const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_format(); } #ifndef RAD_ARCH_NO_EXPORTS RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0", diff --git a/tests/chatparse_gemma4_test.cpp b/tests/chatparse_gemma4_test.cpp index 6e62a944..8a6a36d3 100644 --- a/tests/chatparse_gemma4_test.cpp +++ b/tests/chatparse_gemma4_test.cpp @@ -2,7 +2,7 @@ * name and ONE object in a dialect of JSON. * * Gemma 4's template is one llama.cpp reads with a hand-written handler, so the template analysis - * finds no format in it and the plugin declares one (arch/gemma4_bf16/gemma4_chat_format.h): + * finds no format in it and the plugins declare one (arch/common/rad_gemma4_chat.h): * * <|channel>thought\n ... reasoning * <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3} a call, repeated for more @@ -28,7 +28,7 @@ #include "text/chatparse.h" #include "text/tokenizer.h" -#include "../arch/gemma4_bf16/gemma4_chat_format.h" +#include #include @@ -60,7 +60,7 @@ static std::string fixture() { static const Model& gemma() { static const Model m = { "gemma4", "gemma4", "", "", { "", "", "<|tool_response>" }, - gemma4_bf16::chat_format_decl() }; + rad::arch::gemma4_chat_format() }; return m; } @@ -136,7 +136,7 @@ static std::shared_ptr parser(const std::string& gp, bool too ChatFormat f; std::string why; std::shared_ptr r; - if (chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why) < 0 || + if (chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why) < 0 || ReplyFormat::compile(f, &r, &why) < 0) ::radtest::fail(__FILE__, __LINE__, "gemma4 format: " + why); return r; @@ -167,7 +167,7 @@ static const std::string kAfter = "<|channel>thought\n"; TEST(the_declaration_is_a_format_the_parser_runs) { ChatFormat f; std::string why; - CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why)); + CHECK_OK(chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why)); CHECK_OK(chat_format_check(f, &why)); CHECK(f.object_args()); CHECK(f.reasoning_anywhere); @@ -189,7 +189,7 @@ TEST(the_declaration_is_a_format_the_parser_runs) { * the tagged family, no dialect, reasoning at the start only -- and Gemma's declaration read that * way is refused by name rather than run wrongly. */ TEST(an_older_struct_reads_the_object_fields_as_zero) { - RadChatFormat c = *gemma4_bf16::chat_format_decl(); + RadChatFormat c = *rad::arch::gemma4_chat_format(); c.struct_size = (uint32_t)offsetof(RadChatFormat, args_form); ChatFormat f; std::string why; @@ -204,7 +204,7 @@ TEST(an_older_struct_reads_the_object_fields_as_zero) { TEST(an_object_format_the_parser_cannot_read_is_refused_by_name) { auto refused = [](void (*edit)(RadChatFormat&), const char* word) { - RadChatFormat c = *gemma4_bf16::chat_format_decl(); + RadChatFormat c = *rad::arch::gemma4_chat_format(); edit(c); ChatFormat f; std::string why; @@ -662,7 +662,7 @@ static int admits(const std::string& gbnf, const std::string& prefix, const std: static std::string grammar_for(const ChatGrammarRequest& gq) { ChatFormat f; std::string why; - CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why)); + CHECK_OK(chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why)); ChatGrammar g; CHECK_OK(chat_format_grammar(f, gq, &g, &why)); return g.text; @@ -678,7 +678,7 @@ TEST(the_call_grammar_admits_what_the_model_writes_and_refuses_the_rest) { gq.generation_prompt = b->prompt().generation_prompt; ChatFormat f; std::string why; - CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why)); + CHECK_OK(chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why)); ChatGrammar g; CHECK_OK(chat_format_grammar(f, gq, &g, &why)); CHECK(g.lazy); @@ -791,7 +791,7 @@ TEST(the_chat_bridge_serves_gemma_from_its_declaration) { REQUIRE(v != nullptr); CHECK(v->is_eog(6)); /* <|tool_response>: after its calls the model stops there */ server::ChatTemplateBridge br; - CHECK_OK(br.init(*v, gemma4_bf16::chat_format_decl(), "gemma4_bf16")); + CHECK_OK(br.init(*v, rad::arch::gemma4_chat_format(), "gemma4_bf16")); CHECK(br.supports_tools()); CHECK(br.tool_refusal().empty()); From c2bd41fe95205ea1a5e41af51fdbe1cb0d1a992a Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 10:05:24 -0500 Subject: [PATCH 09/24] arch/gemma4: Gemma 4 text with z-lab's DFlash drafter -- the 26B-A4B MoE and the dense sizes Claims ("gemma4", ""): a container converted from Google's bf16 checkpoint, the recipe choosing what is fp8. gemma4_bf16 keeps ("gemma4", "compressed-tensors"), the CT-INT4 dense release; the two do not overlap. Serves gemma-4-26B-A4B-it (128 experts of 704, top 8) and the dense sizes without per-layer embeddings, with a DFlash block-diffusion drafter merged at convert time. The readings that stay plausible when wrong, each explained at its site: - Proportional rope is not a partial rotary: the full layers rotate the first 64 frequency pairs of the 512-wide head at theta^(-2j/512), pair j = channels (j, j + 256), declared as full-width NeoX with the frequencies past pair 63 divided by 1e30 through the YaRN ramp `rope` carries. - K is V on the full layers: V is the un-normed, un-rotated k projection, so its norm is issued before the key norm overwrites `k`. - The router reads the residual through a gainless rmsnorm times its `scale` times hidden^-0.5, and per_expert_scale multiplies after the renormalised top-k. - Two post-norms a layer's feed-forward, one an arm, each arm's partial reduced before its norm; both partials share one [2T, n_embd] buffer so one all-reduce carries them. - The embedding scale is sqrt(hidden) rounded to bf16 (53.0, not 53.066). - The sliding layers' KV group is RAD_KV_FULL with the window on the attention op: a WINDOW group is not prefix-cached, and on this tree a hit on one re-prefills; FULL keeps the hit. - fp8 experts are two tables by parity, so a rank holds an even count; down at K = 704 cannot be fp8 (whole 128-blocks), hence the 768-padded recipe. - The sharded draft head's merge is pair_argmax at R = 2 on the wire. - The drafter's tap copy is declared at the end of the layer it taps, where it is issued. The buffer planner takes liveness from declaration order; declared once after the trunk, it let the plan share `dflash_src` with `moe_edn`, which every MoE layer writes, whenever the sizes allowed. At --max-num-seqs 16 they did, and on the cards DFlash accepted 2% of its drafts (97 tok/s against 135 with speculation off and 186 with the taps intact), the text fluent throughout. The sandwich joins are asked for as norm_add_norm / join_add_scale (gemma4k) and declared as the rmsnorm / add chain where nothing serves them; RADIANCE_GEMMA4_FUSE=0 asks for the chain. The reply format is the shared one (arch/rad_gemma4_chat.h), so tool calls are parsed in the engine; the plugin as measured declared reasoning only and left calls to an out-of-tree sidecar, so the call path is untested on this plugin's containers. arch_test: the MoE trunk declares both arms and six of each join; both KV groups FULL with the window on the op; the full layers' rope over the whole head with the ramp at 63.5..64; with the joins refused, the chain is declared and issued instead; both Gemma 4 plugins export one format; with a DFlash drafter, `dflash_src` is live from the first tap layer (its range overlaps `moe_edn`'s, so no plan can share them) and a step writes each tap once. Measured on 4x R9700 at TP4 (gemma-4-26B-A4B-it + DFlash, gate_up experts block fp8), with gemma4k and --draft-window adaptive: a story at T 1 177 tok/s, greedy thinking 572 tok/s, code at T 0 319-334 tok/s. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/CMakeLists.txt | 14 + arch/gemma4/gemma4.cpp | 1638 +++++++++++++++++++++++++++++++++++ arch/gemma4/gemma4_dflash.h | 592 +++++++++++++ tests/arch_test.cpp | 250 ++++++ 4 files changed, 2494 insertions(+) create mode 100644 arch/gemma4/CMakeLists.txt create mode 100644 arch/gemma4/gemma4.cpp create mode 100644 arch/gemma4/gemma4_dflash.h diff --git a/arch/gemma4/CMakeLists.txt b/arch/gemma4/CMakeLists.txt new file mode 100644 index 00000000..54e911f6 --- /dev/null +++ b/arch/gemma4/CMakeLists.txt @@ -0,0 +1,14 @@ +# gemma4 -- the architecture plugin for Gemma 4's text model (Gemma4ForConditionalGeneration / +# Gemma4ForCausalLM; the 26B-A4B MoE and the dense sizes without per-layer embeddings), with a +# z-lab DFlash drafter merged at convert time. +# +# Built inside radiance's tree (arch/ discovers it) or on its own against an installed radiance: +# cmake -S arch/gemma4 -B build-gemma4 -DCMAKE_PREFIX_PATH=/opt/radiance && cmake --build build-gemma4 +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(gemma4 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(gemma4 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma4.cpp) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp new file mode 100644 index 00000000..106ee95f --- /dev/null +++ b/arch/gemma4/gemma4.cpp @@ -0,0 +1,1638 @@ +/* gemma4 -- Gemma 4 text decoders (26B-A4B MoE, and the dense members of the family): a bf16 + * trunk, routed experts bf16 or block fp8 (see FP8 EXPERTS), and the DFlash block-diffusion + * drafter. + * + * ============================== THE SHAPE (gemma-4-26B-A4B-it) ============================== + * + * 30 layers, hidden 2816, vocab 262144 (tied to the embedding), rms_norm_eps 1e-6 + * layer_types: five `sliding_attention` then one `full_attention`, five times over + * sliding: 16 heads / 8 KV heads x 256, rope theta 1e4 over the whole head, window 1024 + * full: 16 heads / 2 KV heads x 512, PROPORTIONAL rope theta 1e6 over a quarter of it, + * and K IS V (`attention_k_eq_v`): there is no v_proj, V is the k projection before + * its norm and its rotary + * attention scale 1.0 -- the q/k norms carry the temperature; q and k RMS-normed per head with a + * gain, v with none + * Gemma's sandwich norms, plain gains (x_hat * w, not 1 + w) + * the feed-forward is TWO ARMS BESIDE EACH OTHER, both reading the same residual: + * dense pre_feedforward_layernorm -> gate|up 2112 (gelu-tanh) -> down + * -> post_feedforward_layernorm_1 + * routed router over rmsnorm(x) * scale * hidden^-0.5 -> softmax -> top 8 of 128 -> + * renormalised -> times per_expert_scale[expert]; + * pre_feedforward_layernorm_2 -> 128 experts of 704 (gelu-tanh) -> + * post_feedforward_layernorm_2 + * sum -> post_feedforward_layernorm -> residual add + * layer_scalar multiplies the residual stream at the end of every layer + * embedding scaled by sqrt(hidden) AS A bf16 (53.0, not 53.066); final norm; tied lm_head; + * final_logit_softcapping 30 + * + * The reference is transformers' modeling_gemma4 (Gemma4TextDecoderLayer, Gemma4TextAttention, + * Gemma4TextRouter, _compute_proportional_rope_parameters), read at 5.19. + * + * ============================== THE READINGS THAT STAY PLAUSIBLE WHEN WRONG ============================== + * + * PROPORTIONAL ROPE IS NOT A PARTIAL ROTARY. It rotates the first 64 frequency PAIRS of a + * 512-wide head at theta^(-2j/512) -- the exponent divides by the HEAD, and pair j is channels + * (j, j + 256) -- and leaves the other 192 pairs at frequency zero. `rope` with rotary_dim 128 + * would pair (j, j + 64) at theta^(-2j/128), which is a different function that still produces + * fluent text. It is declared here as a full-width NeoX rotary whose frequencies past pair 63 + * are divided by 1e30 -- the YaRN blend `rope` already carries, with the ramp a step at 63.5..64 + * -- which evaluates to exactly the reference's angles below the step and to cos 1, sin ~1e-31 + * above it. See decl_full_rope(). + * + * V ON A FULL LAYER IS THE UN-NORMED, UN-ROTATED K PROJECTION, RMS-normed with a unit gain. So + * the value norm reads `k` BEFORE the key norm writes it, which is the issue order below. + * + * THE ROUTER DOES NOT READ THE FEED-FORWARD'S INPUT. It reads the residual stream through a + * GAINLESS norm, times its own `scale` vector, times hidden^-0.5 -- one `rmsnorm` with `scale` + * as the gain and `mult` the constant -- while the experts read pre_feedforward_layernorm_2's + * output and the dense arm pre_feedforward_layernorm's. + * + * per_expert_scale MULTIPLIES THE RENORMALISED WEIGHT, after the top-k. It is gathered by expert + * id with `embed_lookup` (a 128 x 1 table) and multiplied in with `mul`. + * + * THE TWO POST-NORMS OF THE ARMS ARE PER ARM, so under tensor parallel each arm's partial sum is + * reduced BEFORE its norm. The two partials sit in one [2T, n_embd] buffer -- dense rows first, + * routed rows after -- so one all-reduce carries both. + * + * ============================== TENSOR PARALLEL ============================== + * + * Heads split by rank, o and down by column with an all-reduce, the vocabulary by row. The full + * layers' two KV heads are REPLICATED past two ranks -- at four, ranks {0,1} hold KV head 0 and + * {2,3} KV head 1, each reading its head's row span of k_proj -- the scheme rad_arch.h's geom_from + * describes. Routed experts are EXPERT-PARALLEL (whole experts, 128/world a rank): a 704-wide + * expert is 5.5 fp8 blocks and has no block-aligned width split. The router is replicated, so + * every rank agrees on the routing without a collective and the arm's all-reduce sums the ranks' + * experts. + * + * ============================== FP8 EXPERTS ============================== + * + * The experts are ~90% of the weight bytes and the decode step reads whichever were routed, so + * their width is the step's bandwidth. Each projection is served as the container holds it -- + * bf16 by `moe_gemm`, block fp8 (the recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`) by + * `moe_gemm_q` at fp8a8 over an E4M3 input -- per layer and per projection (expert_format): + * + * gate_up [2 * 704, 2816]: 1408 rows are whole 64-row tiles and eleven 128-row scale blocks + * (one straddles gate and up, which only shares a scale); K is 22 blocks. fp8 at the + * checkpoint's own width. + * down [2816, 704]: K is the expert width and moe_gemm_q reads K in whole 128-column + * blocks, which 704 is not. It stays bf16 -- unless the checkpoint is padded to 768 + * first, outside the engine: zero rows of gate and up give gelu(0) * 0 = 0 in the + * padded columns, which meet zero columns of down, so the function is unchanged, and + * then both projections are fp8 (data/recipes/gemma4-26b-a4b-df-pad768.recipe). + * + * ============================== WHAT THIS PLUGIN DOES NOT YET DECLARE ============================== + * + * the vision tower (Gemma 4's, which arch/embgemma2 already declares for an encoder) -- this + * serves text; a container that carries a tower is served with --mm-max-patches 0 and the + * server refuses a media part by name; + * an fp8 attention or dense arm -- under a tenth of the weight bytes, and the dense arm's 2112 + * is not whole 128-blocks either. + */ +#include +#include +#include + +#include "gemma4_dflash.h" + +#include +#include +#include +#include +#include +#include + +namespace gemma4 { + +using namespace rad::arch; + +/* ============================================================== metadata */ +/* Gemma4ForConditionalGeneration nests the text model's config under `text_config`; a + * Gemma4ForCausalLM checkpoint does not. rad-convert flattens nested keys with dots, so every key + * is asked for in both spellings, text_config's first. */ +static long long tc_geti(const RadModelMeta* m, const char* k, long long dflt) { + const long long sentinel = -0x7FFFFFFFll; + char key[160]; + std::snprintf(key, sizeof key, "text_config.%s", k); + long long v = rad_meta_geti(m, key, sentinel); + if (v == sentinel) v = rad_meta_geti(m, k, sentinel); + return v == sentinel ? dflt : v; +} +static double tc_getf(const RadModelMeta* m, const char* k, double dflt) { + char key[160]; + std::snprintf(key, sizeof key, "text_config.%s", k); + if (rad_meta_gets(m, key, nullptr)) return rad_meta_getf(m, key, dflt); + return rad_meta_getf(m, k, dflt); +} +static const char* tc_gets(const RadModelMeta* m, const char* k, const char* dflt) { + char key[160]; + std::snprintf(key, sizeof key, "text_config.%s", k); + const char* v = rad_meta_gets(m, key, nullptr); + return v ? v : rad_meta_gets(m, k, dflt); +} +/* A JSON boolean reaches the meta as 1/0 or as true/false, depending on the converter's path. */ +static bool tc_getb(const RadModelMeta* m, const char* k, bool dflt) { + const char* s = tc_gets(m, k, nullptr); + if (!s) return dflt; + if (!std::strcmp(s, "true") || !std::strcmp(s, "True")) return true; + if (!std::strcmp(s, "false") || !std::strcmp(s, "False") || !std::strcmp(s, "null")) return false; + return std::atoll(s) != 0; +} + +/* A value as a bf16 tensor holds it: round to nearest even on the top 16 bits of the f32. The + * reference's embedding scale is a bf16 buffer, so sqrt(2816) = 53.066 multiplies as 53.0. */ +static double bf16_round(double v) { + float f = (float)v; + uint32_t u; + std::memcpy(&u, &f, 4); + u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u; + std::memcpy(&f, &u, 4); + return (double)f; +} + +/* "1 6 11 17 22 27" -> the trunk layers whose output the drafter reads. Out-of-range entries are + * dropped (llama_fp8.cpp says why). */ +static int parse_ids(const char* s, int64_t n, int* out, int max) { + if (!s) return 0; + int k = 0; + for (const char* p = s; *p && k < max;) { + while (*p == ' ' || *p == ',' || *p == '[' || *p == ']') ++p; + if (!*p) break; + char* e = nullptr; + const long v = std::strtol(p, &e, 10); + if (e == p) break; + p = e; + if (v >= 0 && v < n) out[k++] = (int)v; + } + return k; +} + +/* "sliding_attention full_attention ..." -> 1 for each full layer. */ +static int parse_types(const char* s, std::vector* full) { + full->clear(); + if (!s) return RAD_E_INVAL; + for (const char* p = s; *p;) { + while (*p == ' ' || *p == ',' || *p == '[' || *p == ']' || *p == '"') ++p; + if (!*p) break; + const char* t = p; + while (*p && *p != ' ' && *p != ',' && *p != ']' && *p != '"') ++p; + const size_t len = (size_t)(p - t); + if (len == 14 && !std::strncmp(t, "full_attention", 14)) full->push_back(1); + else if (len == 17 && !std::strncmp(t, "sliding_attention", 17)) full->push_back(0); + else { + fprintf(stderr, "radiance: gemma4: layer_types names '%.*s'; this plugin knows " + "full_attention and sliding_attention\n", (int)len, t); + return RAD_E_UNSUPPORTED; + } + } + return RAD_OK; +} + +/* ============================================================== the model */ + +/* One attention kind: the sliding and the full layers differ in head width, KV heads, rotary + * and window, and in whether V has a projection of its own. */ +struct Kind { + int64_t hd = 0; /* head_dim */ + int64_t nh = 0; /* query heads, THIS rank */ + int64_t nkv = 0; /* KV heads, THIS rank */ + int64_t nkv_all = 0; + bool kv_repl = false; /* KV heads replicated across ranks (world > nkv_all) */ + int64_t kv_off = 0; /* this rank's first KV row in the unsharded k/v projection */ + double theta = 0.0; + int64_t window = 0; /* attn_paged's: key j visible to query i when i - j < window */ + int64_t rot_pairs = 0; /* frequency pairs that rotate; < hd/2 is proportional rope */ + bool k_eq_v = false; + rad_kvgroup kv = 0; + int64_t q() const { return nh * hd; } + int64_t kv_dim() const { return nkv * hd; } +}; + +struct Layer { + int full = 0; + /* attention */ + rad_weight w_anorm = 0, w_qkv = 0, w_q = 0, w_k = 0, w_qn = 0, w_kn = 0, w_o = 0, w_apost = 0; + rad_op op_anorm = 0, op_qkv = 0, op_qknr = 0, op_lift = 0; + rad_op op_q = 0, op_k = 0, op_vnorm = 0, op_qn = 0, op_kn = 0, op_qrope = 0, op_krope = 0; + rad_op op_store = 0, op_attn = 0, op_o = 0, op_ar_o = 0, op_apost = 0, op_add_a = 0; + /* dense arm */ + rad_weight w_fnorm = 0, w_gu = 0, w_dn = 0, w_fpost1 = 0; + rad_op op_fnorm = 0, op_gu = 0, op_act = 0, op_dn = 0; + /* routed arm. Each projection's experts are plain bf16 or block fp8, whichever the container + * holds (expert_format). A bf16 projection's handles are its experts in order, one table; an + * fp8 one's are the EVEN local experts then the ODD ones, codes in w_egu/w_edn and the scale + * views in w_egus/w_edns, so each parity is one run (see declare). */ + rad_weight w_rscale = 0, w_router = 0, w_escale = 0, w_enorm = 0, w_fpost2 = 0; + std::vector w_egu, w_edn, w_egus, w_edns; + bool gu_fp8 = false, dn_fp8 = false; + rad_op op_rnorm = 0, op_router = 0, op_topk = 0, op_escale = 0, op_emul = 0, op_enorm = 0; + rad_op op_scatter = 0, op_egu = 0, op_eact = 0, op_eq = 0, op_edn = 0, op_gather = 0; + /* the join */ + rad_weight w_fpost = 0, w_scalar = 0; + rad_op op_ar_f = 0, op_fpost1 = 0, op_fpost2 = 0, op_fsum = 0, op_fpost = 0, op_add_f = 0; + rad_op op_scale = 0; + /* THE SANDWICH JOINS, FUSED (gemma4k): op_join_a is apost + add_a + fnorm, op_join_f the + * routed layer's fpost1 + fpost2 + fsum + fpost + add_f + scale. Zero where not served, and + * then the chain above is declared and issued instead. */ + rad_op op_join_a = 0, op_join_f = 0; + /* the drafter's tap, on a layer the drafter reads (see declare) */ + rad_op op_tap = 0; +}; + +struct Model { + Names nm{""}; + Geom g{}; /* the sliding kind's geometry, and everything model-wide */ + Kind ks{}, kf{}; /* sliding, full */ + int64_t n_layer = 0, E = 0; + int64_t n_ff = 0; /* dense arm, THIS rank */ + bool moe = false; + int64_t n_expert = 0, n_local = 0, expert_base = 0, top_k = 0, n_ffe = 0; + int64_t moe_rows = 0; /* tokens a routed pass */ + double escale = 1.0, softcap = 0.0; + + rad_buf b_x = 0, b_h = 0, b_o = 0; + rad_buf b_qkv = 0, b_qs = 0, b_atts = 0; /* sliding */ + rad_buf b_qf = 0, b_kf = 0, b_vf = 0, b_attf = 0; /* full */ + rad_buf b_ff2 = 0, b_gu = 0, b_act = 0; /* the arms' join; the dense arm */ + rad_buf b_rn = 0, b_logit = 0, b_ids = 0, b_ew = 0, b_es = 0, b_hx = 0; + rad_buf b_sorted = 0, b_eoff = 0, b_ecnt = 0, b_egu = 0, b_eact = 0, b_edn = 0; + /* the experts' E4M3 inputs, declared only where some layer's projection is fp8: gate_up's + * (the normed block input, a row a token) and down's (the gated product, a row a slot) */ + rad_buf b_hq = 0, b_hqs = 0, b_eq = 0, b_eqs = 0; + int n_gu_fp8 = 0, n_dn_fp8 = 0; /* layers whose projection is fp8 */ + rad_buf b_hout = 0, b_logits = 0; + + rad_weight w_tok = 0, w_onorm = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_onorm = 0, op_gather = 0, op_logits = 0, op_cap = 0; + + enum { MAX_TAPS = 8 }; + int n_taps = 0; + int tap_layer[MAX_TAPS] = {}; + rad_buf b_dfsrc = 0; + + Dflash1 df{}; + Dflash1::Wire dfw{}; + rad_kvgroup kv_draft = 0; + bool have_df = false; + + std::vector layers; +}; + +static Model g_model[MAX_RANKS]; + +/* ============================================================== geometry */ + +static int split_heads(Kind& k, int64_t nh_all, int world, int rank, const char* what) { + if (nh_all % world) { + fprintf(stderr, "radiance: gemma4: %lld %s query heads do not divide over %d ranks\n", + (long long)nh_all, what, world); + return RAD_E_INVAL; + } + k.nh = nh_all / world; + if (world <= k.nkv_all) { + if (k.nkv_all % world) { + fprintf(stderr, "radiance: gemma4: %lld %s KV heads do not divide over %d ranks\n", + (long long)k.nkv_all, what, world); + return RAD_E_INVAL; + } + k.nkv = k.nkv_all / world; + k.kv_repl = false; + k.kv_off = rank * k.nkv * k.hd; + } else { + /* REPLICATED: ranks [i*r, (i+1)*r) share KV head i, r = world / nkv_all. A rank's query + * heads [rank*nh, (rank+1)*nh) all belong to that head because gqa = nh_all / nkv_all is a + * multiple of nh exactly when world is a multiple of nkv_all -- which is checked. */ + if (world % k.nkv_all) { + fprintf(stderr, "radiance: gemma4: %d ranks cannot replicate %lld %s KV heads; the " + "world must be a multiple of the KV head count\n", world, + (long long)k.nkv_all, what); + return RAD_E_INVAL; + } + k.nkv = 1; + k.kv_repl = true; + k.kv_off = (rank / (world / k.nkv_all)) * k.hd; + } + return RAD_OK; +} + +/* THE FULL LAYERS' ROTARY (see the header). `rope` rotates n_head + n_head_kv heads of its operand, + * so a q-only tensor is n_head = nh, n_head_kv = 0 and a k-only one n_head = nkv. */ +static rad_op decl_full_rope(RadBuilder* b, const Kind& k, int64_t rows, int64_t heads) { + const int64_t half = k.hd / 2; + if (k.rot_pairs >= half) + return RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", k.hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0), + RAD_F64("theta", k.theta), RAD_F64("scale", 1.0), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", k.hd)), + RAD_NOWEIGHTS); + /* frequency(inv, i) = inv / factor for i >= high, inv for i <= low (rad_yarn.h); the + * magnitude multiplies cos and sin and stays 1. */ + return RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", k.hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0), + RAD_F64("theta", k.theta), RAD_F64("scale", 1.0), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", k.hd), + RAD_F64("yarn_factor", 1e30), + RAD_F64("yarn_low", (double)k.rot_pairs - 0.5), + RAD_F64("yarn_high", (double)k.rot_pairs), + RAD_F64("yarn_magnitude", 1.0)), + RAD_NOWEIGHTS); +} + +/* ============================================================== the drafter */ + +static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Model& m, int base_layer) { + Names& nm = m.nm; + Geom dg = m.g; + dg.n_layer = rad_meta_geti(meta, "draft.num_hidden_layers", 0); + dg.head_dim = rad_meta_geti(meta, "draft.head_dim", 0); + dg.n_head_all = rad_meta_geti(meta, "draft.num_attention_heads", 0); + dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0); + dg.n_ff_all = rad_meta_geti(meta, "draft.intermediate_size", 0); + dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0); + dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta", + rad_meta_getf(meta, "draft.rope_theta", 0.0)); + dg.wadd = dg.wadd_qk = 0.0f; + if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 || + dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) { + fprintf(stderr, "radiance: gemma4: the container's `draft.` config does not describe a " + "DFlash drafter: layers %lld, heads %lld / kv %lld, head_dim %lld, ffn " + "%lld, rms_eps %g, rope_theta %g\n", + (long long)dg.n_layer, (long long)dg.n_head_all, (long long)dg.n_head_kv_all, + (long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta); + return RAD_E_INVAL; + } + if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) { + fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads " + "the target's embedding and head, so it is not this target's drafter\n", + (long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim)); + int s; + if ((s = divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)) < 0) return s; + if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s; + if ((s = divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff)) < 0) return s; + const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all); + if (dvocab != dg.n_vocab_all) { + fprintf(stderr, "radiance: gemma4: the drafter claims a %lld-token vocabulary and the " + "target has %lld\n", dvocab, (long long)dg.n_vocab_all); + return RAD_E_UNSUPPORTED; + } + + Dflash1::Config dc{}; + dc.n_taps = m.n_taps; + dc.escale = m.escale; + /* v1 states its block at the top level; a SpecForge config nests it under dflash_config. */ + long long trained = rad_meta_geti(meta, "draft.block_size", 0); + if (trained <= 0) trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); + if (trained < 2) { + fprintf(stderr, "radiance: gemma4: the DFlash checkpoint states no block_size\n"); + return RAD_E_FORMAT; + } + if ((long long)ctx->max_spec + 1 != trained) { + fprintf(stderr, "radiance: gemma4: the DFlash drafter was trained at block_size %lld, " + "which is %lld draft tokens, and this serve asks for %d. A block-diffusion " + "drafter denoises a fixed number of mask positions; run it at " + "--num-speculative-tokens %lld (or `auto`).\n", + trained, trained - 1, ctx->max_spec, trained - 1); + return RAD_E_UNSUPPORTED; + } + dc.block = trained; + if (dg.n_layer > Dflash1::MAX_LAYERS) return RAD_E_UNSUPPORTED; + { + std::vector full; + const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr); + if (lt) { + RAD_ARCH_TRY(parse_types(lt, &full)); + if ((int64_t)full.size() != dg.n_layer) { + fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and " + "it has %lld\n", full.size(), (long long)dg.n_layer); + return RAD_E_INVAL; + } + } else { + full.assign((size_t)dg.n_layer, 1); + } + bool any_swa = false; + for (int64_t l = 0; l < dg.n_layer; ++l) { + dc.full[l] = full[(size_t)l]; + any_swa = any_swa || !full[(size_t)l]; + } + if (any_swa) { + dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size", + rad_meta_geti(meta, "draft.sliding_window", 0)); + if (!rad_meta_geti(meta, "draft.use_sliding_window", 1) || dc.window <= 0) { + fprintf(stderr, "radiance: gemma4: the drafter names sliding layers and no " + "window\n"); + return RAD_E_INVAL; + } + } + } + + /* ONE CACHE FOR ALL FIVE LAYERS, unbounded, because the full layer reads every position. The + * sliding layers bound themselves with their attention op's `window`, so the declared drafter + * window is 0 and the core stages the whole context. A window group for the four sliding + * layers would cap their share at the window; it is the obvious saving once this runs. */ + RadKVGroupDecl dd{}; + dd.kind = RAD_KV_FULL; + dd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + dd.n_head_kv = dg.n_head_kv; + dd.head_dim = dg.head_dim; + m.kv_draft = rad_decl_kv_group(b, nm.f("kv_draft"), &dd); + for (int64_t l = 0; l < dg.n_layer; ++l) + RAD_ARCH_TRY(rad_bind_layer_kv(b, base_layer + (int)l, m.kv_draft)); + dg.kv_dtype = rad_dtype_name(dd.dtype); + + const int64_t qd = dg.n_head * dg.head_dim; + const int64_t kvd = dg.n_head_kv * dg.head_dim; + int64_t qr = dg.max_seqs * dc.block; + if (qr > dg.max_tok) qr = dg.max_tok; + const int64_t sr = dg.max_seqs * dc.steps(); + const int64_t tw = dc.n_taps * dg.n_embd; + + Dflash1::Wire& dw = m.dfw; + dw.src = m.b_dfsrc; + dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, tw}); + dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(tw)}); + dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd}); + dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd}); + dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)}); + dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd}); + dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd}); + dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd}); + dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd}); + dw.hq = decl_b(b, nm.f("df_hq"), RAD_F8E4M3, {qr, dg.n_embd}); + dw.hs = decl_b(b, nm.f("df_hs"), RAD_F32, {qr, fp8_blocks(dg.n_embd)}); + dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd}); + dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd}); + dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd}); + dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd}); + dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd}); + dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)}); + dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff}); + dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff}); + dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff}); + dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)}); + dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd}); + dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, dg.n_vocab}); + if (Dflash1::head_sharded(dg)) { + const int64_t R = Dflash1::kTopR; + dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, R}); + dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, R}); + dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, R, 2}); + dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * R, 2}); + } else { + dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, 1}); + } + if (!Dflash1::head_sharded(dg) && dg.world > 1) { + fprintf(stderr, "radiance: gemma4: the vocabulary (%lld) does not split evenly into whole " + "16-row blocks over %d ranks, which the drafter's sharded head needs\n", + (long long)dg.n_vocab_all, dg.world); + return RAD_E_UNSUPPORTED; + } + /* THE DRAFT, one row a draft position -- [n_seq * steps, 1], which is [n_seq, steps] with a + * pitch of `steps` -- and the engine reads it by the declaration below. */ + dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {sr, 1}); + + RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw)); + m.have_df = true; + + RadDrafterDecl drf{}; + drf.name = "dflash"; + drf.kind = RAD_DRAFT_BLOCK; + drf.depth = ctx->max_spec; + drf.block = dc.block; /* the anchor predicts nothing: block = depth + 1 */ + drf.proposal = dw.tokens; + drf.proposal_pitch = dc.steps(); + drf.window = 0; /* the full layer reads everything; see the group */ + drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", + rad_meta_geti(meta, "draft.mask_token_id", -1)); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: gemma4: the DFlash checkpoint declares no mask_token_id\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + + int nfull = 0; + for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l]; + rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld " + "sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the " + "trunk at %d tap(s). ONE forward over %lld rows proposes %lld tokens; the head is " + "the target's tied bf16 table, argmax %s", + (long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, nfull, + (long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head, + (long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, m.n_taps, + (long long)dc.block, (long long)dc.steps(), + Dflash1::head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary"); + return RAD_OK; +} + +/* ============================================================== the experts' encoding */ + +/* WHAT ONE EXPERT PROJECTION IS STORED AS -- the container's entry, or in rad-convert the recipe's + * plan for it (rad_weight_encoding) -- which picks the GEMM: plain bf16 is `moe_gemm`, block fp8 + * (fp8_e4m3 codes, a bf16 scale a 128x128 block) is `moe_gemm_q` at fp8a8. Anything else is + * refused by name. A builder with no model behind it answers nothing, and the declared dtype is + * then what is read: bf16. */ +enum { EXP_BF16 = 0, EXP_FP8 = 1 }; +static int expert_format(RadBuilder* b, const char* wn, int* fmt) { + RadEncoding e{}; + *fmt = EXP_BF16; + if (!weight_enc(b, wn, &e)) return RAD_OK; + if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return RAD_OK; + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + if (rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] && + e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 && + sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK) { + *fmt = EXP_FP8; + return RAD_OK; + } + char en[256]; + rad_enc_format(&e, en, sizeof en); + fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16 or " + "block fp8 (fp8_e4m3*bf16[128x128]). Convert with no rule for them, or with " + "`rtn codes=fp8_e4m3 block=128x128 scale=bf16`.\n", wn, en); + return RAD_E_DTYPE; +} + +/* ONE ENCODING A PROJECTION A LAYER, because one table of experts takes one: the first local + * expert's decides, and every other has to match it. `what` is "gate_up" or "down". */ +static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base, int64_t n, + const char* what, int* fmt) { + for (int64_t e = 0; e < n; ++e) { + const char* wn = nm.f("blk.%lld.ffn_%s_exps.%lld.weight", (long long)l, what, + (long long)(base + e)); + int f = EXP_BF16; + RAD_ARCH_TRY(expert_format(b, wn, &f)); + if (e == 0) { *fmt = f; continue; } + if (f != *fmt) { + fprintf(stderr, "radiance: gemma4: '%s' is %s and expert %lld of the same layer is %s; " + "one layer's %s experts take one encoding (a recipe rule for them " + "matches all of a layer's or none)\n", wn, + f == EXP_FP8 ? "block fp8" : "bf16", (long long)base, + *fmt == EXP_FP8 ? "block fp8" : "bf16", what); + return RAD_E_DTYPE; + } + } + return RAD_OK; +} + +/* ============================================================== declare */ + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + if (ctx->is_draft) { + fprintf(stderr, "radiance: gemma4: this plugin has no draft scope\n"); + return RAD_E_UNSUPPORTED; + } + const char* q = meta->quant ? meta->quant : ""; + if (*q) { + fprintf(stderr, "radiance: gemma4 serves a container converted from the bf16 checkpoint " + "(google/gemma-4-*-it), with the recipe choosing what is fp8, and this one " + "declares '%s'.\n", q); + return RAD_E_UNSUPPORTED; + } + + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + Names& nm = m.nm; + Geom& g = m.g; + + /* ---- what this plugin is NOT, refused by name. */ + if (tc_geti(meta, "hidden_size_per_layer_input", 0) > 0 || + tc_geti(meta, "num_kv_shared_layers", 0) > 0 || tc_getb(meta, "use_double_wide_mlp", false) || + tc_getb(meta, "attention_bias", false)) { + fprintf(stderr, "radiance: gemma4: this checkpoint uses per-layer embeddings, shared KV " + "layers, a double-wide MLP or attention biases (the E2B/E4B shape); this " + "plugin serves the 26B-A4B and 31B shape\n"); + return RAD_E_UNSUPPORTED; + } + { + const char* act = tc_gets(meta, "hidden_activation", ""); + if (!act || std::strcmp(act, "gelu_pytorch_tanh")) { + fprintf(stderr, "radiance: gemma4: hidden_activation '%s'; this plugin serves " + "gelu_pytorch_tanh\n", act ? act : ""); + return RAD_E_UNSUPPORTED; + } + } + + /* ---- the geometry. Read, never derived: head_dim is not hidden / heads on this family. */ + m.n_layer = meta->n_layers > 0 ? meta->n_layers : tc_geti(meta, "num_hidden_layers", 0); + m.E = tc_geti(meta, "hidden_size", meta->n_embd); + const int64_t nh_all = tc_geti(meta, "num_attention_heads", meta->n_head); + const int64_t vocab = tc_geti(meta, "vocab_size", meta->n_vocab); + const int64_t ff_all = tc_geti(meta, "intermediate_size", meta->n_ff); + const double eps = tc_getf(meta, "rms_norm_eps", meta->rms_eps); + m.ks.hd = tc_geti(meta, "head_dim", meta->head_dim); + m.ks.nkv_all = tc_geti(meta, "num_key_value_heads", meta->n_head_kv); + m.kf.hd = tc_geti(meta, "global_head_dim", m.ks.hd); + m.kf.nkv_all = tc_geti(meta, "num_global_key_value_heads", m.ks.nkv_all); + m.kf.k_eq_v = tc_getb(meta, "attention_k_eq_v", false); + m.ks.theta = tc_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0); + m.kf.theta = tc_getf(meta, "rope_parameters.full_attention.rope_theta", 0.0); + m.ks.window = tc_geti(meta, "sliding_window", 0); /* HF: q - k < window, attn_paged's rule */ + m.softcap = tc_getf(meta, "final_logit_softcapping", 0.0); + if (m.n_layer <= 0 || m.E <= 0 || nh_all <= 0 || vocab <= 0 || ff_all <= 0 || !(eps > 0) || + m.ks.hd <= 0 || m.ks.nkv_all <= 0 || m.kf.hd <= 0 || m.kf.nkv_all <= 0 || + !(m.ks.theta > 0) || !(m.kf.theta > 0) || m.ks.window <= 0) { + fprintf(stderr, "radiance: gemma4: the container does not describe the model: layers " + "%lld, hidden %lld, heads %lld, vocab %lld, ffn %lld, eps %g, sliding %lld " + "x %lld kv theta %g window %lld, full %lld x %lld kv theta %g\n", + (long long)m.n_layer, (long long)m.E, (long long)nh_all, (long long)vocab, + (long long)ff_all, eps, (long long)m.ks.hd, (long long)m.ks.nkv_all, m.ks.theta, + (long long)m.ks.window, (long long)m.kf.hd, (long long)m.kf.nkv_all, m.kf.theta); + return RAD_E_INVAL; + } + /* The two rotaries. The sliding one is the ordinary full-head NeoX; the full one is read for + * its type and its proportion and refused if it is anything this plugin does not compute. */ + { + const char* st = tc_gets(meta, "rope_parameters.sliding_attention.rope_type", "default"); + const char* ft = tc_gets(meta, "rope_parameters.full_attention.rope_type", "default"); + const double prf = tc_getf(meta, "rope_parameters.full_attention.partial_rotary_factor", 1.0); + const double ff = tc_getf(meta, "rope_parameters.full_attention.factor", 1.0); + if (std::strcmp(st, "default") || (std::strcmp(ft, "default") && std::strcmp(ft, "proportional")) || + ff != 1.0 || !(prf > 0.0) || prf > 1.0) { + fprintf(stderr, "radiance: gemma4: rotary '%s' (sliding) and '%s' factor %g " + "proportion %g (full); this plugin computes default and " + "proportional at factor 1\n", st, ft, ff, prf); + return RAD_E_UNSUPPORTED; + } + m.ks.rot_pairs = m.ks.hd / 2; + /* int(rope_proportion * head_dim // 2), exactly as transformers computes it. */ + m.kf.rot_pairs = !std::strcmp(ft, "proportional") + ? (int64_t)std::floor(prf * (double)m.kf.hd / 2.0) + : m.kf.hd / 2; + if (m.kf.rot_pairs <= 0) return RAD_E_INVAL; + } + + std::vector full; + RAD_ARCH_TRY(parse_types(tc_gets(meta, "layer_types", nullptr), &full)); + if ((int64_t)full.size() != m.n_layer) { + fprintf(stderr, "radiance: gemma4: layer_types names %zu layers and the model has %lld\n", + full.size(), (long long)m.n_layer); + return RAD_E_INVAL; + } + + /* The model-wide Geom, which the shared helpers (and the drafter's copy) read. */ + g.n_layer = m.n_layer; + g.n_embd = m.E; + g.head_dim = m.ks.hd; + g.n_head_all = nh_all; + g.n_head_kv_all = m.ks.nkv_all; + g.n_ff_all = ff_all; + g.n_vocab_all = vocab; + g.max_tok = ctx->max_tok; + g.max_seqs = ctx->max_seqs; + g.max_ctx = ctx->max_ctx; + g.max_spec = ctx->max_spec; + g.max_logit_rows = ctx->max_seqs * (ctx->max_spec > 0 ? ctx->max_spec + 1 : 1); + if (g.max_logit_rows > ctx->max_tok) g.max_logit_rows = ctx->max_tok; + if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows; + g.rank = ctx->rank; + g.world = ctx->world_size > 0 ? ctx->world_size : 1; + g.wire_exact = ctx->tp_wire_lossy ? 0 : 1; + g.wire_min_bytes = ctx->tp_wire_min_bytes; + g.eps = (float)eps; + g.theta = (float)m.ks.theta; + g.rope_scale = 1.0f; + g.dtype = "bf16"; + g.act_dtype = RAD_BF16; + if (g.max_tok <= 0 || g.max_seqs <= 0) return RAD_E_INVAL; + const int W = g.world, R = g.rank; + RAD_ARCH_TRY(split_heads(m.ks, nh_all, W, R, "sliding")); + RAD_ARCH_TRY(split_heads(m.kf, nh_all, W, R, "full")); + g.n_head = m.ks.nh; + g.n_head_kv = m.ks.nkv; + RAD_ARCH_TRY(divide_or_fail(ff_all, W, "intermediate_size", &m.n_ff)); + g.n_ff = m.n_ff; + g.n_vocab = shard_extent(vocab, W, R); + g.vocab_off = shard_begin(vocab, W, R); + if (g.n_vocab <= 0) return RAD_E_INVAL; + const int64_t E = m.E, T = g.max_tok; + + /* ---- the routed arm's geometry. */ + m.moe = tc_getb(meta, "enable_moe_block", false); + if (m.moe) { + m.n_expert = tc_geti(meta, "num_experts", meta->n_expert); + m.top_k = tc_geti(meta, "top_k_experts", meta->n_expert_used); + m.n_ffe = tc_geti(meta, "moe_intermediate_size", 0); + if (m.n_expert <= 0 || m.top_k <= 0 || m.top_k > m.n_expert || m.n_ffe <= 0) { + fprintf(stderr, "radiance: gemma4: enable_moe_block with %lld experts, top %lld, of " + "%lld\n", (long long)m.n_expert, (long long)m.top_k, + (long long)m.n_ffe); + return RAD_E_INVAL; + } + RAD_ARCH_TRY(divide_or_fail(m.n_expert, W, "num_experts", &m.n_local)); + m.expert_base = (int64_t)R * m.n_local; + /* A pass bounds the [rows * top_k, ...] expert planes; 2048 tokens is one pass at the + * default chunk. */ + m.moe_rows = T < 2048 ? T : 2048; + } + + /* ---- the embedding scale and the rotary scaling the converter may have written. */ + m.escale = bf16_round(std::sqrt((double)E)); + RAD_ARCH_TRY(yarn_from(g, meta, "", m.ks.hd)); + if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f) { + fprintf(stderr, "radiance: gemma4: --rope-scaling is not implemented for this family's " + "two rotaries\n"); + return RAD_E_UNSUPPORTED; + } + + /* ---- the KV groups, one a geometry: the sliding layers' (256-wide heads) and the full + * layers' (512). + * + * THE SLIDING LAYERS' GROUP IS RAD_KV_FULL, NOT RAD_KV_WINDOW, and the window lives on the + * attention op (`window` 1024), which reads only the keys inside it. A WINDOW group is not + * prefix-cached (core/mem/prefix.cpp: a hit's blocks do not describe a cache whose floor + * moves). Before the scheduler knew that, a hit gave the sliding layers a table whose reused + * prefix was never written for this request -- recycled blocks of other conversations, and a + * reply that answers someone else's question; now a hit on a model with a windowed trunk group + * reuses nothing and re-prefills (core/sched). As FULL the group is cached with the others and + * a hit is kept, exactly; the drafter's KV gets no hole either. What it costs is the recycling + * below the window, which buys nothing here: the planner gives every paged group the same + * block count, so the full group bounds the tokens a card holds either way. */ + { + RadKVGroupDecl d{}; + d.kind = RAD_KV_FULL; + d.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + d.window = 0; + d.n_head_kv = m.ks.nkv; + d.head_dim = m.ks.hd; + m.ks.kv = rad_decl_kv_group(b, nm.f("kv_swa"), &d); + d.kind = RAD_KV_FULL; + d.window = 0; + d.n_head_kv = m.kf.nkv; + d.head_dim = m.kf.hd; + m.kf.kv = rad_decl_kv_group(b, nm.f("kv_full"), &d); + g.kv_dtype = rad_dtype_name(d.dtype); + } + + /* Gemma4ForConditionalGeneration keeps the text model under model.language_model; + * Gemma4ForCausalLM (a text-only export) under model. */ + const char* archs = rad_meta_gets(meta, "architectures", ""); + const char* L = (archs && std::strstr(archs, "Gemma4ForCausalLM")) ? "model" + : "model.language_model"; + + /* ---- THE EXPERTS' NAME MAPS, AND FROM THEM WHAT EACH LAYER'S EXPERTS ARE, before any buffer: + * an fp8 projection reads an E4M3 input that a bf16 one does not, and a plane nothing reads + * is still charged by the planner. One stacked tensor a projection a layer, sliced by the + * GLOBAL expert index -- this rank declares its window into the checkpoint's experts. */ + m.layers.resize((size_t)m.n_layer); + if (m.moe) { + const int64_t NL = m.n_local; + for (int64_t l = 0; l < m.n_layer; ++l) { + Layer& y = m.layers[(size_t)l]; + const long long ll = (long long)l; + const char* sgu = nm.ckpt("%s.layers.%lld.experts.gate_up_proj", L, ll); + const char* sdn = nm.ckpt("%s.layers.%lld.experts.down_proj", L, ll); + for (int64_t e = 0; e < NL; ++e) { + const long long ge = (long long)(m.expert_base + e); + RAD_ARCH_TRY(map_slice(b, nm.f("blk.%lld.ffn_gate_up_exps.%lld.weight", ll, ge), sgu, (int)ge)); + RAD_ARCH_TRY(map_slice(b, nm.f("blk.%lld.ffn_down_exps.%lld.weight", ll, ge), sdn, (int)ge)); + } + int fgu = EXP_BF16, fdn = EXP_BF16; + RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "gate_up", &fgu)); + RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "down", &fdn)); + y.gu_fp8 = fgu == EXP_FP8; + y.dn_fp8 = fdn == EXP_FP8; + /* moe_gemm_q's geometry, refused here by name rather than as a kernel miss. Its + * experts are two tables by parity, so a rank holds an even count of them. */ + if ((y.gu_fp8 || y.dn_fp8) && NL % 2) { + fprintf(stderr, "radiance: gemma4: block fp8 experts come in pairs on a rank (the " + "fp8 grouped GEMM takes them as two tables by parity); this rank " + "holds %lld\n", (long long)NL); + return RAD_E_INVAL; + } + if (y.gu_fp8 && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) { + fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are block fp8 at " + "%lld x %lld; the fp8 grouped GEMM takes N in 64s and K in whole " + "%d-column blocks\n", ll, (long long)(2 * m.n_ffe), (long long)E, + RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + if (y.dn_fp8 && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) { + fprintf(stderr, "radiance: gemma4: layer %lld's down experts are block fp8, and " + "the experts are %lld wide: the fp8 grouped GEMM reads K in whole " + "%d-column scale blocks. Keep `ffn_down_exps` bf16 (no recipe " + "rule for it), or pad the experts to a multiple of %d (zero rows " + "of gate and up, zero columns of down) and convert the padded " + "checkpoint.\n", ll, + (long long)m.n_ffe, RAD_FP8_BLOCK, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + m.n_gu_fp8 += y.gu_fp8; + m.n_dn_fp8 += y.dn_fp8; + } + } + + /* ---- activations. */ + const int64_t qs = m.ks.q(), kvs = m.ks.kv_dim(), qf = m.kf.q(), kvf = m.kf.kv_dim(); + m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {T, E}); + m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {T, E}); + m.b_o = decl_b(b, nm.f("o"), RAD_BF16, {T, E}); + m.b_qkv = decl_b(b, nm.f("qkv_s"), RAD_BF16, {T, qs + 2 * kvs}); + m.b_qs = decl_b(b, nm.f("q_s"), RAD_BF16, {T, qs}); + m.b_atts = decl_b(b, nm.f("att_s"), RAD_BF16, {T, qs}); + m.b_qf = decl_b(b, nm.f("q_f"), RAD_BF16, {T, qf}); + m.b_kf = decl_b(b, nm.f("k_f"), RAD_BF16, {T, kvf}); + m.b_vf = decl_b(b, nm.f("v_f"), RAD_BF16, {T, kvf}); + m.b_attf = decl_b(b, nm.f("att_f"), RAD_BF16, {T, qf}); + m.b_ff2 = decl_b(b, nm.f("ff2"), RAD_BF16, {2 * T, E}); + m.b_gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * m.n_ff}); + m.b_act = decl_b(b, nm.f("ffn"), RAD_BF16, {T, m.n_ff}); + if (m.moe) { + const int64_t P = m.moe_rows, K = m.top_k; + m.b_rn = decl_b(b, nm.f("moe_rn"), RAD_BF16, {T, E}); + m.b_logit = decl_b(b, nm.f("moe_logits"), RAD_BF16, {T, m.n_expert}); + m.b_ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {T, K}); + m.b_ew = decl_b(b, nm.f("moe_w"), RAD_BF16, {T, K}); + m.b_es = decl_b(b, nm.f("moe_es"), RAD_BF16, {T, K}); + if (m.n_gu_fp8 < m.n_layer) + m.b_hx = decl_b(b, nm.f("moe_h"), RAD_BF16, {T, E}); + if (m.n_gu_fp8 > 0) { + m.b_hq = decl_b(b, nm.f("moe_hq"), RAD_F8E4M3, {T, E}); + m.b_hqs = decl_b(b, nm.f("moe_hqs"), RAD_F32, {T, fp8_blocks(E)}); + } + m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {P * K}); + m.b_eoff = decl_b(b, nm.f("moe_eoff"), RAD_I32, {m.n_local + 1}); + m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.n_local}); + m.b_egu = decl_b(b, nm.f("moe_egu"), RAD_BF16, {P * K, 2 * m.n_ffe}); + m.b_eact = decl_b(b, nm.f("moe_eact"), RAD_BF16, {P * K, m.n_ffe}); + if (m.n_dn_fp8 > 0) { + m.b_eq = decl_b(b, nm.f("moe_eq"), RAD_F8E4M3, {P * K, m.n_ffe}); + m.b_eqs = decl_b(b, nm.f("moe_eqs"), RAD_F32, {P * K, fp8_blocks(m.n_ffe)}); + } + m.b_edn = decl_b(b, nm.f("moe_edn"), RAD_BF16, {P * K, E}); + } + m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, E}); + + /* ---- the drafter's taps: declared when the container carries a DFlash drafter AND this serve + * speculates. DFlash2 is refused by name -- its convolutions and selector are another block. */ + if (ctx->max_spec > 0) { + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "DFlash2")) { + fprintf(stderr, "radiance: gemma4: the container carries a DFlash2 drafter; this plugin " + "serves the DFlash (v1) block z-lab publishes for Gemma 4\n"); + return RAD_E_UNSUPPORTED; + } + if (da && std::strstr(da, "DFlash")) { + const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr); + if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr); + m.n_taps = parse_ids(ids, m.n_layer, m.tap_layer, Model::MAX_TAPS); + if (m.n_taps <= 0) { + fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model " + "has; it is paired with a different target\n"); + return RAD_E_UNSUPPORTED; + } + m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)m.n_taps * E}); + } + } + + m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); + RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); + + /* ---- the vocabulary edges: ONE table, row-sharded with the vocabulary, read as the embedding + * by `embed_lookup` and as the head by `logits_gemm` -- Gemma ties them, so storing the head + * a second time would be 1.4 GiB for nothing. */ + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", L))); + RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", L))); + m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E}, RAD_ACCESS_VOCAB, + RAD_SHARD_ROW, grp_model()); + m.w_onorm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {E}, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model()); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", m.escale)), + RAD_WEIGHTS(m.w_tok)), + {}, {m.b_x}); + if (W > 1) + m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", W), RAD_RANGE("numel", E, T * E), + RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + /* ---- small declaration helpers, every one rows-banded at the step's height unless told. */ + auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, double mult, rad_buf in, rad_buf out) { + rad_op h = w ? RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 0.0), RAD_F64("mult", mult)), + RAD_WEIGHTS(w)) + : RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 0.0), RAD_F64("mult", mult)), + RAD_NOWEIGHTS); + return rw(b, h, {in}, {out}); + }; + auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + {in}, {out}); + }; + auto binop = [&](const char* op, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {a, c}, {out}); + }; + auto act_mul = [&](int64_t rows, int64_t n, rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {in}, {out}); + }; + auto allreduce = [&](int64_t max_numel, rad_buf buf) { + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", W), RAD_RANGE("numel", E, max_numel), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {buf}, {buf}); + }; + auto attn = [&](const Kind& k, rad_buf q, rad_buf out) { + return rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", k.hd), + RAD_INT("gqa", k.nh / k.nkv), RAD_INT("causal", 1), + RAD_INT("window", k.window), RAD_INT("n_head", k.nh), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype), + RAD_F64("scale", 1.0)), + RAD_NOWEIGHTS), + {q}, {out}); + }; + auto kv_store = [&](const Kind& k, rad_buf kb, rad_buf vb) { + return rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.hd), + RAD_INT("n_head_kv", k.nkv), + RAD_INT("block_size", rad_kv_block_size(b, k.kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {kb, vb}, {}); + }; + + /* THE SANDWICH JOINS: asked of the kernel libraries as one op each (gemma4k serves them) and + * declared as the chain where nothing does -- or where RADIANCE_GEMMA4_FUSE=0 asks for the + * chain, the A/B switch. The fused kernels round where the chain rounds (gemma4k/g4k_norm.hip). + * libref has no row for the joins on purpose, so "nothing serves them" stays reachable. */ + const char* fuse_env = std::getenv("RADIANCE_GEMMA4_FUSE"); + const bool fuse_joins = !(fuse_env && fuse_env[0] == '0'); + int n_joins = 0; + + const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE; + for (int64_t l = 0; l < m.n_layer; ++l) { + Layer& y = m.layers[(size_t)l]; + y.full = full[(size_t)l]; + const Kind& k = y.full ? m.kf : m.ks; + const long long ll = (long long)l; + const int li = (int)l; + const RadWeightGroup gl = grp_layer(li); + auto src = [&](const char* s) { return nm.ckpt("%s.layers.%lld.%s", L, ll, s); }; + RAD_ARCH_TRY(rad_bind_layer_kv(b, li, k.kv)); + + /* ------------------------------------------------ attention: weights */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), src("input_layernorm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_q_norm.weight", ll), src("self_attn.q_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_k_norm.weight", ll), src("self_attn.k_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_output.weight", ll), src("self_attn.o_proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_post_norm.weight", ll), + src("post_attention_layernorm.weight"))); + y.w_anorm = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, {E}, A, N, gl); + /* bf16 gains: `qk_norm_rope` reads its gains at the activation's width. */ + y.w_qn = decl_w(b, nm.f("blk.%lld.attn_q_norm.weight", ll), RAD_BF16, {k.hd}, A, N, gl); + y.w_kn = decl_w(b, nm.f("blk.%lld.attn_k_norm.weight", ll), RAD_BF16, {k.hd}, A, N, gl); + y.w_o = decl_w(b, nm.f("blk.%lld.attn_output.weight", ll), RAD_BF16, {E, k.q()}, A, + RAD_SHARD_COL, gl); + y.w_apost = decl_w(b, nm.f("blk.%lld.attn_post_norm.weight", ll), RAD_F32, {E}, A, N, gl); + if (!y.full) { + /* ONE PROJECTION, q|k|v, three row parts: every rank takes its slice of each. */ + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.attn_qkv.weight", ll), + { src("self_attn.q_proj.weight"), src("self_attn.k_proj.weight"), + src("self_attn.v_proj.weight") })); + if (!k.kv_repl) { + y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16, + {k.q() + 2 * k.kv_dim(), E}, A, RAD_SHARD_ROW, gl, 0, + {k.q(), k.kv_dim(), k.kv_dim()}); + } else { + y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16, + {k.q() + 2 * k.kv_dim(), E}, A, RAD_SHARD_ROW, gl, 0, + {k.q(), k.kv_dim(), k.kv_dim()}); + const int64_t lo[3] = { R * k.q(), k.kv_off, k.kv_off }; + const int64_t hi[3] = { lo[0] + k.q(), lo[1] + k.kv_dim(), lo[2] + k.kv_dim() }; + const int64_t tot[3] = { nh_all * k.hd, k.nkv_all * k.hd, k.nkv_all * k.hd }; + RAD_ARCH_TRY(rad_weight_shard_span_parts(b, y.w_qkv, lo, hi, tot, 3)); + } + } else { + if (!k.k_eq_v) { + fprintf(stderr, "radiance: gemma4: full-attention layer %lld has a v_proj " + "(attention_k_eq_v false); this plugin serves K = V\n", ll); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_q.weight", ll), src("self_attn.q_proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_k.weight", ll), src("self_attn.k_proj.weight"))); + y.w_q = decl_w(b, nm.f("blk.%lld.attn_q.weight", ll), RAD_BF16, {k.q(), E}, A, + RAD_SHARD_ROW, gl); + y.w_k = decl_w(b, nm.f("blk.%lld.attn_k.weight", ll), RAD_BF16, {k.kv_dim(), E}, A, + RAD_SHARD_ROW, gl); + if (k.kv_repl) + RAD_ARCH_TRY(rad_weight_shard_span(b, y.w_k, k.kv_off, k.kv_off + k.kv_dim())); + } + + /* ------------------------------------------------ attention: ops, in issue order (the + * attention op is declared ahead of its kv_store, which reads the block size off it). */ + y.op_anorm = rmsnorm(T, E, y.w_anorm, 1.0, m.b_x, m.b_h); + if (!y.full) { + y.op_qkv = gemm(T, k.q() + 2 * k.kv_dim(), E, y.w_qkv, m.b_h, m.b_qkv); + y.op_qknr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.hd), + RAD_INT("n_head", k.nh), RAD_INT("n_head_kv", k.nkv), + RAD_F64("theta", k.theta), RAD_F64("eps", eps), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", k.hd), + RAD_F64("wadd", 0.0), RAD_INT("v_norm", 1)), + RAD_WEIGHTS(y.w_qn, y.w_kn)), + {m.b_qkv}, {m.b_qkv}); + /* libr4d's paged attention reads q as one dense [T, heads, head_dim] block, so q is + * lifted out of the fused row (rad_block_attn_fp8.h says why). */ + y.op_lift = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", k.q()), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {m.b_qkv}, {m.b_qs}); + y.op_attn = attn(k, m.b_qs, m.b_atts); + y.op_store = kv_store(k, m.b_qkv, m.b_qkv); + y.op_o = gemm(T, E, k.q(), y.w_o, m.b_atts, m.b_o); + } else { + y.op_q = gemm(T, k.q(), E, y.w_q, m.b_h, m.b_qf); + y.op_k = gemm(T, k.kv_dim(), E, y.w_k, m.b_h, m.b_kf); + /* V FIRST: the unit-gain norm of the RAW k projection, before the key norm writes k. */ + y.op_vnorm = rmsnorm(T * k.nkv, k.hd, 0, 1.0, m.b_kf, m.b_vf); + y.op_qn = rmsnorm(T * k.nh, k.hd, y.w_qn, 1.0, m.b_qf, m.b_qf); + y.op_kn = rmsnorm(T * k.nkv, k.hd, y.w_kn, 1.0, m.b_kf, m.b_kf); + y.op_qrope = rw(b, decl_full_rope(b, k, T, k.nh), {m.b_qf}, {m.b_qf}); + y.op_krope = rw(b, decl_full_rope(b, k, T, k.nkv), {m.b_kf}, {m.b_kf}); + y.op_attn = attn(k, m.b_qf, m.b_attf); + y.op_store = kv_store(k, m.b_kf, m.b_vf); + y.op_o = gemm(T, E, k.q(), y.w_o, m.b_attf, m.b_o); + } + if (W > 1) y.op_ar_o = allreduce(T * E, m.b_o); + /* The post-norm AFTER the reduction: it is a norm of the whole sum. Declared below, with the + * dense arm's pre-norm, as one `norm_add_norm` where gemma4k serves it. */ + + /* ------------------------------------------------ the dense arm */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm.weight", ll), src("pre_feedforward_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.ffn_gate_up.weight", ll), + { src("mlp.gate_proj.weight"), src("mlp.up_proj.weight") })); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_down.weight", ll), src("mlp.down_proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_post_norm.weight", ll), + src("post_feedforward_layernorm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.layer_scalar", ll), src("layer_scalar"))); + y.w_fnorm = decl_w(b, nm.f("blk.%lld.ffn_norm.weight", ll), RAD_F32, {E}, A, N, gl); + y.w_gu = decl_w(b, nm.f("blk.%lld.ffn_gate_up.weight", ll), RAD_BF16, {2 * m.n_ff, E}, + A, RAD_SHARD_ROW, gl, 0, {m.n_ff, m.n_ff}); + y.w_dn = decl_w(b, nm.f("blk.%lld.ffn_down.weight", ll), RAD_BF16, {E, m.n_ff}, A, + RAD_SHARD_COL, gl); + y.w_fpost = decl_w(b, nm.f("blk.%lld.ffn_post_norm.weight", ll), RAD_F32, {E}, A, N, gl); + /* bf16 and one element: the reference multiplies the bf16 stream by it. */ + y.w_scalar = decl_w(b, nm.f("blk.%lld.layer_scalar", ll), RAD_BF16, {1}, A, N, gl); + + if (fuse_joins) + y.op_join_a = rw(b, RAD_OP(b, "norm_add_norm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(y.w_apost, y.w_fnorm)), + {m.b_o, m.b_x}, {m.b_x, m.b_h}); + if (!y.op_join_a) { + y.op_apost = rmsnorm(T, E, y.w_apost, 1.0, m.b_o, m.b_o); + y.op_add_a = binop("add", T, E, m.b_x, m.b_o, m.b_x); + y.op_fnorm = rmsnorm(T, E, y.w_fnorm, 1.0, m.b_x, m.b_h); + } + y.op_gu = gemm(T, 2 * m.n_ff, E, y.w_gu, m.b_h, m.b_gu); + y.op_act = act_mul(T, m.n_ff, m.b_gu, m.b_act); + /* The dense partial into rows [0, T) of the join. */ + y.op_dn = gemm(T, E, m.n_ff, y.w_dn, m.b_act, m.b_ff2); + + /* ------------------------------------------------ the routed arm */ + if (m.moe) { + const int64_t P = m.moe_rows, K = m.top_k, NL = m.n_local; + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_post_norm1.weight", ll), + src("post_feedforward_layernorm_1.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_post_norm2.weight", ll), + src("post_feedforward_layernorm_2.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), + src("pre_feedforward_layernorm_2.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.weight", ll), src("router.proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), src("router.scale"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_exp_scale", ll), src("router.per_expert_scale"))); + y.w_fpost1 = decl_w(b, nm.f("blk.%lld.ffn_post_norm1.weight", ll), RAD_F32, {E}, A, N, gl); + y.w_fpost2 = decl_w(b, nm.f("blk.%lld.ffn_post_norm2.weight", ll), RAD_F32, {E}, A, N, gl); + y.w_enorm = decl_w(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), RAD_F32, {E}, A, N, gl); + /* THE ROUTER IS REPLICATED (rad_block_moe_fp8.h argues it): every rank routes every + * token the same way from the same residual stream. */ + y.w_router = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.weight", ll), RAD_BF16, + {m.n_expert, E}, A, N, gl); + y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl); + y.w_escale = decl_w(b, nm.f("blk.%lld.ffn_exp_scale", ll), RAD_BF16, {m.n_expert}, A, + N, gl); + /* THE EXPERTS: whole experts, this rank's run of them (their name maps and encodings + * were settled before the buffers). Each projection's handles are declared as the + * runs its GEMM's tables are: bf16, one run in expert order; block fp8, the codes of + * the even local experts, then the odd ones', then the scale views in the same two + * runs -- `moe_gemm_q` takes a projection's experts as two tables by parity, and a + * table is a run of consecutively declared handles. The codes and the scale plane are + * two views of one stored weight and one movement unit (slot 0 gate_up, 1 down). */ + auto experts = [&](bool fp8, const char* what, int slot, int64_t rows, int64_t cols, + std::vector& wc, std::vector& ws) { + wc.assign((size_t)NL, 0); + ws.clear(); + if (!fp8) { + for (int64_t e = 0; e < NL; ++e) { + const long long ge = (long long)(m.expert_base + e); + wc[(size_t)e] = decl_w(b, nm.f("blk.%lld.ffn_%s_exps.%lld.weight", ll, what, ge), + RAD_BF16, {rows, cols}, RAD_ACCESS_CONDITIONAL, N, + grp_expert_slot(li, (int)e, slot)); + if (!wc[(size_t)e]) return RAD_E_INVAL; + } + return RAD_OK; + } + ws.assign((size_t)NL, 0); + const int64_t half = NL / 2; + for (int pass = 0; pass < 2; ++pass) /* codes, then scales */ + for (int par = 0; par < 2; ++par) /* even, then odd */ + for (int64_t i = 0; i < half; ++i) { + const int64_t e = 2 * i + par; + const long long ge = (long long)(m.expert_base + e); + const char* wn = nm.f("blk.%lld.ffn_%s_exps.%lld.weight", ll, what, ge); + rad_weight& h = (pass ? ws : wc)[(size_t)(par * half + i)]; + h = pass ? decl_view(b, nm.f("blk.%lld.ffn_%s_exps.%lld.scale", ll, what, ge), + wn, "scale", RAD_BF16, + {fp8_blocks(rows), fp8_blocks(cols)}, + RAD_ACCESS_CONDITIONAL, N, + grp_expert_slot(li, (int)e, slot)) + : decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, {rows, cols}, + RAD_ACCESS_CONDITIONAL, N, + grp_expert_slot(li, (int)e, slot)); + if (!h) return RAD_E_INVAL; + } + return RAD_OK; + }; + RAD_ARCH_TRY(experts(y.gu_fp8, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus)); + RAD_ARCH_TRY(experts(y.dn_fp8, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns)); + /* An fp8 projection's op takes its weights in its table operands' order: even codes, + * even scales, odd codes, odd scales. */ + auto tables = [&](const std::vector& wc, const std::vector& ws) { + const size_t h = wc.size() / 2; + std::vector t; + t.insert(t.end(), wc.begin(), wc.begin() + (long)h); + t.insert(t.end(), ws.begin(), ws.begin() + (long)h); + t.insert(t.end(), wc.begin() + (long)h, wc.end()); + t.insert(t.end(), ws.begin() + (long)h, ws.end()); + return t; + }; + + y.op_rnorm = rmsnorm(P, E, y.w_rscale, 1.0 / std::sqrt((double)E), m.b_x, m.b_rn); + y.op_router = gemm(P, m.n_expert, E, y.w_router, m.b_rn, m.b_logit); + y.op_topk = rw(b, RAD_OP(b, "router_topk", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_expert", m.n_expert), + RAD_INT("top_k", K), RAD_INT("norm", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_logit}, {m.b_ids, m.b_ew}); + /* per_expert_scale[expert], gathered as a [n_expert, 1] table by the ids, then the + * routing weight times it. */ + y.op_escale = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n_embd", 1), + RAD_INT("n_vocab", m.n_expert), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(y.w_escale)), + {m.b_ids}, {m.b_es}); + y.op_emul = binop("mul", P, K, m.b_ew, m.b_es, m.b_ew); + /* THE EXPERTS' INPUT: pre_feedforward_layernorm_2 of the stream -- for an fp8 gate_up, + * normed and quantised in one pass (`rmsnorm_quant_fp8`), with no bf16 copy, since the + * fp8 GEMM reads only the codes and their scales. */ + if (y.gu_fp8) { + y.op_enorm = RAD_OP(b, "rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", E), + RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "bf16"), RAD_F64("wadd", 0.0)), + RAD_WEIGHTS(y.w_enorm)); + y.op_enorm = rw(b, y.op_enorm, {m.b_x}, {m.b_hq, m.b_hqs}); + } else { + y.op_enorm = rmsnorm(P, E, y.w_enorm, 1.0, m.b_x, m.b_hx); + } + y.op_scatter = rw(b, RAD_OP(b, "moe_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), + RAD_INT("expert_base", m.expert_base)), + RAD_NOWEIGHTS), + {m.b_ids}, {m.b_sorted, m.b_eoff, m.b_ecnt}); + /* THE TWO GROUPED GEMMs DISAGREE ABOUT a_order, and must: gate_up reads the block + * input, a row a TOKEN, gathered through sorted_tok; down reads gate_up's product, + * already a row a (token, slot) in the scatter's order (rad_block_moe_fp8.h). */ + if (y.gu_fp8) { + const std::vector tab = tables(y.w_egu, y.w_egus); + y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe), + RAD_INT("K", E), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("a_order", "token"), RAD_STR("dtype", "fp8a8")), + tab.data(), (int)tab.size()), + {m.b_hq, m.b_hqs, m.b_sorted, m.b_eoff}, {m.b_egu}); + } else { + y.op_egu = rw(b, rad_decl_op(b, "moe_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe), + RAD_INT("K", E), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), RAD_STR("a_order", "token"), + RAD_STR("dtype", "bf16")), + y.w_egu.data(), (int)NL), + {m.b_hx, m.b_sorted, m.b_eoff}, {m.b_egu}); + } + /* gelu_tanh(gate) * up over the two column halves. An fp8 down then quantises the + * product on its own launch: libr4d's fused gated quantiser is compiled for silu. */ + y.op_eact = act_mul(P * K, m.n_ffe, m.b_egu, m.b_eact); + if (y.dn_fp8) { + y.op_eq = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n", m.n_ffe), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_eact}, {m.b_eq, m.b_eqs}); + const std::vector tab = tables(y.w_edn, y.w_edns); + y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", E), + RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("a_order", "sorted"), RAD_STR("dtype", "fp8a8")), + tab.data(), (int)tab.size()), + {m.b_eq, m.b_eqs, m.b_sorted, m.b_eoff}, {m.b_edn}); + } else { + y.op_edn = rw(b, rad_decl_op(b, "moe_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", E), + RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), RAD_STR("a_order", "sorted"), + RAD_STR("dtype", "bf16")), + y.w_edn.data(), (int)NL), + {m.b_eact, m.b_sorted, m.b_eoff}, {m.b_edn}); + } + { + rad_buf rd[3] = { m.b_edn, m.b_ew, m.b_sorted }; + rad_buf wr[1] = { m.b_ff2 }; + y.op_gather = RAD_OP(b, "moe_gather", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", E), + RAD_INT("top_k", K), RAD_STR("dtype", "bf16"), + RAD_STR("act", "none")), + RAD_NOWEIGHTS); + if (!y.op_gather) return RAD_E_INVAL; + rad_op_reads(b, y.op_gather, rd, 3); + rad_op_writes(b, y.op_gather, wr, 1); + } + if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_fp8 && !y.op_eq)) return RAD_E_INVAL; + if (W > 1) y.op_ar_f = allreduce(2 * T * E, m.b_ff2); + if (fuse_joins) + y.op_join_f = rw(b, RAD_OP(b, "join_add_scale", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(y.w_fpost1, y.w_fpost2, y.w_fpost, y.w_scalar)), + {m.b_ff2, m.b_x}, {m.b_x}); + if (!y.op_join_f) { + y.op_fpost1 = rmsnorm(T, E, y.w_fpost1, 1.0, m.b_ff2, m.b_ff2); + y.op_fpost2 = rmsnorm(T, E, y.w_fpost2, 1.0, m.b_ff2, m.b_ff2); + y.op_fsum = binop("add", T, E, m.b_ff2, m.b_ff2, m.b_h); + y.op_fpost = rmsnorm(T, E, y.w_fpost, 1.0, m.b_h, m.b_h); + } + } else { + if (W > 1) y.op_ar_f = allreduce(T * E, m.b_ff2); + y.op_fpost = rmsnorm(T, E, y.w_fpost, 1.0, m.b_ff2, m.b_h); + } + if (!y.op_join_f) { + y.op_add_f = binop("add", T, E, m.b_x, m.b_h, m.b_x); + y.op_scale = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_STR("dtype", "bf16"), RAD_INT("scalar", 1)), + RAD_WEIGHTS(y.w_scalar)), + {m.b_x}, {m.b_x}); + } + n_joins += (y.op_join_a ? 1 : 0) + (y.op_join_f ? 1 : 0); + + /* THE TAP: a row copy of the layer's output into the column slice a tap owns, DECLARED + * HERE, after the layer's last op, because that is where step() issues it. The buffer + * planner's liveness is declaration order. One tap op declared after the whole trunk made + * `dflash_src` look born at the end of it, so the plan was free to put it on top of + * buffers every layer writes -- and at --max-num-seqs 16 it did, under `moe_edn`, the + * routed experts' output: every MoE layer after a tap overwrote what the drafter reads, + * and on gemma-4-26B-A4B-it it accepted 2% of its drafts with the reply still fluent. */ + for (int t = 0; t < m.n_taps; ++t) + if (m.tap_layer[t] == (int)l && !y.op_tap) + y.op_tap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_dfsrc}); + } + + m.op_onorm = rmsnorm(T, E, m.w_onorm, 1.0, m.b_x, m.b_h); + m.op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_h}, {m.b_hout}); + m.op_logits = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), + RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", E), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_tok)), + {m.b_hout}, {m.b_logits}); + /* FINAL LOGIT SOFTCAPPING, cap * tanh(x / cap) over the f32 logits: `logit_softcap`, which + * libref, libavx and libr4d serve. Where nothing does the model still runs and greedy decoding + * is unchanged -- the cap is strictly increasing -- but a sampled distribution is SHARPER than + * the model's, so the startup log says so. */ + if (m.softcap > 0.0) { + m.op_cap = rw(b, RAD_OP(b, "logit_softcap", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), + RAD_INT("n", g.n_vocab), RAD_F64("cap", m.softcap), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {m.b_logits}, {m.b_logits}); + if (!m.op_cap) + rad_note(b, "WARNING: nothing serves `logit_softcap` (load libr4d or libavx). " + "The model's logits are %g * tanh(x / %g); without it greedy output is " + "unchanged and SAMPLED output draws from a sharper distribution than the " + "model's", m.softcap, m.softcap); + } + + /* THE DRAFTER LAST: declaration order is the buffer planner's liveness (llama_fp8.cpp). */ + if (m.n_taps > 0) + RAD_ARCH_TRY(declare_dflash(b, meta, ctx, m, (int)m.n_layer)); + + int nfull = 0; + for (int f : full) nfull += f; + rad_note(b, "rank %d/%d: %lld layers (%d full attention %lld x %lld over %lld kv%s, %lld " + "sliding %lld x %lld over %lld kv, window %lld); dense ffn %lld; %s; vocab " + "[%lld,%lld) tied", + R, W, (long long)m.n_layer, nfull, (long long)m.kf.nh, (long long)m.kf.hd, + (long long)m.kf.nkv, m.kf.kv_repl ? " replicated" : "", + (long long)(m.n_layer - nfull), (long long)m.ks.nh, (long long)m.ks.hd, + (long long)m.ks.nkv, (long long)m.ks.window, (long long)m.n_ff, + m.moe ? "routed: experts [base, base + local) of the model's, top-k" : "no routed arm", + (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab)); + rad_note(b, "sandwich joins: %d of %lld fused (gemma4k norm_add_norm / join_add_scale)%s", + n_joins, (long long)(m.moe ? 2 * m.n_layer : m.n_layer), + !fuse_joins ? " -- RADIANCE_GEMMA4_FUSE=0, the rmsnorm / add / mul_weight chain" + : n_joins == 0 ? " -- not served (load gemma4k), the rmsnorm / add / mul_weight chain" : ""); + if (m.moe) { + auto how = [&](int n_fp8) { + return n_fp8 == m.n_layer ? "block fp8" : n_fp8 == 0 ? "bf16" : "mixed"; + }; + rad_note(b, "routed arm: %lld local experts from %lld of %lld, top %lld, %lld wide; " + "gate_up %s (%d of %lld layers fp8), down %s (%d fp8); passes of %lld tokens", + (long long)m.n_local, (long long)m.expert_base, (long long)m.n_expert, + (long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_fp8), m.n_gu_fp8, + (long long)m.n_layer, how(m.n_dn_fp8), m.n_dn_fp8, (long long)m.moe_rows); + } + if (m.kf.rot_pairs < m.kf.hd / 2) + rad_note(b, "full layers: PROPORTIONAL rope -- %lld of %lld frequency pairs rotate at " + "theta %g over the whole %lld-wide head, the rest stay at frequency zero", + (long long)m.kf.rot_pairs, (long long)(m.kf.hd / 2), m.kf.theta, + (long long)m.kf.hd); + return RAD_OK; +} + +/* ============================================================== step */ + +static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T) { + const int64_t E = m.E, K = m.top_k, NL = m.n_local, NE = m.n_expert; + for (int64_t r0 = 0; r0 < T; r0 += m.moe_rows) { + const int64_t n = (T - r0 < m.moe_rows) ? (T - r0) : m.moe_rows; + int32_t* const counts = rad_route_counts(c, (int)(&y - m.layers.data()), NL); + const RadOperand ecnt = counts ? praw(counts, RAD_I32, NL) : brows(m.b_ecnt, NL); + RAD_ISSUE_N(c, y.op_rnorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_rscale), + brow_slice(m.b_rn, r0, n, E)); + RAD_ISSUE_N(c, y.op_router, n, brow_slice(m.b_rn, r0, n, E), RAD_W(y.w_router), + brow_slice(m.b_logit, r0, n, NE)); + RAD_ISSUE_N(c, y.op_topk, n, brow_slice(m.b_logit, r0, n, NE), + brow_slice(m.b_ids, r0, n, K), brow_slice(m.b_ew, r0, n, K)); + /* The ids and the gathered scales read as flat [n * K] vectors: the same bytes. */ + int32_t* ids = (int32_t*)rad_buf_ptr(c, m.b_ids); + uint16_t* es = (uint16_t*)rad_buf_ptr(c, m.b_es); + RAD_ISSUE_N(c, y.op_escale, n * K, praw(ids ? ids + r0 * K : nullptr, RAD_I32, n * K), + RAD_W(y.w_escale), praw2(es ? es + r0 * K : nullptr, RAD_BF16, n * K, 1)); + RAD_ISSUE_N(c, y.op_emul, n, brow_slice(m.b_ew, r0, n, K), brow_slice(m.b_es, r0, n, K), + brow_slice(m.b_ew, r0, n, K)); + /* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent). */ + if (y.gu_fp8) + RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm), + brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK), + RAD_NONE); + else + RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_enorm), + brow_slice(m.b_hx, r0, n, E)); + RAD_ISSUE_N(c, y.op_scatter, n, brow_slice(m.b_ids, r0, n, K), brows(m.b_sorted, n * K), + brows(m.b_eoff, NL + 1), ecnt); + /* An fp8 projection's tables: the first handle of each parity's run and its length -- + * even codes, even scales, odd codes, odd scales (declare). */ + const int64_t H = NL / 2; + if (y.gu_fp8) + RAD_ISSUE_N(c, y.op_egu, n, brow_slice(m.b_hq, r0, n, E), + brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK), + RAD_WTAB(y.w_egu[0], H), RAD_WTAB(y.w_egus[0], H), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), + RAD_WTAB(y.w_egu[(size_t)H], H), RAD_WTAB(y.w_egus[(size_t)H], H), + brows(m.b_egu, n * K)); + else + RAD_ISSUE_N(c, y.op_egu, n, brow_slice(m.b_hx, r0, n, E), RAD_WTAB(y.w_egu[0], NL), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), brows(m.b_egu, n * K)); + RAD_ISSUE_N(c, y.op_eact, n * K, bcol(m.b_egu, 0, m.n_ffe, n * K), + bcol(m.b_egu, m.n_ffe, m.n_ffe, n * K), brows(m.b_eact, n * K)); + if (y.dn_fp8) { + RAD_ISSUE_N(c, y.op_eq, n * K, brows(m.b_eact, n * K), brows(m.b_eq, n * K), + brows(m.b_eqs, n * K)); + RAD_ISSUE_N(c, y.op_edn, n, brows(m.b_eq, n * K), brows(m.b_eqs, n * K), + RAD_WTAB(y.w_edn[0], H), RAD_WTAB(y.w_edns[0], H), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), + RAD_WTAB(y.w_edn[(size_t)H], H), RAD_WTAB(y.w_edns[(size_t)H], H), + brows(m.b_edn, n * K)); + } else { + RAD_ISSUE_N(c, y.op_edn, n, brows(m.b_eact, n * K), RAD_WTAB(y.w_edn[0], NL), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), brows(m.b_edn, n * K)); + } + /* The routed partial into rows [T + r0, T + r0 + n) of the join. */ + RAD_ISSUE_N(c, y.op_gather, n, brows(m.b_edn, n * K), brow_slice(m.b_ew, r0, n, K), + brows(m.b_sorted, n * K), RAD_NONE, RAD_NONE, + brow_slice(m.b_ff2, T + r0, n, E)); + if (r0 + n >= T) { + RadRouting rt{}; + rt.expert_ids = ids; + rt.expert_w = nullptr; /* bf16 weights; the field is const float* (moe_fp8.h) */ + rt.expert_count = counts ? counts : (const int32_t*)rad_buf_ptr(c, m.b_ecnt); + rt.sorted_tok = (const int32_t*)rad_buf_ptr(c, m.b_sorted); + rt.expert_offset = (const int32_t*)rad_buf_ptr(c, m.b_eoff); + rt.top_k = K; + rt.n_expert = NL; + rad_route_report(c, (int)(&y - m.layers.data()), &rt); + } + } +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (batch->draft_pass != 0) { + if (!m.have_df) { + rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " + "container carries no DFlash `draft.` block, or declare ran at " + "max_spec 0"); + return; + } + if (batch->draft_pass > 0) m.df.step(c, batch); + else m.df.context(c, batch); + return; + } + if (batch->enc) { + rad_step_fail(c, "gemma4 declares no encoder; serve this container with --mm-max-patches 0"); + return; + } + const int64_t T = batch->n_tok, E = m.E; + if (T <= 0) return; + const RadOperand pos = praw(batch->positions, RAD_I32, T); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); + if (m.op_embed_ar) + RAD_ISSUE_N(c, m.op_embed_ar, T * E, brows(m.b_x, T), RAD_NONE); + + for (size_t li = 0; li < m.layers.size(); ++li) { + const Layer& y = m.layers[li]; + const Kind& k = y.full ? m.kf : m.ks; + const RadKVGroupBatch* kvb = kv_batch(batch, k.kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + const RadOperand bt = praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0); + const RadOperand su = praw(used, RAD_I32, batch->n_seq); + + RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); + if (!y.full) { + const int64_t qd = k.q(), kvd = k.kv_dim(); + RAD_ISSUE(c, y.op_qkv, brows(m.b_h, T), RAD_W(y.w_qkv), brows(m.b_qkv, T)); + RAD_ISSUE(c, y.op_qknr, brows(m.b_qkv, T), pos, RAD_W(y.w_qn), RAD_W(y.w_kn)); + RAD_ISSUE(c, y.op_store, bcol(m.b_qkv, qd, kvd, T), bcol(m.b_qkv, qd + kvd, kvd, T), + praw(slot, RAD_I32, T), kv_cache(k.kv, (int)li)); + RAD_ISSUE(c, y.op_lift, bcol(m.b_qkv, 0, qd, T), brows(m.b_qs, T)); + RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, brows(m.b_qs, T), kv_cache(k.kv, (int)li), + bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_atts, T)); + RAD_ISSUE(c, y.op_o, brows(m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T)); + } else { + RAD_ISSUE(c, y.op_q, brows(m.b_h, T), RAD_W(y.w_q), brows(m.b_qf, T)); + RAD_ISSUE(c, y.op_k, brows(m.b_h, T), RAD_W(y.w_k), brows(m.b_kf, T)); + RAD_ISSUE_N(c, y.op_vnorm, T * k.nkv, brows(m.b_kf, T), RAD_NONE, brows(m.b_vf, T)); + RAD_ISSUE_N(c, y.op_qn, T * k.nh, brows(m.b_qf, T), RAD_W(y.w_qn), brows(m.b_qf, T)); + RAD_ISSUE_N(c, y.op_kn, T * k.nkv, brows(m.b_kf, T), RAD_W(y.w_kn), brows(m.b_kf, T)); + RAD_ISSUE(c, y.op_qrope, brows(m.b_qf, T), pos); + RAD_ISSUE(c, y.op_krope, brows(m.b_kf, T), pos); + RAD_ISSUE(c, y.op_store, brows(m.b_kf, T), brows(m.b_vf, T), praw(slot, RAD_I32, T), + kv_cache(k.kv, (int)li)); + RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, brows(m.b_qf, T), kv_cache(k.kv, (int)li), + bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_attf, T)); + RAD_ISSUE(c, y.op_o, brows(m.b_attf, T), RAD_W(y.w_o), brows(m.b_o, T)); + } + if (y.op_ar_o) RAD_ISSUE_N(c, y.op_ar_o, T * E, brows(m.b_o, T), RAD_NONE); + if (y.op_join_a) { + RAD_ISSUE(c, y.op_join_a, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T), + RAD_W(y.w_fnorm), brows(m.b_h, T)); + } else { + RAD_ISSUE(c, y.op_apost, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_o, T)); + RAD_ISSUE(c, y.op_add_a, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T)); + RAD_ISSUE(c, y.op_fnorm, brows(m.b_x, T), RAD_W(y.w_fnorm), brows(m.b_h, T)); + } + + /* dense arm -> rows [0, T) of the join */ + RAD_ISSUE(c, y.op_gu, brows(m.b_h, T), RAD_W(y.w_gu), brows(m.b_gu, T)); + RAD_ISSUE(c, y.op_act, bcol(m.b_gu, 0, m.n_ff, T), bcol(m.b_gu, m.n_ff, m.n_ff, T), + brows(m.b_act, T)); + RAD_ISSUE(c, y.op_dn, brows(m.b_act, T), RAD_W(y.w_dn), brows(m.b_ff2, T)); + if (m.moe) { + routed(c, m, y, T); + if (y.op_ar_f) RAD_ISSUE_N(c, y.op_ar_f, 2 * T * E, brows(m.b_ff2, 2 * T), RAD_NONE); + if (y.op_join_f) { + RAD_ISSUE(c, y.op_join_f, brows(m.b_ff2, T), RAD_W(y.w_fpost1), + brow_slice(m.b_ff2, T, T, E), RAD_W(y.w_fpost2), RAD_W(y.w_fpost), + brows(m.b_x, T), RAD_W(y.w_scalar)); + } else { + RAD_ISSUE(c, y.op_fpost1, brows(m.b_ff2, T), RAD_W(y.w_fpost1), brows(m.b_ff2, T)); + RAD_ISSUE(c, y.op_fpost2, brow_slice(m.b_ff2, T, T, E), RAD_W(y.w_fpost2), + brow_slice(m.b_ff2, T, T, E)); + RAD_ISSUE(c, y.op_fsum, brows(m.b_ff2, T), brow_slice(m.b_ff2, T, T, E), brows(m.b_h, T)); + RAD_ISSUE(c, y.op_fpost, brows(m.b_h, T), RAD_W(y.w_fpost), brows(m.b_h, T)); + } + } else { + if (y.op_ar_f) RAD_ISSUE_N(c, y.op_ar_f, T * E, brows(m.b_ff2, T), RAD_NONE); + RAD_ISSUE(c, y.op_fpost, brows(m.b_ff2, T), RAD_W(y.w_fpost), brows(m.b_h, T)); + } + if (!y.op_join_f) { + RAD_ISSUE(c, y.op_add_f, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); + RAD_ISSUE(c, y.op_scale, brows(m.b_x, T), RAD_W(y.w_scalar), brows(m.b_x, T)); + } + + /* The tap AFTER the scalar: HF's hidden_states[i + 1] is the decoder layer's return value, + * which has been multiplied by it. */ + for (int t = 0; t < m.n_taps && y.op_tap; ++t) { + if (m.tap_layer[t] != (int)li) continue; + RAD_ISSUE(c, y.op_tap, brows(m.b_x, T), + bcol(m.b_dfsrc, (int64_t)t * E, E, T)); + } + } + + RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T)); + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T), + praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out)); + RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out), RAD_W(m.w_tok), + brows(m.b_logits, batch->n_out)); + if (m.op_cap) + RAD_ISSUE_N(c, m.op_cap, batch->n_out, brows(m.b_logits, batch->n_out), + brows(m.b_logits, batch->n_out)); + } +} + +/* ============================================================== probe */ +/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less + * the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->draft_depth = 0; + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "DFlash") && !std::strstr(da, "DFlash2")) { + long long bs = rad_meta_geti(meta, "draft.block_size", 0); + if (bs <= 0) bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); + if (bs > 1) { + out->draft_depth = (int)(bs - 1); + out->draft_depth_fixed = 1; + } + } + return RAD_OK; +} + +/* ============================================================== the reply format + * The model's, not this plugin's -- the thought channel, and calls written as a name and one + * object in Gemma's dialect of JSON -- and shared with gemma4_bf16 (arch/rad_gemma4_chat.h). The + * container's template is not visible from here (it lives in the vocab section, not the metadata), + * so this answers for every Gemma 4 container. */ +static const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_format(); } + +} /* namespace gemma4 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PLUGIN(gemma4, "gemma4", "", "0.1.0", + "Gemma 4 text decoders (26B-A4B MoE, dense 31B), bf16: sliding and full attention " + "with proportional rope and K = V, a dense and a routed feed-forward side by side, " + "and z-lab's DFlash block-diffusion drafter") +RAD_ARCH_PROBE(gemma4) +RAD_ARCH_CHAT_FORMAT(gemma4) +#endif diff --git a/arch/gemma4/gemma4_dflash.h b/arch/gemma4/gemma4_dflash.h new file mode 100644 index 00000000..cc29dad8 --- /dev/null +++ b/arch/gemma4/gemma4_dflash.h @@ -0,0 +1,592 @@ +/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4. + * + * ============================== WHAT IT IS ============================== + * + * rad_block_dflash2.h WITHOUT THE TWO THINGS DFLASH2 ADDED: the per-layer dynamic convolutions + * around attention and the feed-forward, and the candidate selector that walks a path through the + * block. What is left is the original DFlash: a small Qwen3-shaped transformer that denoises one + * anchor token plus `block - 1` mask tokens in ONE forward and reads every position's argmax off + * the TARGET's lm_head. + * + * context pass, one row a committed token: + * c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids))) + * for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v) + * + * query pass, `block` rows a sequence: + * x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below + * for each layer: + * h = input_layernorm(x) + * q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store + * x += o_proj(attention(q, cache)) sliding layers CAUSAL over a 2048 window, + * the full layer NON-causal over everything + * x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x) + * x = norm(x) + * over the mask rows: logits = lm_head(x) [the TARGET's]; draft = argmax + * + * ============================== THE THREE GEMMA-SPECIFIC FACTS ============================== + * + * They are vLLM PR #41703's, and each one costs acceptance and nothing else when it is wrong -- + * every draft is verified against the trunk, so the model's output never depends on any of them. + * + * THE EMBEDDING IS SCALED. Gemma multiplies its token embedding by sqrt(hidden_size), stored as a + * bf16 (53.0 at 2816), and the drafter was trained reading the target's embedding module, which + * applies it. `embed_lookup`'s `mult` carries it. + * + * THE SLIDING LAYERS ARE CAUSAL AND THE FULL LAYER IS NOT. The checkpoint's `layer_types` names + * four sliding layers and one full one; the PR's own test pins `causal True` on the sliding + * layers and `False` on the full one. So this block declares TWO attention ops and issues the + * one each layer's type names. + * + * THE LOGITS ARE SOFT-CAPPED, and that is ignored on purpose: the draft is an argmax, and + * cap * tanh(x / cap) is strictly increasing, so it cannot move one. + * + * ============================== THE HEAD ============================== + * + * The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma + * ties it to the embedding, so it is the same weight the trunk's `embed_lookup` and `logits_gemm` + * read: no extra bytes are stored. It is vocab-sharded with the trunk, so the top-1 runs over this + * rank's slice and the ranks' candidates are merged exactly (`row_topk` at R = 2 -> `all_gather` -> + * `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR). + * + * Reading the bf16 head every draft pass is the expensive way to do it -- 262144 x 2816 x 2 bytes + * over the ranks. The cheaper way is the 2-bit copy plus an exact rerank that DFlash2 uses, and + * that needs the trunk's head in fp8 or int8, which a tied Gemma head is not. Stated rather than + * hidden: it is the first thing to change once the model runs. + * + * ============================== THE LINEARS ARE FP8 ============================== + * + * The same as DFlash2 and for the same reason -- the drafter is read whole on every decode step -- + * so the container must be converted with a recipe that makes the six linears block fp8 (or + * MXFP4). declare() refuses a bf16 one by name rather than letting the loader fail on a view. + */ +#ifndef GEMMA4_DFLASH_H +#define GEMMA4_DFLASH_H + +#include +#include + +#include +#include + +namespace gemma4 { + +using namespace rad::arch; + +struct Dflash1 { + enum { MAX_LAYERS = 8 }; + + struct Config { + int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */ + int64_t block = 0; /* query rows a sequence: the anchor plus block - 1 masks */ + int64_t window = 0; /* the sliding layers' window; 0 for none */ + int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */ + double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */ + int64_t steps() const { return block - 1; } + }; + + struct Wire { + /* the context pass */ + rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */ + rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */ + rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */ + /* the query pass */ + rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */ + rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */ + rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */ + rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */ + rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */ + /* the head, one row a draft position */ + rad_buf sel_h = 0; /* [srows, n_embd] */ + rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */ + rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */ + rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */ + rad_buf tokens = 0; /* [srows, 1] i32: THE DRAFT, pitch `steps` */ + }; + + Geom g{}; /* the drafter's geometry */ + Config cfg{}; + Wire w{}; + int first_layer = 0; + int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0; + rad_kvgroup kv = 0; + bool sharded = false; + + DenseFP8 w_fc{}; + rad_weight w_hnorm = 0, w_norm = 0; + rad_weight w_tok = 0; /* the TARGET's table: embedding AND head */ + rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; + DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{}; + rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}; + DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{}; + + rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0; + rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; + + rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0; + rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}; + rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; + rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}; + rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; + rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0; + rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; + rad_op op_gather = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0; + + /* CANDIDATES A RANK CONTRIBUTES under a sharded head. The draft needs one, but the gather moves + * whole 16-byte words a row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is refused at + * launch ("shape this kernel does not serve") -- the bound rad_block_mtp_hc.h states. Two pairs + * are one word; `pair_argmax` reduces the world * 2 of them to the global top-1. */ + static constexpr int64_t kTopR = 2; + + static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); } + + int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, + rad_kvgroup group, rad_weight tok_embd, const char* ck, const Wire& wire); + void context(RadCtx* c, const RadBatch* batch) const; + void step(RadCtx* c, const RadBatch* batch) const; + +private: + int64_t q_dim() const { return g.n_head * g.head_dim; } + int64_t kv_dim() const { return g.n_head_kv * g.head_dim; } + /* The six linears must be what the recipe made them. DenseFP8 declares E4M3 (or MXFP4) views + * whatever the container holds, and the loader's complaint about a bf16 weight read through an + * fp8 view names the view, not the missing recipe. */ + static int need_quantised(RadBuilder* b, const char* wn) { + RadEncoding e{}; + if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */ + const uint32_t dt = e.plane[0].dtype; + if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK; + fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears " + "are served block fp8 (or MXFP4): convert with a recipe that names them, " + "e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 " + "scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and " + "ffn_down.\n", wn, rad_dtype_name(dt)); + return RAD_E_DTYPE; + } +}; + +/* ------------------------------------------------------------------------------ declare */ + +inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, + int base_layer, rad_kvgroup group, rad_weight tok_embd, + const char* ck, const Wire& wire) { + g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd; + if (!ck || !w_tok) return RAD_E_INVAL; + if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) { + fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most " + "%d\n", (long long)g.n_layer, MAX_LAYERS); + return RAD_E_UNSUPPORTED; + } + if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL; + + const int64_t qd = q_dim(), kvd = kv_dim(); + crows = g.max_tok; + qrows = g.max_seqs * cfg.block; + if (qrows > g.max_tok) qrows = g.max_tok; + srows = g.max_seqs * cfg.steps(); + if (qrows <= 0 || srows <= 0) return RAD_E_INVAL; + sharded = head_sharded(g); + + /* ---------------------------------------------------------------- model-scope weights */ + RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(), + { nm.ckpt("%s.fc.weight", ck) })); + RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck))); + w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + + /* ---------------------------------------------------------------- per-layer weights */ + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + const RadWeightGroup gl = grp_layer(first_layer + i); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i), + nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), + nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), + nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), + nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i))); + w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + /* The declared names are rad_block_dflash2.h's, deliberately: the recipe that quantises a + * DFlash2 drafter's linears names exactly these, so one recipe serves both drafters. */ + RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, + { nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff, + g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i), + nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) }, + { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, + { nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) })); + for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", + "ffn_down" }) + RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s))); + } + + /* ---------------------------------------------------------------- attention: two kinds + * Declared before either kv_store: `block_size` is read back off the resolved kernel. Both + * read the one KV group, so whichever resolves first answers for it. */ + auto attn = [&](int causal, int64_t window) { + return rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", causal), + RAD_INT("window", window), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.attn}); + }; + bool any_full = false, any_swa = false; + for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true; + if (any_swa) op_attn_swa = attn(1, cfg.window); + if (any_full) op_attn_full = attn(0, 0); + + /* ---------------------------------------------------------------- the context pass */ + op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.src}, {w.srcq, w.srcs}); + op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c}); + op_cnorm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_hnorm)), + {w.c}, {w.c}); + op_qc = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.c}, {w.cq, w.cs}); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck}); + op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv}); + op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn[i])), + {w.ck}, {w.ck}); + } + op_crope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.ck}, {w.ck}); + op_cstore = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.ck, w.cv}, {}); + + /* ---------------------------------------------------------------- the query pass */ + op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)), + RAD_WEIGHTS(w_tok)), + {}, {w.x}); + if (g.world > 1) + op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {w.x}, {w.x}); + op_qh = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.h}, {w.hq, w.hs}); + op_qat = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.attn}, {w.atq, w.ats}); + op_qff = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.ffn}, {w.ffq, w.ffs}); + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_anorm[i])), + {w.x}, {w.h}); + op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q}); + op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k}); + op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v}); + op_qn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qn[i])), + {w.q}, {w.q}); + op_kn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn[i])), + {w.k}, {w.k}); + op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h}); + op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_fnorm[i])), + {w.x}, {w.h}); + op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up}); + /* The gate_up|silu|quant fold where it resolves, the pair where it does not -- + * rad_block_dflash2.h's rule, band included. */ + { + const int64_t hi = qrows < 64 ? qrows : 64; + if (hi > 0 && !w_gu[i].mx) { + op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff), + RAD_INT("K", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")), + RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)), + {w.hq, w.hs}, {w.ffq, w.ffs}); + if (op_gug[i]) gated_rows = hi; + } + } + op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h}); + } + op_qrope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.q}, {w.q}); + op_krope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.k}, {w.k}); + op_store = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.k, w.v}, {}); + op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.gate_up}, {w.ffn}); + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + op_final = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + + /* ---------------------------------------------------------------- the head + * The MASK rows -- offsets 1..block-1 of each block; the core names them through out_ids -- + * gathered contiguous, projected onto THIS RANK's slice of the target's vocabulary, and the + * argmax taken. Sharded, each rank's best kTopR are reported as global ids with their logits, + * all-gathered, and reduced to the global top-1 by `pair_argmax` (gemma4k), ties to the lower + * id -- exact, since the global winner is its own shard's first. */ + op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.h}, {w.sel_h}); + op_head = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_tok)), + {w.sel_h}, {w.dlog}); + if (sharded) { + op_topk = rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.dlog}, {w.cand, w.unary, w.dpair}); + /* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side. */ + op_dgather = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"), + RAD_INT("row", kTopR * 2)), + RAD_NOWEIGHTS), + {w.dpair}, {w.dgath}); + op_pick = rw(b, RAD_OP(b, "pair_argmax", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {w.dgath}, {w.tokens}); + if (!op_pick) { + fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax`, which the " + "gemma4k kernel library serves -- load it (--kernels gemma4k,libr4d,...)\n"); + return RAD_E_UNSUPPORTED; + } + } else { + op_topk = rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", 1), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.dlog}, {w.tokens, w.unary}); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------------------ the context pass */ + +inline void Dflash1::context(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + + RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T)); + RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s), + brows(w.c, T), RAD_NONE, w_fc.bref()); + RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T)); + RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T)); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T), + RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref()); + RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T), + RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref()); + RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]), + brows(w.ck, T)); + RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T), praw(slot, RAD_I32, T), + kv_cache(kv, first_layer + i)); + } +} + +/* ------------------------------------------------------------------------------ the query pass */ + +inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + + RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T)); + if (op_embed_ar) + RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE); + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa; + + RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); + RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref()); + RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref()); + RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref()); + RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T)); + RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T)); + RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), + kv_cache(kv, first_layer + i)); + RAD_ISSUE_N(c, op_attn, batch->max_q_len, + brows(w.q, T), kv_cache(kv, first_layer + i), + praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), + praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T)); + RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T)); + RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T), + RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref()); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + + RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); + RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + if (op_gug[i] && T <= gated_rows) { + RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T), + RAD_NONE); + } else { + RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE, + w_gu[i].bref()); + RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T)); + RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T)); + } + RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T), + RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref()); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + } + RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + + const int64_t S = batch->n_out; + if (S <= 0) return; + RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S)); + RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S)); + if (sharded) { + RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S), + brows(w.dpair, S)); + RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S)); + RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE); + } else { + RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S), + RAD_NONE); + } +} + +} /* namespace gemma4 */ + +#endif /* GEMMA4_DFLASH_H */ diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 527fe57c..dd4ced0a 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -320,6 +320,8 @@ extern "C" void* rad_buf_ptr (RadCtx* c, rad_buf b) { (void)c; return (void #include "../arch/llama_fp8/llama_fp8.cpp" /* Gemma 4 dense: two attention classes (sliding-window + proportional-RoPE global) on one stream. */ #include "../arch/gemma4_bf16/gemma4_bf16.cpp" +/* And the bf16 / fp8-expert Gemma 4 plugin: the 26B-A4B's dense and routed arms side by side. */ +#include "../arch/gemma4/gemma4.cpp" /* The PLE block on its own: no architecture in this file declares it, and what its step() hands * the two windowed ops is a contract of its own (rad_block_ple.h). */ #include @@ -3374,3 +3376,251 @@ TEST(a_gemma4_decode_step_runs_both_classes_in_order) { CHECK_EQ(i.n, (int64_t)batch.n_out); } } + +/* ===================== gemma4: the 26B-A4B, a dense and a routed arm side by side ===================== */ + +namespace { + +/* gemma-4-26B-A4B-it's text geometry cut to SIX layers -- five sliding then one full, the model's + * own 5:1 -- with the routed arm on. The keys are the checkpoint's (text_config flattened), which + * is what arch/gemma4 reads, and quant is empty: the container this plugin claims. */ +const char* k_g4moe_keys[] = { + "hidden_size", "num_attention_heads", "num_key_value_heads", "head_dim", "global_head_dim", + "num_global_key_value_heads", "attention_k_eq_v", "vocab_size", "intermediate_size", + "rms_norm_eps", "sliding_window", "final_logit_softcapping", "hidden_activation", "layer_types", + "rope_parameters.sliding_attention.rope_theta", "rope_parameters.sliding_attention.rope_type", + "rope_parameters.full_attention.rope_theta", "rope_parameters.full_attention.rope_type", + "rope_parameters.full_attention.partial_rotary_factor", "enable_moe_block", "num_experts", + "top_k_experts", "moe_intermediate_size", +}; +const char* k_g4moe_vals[] = { + "2816", "16", "8", "256", "512", + "2", "true", "262144", "2112", + "1e-06", "1024", "30.0", "gelu_pytorch_tanh", + "[\"sliding_attention\", \"sliding_attention\", \"sliding_attention\", \"sliding_attention\", " + "\"sliding_attention\", \"full_attention\"]", + "10000.0", "default", + "1000000.0", "proportional", + "0.25", "true", "128", + "8", "704", +}; +static_assert(sizeof(k_g4moe_keys) == sizeof(k_g4moe_vals), "one value a key"); + +RadModelMeta gemma4_moe_meta() { + RadModelMeta m{}; + m.arch_id = "gemma4"; + m.name = "test-gemma4-26b-a4b"; + m.quant = ""; + m.n_layers = 6; + m.n_embd = 2816; + m.n_head = 16; + m.n_head_kv = 8; + m.head_dim = 256; + m.n_ff = 2112; + m.n_vocab = 262144; + m.n_ctx_train = 262144; + m.rms_eps = 1e-6f; + m.n_kv = (int)(sizeof(k_g4moe_keys) / sizeof(k_g4moe_keys[0])); + m.kv_key = k_g4moe_keys; + m.kv_val = k_g4moe_vals; + return m; +} + +int count_resolved(const RadBuilder& b, const std::string& name) { + int n = 0; + for (const auto& o : b.ops) if (o.op == name && o.resolved) ++n; + return n; +} + +int count_issued(const std::vector& v, const std::string& name) { + return (int)std::count(v.begin(), v.end(), name); +} + +} /* namespace */ + +TEST(a_gemma4_moe_trunk_declares_both_arms_and_the_joins) { + RadBuilder b; + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + + CHECK_EQ(count_op(b, "attn_paged"), 6); + CHECK_EQ(count_op(b, "kv_store"), 6); + /* One join after attention and one after the two feed-forward arms, a layer. */ + CHECK_EQ(count_resolved(b, "norm_add_norm"), 6); + CHECK_EQ(count_resolved(b, "join_add_scale"), 6); + /* The routed arm: experts served bf16 where the container holds no encoding for them. */ + CHECK(count_op(b, "moe_gemm") > 0); + CHECK_EQ(count_op(b, "moe_gemm_q"), 0); + CHECK_EQ(count_op(b, "logit_softcap"), 1); + CHECK_EQ(count_op(b, "all_reduce"), 0); /* world 1 */ + + for (const auto& o : b.ops) + if (o.resolved) CHECK(o.uses_declared); + for (const auto& w : b.weights) + CHECK(find_map(b, w.name) != nullptr); +} + +/* THE SLIDING GROUP IS FULL, with the window on the attention op: a WINDOW group is not + * prefix-cached, and FULL keeps a hit (arch/gemma4/gemma4.cpp, the KV groups). */ +TEST(gemma4_moe_kv_groups_are_both_full_and_the_window_rides_the_op) { + RadBuilder b; + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + + REQUIRE((int)b.kv_groups.size() == 2); + for (const auto& g : b.kv_groups) { + CHECK_EQ((int)g.d.kind, RAD_KV_FULL); + CHECK_EQ(g.d.window, 0); + } + const RecOp* sl = find_op(b, "attn_paged", 0); + REQUIRE(sl != nullptr); + CHECK_EQ(pint(sl, "head_dim"), 256); + CHECK_EQ(pint(sl, "window"), 1024); + const RecOp* fu = find_op(b, "attn_paged", 5); + REQUIRE(fu != nullptr); + CHECK_EQ(pint(fu, "head_dim"), 512); + CHECK_EQ(pint(fu, "gqa"), 8); + CHECK_EQ(pint(fu, "window"), 0); +} + +/* PROPORTIONAL ROPE IS NOT A PARTIAL ROTARY: the full layers rotate the whole 512-wide head as a + * NeoX pair (j, j + 256), with every frequency past pair 63 divided away by the YaRN ramp. A + * rotary_dim of 128 would pair (j, j + 64) -- fluent, and wrong. */ +TEST(gemma4_full_rope_is_the_whole_head_with_the_frequencies_past_64_pairs_cut) { + RadBuilder b; + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + + int full = 0; + for (const auto& o : b.ops) { + if (o.op != "rope" || pint(&o, "head_dim") != 512) continue; + ++full; + CHECK_EQ(pint(&o, "rotary_dim"), 512); + CHECK_EQ(pstr(&o, "mode"), std::string("neox")); + CHECK_NEAR(pflt(&o, "theta"), 1e6, 1.0); + CHECK_NEAR(pflt(&o, "yarn_low"), 63.5, 1e-9); + CHECK_NEAR(pflt(&o, "yarn_high"), 64.0, 1e-9); + CHECK(pflt(&o, "yarn_factor") >= 1e30); + } + CHECK(full > 0); +} + +/* Where no kernel library serves a join, the plugin declares the rmsnorm / add chain instead and + * issues that -- and libref has no row for the joins precisely so that this path stays reachable + * (docs/OPS.md). */ +TEST(gemma4_falls_back_to_the_chain_where_no_join_resolves) { + std::vector fused, chain; + for (int refuse = 0; refuse < 2; ++refuse) { + RadBuilder b; + if (refuse) { b.refuse.insert("norm_add_norm"); b.refuse.insert("join_add_scale"); } + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + (refuse ? chain : fused) = issued_ops(b, c); + } + CHECK_EQ(count_issued(fused, "norm_add_norm"), 6); + CHECK_EQ(count_issued(fused, "join_add_scale"), 6); + CHECK_EQ(count_issued(chain, "norm_add_norm"), 0); + CHECK_EQ(count_issued(chain, "join_add_scale"), 0); + CHECK_EQ(count_issued(fused, "attn_paged"), 6); + CHECK_EQ(count_issued(chain, "attn_paged"), 6); + /* The chain is longer, by the norms and adds the joins fold in. */ + CHECK(count_issued(chain, "rmsnorm") > count_issued(fused, "rmsnorm")); + CHECK(count_issued(chain, "add") > count_issued(fused, "add")); +} + +/* Both Gemma 4 plugins state the model's reply format, and it is one declaration. */ +TEST(both_gemma4_plugins_export_one_reply_format) { + RadModelMeta moe = gemma4_moe_meta(), dense = gemma4_meta(); + CHECK(gemma4::chat_format(&moe) == rad::arch::gemma4_chat_format()); + CHECK(gemma4_bf16::chat_format(&dense) == rad::arch::gemma4_chat_format()); +} + +/* ================== gemma4 + DFlash: the drafter's taps, live where they are written ================== */ + +namespace { + +/* The MoE trunk above with z-lab's DFlash drafter merged: five layers, four sliding and one full, + * reading the trunk at layers 1, 3 and 5. */ +std::vector g4df_keys() { + std::vector k(std::begin(k_g4moe_keys), std::end(k_g4moe_keys)); + for (const char* s : { "draft.architectures", "draft.num_hidden_layers", "draft.head_dim", + "draft.num_attention_heads", "draft.num_key_value_heads", + "draft.intermediate_size", "draft.rms_norm_eps", "draft.rope_theta", + "draft.hidden_size", "draft.vocab_size", "draft.block_size", + "draft.dflash_config.target_layer_ids", + "draft.dflash_config.mask_token_id", "draft.layer_types", + "draft.sliding_window" }) + k.push_back(s); + return k; +} +std::vector g4df_vals() { + std::vector v(std::begin(k_g4moe_vals), std::end(k_g4moe_vals)); + for (const char* s : { "[\"DFlashDraftModel\"]", "5", "128", "32", "8", "5632", "1e-06", + "1000000.0", "2816", "262144", "16", "[1, 3, 5]", "4", + "[\"sliding_attention\", \"sliding_attention\", \"sliding_attention\", " + "\"sliding_attention\", \"full_attention\"]", + "2048" }) + v.push_back(s); + return v; +} + +int buf_named(const RadBuilder& b, const char* name) { + for (size_t i = 0; i < b.bufs.size(); ++i) + if (b.bufs[i].name == name) return (int)i + 1; + return 0; +} + +} /* namespace */ + +/* THE TAP IS DECLARED WHERE IT IS ISSUED. The buffer planner takes liveness from declaration order, + * so `dflash_src` is live from its first DECLARED write. A tap op declared once after the whole + * trunk -- and issued inside it, at each tap layer -- made the buffer look born at the end, and the + * plan was free to put it on top of `moe_edn`, which every MoE layer writes. At --max-num-seqs 16 + * it did: every layer after a tap overwrote what the drafter reads, and acceptance fell to 2% with + * the reply still fluent. The two ranges must overlap, so no plan can share them. */ +TEST(gemma4_dflash_taps_are_live_from_the_layer_that_writes_them) { + const std::vector keys = g4df_keys(), vals = g4df_vals(); + RadModelMeta meta = gemma4_moe_meta(); + meta.n_kv = (int)keys.size(); + meta.kv_key = keys.data(); + meta.kv_val = vals.data(); + RadBuilder b; + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + + const int src = buf_named(b, "dflash_src"), edn = buf_named(b, "moe_edn"); + REQUIRE(src > 0 && edn > 0); + int first_src = -1, last_edn = -1; + for (size_t i = 0; i < b.ops.size(); ++i) + for (rad_buf w : b.ops[i].writes) { + if ((int)w == src && first_src < 0) first_src = (int)i; + if ((int)w == edn) last_edn = (int)i; + } + REQUIRE(first_src >= 0 && last_edn >= 0); + CHECK(first_src < last_edn); + + /* And a trunk step writes each tap once: three taps, three copies into `dflash_src`. */ + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + int taps = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (o && std::find(o->writes.begin(), o->writes.end(), (rad_buf)src) != o->writes.end()) + ++taps; + } + CHECK_EQ(taps, 3); +} From 753e9c598bcf459de167bfefe9696499dfe49889 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 10:06:29 -0500 Subject: [PATCH 10/24] data/recipes: gemma4-26b-a4b with DFlash -- fp8 gate_up, 768-padded fp8 experts, bf16 experts The three containers arch/gemma4 has been served from, each with the usage header the in-tree recipes carry: - gemma4-26b-a4b-df: the routed experts' gate_up block fp8, their down bf16 (K = 704 is not whole 128-blocks), the drafter's linears block fp8. The measured container. - gemma4-26b-a4b-df-pad768: both expert projections fp8, from a checkpoint whose experts were padded 704 -> 768 before conversion (zero rows of gate and up, zero columns of down: exact). The padding is described rather than shipped: the tool that did it is Python and stays out of the tree. - gemma4-26b-a4b-df-bf16x: only the drafter quantised -- the bf16 reference for the KL mode. The rules are the ones the containers were converted with; only the headers are new. Co-Authored-By: Claude Opus 5.5 --- data/recipes/gemma4-26b-a4b-df-bf16x.recipe | 17 ++++++++++++ data/recipes/gemma4-26b-a4b-df-pad768.recipe | 25 ++++++++++++++++++ data/recipes/gemma4-26b-a4b-df.recipe | 27 ++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 data/recipes/gemma4-26b-a4b-df-bf16x.recipe create mode 100644 data/recipes/gemma4-26b-a4b-df-pad768.recipe create mode 100644 data/recipes/gemma4-26b-a4b-df.recipe diff --git a/data/recipes/gemma4-26b-a4b-df-bf16x.recipe b/data/recipes/gemma4-26b-a4b-df-bf16x.recipe new file mode 100644 index 00000000..204ae3bb --- /dev/null +++ b/data/recipes/gemma4-26b-a4b-df-bf16x.recipe @@ -0,0 +1,17 @@ +# gemma4-26b-a4b-df-bf16x.recipe -- gemma-4-26B-A4B-it with z-lab's DFlash drafter and the routed +# experts left bf16, as arch/gemma4 serves it. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-26b-a4b-df-bf16x.recipe -o gemma4-26b-a4b-df-bf16x.rad +# +# The trunk exactly as the checkpoint holds it -- the bf16 reference the fp8-expert containers are +# measured against (radiance --kld-record) -- with only the drafter quantised. + +# The DFlash drafter's six linears: block fp8 (the drafter only proposes; the trunk verifies). +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/gemma4-26b-a4b-df-pad768.recipe b/data/recipes/gemma4-26b-a4b-df-pad768.recipe new file mode 100644 index 00000000..f88c1dee --- /dev/null +++ b/data/recipes/gemma4-26b-a4b-df-pad768.recipe @@ -0,0 +1,25 @@ +# gemma4-26b-a4b-df-pad768.recipe -- gemma-4-26B-A4B-it with its experts PADDED TO 768 wide, and +# z-lab's DFlash drafter, as arch/gemma4 serves it. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-26b-a4b-df-pad768.recipe -o gemma4-26b-a4b-df-pad768.rad +# +# The padding happens BEFORE conversion, outside the engine: each expert's gate and up gain 64 +# zero rows (704 -> 768) and its down 64 zero columns, and moe_intermediate_size becomes 768. It is +# exact -- gelu(0) * 0 = 0 in the added intermediate columns, which meet zero columns of down -- so +# the padded model computes the original's function. 768 is six whole 128-blocks, which the fp8 +# grouped GEMM needs for down's K, and gate and up each start on a block boundary. +# +# Both expert projections block fp8. Everything else as gemma4-26b-a4b-df.recipe says. + +blk.*.ffn_gate_up_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The DFlash drafter's six linears: block fp8 (the drafter only proposes; the trunk verifies). +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/gemma4-26b-a4b-df.recipe b/data/recipes/gemma4-26b-a4b-df.recipe new file mode 100644 index 00000000..35bd4a3f --- /dev/null +++ b/data/recipes/gemma4-26b-a4b-df.recipe @@ -0,0 +1,27 @@ +# gemma4-26b-a4b-df.recipe -- gemma-4-26B-A4B-it with z-lab's DFlash drafter, from the bf16 +# checkpoint as Google ships it, as arch/gemma4 serves it. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-26b-a4b-df.recipe -o gemma4-26b-a4b-df.rad +# +# The routed experts are ~90% of the weight bytes and a decode step reads whichever were routed. +# Their gate_up is block fp8: 2 x 704 = 1408 rows are whole 64-row GEMM tiles and eleven 128-row +# scale blocks, and K = 2816 is 22. A third of the expert bytes a decode step reads. +# +# Their down projection stays bf16: K is the expert width, 704, and the fp8 grouped GEMM reads K +# in whole 128-column blocks. gemma4-26b-a4b-df-pad768.recipe makes it fp8 as well, from a +# checkpoint whose experts were padded to 768 first. +# +# The attention, the dense arm, the router, the norms and the tied embedding stay bf16: together +# under a tenth of the bytes, and the dense arm's 2112 is not whole 128-blocks either. + +blk.*.ffn_gate_up_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The DFlash drafter's six linears: block fp8 (the drafter only proposes; the trunk verifies). +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 From 9967158d4af6b9ea837f2f544eb09a31443ab666 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 10:08:34 -0500 Subject: [PATCH 11/24] docs: gemma4 -- the architecture, its kernels, converting it, its two switches ARCHITECTURES.md: a `gemma4` section in the file's form -- the 26B-A4B's geometry, the readings that stay plausible when wrong (proportional rope is not a partial rotary, K is V, the router reads the residual, per-arm post-norms, the bf16 embedding scale, the FULL sliding group, the drafter's causality), tensor parallel, fp8 experts, which kernel library serves what, and what is not declared. Its table gains the arch/gemma4 row, and the gemma4_bf16 row is corrected: that plugin claims ("gemma4", "compressed-tensors"), not ("gemma4_bf16", "i4"). GUIDE.md: converting gemma-4-26B-A4B-it with its drafter, and RADIANCE_G4K_WMMA / RADIANCE_GEMMA4_FUSE in the tooling table. IMPLEMENTATION.md: gemma4k/ in the layout. KERNELS.md is rad-kbench's and is not edited here; it wants regenerating on a card with gemma4k loaded. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURES.md | 95 +++++++++++++++++++++++++++++++++++++++++- docs/GUIDE.md | 8 ++++ docs/IMPLEMENTATION.md | 2 + 3 files changed, 104 insertions(+), 1 deletion(-) diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index c75711cf..867b2ea3 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -14,7 +14,8 @@ into the id an architecture plugin claims. | `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed | | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | -| `arch/gemma4_bf16` | `gemma4_bf16` | `i4` (group-128 codes, f16 scale) | Gemma 4 31B dense (text): two attention classes — sliding-window and proportional-RoPE global (`attention_k_eq_v`) — over one GemmaRMSNorm stream, GELU ffn, two KV groups, softcapped logits, tied scaled embedding; served from a CT-INT4 (QAT w4a16) checkpoint | +| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense (text): two attention classes — sliding-window and proportional-RoPE global (`attention_k_eq_v`) — over one GemmaRMSNorm stream, GELU ffn, two KV groups, softcapped logits, tied scaled embedding; served from a CT-INT4 (QAT w4a16) checkpoint as group-128 int4 codes with an f16 scale | +| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint — the 26B-A4B MoE (a dense and a routed arm side by side) and the dense sizes without per-layer embeddings — with z-lab's DFlash drafter; routed experts bf16 or block fp8, as the recipe chose | This document is the geometry of each, and the handful of readings that are **arithmetically silent** — wrong in a way that produces fluent output and no error anywhere. @@ -447,3 +448,95 @@ The traps: is a real one; the processor stages exactly those plus zero frames to whole rows, which reproduces every row the reference keeps. +--- + +# `gemma4` — Gemma 4 text, and its DFlash drafter + +`arch/gemma4` serves a container converted from Google's bf16 checkpoint (`Gemma4ForConditionalGeneration` +or `Gemma4ForCausalLM`), the recipe choosing what is fp8: gemma-4-26B-A4B-it, and the dense sizes +without per-layer embeddings. The CT-INT4 31B release is `arch/gemma4_bf16`'s. A z-lab DFlash +drafter is merged at convert time (`--draft-model`); the recipes are +`data/recipes/gemma4-26b-a4b-df*.recipe`. The reference is transformers' `modeling_gemma4`. + +``` +gemma-4-26B-A4B-it + 30 layers, hidden 2816, vocab 262144 tied to the embedding, rms_norm_eps 1e-6 + layer_types: five sliding_attention then one full_attention, five times + sliding 16 heads / 8 kv x 256, rope theta 1e4 over the whole head, window 1024 + full 16 heads / 2 kv x 512, PROPORTIONAL rope theta 1e6 over a quarter of it, K = V + attention scale 1: q and k RMS-normed per head with a gain, v with none + sandwich norms, plain gains (x_hat * w) + the feed-forward is two arms reading the same residual, summed: + dense pre_feedforward_layernorm -> gate|up 2112 (gelu-tanh) -> down -> post_feedforward_layernorm_1 + routed router -> softmax -> top 8 of 128 -> renormalised -> * per_expert_scale[expert]; + pre_feedforward_layernorm_2 -> 128 experts of 704 (gelu-tanh) -> post_feedforward_layernorm_2 + sum -> post_feedforward_layernorm -> residual add + layer_scalar multiplies the residual stream at the end of every layer + embedding * sqrt(2816) as a bf16; final norm; tied head; final_logit_softcapping 30 +DFlash a small Qwen3-shaped block drafter: an anchor and block - 1 mask tokens denoised in one + pass over the trunk's hidden states at target_layer_ids; drafts read off the TARGET's head +``` + +The readings that stay plausible when wrong: + +- **Proportional rope is not a partial rotary.** The full layers rotate the first 64 frequency + pairs of the 512-wide head at theta^(-2j/512) — the exponent divides by the HEAD — with pair j + channels (j, j + 256), and leave the other 192 pairs at frequency zero. `rope` with + `rotary_dim` 128 pairs (j, j + 64) at theta^(-2j/128): a different function that still produces + fluent text. The plugin declares a full-width NeoX `rope` whose frequencies past pair 63 are + divided by 1e30 through the YaRN ramp `rope` already carries, a step at 63.5..64. +- **V on a full layer is the un-normed, un-rotated k projection**, RMS-normed with a unit gain, so + the value norm reads `k` before the key norm writes it. +- **The router does not read the feed-forward's input.** It reads the residual stream through a + gainless norm times its own `scale` vector times hidden^-0.5, while the experts read + pre_feedforward_layernorm_2's output. `per_expert_scale` multiplies the weight AFTER the + renormalised top-k. +- **The arms' two post-norms are per arm**, so under tensor parallel each arm's partial sum is + reduced before its norm. The partials share one [2T, hidden] buffer, dense rows first, so one + all-reduce carries both. +- **The embedding scale is sqrt(hidden) rounded to bf16**: 53.0, not 53.066. The drafter reads the + same scaled embedding. +- **The sliding layers' KV group is `RAD_KV_FULL`**, with the window on the attention op. A + `RAD_KV_WINDOW` group is not prefix-cached, so a hit on it reuses nothing and re-prefills; as + FULL the hit is kept. The planner gives every paged group the same block count, so the recycling + a window group would buy is worth nothing here. +- **The drafter's sliding layers are causal and its full layer is not**, and its logits' softcap + is ignored on purpose: a draft is an argmax and the cap is strictly increasing. + +**Tensor parallel.** Heads split by rank, o and down by column with an all-reduce, the vocabulary +by row. The full layers' two KV heads are replicated past two ranks. Routed experts are +expert-parallel, 128 / world whole experts a rank, because a 704-wide expert has no block-aligned +width split; the router is replicated, so every rank agrees on the routing without a collective. +The drafter's head is vocab-sharded with the trunk's: each rank's top-2 are all-gathered and +`pair_argmax` picks the winner (two a rank, because a row-interleaved `all_gather` moves 16-byte +words and one pair is 8 bytes). + +**FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the +container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up `[1408, 2816]` +is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not — the fp8 grouped GEMM reads K in +whole 128-column blocks — so it stays bf16 unless the checkpoint's experts were padded to 768 before +conversion (zero rows of gate and up, zero columns of down: exact). The fp8 tables are split by +expert parity, so a rank holds an even number of experts. + +**Kernels.** `--kernels gemma4k,libr4d,libavx`, **gemma4k first.** It serves all of the trunk's +attention -- the sliding layers (h256, gqa 2) and the full layers at gqa 8, 4 and 2 (one or two, +four, eight ranks) -- plus `pair_argmax` and the two sandwich-norm joins (`norm_add_norm`, +`join_add_scale`), which the plugin declares as the rmsnorm / add chain where nothing serves them; +the startup note says how many were fused. libr4d has h256/gqa2 and h512/gqa8 rows as well, +written for the dense 31B; with gemma4k first the 26B-A4B runs on the kernels it was measured with. +Without `gemma4k` at all, the full layers have no kernel at four and eight ranks, and a drafter head +sharded over more than one rank has no `pair_argmax`. + +**A drafter that is not working still writes fluent text.** Every draft is verified, so a broken +drafter costs speed and nothing else: judge it by `draft_n_accepted` (about a third of `draft_n` on +prose, at about two tokens a step), not by the reply. The trap that showed it: the buffer planner +takes liveness from DECLARATION order, so the tap copy into `dflash_src` is declared at the end of +the layer it taps, where it is issued. Declared once after the trunk, it let the planner share +`dflash_src` with `moe_edn`, which every MoE layer writes, whenever the sizes allowed it +(`--max-num-seqs 16` did): 2% acceptance, slower than no speculation, and nothing in the text to +say so. arch_test holds the two live ranges to overlap. + +**Not declared.** The vision tower (`arch/embgemma2` declares Gemma 4's, for an encoder): a container +that carries one is served with `--mm-max-patches 0`. An fp8 attention or dense arm — under a tenth +of the weight bytes, and the dense arm's 2112 is not whole 128-blocks either. + diff --git a/docs/GUIDE.md b/docs/GUIDE.md index bd57fc8a..dadeeb33 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -334,6 +334,12 @@ rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-27b -o swift-27b-fp8.rad \ --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 --recipe data/recipes/q38-27b-fp8block-df2.recipe \ --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \ --set "quantization_config.weight_block_size=128 128" --set quantization_config.activation_scheme=dynamic + +# gemma-4-26B-A4B-it with z-lab's DFlash drafter, the routed experts' gate_up as block fp8 (served by +# arch/gemma4 with `--kernels gemma4k,libr4d,libavx` -- gemma4k FIRST; docs/ARCHITECTURES.md says +# why, and why down stays bf16 unless the experts were padded to 768) +rad-convert ~/models/google/gemma-4-26B-A4B-it -o gemma4-26b-a4b-df.rad \ + --draft-model ~/models/z-lab/gemma-4-26B-A4B-it-DFlash --recipe data/recipes/gemma4-26b-a4b-df.recipe ``` A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read @@ -1852,6 +1858,8 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct at al | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | +| `RADIANCE_G4K_WMMA` | `0` keeps `gemma4k`'s prefill attention on its scalar kernel instead of the WMMA one. An A/B switch and a way out if the matrix path misbehaves on a card; read once | +| `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the rmsnorm / add chain instead of `gemma4k`'s sandwich joins (`norm_add_norm`, `join_add_scale`). An A/B switch; read at declare | There is also a family of instruments for engine development — `RADIANCE_DEBUG_*` (residual probes, idle scrubs, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on diff --git a/docs/IMPLEMENTATION.md b/docs/IMPLEMENTATION.md index 1df30cde..c33e29d2 100644 --- a/docs/IMPLEMENTATION.md +++ b/docs/IMPLEMENTATION.md @@ -33,6 +33,8 @@ core/kld.* the KL mode: --kld-record / --kld-ref core/engine* the thing that ties them together, and `radiance` the binary libref/ every op, naively, correct, host domain: the fallback and the oracle libr4d/ the RDNA4 (gfx12xx) kernel library: kernels, rows, layouts, fusion claims +gemma4k/ Gemma 4's kernels beyond libr4d (gfx12): its paged attention (ahead of libr4d + for that model), pair_argmax, and the sandwich-norm joins libavx/ the same vocabulary in x86 SIMD, host domain: the production host kernels, built on every x86-64 build because an op placed on the host cannot run on libref libquant/ the built-in quantisers rad-convert's recipes name: grids, transforms, rtn, gptq From 3a48ee78de4528abc902c299d1db99bbd394334b Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 13:21:52 -0500 Subject: [PATCH 12/24] arch/gemma4: the sliding layers' attention reads q in the fused qkv row The q lift -- a `cast` copying q out of the fused [q|k|v] projection into a dense block -- was there because libr4d's paged attention reads q only dense. gemma4k's takes q at any row pitch (its head_view, and g4k_emu's q-pitch-slice cases), and gemma4k serves all of Gemma 4's attention, so the slice goes straight in: one launch and a [T, q] copy less on each of the 25 sliding layers, every step. With libr4d ahead of gemma4k its attention refuses the slice by name (RAD_E_STRIDE) rather than reading it wrong. arch_test: no copy between projection and attention, and the attention reads `qkv_s`. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 22 +++++++++------------- tests/arch_test.cpp | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index 106ee95f..20d15d5c 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -211,7 +211,7 @@ struct Layer { int full = 0; /* attention */ rad_weight w_anorm = 0, w_qkv = 0, w_q = 0, w_k = 0, w_qn = 0, w_kn = 0, w_o = 0, w_apost = 0; - rad_op op_anorm = 0, op_qkv = 0, op_qknr = 0, op_lift = 0; + rad_op op_anorm = 0, op_qkv = 0, op_qknr = 0; rad_op op_q = 0, op_k = 0, op_vnorm = 0, op_qn = 0, op_kn = 0, op_qrope = 0, op_krope = 0; rad_op op_store = 0, op_attn = 0, op_o = 0, op_ar_o = 0, op_apost = 0, op_add_a = 0; /* dense arm */ @@ -250,7 +250,7 @@ struct Model { double escale = 1.0, softcap = 0.0; rad_buf b_x = 0, b_h = 0, b_o = 0; - rad_buf b_qkv = 0, b_qs = 0, b_atts = 0; /* sliding */ + rad_buf b_qkv = 0, b_atts = 0; /* sliding */ rad_buf b_qf = 0, b_kf = 0, b_vf = 0, b_attf = 0; /* full */ rad_buf b_ff2 = 0, b_gu = 0, b_act = 0; /* the arms' join; the dense arm */ rad_buf b_rn = 0, b_logit = 0, b_ids = 0, b_ew = 0, b_es = 0, b_hx = 0; @@ -834,7 +834,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {T, E}); m.b_o = decl_b(b, nm.f("o"), RAD_BF16, {T, E}); m.b_qkv = decl_b(b, nm.f("qkv_s"), RAD_BF16, {T, qs + 2 * kvs}); - m.b_qs = decl_b(b, nm.f("q_s"), RAD_BF16, {T, qs}); m.b_atts = decl_b(b, nm.f("att_s"), RAD_BF16, {T, qs}); m.b_qf = decl_b(b, nm.f("q_f"), RAD_BF16, {T, qf}); m.b_kf = decl_b(b, nm.f("k_f"), RAD_BF16, {T, kvf}); @@ -1061,14 +1060,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_F64("wadd", 0.0), RAD_INT("v_norm", 1)), RAD_WEIGHTS(y.w_qn, y.w_kn)), {m.b_qkv}, {m.b_qkv}); - /* libr4d's paged attention reads q as one dense [T, heads, head_dim] block, so q is - * lifted out of the fused row (rad_block_attn_fp8.h says why). */ - y.op_lift = rw(b, RAD_OP(b, "cast", - RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", k.q()), - RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), - RAD_NOWEIGHTS), - {m.b_qkv}, {m.b_qs}); - y.op_attn = attn(k, m.b_qs, m.b_atts); + /* Q IS READ WHERE THE PROJECTION LEFT IT, a column slice of the fused [q|k|v] row: + * gemma4k's attention takes q at any row pitch, so there is no copy into a dense block + * -- a launch and a [T, q] round trip a sliding layer. libr4d's attention reads q only + * dense and refuses the slice by name (RAD_E_STRIDE), which is one more reason the + * order is `--kernels gemma4k,libr4d` for this model. */ + y.op_attn = attn(k, m.b_qkv, m.b_atts); y.op_store = kv_store(k, m.b_qkv, m.b_qkv); y.op_o = gemm(T, E, k.q(), y.w_o, m.b_atts, m.b_o); } else { @@ -1524,8 +1521,7 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_ISSUE(c, y.op_qknr, brows(m.b_qkv, T), pos, RAD_W(y.w_qn), RAD_W(y.w_kn)); RAD_ISSUE(c, y.op_store, bcol(m.b_qkv, qd, kvd, T), bcol(m.b_qkv, qd + kvd, kvd, T), praw(slot, RAD_I32, T), kv_cache(k.kv, (int)li)); - RAD_ISSUE(c, y.op_lift, bcol(m.b_qkv, 0, qd, T), brows(m.b_qs, T)); - RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, brows(m.b_qs, T), kv_cache(k.kv, (int)li), + RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, bcol(m.b_qkv, 0, qd, T), kv_cache(k.kv, (int)li), bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_atts, T)); RAD_ISSUE(c, y.op_o, brows(m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T)); } else { diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index dd4ced0a..47bee29c 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3624,3 +3624,19 @@ TEST(gemma4_dflash_taps_are_live_from_the_layer_that_writes_them) { } CHECK_EQ(taps, 3); } + +/* The sliding layers' attention reads q where the fused projection left it: no copy op between + * the qkv projection and the attention, and the attention's declared reads name the fused row. */ +TEST(gemma4_sliding_attention_reads_q_in_the_fused_row) { + RadBuilder b; + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + const int qkv = buf_named(b, "qkv_s"); + REQUIRE(qkv > 0); + CHECK_EQ(buf_named(b, "q_s"), 0); + const RecOp* at = find_op(b, "attn_paged", 0); + REQUIRE(at != nullptr); + CHECK(std::find(at->reads.begin(), at->reads.end(), (rad_buf)qkv) != at->reads.end()); + CHECK_EQ(count_op(b, "cast"), 0); /* no drafter here, so no taps either */ +} From 171dcee15b51d6c238f84f6605d46ff64cd4d98f Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 13:30:32 -0500 Subject: [PATCH 13/24] gemma4k, arch/gemma4: the feed-forward join writes the next layer's input norm join_add_scale takes an optional gain `w_n` and output `y` (both or neither) and, given them, writes y = rmsnorm(x) * w_n over the residual it has just stored -- the next layer's input_layernorm, or the final norm after the last layer. Those norms read the x the join writes and nothing else, so each was a launch of its own and a second read of the row; now it is a fourth reduction in a block that already holds x in registers. On the 26B-A4B that is 30 launches a forward pass the fewer (29 input norms and the final norm), at decode a step's worth of ~8 us launches. Rounding where the chain rounds: y is taken over the bf16 x the join stores, with libr4d's expression, so g4k_emu holds it to the chain bit for bit (+next cases, decode to prefill heights, odd widths and pitches) and to the host arm within a flipped rounding. arch/gemma4 declares every layer's input-norm gain ahead of the layers so a join can name the next one's; where a join resolves, the norm it replaces is neither declared nor issued, and where it does not, the chain is as before. docs/OPS.md: the row and its paragraph. arch_test: fused, the only x -> h rmsnorm is layer 0's and every join writes h; refused, all thirteen come back. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 42 +++++++++++++++++++++++++-------- docs/OPS.md | 6 +++-- gemma4k/g4k_norm.hip | 46 ++++++++++++++++++++++++++++++------- gemma4k/g4k_rows.cpp | 23 +++++++++++++++---- tests/arch_test.cpp | 36 +++++++++++++++++++++++++++++ tests/g4k_emu/test_norm.cpp | 42 ++++++++++++++++++++++----------- 6 files changed, 158 insertions(+), 37 deletions(-) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index 20d15d5c..68fe853c 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -234,6 +234,11 @@ struct Layer { * routed layer's fpost1 + fpost2 + fsum + fpost + add_f + scale. Zero where not served, and * then the chain above is declared and issued instead. */ rad_op op_join_a = 0, op_join_f = 0; + /* op_join_f also writes the NEXT norm -- the following layer's input norm, or the final norm + * after the last layer -- into `h`, with that norm's gain `w_next`; the norm it replaces is + * then neither declared nor issued. */ + bool next_norm = false; + rad_weight w_next = 0; /* the drafter's tap, on a layer the drafter reads (see declare) */ rad_op op_tap = 0; }; @@ -989,6 +994,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c int n_joins = 0; const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE; + /* EVERY LAYER'S INPUT NORM GAIN, AHEAD OF THE LAYERS: a feed-forward join writes the next + * layer's input norm (join_add_scale's `y`) and so names that layer's gain before the layer + * itself is declared. */ + for (int64_t l = 0; l < m.n_layer; ++l) { + const long long ll = (long long)l; + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), + nm.ckpt("%s.layers.%lld.input_layernorm.weight", L, ll))); + m.layers[(size_t)l].w_anorm = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, + {E}, A, N, grp_layer((int)l)); + } + for (int64_t l = 0; l < m.n_layer; ++l) { Layer& y = m.layers[(size_t)l]; y.full = full[(size_t)l]; @@ -1000,13 +1016,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(rad_bind_layer_kv(b, li, k.kv)); /* ------------------------------------------------ attention: weights */ - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), src("input_layernorm.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_q_norm.weight", ll), src("self_attn.q_norm.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_k_norm.weight", ll), src("self_attn.k_norm.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_output.weight", ll), src("self_attn.o_proj.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_post_norm.weight", ll), src("post_attention_layernorm.weight"))); - y.w_anorm = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, {E}, A, N, gl); /* bf16 gains: `qk_norm_rope` reads its gains at the activation's width. */ y.w_qn = decl_w(b, nm.f("blk.%lld.attn_q_norm.weight", ll), RAD_BF16, {k.hd}, A, N, gl); y.w_kn = decl_w(b, nm.f("blk.%lld.attn_k_norm.weight", ll), RAD_BF16, {k.hd}, A, N, gl); @@ -1049,7 +1063,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ------------------------------------------------ attention: ops, in issue order (the * attention op is declared ahead of its kv_store, which reads the block size off it). */ - y.op_anorm = rmsnorm(T, E, y.w_anorm, 1.0, m.b_x, m.b_h); + if (!(l > 0 && m.layers[(size_t)l - 1].next_norm)) + y.op_anorm = rmsnorm(T, E, y.w_anorm, 1.0, m.b_x, m.b_h); if (!y.full) { y.op_qkv = gemm(T, k.q() + 2 * k.kv_dim(), E, y.w_qkv, m.b_h, m.b_qkv); y.op_qknr = rw(b, RAD_OP(b, "qk_norm_rope", @@ -1294,11 +1309,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_fp8 && !y.op_eq)) return RAD_E_INVAL; if (W > 1) y.op_ar_f = allreduce(2 * T * E, m.b_ff2); if (fuse_joins) + { + /* ...and the norm that reads the x it writes: the next layer's input norm, or the + * final norm after the last layer -- one launch and one read of x the less. */ + const rad_weight w_next = l + 1 < m.n_layer ? m.layers[(size_t)l + 1].w_anorm + : m.w_onorm; y.op_join_f = rw(b, RAD_OP(b, "join_add_scale", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(y.w_fpost1, y.w_fpost2, y.w_fpost, y.w_scalar)), - {m.b_ff2, m.b_x}, {m.b_x}); + RAD_WEIGHTS(y.w_fpost1, y.w_fpost2, y.w_fpost, y.w_scalar, + w_next)), + {m.b_ff2, m.b_x}, {m.b_x, m.b_h}); + if (y.op_join_f) { y.next_norm = true; y.w_next = w_next; } + } if (!y.op_join_f) { y.op_fpost1 = rmsnorm(T, E, y.w_fpost1, 1.0, m.b_ff2, m.b_ff2); y.op_fpost2 = rmsnorm(T, E, y.w_fpost2, 1.0, m.b_ff2, m.b_ff2); @@ -1335,7 +1358,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c {m.b_x}, {m.b_dfsrc}); } - m.op_onorm = rmsnorm(T, E, m.w_onorm, 1.0, m.b_x, m.b_h); + if (m.layers.empty() || !m.layers.back().next_norm) + m.op_onorm = rmsnorm(T, E, m.w_onorm, 1.0, m.b_x, m.b_h); m.op_gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", E), RAD_STR("dtype", "bf16")), @@ -1514,7 +1538,7 @@ static void step(RadCtx* c, const RadBatch* batch) { const RadOperand bt = praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0); const RadOperand su = praw(used, RAD_I32, batch->n_seq); - RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); + if (y.op_anorm) RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); if (!y.full) { const int64_t qd = k.q(), kvd = k.kv_dim(); RAD_ISSUE(c, y.op_qkv, brows(m.b_h, T), RAD_W(y.w_qkv), brows(m.b_qkv, T)); @@ -1559,7 +1583,7 @@ static void step(RadCtx* c, const RadBatch* batch) { if (y.op_join_f) { RAD_ISSUE(c, y.op_join_f, brows(m.b_ff2, T), RAD_W(y.w_fpost1), brow_slice(m.b_ff2, T, T, E), RAD_W(y.w_fpost2), RAD_W(y.w_fpost), - brows(m.b_x, T), RAD_W(y.w_scalar)); + brows(m.b_x, T), RAD_W(y.w_scalar), RAD_W(y.w_next), brows(m.b_h, T)); } else { RAD_ISSUE(c, y.op_fpost1, brows(m.b_ff2, T), RAD_W(y.w_fpost1), brows(m.b_ff2, T)); RAD_ISSUE(c, y.op_fpost2, brow_slice(m.b_ff2, T, T, E), RAD_W(y.w_fpost2), @@ -1585,7 +1609,7 @@ static void step(RadCtx* c, const RadBatch* batch) { } } - RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T)); + if (m.op_onorm) RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T)); if (batch->n_out > 0) { RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T), praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out)); diff --git a/docs/OPS.md b/docs/OPS.md index cbb4451d..08359947 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -299,13 +299,15 @@ rounding. | op | params | operands | |---|---|---| | `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` | -| `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w | +| `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w, `w_n`w? → `y`? | Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add` and `mul_weight`. `norm_add_norm` is `t = rmsnorm(a) * w_a; x += t; y = rmsnorm(x) * w_y` -- a post-norm, the residual add, the next pre-norm. `join_add_scale` is `x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s` -- two arms' post-norms, their sum, its norm, the residual add and a -one-element layer scalar (Gemma 4's MoE feed-forward). Every value the chain stores is rounded to +one-element layer scalar (Gemma 4's MoE feed-forward) -- and, given `w_n` and `y` (both or +neither), `y = rmsnorm(x) * w_n` over the `x` it writes: the next layer's input norm, or the final +norm after the last layer, which would otherwise be a launch of its own reading that `x` back. Every value the chain stores is rounded to the activation dtype at the same point, so the two differ from the chain only in the order a sum of squares is added in: with the same order they are bit-identical to it, and against a chain summed in another block width a norm factor can differ in its last bit. diff --git a/gemma4k/g4k_norm.hip b/gemma4k/g4k_norm.hip index dea63fd4..a84fde2a 100644 --- a/gemma4k/g4k_norm.hip +++ b/gemma4k/g4k_norm.hip @@ -7,9 +7,10 @@ * norm_add_norm the attention's join: t = norm(a) * w_a; x += t; y = norm(x) * w_y * (post_attention_layernorm, the residual add, pre_feedforward_layernorm) * join_add_scale the feed-forward's: d' = norm(d) * w_d; r' = norm(r) * w_r; - * j = norm(d' + r') * w_j; x = (x + j) * s + * j = norm(d' + r') * w_j; x = (x + j) * s; and optionally y = norm(x) * w_n * (post_feedforward_layernorm_1 and _2, the arms' sum, post_feedforward_layernorm, - * the residual add, layer_scalar) + * the residual add, layer_scalar -- and the NEXT layer's input_layernorm, or the + * final norm after the last layer, which read the x this writes) * * THE SAME FUNCTION AS THE CHAIN, ROUNDING FOR ROUNDING. Every value the chain stores as bf16 is * rounded to bf16 here at the same point, and every element is computed with libr4d's own @@ -74,6 +75,7 @@ struct NormArgs { const float* w0; /* w_a, or w_d */ const float* w1; /* w_y, or w_r */ const float* w2; /* w_j */ + const float* w3; /* w_n, the next norm's gain (or null) */ const uint16_t* s; /* the layer scalar, bf16, one element */ int n; float eps; @@ -118,7 +120,9 @@ __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { } } -/* x = (x + norm(norm(d) * w_d + norm(r) * w_r) * w_j) * s */ +/* x = (x + norm(norm(d) * w_d + norm(r) * w_r) * w_j) * s, and with NEXT y = norm(x) * w_n: the + * next layer's input norm taken over the bf16 x this stores, which is what that norm would read. */ +template __global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { __shared__ float lds[kWaves]; const int tid = (int)threadIdx.x, n = A.n; @@ -155,13 +159,28 @@ __global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { } const float sj = norm_factor(block_sum(ss, lds), n, A.eps); const float sc = bf2f(*A.s); + ss = 0.0f; #pragma unroll for (int k = 0; k < kMaxPer; ++k) { const int i = tid + k * kThreads; if (i < n) { const float j = rbf((dv[k] * sj) * A.w2[i]); const float x1 = rbf(bf2f(xr[i]) + j); - xr[i] = f2bf(x1 * sc); + const uint16_t xn = f2bf(x1 * sc); + xr[i] = xn; + rv[k] = bf2f(xn); /* the new x, kept for the next norm */ + } else { + rv[k] = 0.0f; + } + if (NEXT) ss += rv[k] * rv[k]; + } + if (NEXT) { + const float sn = norm_factor(block_sum(ss, lds), n, A.eps); + uint16_t* yr = A.y + m * A.y_ld; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) yr[i] = f2bf((rv[k] * sn) * A.w3[i]); } } } @@ -219,7 +238,7 @@ int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream stream) { return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } -/* operands: d, w_d, r, w_r, w_j, x (inout), s */ +/* operands: d, w_d, r, w_r, w_j, x (inout), s, w_n?, y? -- the last two both or neither */ int g4k_join_add_scale_bf16(const RadArgs* a, RadStream stream) { using namespace g4kn; if (!a || a->n_t < 7) return RAD_E_INVAL; @@ -232,20 +251,31 @@ int g4k_join_add_scale_bf16(const RadArgs* a, RadStream stream) { if (!D || !R || !X || !Sc) return RAD_E_INVAL; if (!gain(Wd, n) || !gain(Wr, n) || !gain(Wj, n)) return RAD_E_DTYPE; if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE; - int64_t rd = 0, ld = 0, rr = 0, lr = 0, rx = 0, lx = 0; + const RadTensor *Wn = a->n_t > 7 ? rad_arg_in(a, 7) : nullptr, + *Y = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr; + if (!Wn != !Y) return RAD_E_INVAL; + if (Wn && !gain(Wn, n)) return RAD_E_DTYPE; + int64_t rd = 0, ld = 0, rr = 0, lr = 0, rx = 0, lx = 0, ry = 0, ly = 0; if (!rows_of(D, n, &rd, &ld) || !rows_of(R, n, &rr, &lr) || !rows_of(X, n, &rx, &lx)) return RAD_E_SHAPE; + if (Y && !rows_of(Y, n, &ry, &ly)) return RAD_E_SHAPE; const int64_t M = rx; /* the step's rows: the stream's view */ if (M <= 0) return RAD_OK; - if (rd < M || rr < M || M > 0x7fffffff) return RAD_E_SHAPE; + if (rd < M || rr < M || (Y && ry < M) || M > 0x7fffffff) return RAD_E_SHAPE; NormArgs P{}; P.d = (const uint16_t*)D->data; P.d_ld = ld; P.r = (const uint16_t*)R->data; P.r_ld = lr; P.x = (uint16_t*)X->data; P.x_ld = lx; P.w0 = (const float*)Wd->data; P.w1 = (const float*)Wr->data; P.w2 = (const float*)Wj->data; P.s = (const uint16_t*)Sc->data; + if (Y) { P.w3 = (const float*)Wn->data; P.y = (uint16_t*)Y->data; P.y_ld = ly; } P.n = (int)n; P.eps = eps; - G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + if (Y) + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); + else + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } diff --git a/gemma4k/g4k_rows.cpp b/gemma4k/g4k_rows.cpp index 7376d9e6..4bfd8eca 100644 --- a/gemma4k/g4k_rows.cpp +++ b/gemma4k/g4k_rows.cpp @@ -82,6 +82,8 @@ static const RadOperandSpec oJas[] = { { "w_j", RAD_OPD_WEIGHT, 0 }, { "x", RAD_OPD_INOUT, 0 }, { "s", RAD_OPD_WEIGHT, 0 }, + { "w_n", RAD_OPD_WEIGHT, 1 }, + { "y", RAD_OPD_OUT, 1 }, }; static const RadOpSchema kSchemas[] = { { "pair_argmax", ROW(pPick), ROW(oPick), @@ -95,8 +97,9 @@ static const RadOpSchema kSchemas[] = { "point. A post-norm, the residual add and the next pre-norm (Gemma's sandwich)." }, { "join_add_scale", ROW(pJoin), ROW(oJas), "x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s, over [M, n] rows, s one " - "element; rounding where the unfused chain rounds. Two arms' post-norms, their sum, its norm, " - "the residual add and a per-layer scalar (Gemma 4's feed-forward join)." }, + "element; and with w_n and y, y = rmsnorm(x) * w_n over the x written. Rounding where the " + "unfused chain rounds. Two arms' post-norms, their sum, its norm, the residual add, a " + "per-layer scalar and the next layer's input norm (Gemma 4's feed-forward join)." }, }; /* ==================================================================== operand descriptions @@ -279,6 +282,9 @@ int norm_add_norm_host(const RadArgs* a, RadStream) { int join_add_scale_host(const RadArgs* a, RadStream) { if (!a || a->n_t < 7) return RAD_E_INVAL; + const RadTensor *Wn = a->n_t > 7 ? rad_arg_in(a, 7) : nullptr, + *Y = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr; + if (!Wn != !Y) return RAD_E_INVAL; const int64_t n = rad_args_geti_or(a, "n", 0); const double eps = rad_args_getf_or(a, "eps", 1e-6); const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2), @@ -287,9 +293,11 @@ int join_add_scale_host(const RadArgs* a, RadStream) { if (n <= 0 || !D || !R || !X || !Sc) return RAD_E_INVAL; if (!hgain(Wd, n) || !hgain(Wr, n) || !hgain(Wj, n)) return RAD_E_DTYPE; if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE; - int64_t rd, ld, rr, lr, rx, lx; + if (Wn && !hgain(Wn, n)) return RAD_E_DTYPE; + int64_t rd, ld, rr, lr, rx, lx, ry = 0, ly = 0; if (!hrows(D, n, &rd, &ld) || !hrows(R, n, &rr, &lr) || !hrows(X, n, &rx, &lx)) return RAD_E_SHAPE; - if (rd < rx || rr < rx) return RAD_E_SHAPE; + if (Y && !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE; + if (rd < rx || rr < rx || (Y && ry < rx)) return RAD_E_SHAPE; const float *wd = (const float*)Wd->data, *wr = (const float*)Wr->data, *wj = (const float*)Wj->data; const float sc = hb2f(*(const uint16_t*)Sc->data); std::vector dv((size_t)n), rv((size_t)n); @@ -305,6 +313,13 @@ int join_add_scale_host(const RadArgs* a, RadStream) { for (int64_t i = 0; i < n; ++i) { const float x1 = hrbf(hb2f(xr[i]) + hrbf((dv[(size_t)i] * sj) * wj[i])); xr[i] = hf2b(x1 * sc); + rv[(size_t)i] = hb2f(xr[i]); + } + if (Y) { + const float* wn = (const float*)Wn->data; + uint16_t* yr = (uint16_t*)Y->data + m * ly; + const float sn = hnorm(rv.data(), n, eps); + for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((rv[(size_t)i] * sn) * wn[i]); } } return RAD_OK; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 47bee29c..881da9f7 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3640,3 +3640,39 @@ TEST(gemma4_sliding_attention_reads_q_in_the_fused_row) { CHECK(std::find(at->reads.begin(), at->reads.end(), (rad_buf)qkv) != at->reads.end()); CHECK_EQ(count_op(b, "cast"), 0); /* no drafter here, so no taps either */ } + +/* The feed-forward join writes the next layer's input norm: with the joins served, the only + * rmsnorm from the residual `x` into `h` is layer 0's (nothing precedes it), the final norm is the + * last join's, and every join writes `h`. Refused, the chain declares all of them again. */ +TEST(gemma4_feed_forward_join_writes_the_next_input_norm) { + for (int refuse = 0; refuse < 2; ++refuse) { + RadBuilder b; + if (refuse) { b.refuse.insert("norm_add_norm"); b.refuse.insert("join_add_scale"); } + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + const int x = buf_named(b, "x"), h = buf_named(b, "h"); + REQUIRE(x > 0 && h > 0); + int x_to_h = 0, joins_to_h = 0; + for (const auto& o : b.ops) { + if (!o.resolved) continue; + const bool rx = std::find(o.reads.begin(), o.reads.end(), (rad_buf)x) != o.reads.end(); + const bool wh = std::find(o.writes.begin(), o.writes.end(), (rad_buf)h) != o.writes.end(); + if (o.op == "rmsnorm" && rx && wh) ++x_to_h; + if (o.op == "join_add_scale" && wh) ++joins_to_h; + } + /* fused: layer 0's input norm. Chained: six input norms, six pre-feedforward norms, the + * final norm. */ + CHECK_EQ(x_to_h, refuse ? 13 : 1); + CHECK_EQ(joins_to_h, refuse ? 0 : 6); + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector issued = issued_ops(b, c); + CHECK_EQ(count_issued(issued, "join_add_scale"), refuse ? 0 : 6); + CHECK_EQ(count_issued(issued, "logits_gemm"), 1); + } +} diff --git a/tests/g4k_emu/test_norm.cpp b/tests/g4k_emu/test_norm.cpp index 32c89094..7e09c672 100644 --- a/tests/g4k_emu/test_norm.cpp +++ b/tests/g4k_emu/test_norm.cpp @@ -135,28 +135,30 @@ static int case_nan(int M, int n, int pad, int extra_rows) { return ok ? 0 : 1; } -static int case_jas(int M, int n, int pad, int extra_rows) { +/* `next`: also the next layer's input norm, y = norm(x) * w_n over the x the join writes */ +static int case_jas(int M, int n, int pad, int extra_rows, bool next = false) { const int ld = n + pad, R = M + extra_rows; const float eps = 1e-6f; /* the two arms as one [2M, n] buffer, as the plugin holds them: dense rows, then routed */ - auto ff = randb((size_t)2 * R * ld, 2.f), x = randb((size_t)R * ld, 4.f); - auto wd = gains(n), wr = gains(n), wj = gains(n); + auto ff = randb((size_t)2 * R * ld, 2.f), x = randb((size_t)R * ld, 4.f), y0 = randb((size_t)R * ld, 1.f); + auto wd = gains(n), wr = gains(n), wj = gains(n), wn = gains(n); uint16_t sc = f2b(0.4375f + (float)(rng() % 64) / 128.f); - auto xd = x, xh = x; - RadTensor t[7] = { rows(ff.data(), RAD_BF16, M, n, ld), vec(wd.data(), RAD_F32, n), + auto xd = x, xh = x, yd = y0, yh = y0; + RadTensor t[9] = { rows(ff.data(), RAD_BF16, M, n, ld), vec(wd.data(), RAD_F32, n), rows(ff.data() + (size_t)M * ld, RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n), - vec(wj.data(), RAD_F32, n), rows(xd.data(), RAD_BF16, M, n, ld), vec(&sc, RAD_BF16, 1) }; + vec(wj.data(), RAD_F32, n), rows(xd.data(), RAD_BF16, M, n, ld), vec(&sc, RAD_BF16, 1), + vec(wn.data(), RAD_F32, n), rows(yd.data(), RAD_BF16, M, n, ld) }; RadParam p[4]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n}; p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16"; - RadArgs ar{}; ar.t = t; ar.n_t = 7; ar.p = p; ar.n_p = 4; + RadArgs ar{}; ar.t = t; ar.n_t = next ? 9 : 7; ar.p = p; ar.n_p = 4; if (g4k_join_add_scale_bf16(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: device launch failed"); return 1; } - t[5].data = xh.data(); + t[5].data = xh.data(); t[8].data = yh.data(); if (host_row("join_add_scale")->launch(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: host launch failed"); return 1; } - Tally tx; + Tally tx, ty; for (int m = 0; m < R; ++m) { const size_t o = (size_t)m * ld; - if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += xd[o + i] != x[o + i]; continue; } - for (int i = n; i < ld; ++i) tx.pad += xd[o + i] != x[o + i]; + if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]); continue; } + for (int i = n; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]); std::vector dv((size_t)n), rv((size_t)n), sv((size_t)n); for (int i = 0; i < n; ++i) { dv[(size_t)i] = b2f(ff[o + i]); rv[(size_t)i] = b2f(ff[(size_t)M * ld + o + i]); } const auto d1 = chain_norm(dv, wd.data(), n, eps); /* rmsnorm (arm 1) */ @@ -166,10 +168,19 @@ static int case_jas(int M, int n, int pad, int extra_rows) { std::vector cx((size_t)n); for (int i = 0; i < n; ++i) cx[(size_t)i] = f2b(rb(b2f(x[o + i]) + j[(size_t)i]) * b2f(sc)); /* add, mul_weight */ cmp(&xd[o], cx.data(), &xh[o], n, tx); + if (next) { /* the next rmsnorm */ + std::vector xv((size_t)n); + for (int i = 0; i < n; ++i) xv[(size_t)i] = b2f(cx[(size_t)i]); + const auto yn = chain_norm(xv, wn.data(), n, eps); + std::vector cy((size_t)n); + for (int i = 0; i < n; ++i) cy[(size_t)i] = f2b(yn[(size_t)i]); + cmp(&yd[o], cy.data(), &yh[o], n, ty); + } } - const bool ok = tx.chain_bad == 0 && tx.host_bad == 0 && tx.pad == 0; - std::printf("join_add_scale M %3d n %4d pitch %4d: vs chain %ld differ; vs host arm %ld differ, worst %.1e of the " - "row rms; padding touched %ld -> %s\n", M, n, ld, tx.chain_bad, tx.host_diff, tx.worst, tx.pad, + const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tx.host_bad == 0 && ty.host_bad == 0 && tx.pad == 0; + std::printf("join_add_scale%s M %3d n %4d pitch %4d: vs chain %ld/%ld differ; vs host arm %ld/%ld differ, worst %.1e " + "of the row rms; padding touched %ld -> %s\n", next ? "+next" : " ", M, n, ld, tx.chain_bad, + ty.chain_bad, tx.host_diff, ty.host_diff, tx.worst > ty.worst ? tx.worst : ty.worst, tx.pad, ok ? "PASS" : "FAIL"); return ok ? 0 : 1; } @@ -183,6 +194,9 @@ int main() { fails += case_nan(3, 1000, 24, 1) + case_jas(3, 1000, 24, 1); fails += case_nan(2, 6144, 0, 0) + case_jas(2, 6144, 16, 0); fails += case_nan(5, 256, 8, 1) + case_jas(5, 5376, 0, 1); + /* and with the next layer's input norm folded in */ + for (int M : Ms) fails += case_jas(M, 2816, M % 2 ? 64 : 0, 2, true); + fails += case_jas(3, 1000, 24, 1, true) + case_jas(2, 6144, 16, 0, true); std::printf("norm joins: %d failure(s)\n", fails); return fails ? 1 : 0; } From 29f981fd6c8686f789c90ebca546b662fce71559 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 13:35:07 -0500 Subject: [PATCH 14/24] arch/gemma4: route a decode step in one launch -- libr4d's fused router, top-k and sort At decode heights the router GEMM (128 x 2816), its top-k and the expert sort are each one small workgroup's work behind a full dispatch: --profile-ops put the three at ~0.27, 0.29 and 0.24 ms a step across the 30 MoE layers. libr4d already fuses them for the Qwen MoE blocks -- `router_topk_scatter` for the pair, `router_gemm_topk_scatter` with the GEMM in front -- and documents both as byte-identical to the launches they replace, so the routing does not move. arch/gemma4 now asks for them as rad_block_moe_fp8.h does: the pair up to the sort's single-workgroup bound (1024 routing slots, 128 rows at top-8), the GEMM form up to the skinny GEMM's decode band (64 rows), and the separate ops for a pass past either, declared regardless. The per-expert scale and the experts' input norm sit between them in the issue order and read only the ids and weights the fused op writes. Two launches a MoE layer the fewer at decode, 60 a step. arch_test: a decode step routes with the fused op; refused, with the pair; both refused, with the three separate ops -- and the per-expert scale and the gather run in every case. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 75 ++++++++++++++++++++++++++++++++++++++---- tests/arch_test.cpp | 27 +++++++++++++++ 2 files changed, 96 insertions(+), 6 deletions(-) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index 68fe853c..fff47a01 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -105,6 +105,12 @@ namespace gemma4 { using namespace rad::arch; +/* The fused router's two bounds, as rad_block_moe_fp8.h states them: the most routing slots + * libr4d's sort serves in one workgroup (its kScatterSmall), and the skinny bf16 GEMM's decode + * band, where the fused op's GEMM is that GEMM's own arithmetic. */ +static const int64_t kMoeSortRows = 1024; +static const int64_t kMoeRouterFusedRows = 64; + /* ============================================================== metadata */ /* Gemma4ForConditionalGeneration nests the text model's config under `text_config`; a * Gemma4ForCausalLM checkpoint does not. rad-convert flattens nested keys with dots, so every key @@ -226,6 +232,12 @@ struct Layer { bool gu_fp8 = false, dn_fp8 = false; rad_op op_rnorm = 0, op_router = 0, op_topk = 0, op_escale = 0, op_emul = 0, op_enorm = 0; rad_op op_scatter = 0, op_egu = 0, op_eact = 0, op_eq = 0, op_edn = 0, op_gather = 0; + /* libr4d's fused forms of the router, its top-k and the sort, where they resolve: the pair + * (`router_topk_scatter`) up to `topk_scatter_rows`, and the router GEMM in front of it + * (`router_gemm_topk_scatter`) up to `router_fused_rows`. A pass past their rows issues the + * separate ops, which are declared either way. */ + rad_op op_topk_scatter = 0, op_router_fused = 0; + int64_t topk_scatter_rows = 0, router_fused_rows = 0; /* the join */ rad_weight w_fpost = 0, w_scalar = 0; rad_op op_ar_f = 0, op_fpost1 = 0, op_fpost2 = 0, op_fsum = 0, op_fpost = 0, op_add_f = 0; @@ -1246,6 +1258,41 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_INT("expert_base", m.expert_base)), RAD_NOWEIGHTS), {m.b_ids}, {m.b_sorted, m.b_eoff, m.b_ecnt}); + /* THE ROUTER, ITS TOP-K AND THE SORT IN ONE LAUNCH at decode heights. At a decode step + * each of the three is one small workgroup's work behind a full dispatch, and libr4d + * fuses them: `router_topk_scatter` for the pair, bounded by the sort's single-workgroup + * form (kMoeSortRows routing slots), and `router_gemm_topk_scatter` with the router's + * GEMM in front, up to the skinny GEMM's decode band -- byte-identical to the launches + * they stand in for (docs/OPS.md), so the routing does not move. The per-expert scale + * and the experts' input norm sit between them in the issue order and read only the ids + * and weights the fused op writes. Declared here, after every buffer they name: a late + * declaration only lengthens a buffer's planned life (rad_block_moe_fp8.h). */ + { + const int64_t sort_rows = P * K <= kMoeSortRows ? P : kMoeSortRows / K; + if (sort_rows > 0) + y.op_topk_scatter = rw(b, RAD_OP(b, "router_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, sort_rows), + RAD_INT("n_expert", m.n_expert), + RAD_INT("n_local", NL), RAD_INT("top_k", K), + RAD_INT("norm", 1), RAD_STR("dtype", "bf16"), + RAD_INT("expert_base", m.expert_base)), + RAD_NOWEIGHTS), + {m.b_logit}, {m.b_ids, m.b_ew, m.b_sorted, m.b_eoff, m.b_ecnt}); + if (y.op_topk_scatter) { + y.topk_scatter_rows = sort_rows; + const int64_t fr = sort_rows < kMoeRouterFusedRows ? sort_rows : kMoeRouterFusedRows; + y.op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", E), + RAD_INT("n_expert", m.n_expert), + RAD_INT("n_local", NL), RAD_INT("top_k", K), + RAD_INT("norm", 1), RAD_STR("dtype", "bf16"), + RAD_INT("expert_base", m.expert_base)), + RAD_WEIGHTS(y.w_router)), + {m.b_rn}, + {m.b_logit, m.b_ids, m.b_ew, m.b_sorted, m.b_eoff, m.b_ecnt}); + if (y.op_router_fused) y.router_fused_rows = fr; + } + } /* THE TWO GROUPED GEMMs DISAGREE ABOUT a_order, and must: gate_up reads the block * input, a row a TOKEN, gathered through sorted_tok; down reads gate_up's product, * already a row a (token, slot) in the scatter's order (rad_block_moe_fp8.h). */ @@ -1436,10 +1483,25 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T) { const RadOperand ecnt = counts ? praw(counts, RAD_I32, NL) : brows(m.b_ecnt, NL); RAD_ISSUE_N(c, y.op_rnorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_rscale), brow_slice(m.b_rn, r0, n, E)); - RAD_ISSUE_N(c, y.op_router, n, brow_slice(m.b_rn, r0, n, E), RAD_W(y.w_router), - brow_slice(m.b_logit, r0, n, NE)); - RAD_ISSUE_N(c, y.op_topk, n, brow_slice(m.b_logit, r0, n, NE), - brow_slice(m.b_ids, r0, n, K), brow_slice(m.b_ew, r0, n, K)); + /* One launch, two or three: the router, its top-k and the sort (see declare). */ + const bool rfused = y.op_router_fused && n <= y.router_fused_rows; + const bool pair = !rfused && y.op_topk_scatter && n <= y.topk_scatter_rows; + if (rfused) { + RAD_ISSUE_N(c, y.op_router_fused, n, brow_slice(m.b_rn, r0, n, E), RAD_W(y.w_router), + RAD_NONE, brow_slice(m.b_logit, r0, n, NE), + brow_slice(m.b_ids, r0, n, K), brow_slice(m.b_ew, r0, n, K), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), ecnt, RAD_NONE); + } else { + RAD_ISSUE_N(c, y.op_router, n, brow_slice(m.b_rn, r0, n, E), RAD_W(y.w_router), + brow_slice(m.b_logit, r0, n, NE)); + if (pair) + RAD_ISSUE_N(c, y.op_topk_scatter, n, brow_slice(m.b_logit, r0, n, NE), + brow_slice(m.b_ids, r0, n, K), brow_slice(m.b_ew, r0, n, K), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), ecnt); + else + RAD_ISSUE_N(c, y.op_topk, n, brow_slice(m.b_logit, r0, n, NE), + brow_slice(m.b_ids, r0, n, K), brow_slice(m.b_ew, r0, n, K)); + } /* The ids and the gathered scales read as flat [n * K] vectors: the same bytes. */ int32_t* ids = (int32_t*)rad_buf_ptr(c, m.b_ids); uint16_t* es = (uint16_t*)rad_buf_ptr(c, m.b_es); @@ -1455,8 +1517,9 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T) { else RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_enorm), brow_slice(m.b_hx, r0, n, E)); - RAD_ISSUE_N(c, y.op_scatter, n, brow_slice(m.b_ids, r0, n, K), brows(m.b_sorted, n * K), - brows(m.b_eoff, NL + 1), ecnt); + if (!rfused && !pair) + RAD_ISSUE_N(c, y.op_scatter, n, brow_slice(m.b_ids, r0, n, K), brows(m.b_sorted, n * K), + brows(m.b_eoff, NL + 1), ecnt); /* An fp8 projection's tables: the first handle of each parity's run and its length -- * even codes, even scales, odd codes, odd scales (declare). */ const int64_t H = NL / 2; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 881da9f7..4e3fa5ec 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3676,3 +3676,30 @@ TEST(gemma4_feed_forward_join_writes_the_next_input_norm) { CHECK_EQ(count_issued(issued, "logits_gemm"), 1); } } + +/* At decode heights the router, its top-k and the sort are one launch (libr4d's + * router_gemm_topk_scatter); refused, the pair (router_topk_scatter) behind the router GEMM; both + * refused, the three separate ops as before. The routing's buffers are the same either way. */ +TEST(gemma4_routes_a_decode_step_in_one_launch) { + for (int refuse = 0; refuse < 3; ++refuse) { + RadBuilder b; + if (refuse >= 1) b.refuse.insert("router_gemm_topk_scatter"); + if (refuse >= 2) b.refuse.insert("router_topk_scatter"); + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector issued = issued_ops(b, c); + CHECK_EQ(count_issued(issued, "router_gemm_topk_scatter"), refuse == 0 ? 6 : 0); + CHECK_EQ(count_issued(issued, "router_topk_scatter"), refuse == 1 ? 6 : 0); + CHECK_EQ(count_issued(issued, "router_topk"), refuse == 2 ? 6 : 0); + CHECK_EQ(count_issued(issued, "moe_scatter"), refuse == 2 ? 6 : 0); + /* the per-expert scale and the experts' gather run whichever form routed */ + CHECK_EQ(count_issued(issued, "embed_lookup"), 1 + 6); + CHECK_EQ(count_issued(issued, "moe_gather"), 6); + } +} From 0d95046f6fde1c4a44a549391ebc7243d5c7ee94 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 13:47:58 -0500 Subject: [PATCH 15/24] gemma4k, arch/gemma4: expert_scale -- per_expert_scale on the routing weights in one launch Gemma 4 multiplies each renormalised routing weight by per_expert_scale of the expert it chose. In the conventional vocabulary that is an `embed_lookup` of the [n_expert, 1] table by the ids and a `mul` into the weights -- two launches a MoE layer, a few dozen elements each at decode (--profile-ops: ~0.26 and ~0.22 ms a step across the 30 layers). gemma4k's `expert_scale` is the pair as one kernel, ew = bf16(ew * w_e[id]), with an id outside the table reading 0 as embed_lookup's missed row does: one product rounded once, so the pair's value bit for bit. Like the joins it has no libref row on purpose, so arch/gemma4 falls back to the pair wherever gemma4k is not loaded, and RADIANCE_GEMMA4_FUSE=0 turns it off with them. 30 launches a step the fewer. g4k_emu: device and host rows against the pair over 32 shapes -- top-k 1 and 8, pitched rows, pads and one-past-the-end ids, rows past M untouched -- every element equal. arch_test: a decode step scales in one launch, and in two with it refused. docs/OPS.md: the row and its paragraph; GUIDE: what the switch now covers. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 43 +++++++++++------ docs/GUIDE.md | 2 +- docs/OPS.md | 12 +++-- gemma4k/CMakeLists.txt | 2 +- gemma4k/g4k.h | 4 ++ gemma4k/g4k_escale.hip | 87 +++++++++++++++++++++++++++++++++++ gemma4k/g4k_rows.cpp | 56 ++++++++++++++++++++++ tests/CMakeLists.txt | 7 +-- tests/arch_test.cpp | 25 +++++++++- tests/g4k_emu/run.sh | 8 ++-- tests/g4k_emu/test_escale.cpp | 68 +++++++++++++++++++++++++++ 11 files changed, 289 insertions(+), 25 deletions(-) create mode 100644 gemma4k/g4k_escale.hip create mode 100644 tests/g4k_emu/test_escale.cpp diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index fff47a01..aea10675 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -237,6 +237,8 @@ struct Layer { * (`router_gemm_topk_scatter`) up to `router_fused_rows`. A pass past their rows issues the * separate ops, which are declared either way. */ rad_op op_topk_scatter = 0, op_router_fused = 0; + /* gemma4k's expert_scale: op_escale and op_emul in one launch, where it resolves */ + rad_op op_expert_scale = 0; int64_t topk_scatter_rows = 0, router_fused_rows = 0; /* the join */ rad_weight w_fpost = 0, w_scalar = 0; @@ -999,7 +1001,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* THE SANDWICH JOINS: asked of the kernel libraries as one op each (gemma4k serves them) and * declared as the chain where nothing does -- or where RADIANCE_GEMMA4_FUSE=0 asks for the - * chain, the A/B switch. The fused kernels round where the chain rounds (gemma4k/g4k_norm.hip). + * chain, the A/B switch, which turns off gemma4k's `expert_scale` with them. The fused kernels round where the chain rounds (gemma4k/g4k_norm.hip). * libref has no row for the joins on purpose, so "nothing serves them" stays reachable. */ const char* fuse_env = std::getenv("RADIANCE_GEMMA4_FUSE"); const bool fuse_joins = !(fuse_env && fuse_env[0] == '0'); @@ -1231,14 +1233,24 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.b_logit}, {m.b_ids, m.b_ew}); - /* per_expert_scale[expert], gathered as a [n_expert, 1] table by the ids, then the - * routing weight times it. */ - y.op_escale = rw(b, RAD_OP(b, "embed_lookup", - RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n_embd", 1), - RAD_INT("n_vocab", m.n_expert), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(y.w_escale)), - {m.b_ids}, {m.b_es}); - y.op_emul = binop("mul", P, K, m.b_ew, m.b_es, m.b_ew); + /* per_expert_scale[expert] times the routing weight: one launch where gemma4k serves + * `expert_scale`, and otherwise the table gathered as [n_expert, 1] by the ids and a + * `mul` -- the same bf16 product either way (docs/OPS.md). */ + if (fuse_joins) + y.op_expert_scale = rw(b, RAD_OP(b, "expert_scale", + RAD_PARAMS(RAD_RANGE("M", 1, P), + RAD_INT("n_expert", m.n_expert), + RAD_INT("top_k", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(y.w_escale)), + {m.b_ids, m.b_ew}, {m.b_ew}); + if (!y.op_expert_scale) { + y.op_escale = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n_embd", 1), + RAD_INT("n_vocab", m.n_expert), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(y.w_escale)), + {m.b_ids}, {m.b_es}); + y.op_emul = binop("mul", P, K, m.b_ew, m.b_es, m.b_ew); + } /* THE EXPERTS' INPUT: pre_feedforward_layernorm_2 of the stream -- for an fp8 gate_up, * normed and quantised in one pass (`rmsnorm_quant_fp8`), with no bf16 copy, since the * fp8 GEMM reads only the codes and their scales. */ @@ -1505,10 +1517,15 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T) { /* The ids and the gathered scales read as flat [n * K] vectors: the same bytes. */ int32_t* ids = (int32_t*)rad_buf_ptr(c, m.b_ids); uint16_t* es = (uint16_t*)rad_buf_ptr(c, m.b_es); - RAD_ISSUE_N(c, y.op_escale, n * K, praw(ids ? ids + r0 * K : nullptr, RAD_I32, n * K), - RAD_W(y.w_escale), praw2(es ? es + r0 * K : nullptr, RAD_BF16, n * K, 1)); - RAD_ISSUE_N(c, y.op_emul, n, brow_slice(m.b_ew, r0, n, K), brow_slice(m.b_es, r0, n, K), - brow_slice(m.b_ew, r0, n, K)); + if (y.op_expert_scale) { + RAD_ISSUE_N(c, y.op_expert_scale, n, brow_slice(m.b_ids, r0, n, K), RAD_W(y.w_escale), + brow_slice(m.b_ew, r0, n, K)); + } else { + RAD_ISSUE_N(c, y.op_escale, n * K, praw(ids ? ids + r0 * K : nullptr, RAD_I32, n * K), + RAD_W(y.w_escale), praw2(es ? es + r0 * K : nullptr, RAD_BF16, n * K, 1)); + RAD_ISSUE_N(c, y.op_emul, n, brow_slice(m.b_ew, r0, n, K), brow_slice(m.b_es, r0, n, K), + brow_slice(m.b_ew, r0, n, K)); + } /* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent). */ if (y.gu_fp8) RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm), diff --git a/docs/GUIDE.md b/docs/GUIDE.md index dadeeb33..55b39020 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1859,7 +1859,7 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct at al | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_G4K_WMMA` | `0` keeps `gemma4k`'s prefill attention on its scalar kernel instead of the WMMA one. An A/B switch and a way out if the matrix path misbehaves on a card; read once | -| `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the rmsnorm / add chain instead of `gemma4k`'s sandwich joins (`norm_add_norm`, `join_add_scale`). An A/B switch; read at declare | +| `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the chains instead of `gemma4k`'s fusions: the rmsnorm / add chain for the sandwich joins (`norm_add_norm`, `join_add_scale`), and `embed_lookup` + `mul` for `expert_scale`. An A/B switch; read at declare | There is also a family of instruments for engine development — `RADIANCE_DEBUG_*` (residual probes, idle scrubs, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on diff --git a/docs/OPS.md b/docs/OPS.md index 08359947..4e3ece12 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -294,12 +294,13 @@ rounding. -log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's torch expressions are, then rounded. -### The sandwich-norm joins — no reference row +### gemma4k's fusions: the sandwich-norm joins and `expert_scale` — no reference row | op | params | operands | |---|---|---| | `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` | | `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w, `w_n`w? → `y`? | +| `expert_scale` | `M`(range) `n_expert` `top_k` `dtype` | `ids`, `w_e`w, `ew`:inout | Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add` and `mul_weight`. `norm_add_norm` is `t = rmsnorm(a) * w_a; x += t; y = rmsnorm(x) * w_y` -- a post-norm, the @@ -312,11 +313,16 @@ the activation dtype at the same point, so the two differ from the chain only in of squares is added in: with the same order they are bit-identical to it, and against a chain summed in another block width a norm factor can differ in its last bit. -**libref has no row for either, on purpose.** An architecture asks for a join and declares the +`expert_scale` is `ew[t, k] = ew[t, k] * w_e[ids[t, k]]` over `[M, top_k]`, `w_e` an `[n_expert]` +table and an id outside it reading 0: Gemma 4's per_expert_scale on the renormalised routing +weights, in place of an `embed_lookup` of the table by the ids and a `mul` into the weights. One +product rounded once, so the pair's value bit for bit. + +**libref has no row for any of them, on purpose.** An architecture asks for a join and declares the chain where it does not resolve (`rad_op_resolved`), and a reference row would resolve it everywhere -- so a model loaded without the library that serves the join would resolve it to the reference and be refused at serve, instead of running the chain on libr4d or libavx. The -`gemma4k` kernel library declares both (device and host rows); with no oracle, its kernels are held +`gemma4k` kernel library declares them (device and host rows); with no oracle, its kernels are held to the chain bit for bit by `tests/g4k_emu`, and no row declares `replaces`, because rad-kbench assembles a replaced chain from the fusing library's own rows and gemma4k has none of the chain's ops. diff --git a/gemma4k/CMakeLists.txt b/gemma4k/CMakeLists.txt index 6fa5692a..a744ab76 100644 --- a/gemma4k/CMakeLists.txt +++ b/gemma4k/CMakeLists.txt @@ -27,7 +27,7 @@ endif() rad_add_plugin(gemma4k kernels SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/g4k_rows.cpp HIP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/g4k_attn.hip ${CMAKE_CURRENT_SOURCE_DIR}/g4k_pick.hip - ${CMAKE_CURRENT_SOURCE_DIR}/g4k_norm.hip + ${CMAKE_CURRENT_SOURCE_DIR}/g4k_norm.hip ${CMAKE_CURRENT_SOURCE_DIR}/g4k_escale.hip GPU_TARGETS ${_g4k_targets}) string(REPLACE ";" " " _g4k_desc "${_g4k_targets}") target_compile_definitions(gemma4k PRIVATE "G4K_BUILD_TARGET=\"${_g4k_desc}\"") diff --git a/gemma4k/g4k.h b/gemma4k/g4k.h index d6e109c1..8350d8be 100644 --- a/gemma4k/g4k.h +++ b/gemma4k/g4k.h @@ -30,6 +30,10 @@ int g4k_pair_argmax_f32(const RadArgs* a, RadStream s); * norm_add_norm operands a, w_a, x (inout), w_y, y * join_add_scale operands d, w_d, r, w_r, w_j, x (inout), s */ int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream s); + +/* expert_scale: each routing weight times its expert's scale, in place (g4k_escale.hip): + * operands ids, w_e, ew (inout) */ +int g4k_expert_scale_bf16(const RadArgs* a, RadStream s); int g4k_join_add_scale_bf16(const RadArgs* a, RadStream s); #ifdef __cplusplus diff --git a/gemma4k/g4k_escale.hip b/gemma4k/g4k_escale.hip new file mode 100644 index 00000000..3d660a97 --- /dev/null +++ b/gemma4k/g4k_escale.hip @@ -0,0 +1,87 @@ +/* g4k_escale.hip -- expert_scale: each routing weight times its expert's own scale, in place. + * + * Gemma 4's router renormalises its top-k and then multiplies each weight by per_expert_scale of + * the expert it chose. Said in the conventional vocabulary that is two launches a MoE layer -- an + * `embed_lookup` of the [n_expert, 1] scale table by the expert ids, then a `mul` into the weights + * -- each a few dozen elements behind a full dispatch at decode. This is the pair as one: + * + * ew[t, k] = bf16( ew[t, k] * scale[ids[t, k]] ) + * + * THE CHAIN'S VALUE, BIT FOR BIT: the lookup copies a bf16 scale and the multiply is one f32 + * product rounded once to nearest even, which is all this does. An id outside the table reads a + * zero scale, as embed_lookup writes a zero row for an id it does not hold, and the product's sign + * survives it the same way. One thread an element; a decode step is a handful of rows. + */ +#include + +#include + +#include "g4k.h" +#include "g4k_launch.h" +#include "rad_plugin.h" + +namespace g4ke { + +struct EscaleArgs { + const int32_t* ids; long long ids_ld; + const uint16_t* sc; /* [n_expert], bf16 */ + uint16_t* ew; long long ew_ld; + long long rows; + int k, n_expert; +}; + +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((unsigned)h << 16); } +__device__ __forceinline__ uint16_t f2bf(float f) { + const unsigned u = __float_as_uint(f); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +__global__ __launch_bounds__(256) void expert_scale_kernel(EscaleArgs A) { + const long long e = (long long)blockIdx.x * 256 + threadIdx.x; + if (e >= A.rows * A.k) return; + const long long r = e / A.k; + const int c = (int)(e - r * A.k); + const int id = A.ids[r * A.ids_ld + c]; + const float s = (id >= 0 && id < A.n_expert) ? bf2f(A.sc[id]) : 0.0f; + uint16_t* w = A.ew + r * A.ew_ld + c; + *w = f2bf(bf2f(*w) * s); +} + +/* [rows, k] with a dense last axis: its rows and row pitch, or false */ +static bool rows_k(const RadTensor* t, uint32_t dt, int64_t k, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != dt || t->rank < 1) return false; + if (rad_tensor_lastdim(t) != k || t->stride[t->rank - 1] != 1) return false; + *rows = rad_tensor_rows(t); + *ld = rad_tensor_row_pitch(t); + return *ld >= k || *rows <= 1; +} + +} /* namespace g4ke */ + +extern "C" { + +/* operands: ids, w_e (the [n_expert] scale table), ew (inout) */ +int g4k_expert_scale_bf16(const RadArgs* a, RadStream stream) { + using namespace g4ke; + if (!a || a->n_t < 3) return RAD_E_INVAL; + const int64_t k = rad_args_geti_or(a, "top_k", 0), ne = rad_args_geti_or(a, "n_expert", 0); + if (k <= 0 || k > 64 || ne <= 0 || ne > (1 << 20)) return RAD_E_SHAPE; + const RadTensor *I = rad_arg_in(a, 0), *S = rad_arg_in(a, 1), *W = rad_arg_in(a, 2); + if (!I || !S || !W) return RAD_E_INVAL; + if (S->dtype != RAD_BF16 || rad_tensor_numel(S) < ne) return RAD_E_DTYPE; + int64_t ri = 0, li = 0, rw = 0, lw = 0; + if (!rows_k(I, RAD_I32, k, &ri, &li) || !rows_k(W, RAD_BF16, k, &rw, &lw)) return RAD_E_SHAPE; + const int64_t M = rw; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (ri < M || M * k > 0x7fffffff) return RAD_E_SHAPE; + EscaleArgs P{}; + P.ids = (const int32_t*)I->data; P.ids_ld = li; + P.sc = (const uint16_t*)S->data; + P.ew = (uint16_t*)W->data; P.ew_ld = lw; + P.rows = M; P.k = (int)k; P.n_expert = (int)ne; + const unsigned blocks = (unsigned)((M * k + 255) / 256); + G4K_LAUNCH(G4K_KNAME(expert_scale_kernel), dim3(blocks), dim3(256), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* extern "C" */ diff --git a/gemma4k/g4k_rows.cpp b/gemma4k/g4k_rows.cpp index 4bfd8eca..14476680 100644 --- a/gemma4k/g4k_rows.cpp +++ b/gemma4k/g4k_rows.cpp @@ -85,6 +85,17 @@ static const RadOperandSpec oJas[] = { { "w_n", RAD_OPD_WEIGHT, 1 }, { "y", RAD_OPD_OUT, 1 }, }; +static const RadParamSpec pEscale[] = { + { "M", RAD_P_INT, RAD_REQUIRED, 0 }, + { "n_expert", RAD_P_INT, RAD_REQUIRED, 0 }, + { "top_k", RAD_P_INT, RAD_REQUIRED, 0 }, + { "dtype", RAD_P_STR, RAD_REQUIRED, 0 }, +}; +static const RadOperandSpec oEscale[] = { + { "ids", RAD_OPD_IN, 0 }, + { "w_e", RAD_OPD_WEIGHT, 0 }, + { "ew", RAD_OPD_INOUT, 0 }, +}; static const RadOpSchema kSchemas[] = { { "pair_argmax", ROW(pPick), ROW(oPick), "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in the first " @@ -100,6 +111,10 @@ static const RadOpSchema kSchemas[] = { "element; and with w_n and y, y = rmsnorm(x) * w_n over the x written. Rounding where the " "unfused chain rounds. Two arms' post-norms, their sum, its norm, the residual add, a " "per-layer scalar and the next layer's input norm (Gemma 4's feed-forward join)." }, + { "expert_scale", ROW(pEscale), ROW(oEscale), + "ew[t, k] = ew[t, k] * w_e[ids[t, k]] over [M, top_k], w_e an [n_expert] table, an id outside " + "it reading 0; one product rounded once, so the embed_lookup + mul pair's value bit for bit. " + "Gemma 4's per_expert_scale on the renormalised routing weights." }, }; /* ==================================================================== operand descriptions @@ -325,6 +340,31 @@ int join_add_scale_host(const RadArgs* a, RadStream) { return RAD_OK; } +/* The host arm of expert_scale, the device kernel's one product in plain C++. */ +int expert_scale_host(const RadArgs* a, RadStream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const int64_t k = rad_args_geti_or(a, "top_k", 0), ne = rad_args_geti_or(a, "n_expert", 0); + if (k <= 0 || ne <= 0) return RAD_E_SHAPE; + const RadTensor *I = rad_arg_in(a, 0), *S = rad_arg_in(a, 1), *W = rad_arg_in(a, 2); + if (!I || !S || !W) return RAD_E_INVAL; + if (I->dtype != RAD_I32 || S->dtype != RAD_BF16 || W->dtype != RAD_BF16) return RAD_E_DTYPE; + if (rad_tensor_numel(S) < ne || rad_tensor_lastdim(I) != k || rad_tensor_lastdim(W) != k) + return RAD_E_SHAPE; + if (I->stride[I->rank - 1] != 1 || W->stride[W->rank - 1] != 1) return RAD_E_STRIDE; + const int64_t rows = rad_tensor_rows(W); + if (rad_tensor_rows(I) < rows) return RAD_E_SHAPE; + const int64_t li = rad_tensor_row_pitch(I), lw = rad_tensor_row_pitch(W); + const uint16_t* sc = (const uint16_t*)S->data; + for (int64_t r = 0; r < rows; ++r) + for (int64_t c = 0; c < k; ++c) { + const int32_t id = ((const int32_t*)I->data)[r * li + c]; + const float s = (id >= 0 && id < ne) ? hb2f(sc[id]) : 0.0f; + uint16_t* w = (uint16_t*)W->data + r * lw + c; + *w = hf2b(hb2f(*w) * s); + } + return RAD_OK; +} + /* ==================================================================== constraints * * The attention rows serve their (head_dim, gqa) at ANY q_len -- one kernel does decode, verify and @@ -356,6 +396,8 @@ G4K_ATTN_C(cH512x8B, 512, 8, "bf16", 0) G4K_ATTN_C(cH512x8F, 512, 8, "fp8_e4m3", static const RadConstraint cJoin[] = { C_GE("n", 1), C_LE("n", 6144), C_IN("dtype", "bf16") }; static const RadConstraint cJoinHost[] = { C_GE("n", 1), C_IN("dtype", "bf16") }; static const RadConstraint cPick[] = { C_GE("n", 1), C_IN("dtype", "f32 fp32") }; +static const RadConstraint cEscale[] = { C_GE("top_k", 1), C_LE("top_k", 64), C_GE("n_expert", 1), + C_IN("dtype", "bf16") }; /* ==================================================================== the rows */ #define G4K_ATTN_ROW(HD, G, KVN, C, KVDOC) \ @@ -409,6 +451,20 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_HOST, 10, ROW(cJoinHost), NOTUNE, nullptr, nullptr, join_add_scale_host, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }, + /* NO opd_shape, as the joins: no libref row, so no oracle; g4k_emu holds both arms to the + * embed_lookup + mul pair. */ + { "expert_scale_bf16", "expert_scale", "moe", + "routing weight times its expert's scale, in place: one thread an element", + "any M, top_k <= 64, row pitches honoured", "i32 ids, bf16 table and weights", + RAD_DOMAIN_DEVICE, 10, ROW(cEscale), NOTUNE, + nullptr, nullptr, g4k_expert_scale_bf16, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "expert_scale_bf16_host", "expert_scale", "moe", + "routing weight times its expert's scale, in place", "any M, top_k <= 64", + "i32 ids, bf16 table and weights", + RAD_DOMAIN_HOST, 10, ROW(cEscale), NOTUNE, + nullptr, nullptr, expert_scale_host, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, { "pair_argmax_f32_host", "pair_argmax", "select", "the top-1 of a row of (id, value) pairs, ties to the lower id, negative ids skipped", "any M and n", "f32 pairs (int32 id bits, f32 value), i32 idx, f32 val", diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index a8eafe75..2693c362 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -202,7 +202,8 @@ set(G4K_EMU ${CMAKE_CURRENT_SOURCE_DIR}/g4k_emu) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") # no fiber switch for this ISA: nothing to register elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set(G4K_HIP ${G4K_DIR}/g4k_attn.hip ${G4K_DIR}/g4k_pick.hip ${G4K_DIR}/g4k_norm.hip) + set(G4K_HIP ${G4K_DIR}/g4k_attn.hip ${G4K_DIR}/g4k_pick.hip ${G4K_DIR}/g4k_norm.hip + ${G4K_DIR}/g4k_escale.hip) set_source_files_properties(${G4K_HIP} PROPERTIES LANGUAGE CXX COMPILE_OPTIONS "-x;c++") add_library(g4k_emu_kernels OBJECT ${G4K_HIP} ${G4K_DIR}/g4k_rows.cpp ${G4K_EMU}/emu/emu.cpp) target_include_directories(g4k_emu_kernels PUBLIC ${G4K_EMU}/emu ${G4K_DIR}) @@ -210,7 +211,7 @@ elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang") # As libr4d compiles every unit: the joins are held to the chain bit for bit, and a contracted # multiply-add is a different rounding. target_compile_options(g4k_emu_kernels PRIVATE -ffp-contract=off -Wno-psabi) - foreach(t attn pick norm) + foreach(t attn pick norm escale) add_executable(g4k_emu_${t} ${G4K_EMU}/test_${t}.cpp) target_link_libraries(g4k_emu_${t} PRIVATE g4k_emu_kernels) target_compile_options(g4k_emu_${t} PRIVATE -ffp-contract=off -Wno-psabi) @@ -219,7 +220,7 @@ elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang") endforeach() # The random sweep at a size the inner loop can afford; `g4k_emu_attn sweep 200` is the long one. add_test(NAME g4k_emu_attn_sweep COMMAND g4k_emu_attn sweep 40) - set_tests_properties(g4k_emu_attn g4k_emu_pick g4k_emu_norm g4k_emu_attn_sweep + set_tests_properties(g4k_emu_attn g4k_emu_pick g4k_emu_norm g4k_emu_escale g4k_emu_attn_sweep PROPERTIES LABELS "g4k_emu" TIMEOUT 600) elseif(RAD_HIP_FOUND AND CMAKE_HIP_COMPILER_ID MATCHES "Clang") add_test(NAME g4k_emu diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 4e3fa5ec..ee58db94 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3699,7 +3699,30 @@ TEST(gemma4_routes_a_decode_step_in_one_launch) { CHECK_EQ(count_issued(issued, "router_topk"), refuse == 2 ? 6 : 0); CHECK_EQ(count_issued(issued, "moe_scatter"), refuse == 2 ? 6 : 0); /* the per-expert scale and the experts' gather run whichever form routed */ - CHECK_EQ(count_issued(issued, "embed_lookup"), 1 + 6); + CHECK_EQ(count_issued(issued, "expert_scale"), 6); CHECK_EQ(count_issued(issued, "moe_gather"), 6); } } + +/* The per-expert scale is one launch where gemma4k serves `expert_scale`, and the table lookup and + * the multiply where it does not -- the same buffers read and written either way. */ +TEST(gemma4_scales_the_routing_weights_in_one_launch) { + for (int refuse = 0; refuse < 2; ++refuse) { + RadBuilder b; + if (refuse) b.refuse.insert("expert_scale"); + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector issued = issued_ops(b, c); + CHECK_EQ(count_issued(issued, "expert_scale"), refuse ? 0 : 6); + CHECK_EQ(count_issued(issued, "embed_lookup"), refuse ? 1 + 6 : 1); /* + the token embedding */ + CHECK_EQ(count_issued(issued, "mul"), refuse ? 6 : 0); + for (const auto& o : b.ops) + if (o.resolved) CHECK(o.uses_declared); + } +} diff --git a/tests/g4k_emu/run.sh b/tests/g4k_emu/run.sh index 01659103..b4ccf095 100644 --- a/tests/g4k_emu/run.sh +++ b/tests/g4k_emu/run.sh @@ -12,14 +12,16 @@ ABI=$2; G=$3; B=$4; N=${5:-40} HERE=$(cd "$(dirname "$0")" && pwd) mkdir -p "$B" F="-std=c++20 -O2 -ffp-contract=off -Wno-psabi -I$HERE/emu -I$ABI -I$G" -for u in attn pick norm; do $CXX $F -x c++ -c "$G/g4k_$u.hip" -o "$B/k_$u.o"; done +for u in attn pick norm escale; do $CXX $F -x c++ -c "$G/g4k_$u.hip" -o "$B/k_$u.o"; done $CXX $F -c "$G/g4k_rows.cpp" -o "$B/rows.o" $CXX $F -c "$HERE/emu/emu.cpp" -o "$B/emu.o" -for t in attn pick norm; do +for t in attn pick norm escale; do $CXX $F -c "$HERE/test_$t.cpp" -o "$B/test_$t.o" - $CXX "$B/test_$t.o" "$B/k_attn.o" "$B/k_pick.o" "$B/k_norm.o" "$B/rows.o" "$B/emu.o" -o "$B/test_$t" + $CXX "$B/test_$t.o" "$B/k_attn.o" "$B/k_pick.o" "$B/k_norm.o" "$B/k_escale.o" "$B/rows.o" \ + "$B/emu.o" -o "$B/test_$t" done "$B/test_attn" "$B/test_attn" sweep "$N" "$B/test_pick" "$B/test_norm" +"$B/test_escale" diff --git a/tests/g4k_emu/test_escale.cpp b/tests/g4k_emu/test_escale.cpp new file mode 100644 index 00000000..8561af12 --- /dev/null +++ b/tests/g4k_emu/test_escale.cpp @@ -0,0 +1,68 @@ +/* tests/g4k_emu: expert_scale (g4k_escale.hip) on the host SIMT emulator, against the chain it + * replaces -- embed_lookup of the [n_expert, 1] scale table by the ids, then mul into the weights -- + * and against the host row, bit for bit: one product rounded once has no other answer. Ids outside + * the table (a negative pad, one past the end) read a zero scale; rows past M and the pitch's + * padding stay untouched. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "g4k.h" +#include +#include +#include +#include +#include +extern "C" const RadKernelInfo* rad_kernel_at(int); +extern "C" int rad_kernel_count(void); + +static float b2f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; } +static uint16_t f2b(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } + +int main() { + std::mt19937 rng(5); + std::normal_distribution nd(0.f, 1.f); + const RadKernelInfo* host = nullptr; + for (int i = 0; i < rad_kernel_count(); ++i) + if (!std::strcmp(rad_kernel_at(i)->op, "expert_scale") && rad_kernel_at(i)->domain == RAD_DOMAIN_HOST) + host = rad_kernel_at(i); + if (!host) { std::puts("expert_scale: no host row"); return 1; } + int fails = 0, cases = 0; + for (int ne : {32, 128}) for (int k : {1, 8}) for (int M : {1, 4, 16, 37}) for (int pad : {0, 3}) { + const int ld = k + pad, R = M + 2; + std::vector ids((size_t)R * ld); + for (auto& v : ids) { + const int u = (int)(rng() % 40); + v = u == 0 ? -1 : u == 1 ? ne : (int)(rng() % (unsigned)ne); /* pads, one past */ + } + std::vector table((size_t)ne), ew0((size_t)R * ld); + for (auto& v : table) v = f2b(0.5f + 0.25f * nd(rng)); + for (auto& v : ew0) v = f2b(nd(rng)); + auto dev = ew0, hst = ew0; + RadTensor t[3]{}; + t[0].data = ids.data(); t[0].dtype = RAD_I32; t[0].rank = 2; t[0].shape[0] = M; t[0].shape[1] = k; t[0].stride[0] = ld; t[0].stride[1] = 1; + t[1].data = table.data(); t[1].dtype = RAD_BF16; t[1].rank = 1; t[1].shape[0] = ne; t[1].stride[0] = 1; + t[2].dtype = RAD_BF16; t[2].rank = 2; t[2].shape[0] = M; t[2].shape[1] = k; t[2].stride[0] = ld; t[2].stride[1] = 1; + RadParam p[4]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n_expert", RAD_P_INT, ne}; p[2] = {"top_k", RAD_P_INT, k}; + p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16"; + RadArgs a{}; a.t = t; a.n_t = 3; a.p = p; a.n_p = 4; + t[2].data = dev.data(); + const int rd = g4k_expert_scale_bf16(&a, nullptr); + t[2].data = hst.data(); + const int rh = host->launch(&a, nullptr); + bool ok = rd == RAD_OK && rh == RAD_OK; + for (int r = 0; r < R && ok; ++r) + for (int c = 0; c < ld && ok; ++c) { + const size_t o = (size_t)r * ld + c; + uint16_t want = ew0[o]; + if (r < M && c < k) { + const int id = ids[o]; + const uint16_t es = (id >= 0 && id < ne) ? table[(size_t)id] : f2b(0.0f); /* embed_lookup */ + want = f2b(b2f(ew0[o]) * b2f(es)); /* mul */ + } + ok = dev[o] == want && hst[o] == want; + } + ++cases; + if (!ok) { ++fails; std::printf("FAIL n_expert %d top_k %d M %d pitch %d\n", ne, k, M, ld); } + } + std::printf("expert_scale: %d cases, %d failure(s)\n", cases, fails); + return fails != 0; +} From a378b41abbd1fd68602b14cbb97cd6f923b115e4 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 14:52:24 -0500 Subject: [PATCH 16/24] libr4d: the exact two-shot all-reduce takes every prefill-sized message R4D_AR_TWOSHOT_WIDE_MAX_ELEMS was 20971520 -- a 4096-token chunk of a 5120-wide residual -- and the band above it went back to the one-shot, which sends (ws-1)*N bytes a rank where the two-shot sends 2*(ws-1)/ws*N. At the default --max-num-batched-tokens 8192, Gemma 4 26B-A4B's attention reduce is 8192 x 2816 = 23M elements and its feed-forward reduce, which carries both branches for their own post-norms, 46M: both over the bound, so every full prefill chunk went one-shot at twice the bytes. --profile-ops on 4x R9700, tp 4, a 20489-token prefill (chunks of 8192, 8192, 4105) fits one link rate across all of it: the attention reduces 16.8 ms the three calls (two one-shot, one two-shot) and the feed-forward reduces ~37 ms (all one-shot), 1.6 s of the 2.7 s prefill. The same rate with every call two-shot is ~9 and ~19 ms: about 0.8 s less a 20k prefill. The bound guards the kernel's int word offsets and nothing else -- the scratch already holds a full message per slot (r4d_ar_entry.hip build()), twice what the two-shot uses -- so it is now 2^28 elements, 2^26 words at fp32. The fold is the one-shot's, fp32 in ascending rank order, so the band edge moves no bits. Fewer bands also means one scratch set less: the old 20971520 band was its own instance, ~335 MiB a rank at tp 4. plugin_test: a 16384-token chunk is two-shot to its end, and the one-shot still takes a message past the bound. r4d_selftest's three-rank pattern walks a 46137344-element message, past the old ceiling. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d.h | 8 ++++++-- libr4d/r4d_ar_entry.hip | 2 +- libr4d/r4d_rows.cpp | 2 +- libr4d/r4d_selftest.cpp | 7 ++++--- tests/plugin_test.cpp | 15 ++++++++++----- 5 files changed, 22 insertions(+), 12 deletions(-) diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 72ef2813..12cfdd27 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -418,8 +418,12 @@ void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers); // Shards are as even as the word count allows (the first n16 % ws take one more word), so a // message need not divide by the rank count -- at three it almost never does. Regions A and B sit // at 0 and the longest shard, so the slot stride must hold twice that. Above this bound the caller -// falls back: -enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 20971520 }; // a 4096-token hidden-5120 prefill chunk +// falls back to the one-shot. The bound guards the kernel's int word offsets (the message, the +// slot stride) and nothing else: 2^28 elements is 2^26 words at fp32. It was 20971520 -- a +// 4096-token chunk of a 5120-wide residual -- which handed every larger prefill chunk back to the +// one-shot and its (ws-1)*N send: an 8192-token chunk at Gemma 4's 2816 is 23M elements at the +// attention's reduce and 46M at the feed-forward's, which carries both branches. +enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456 }; void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 2e52c93c..991953a9 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -38,7 +38,7 @@ #include #include -static_assert(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS == 20971520, +static_assert(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS == 268435456, "r4d_rows.cpp restates this bound; libr4d changed it"); static_assert(R4D_MAX_RANKS == 8, "the 8-rank entry point names exactly seven peers"); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index eca5fc73..6e3a5094 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -71,7 +71,7 @@ /* libr4d's R4D_AR_TWOSHOT_WIDE_MAX_ELEMS, restated because this file must not include r4d.h. * r4d_ar_entry.hip static_asserts the two against each other. */ -#define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 20971520 +#define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 268435456 /* The largest message, in elements, a 4- or 8-rank exact all-reduce keeps on the one-shot; above it * the two-shot rows take it. 1 MiB of a 16-bit payload. The one-shot sends (ws-1)*N bytes a rank diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 506567ba..f7ad8902 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -11241,7 +11241,7 @@ static void ar_three_rank(const Plugin& pl, const std::vector& devs, const * sums correctly. This one gives every element its own value, so a word reduced by the wrong * owner, gathered from the wrong slot or dropped at a short shard's end is a wrong number at a * known index. The sizes walk the uneven split: words % 3 of 0, 1 and 2, from a 16-word message - * to the row's 20971520-element ceiling, in place (how every block issues it) and once out of + * to past the old 20971520 ceiling, in place (how every block issues it) and once out of * place, back to back on ONE instance so the slot parity and the changing block count are * exercised the way a step's mixed messages exercise them. The oracle is the fold the kernel * claims -- fp32 in ascending rank order, rounded once -- so it is bit for bit, and so it is also @@ -11320,8 +11320,9 @@ static void ar_three_rank_pattern(const Plugin& pl, const std::vector& devs struct Run { const char* dtype; std::vector sizes; int oop; }; const std::vector runs = { /* bf16, the residual: words = numel / 8. 2048 x 2048 rows is words % 3 == 2, x 2049 is - * 0, x 2050 is 1; 128 is 16 words (1), 24008 is 3001 (1); 20971520 the ceiling (1). */ - { "bf16", { 4194304, 128, 4196352, 24008, 4198400, 20971520, 4194304 }, 2 }, + * 0, x 2050 is 1; 128 is 16 words (1), 24008 is 3001 (1); 20971520 the old ceiling (1); + * 46137344, Gemma 4's feed-forward reduce at an 8192-token chunk, past it (1). */ + { "bf16", { 4194304, 128, 4196352, 24008, 4198400, 20971520, 46137344, 4194304 }, 2 }, /* fp32: words = numel / 4. 8196 -> 2049 (0), 4100 -> 1025 (2), 1048580 -> 262145 (2). */ { "fp32", { 8196, 4100, 1048580 }, 0 }, }; diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index ebc1d4d9..d376d606 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -901,13 +901,18 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) { CHECK_EQ(names(bands(2, 1, chunk)), "524288:ar_oneshot_2rank_exact 5242880:ar_oneshot_2rank_exact "); - /* Above the two-shot's cap the one-shot takes the message back. */ + /* A 16384-token chunk is two-shot to its end: the two-shot's bound is a guard on its word + * offsets, not a prefill size, and a chunk past the old 20971520 went back to the one-shot's + * twice-as-heavy send. */ CHECK_EQ(names(bands(4, 1, 16384)), - "524288:ar_oneshot_4rank_exact 20971520:ar_twoshot_4rank_exact " - "41943040:ar_oneshot_4rank_exact "); + "524288:ar_oneshot_4rank_exact 41943040:ar_twoshot_4rank_exact "); CHECK_EQ(names(bands(3, 1, 16384)), - "524288:ar_oneshot_3rank_exact 20971520:ar_twoshot_3rank_exact " - "41943040:ar_oneshot_3rank_exact "); + "524288:ar_oneshot_3rank_exact 41943040:ar_twoshot_3rank_exact "); + + /* Above the two-shot's bound the one-shot takes the message back. */ + CHECK_EQ(names(bands(4, 1, 131072)), + "524288:ar_oneshot_4rank_exact 268435456:ar_twoshot_4rank_exact " + "335544320:ar_oneshot_4rank_exact "); /* A step that never exceeds the bound has one band, and it is the one-shot's. */ CHECK_EQ(names(bands(4, 1, 128)), "327680:ar_oneshot_4rank_exact "); From 76dd0019ac88e00fa7a7e21d62221f41a9d63eb4 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 14:53:02 -0500 Subject: [PATCH 17/24] libr4d: logit_softcap spreads a row over blocks One 256-thread block a row: at Gemma 4's tp 4 a row is a 65536-wide vocabulary shard and a step has a decode's few rows, so a handful of blocks walked 256 elements a thread of tanhf each. --profile-ops on 4x R9700: 82.7 us a decode step and 85.6 us for the prefill's single row, for 256 KiB of f32 a row -- four times the drafter's row_topk over a row as wide (18.6 us). Both legs now put a row on up to 64 blocks, eight elements a thread (32 blocks at 65536). Elementwise, so no bit moves; libr4d's selftest and rad-kbench's libref comparison hold it as before. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_model_bf16.hip | 21 +++++++++++++++++---- libr4d/r4d_rows.cpp | 4 ++-- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index b5fd739b..88e2a14e 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -688,13 +688,18 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel( // ref_logit_softcap: y = cap * tanh(x / cap), the final-logit softcap. THE ROW-WISE-WITH-A-PITCH // SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the logits_gemm's output, // and the pitch form costs nothing on a contiguous buffer -- it is x_ld == n. +// +// A ROW IS SPREAD OVER gridDim.y BLOCKS, because a row is a vocabulary shard: 65536 wide at Gemma +// 4's tp 4, and the step's rows are a decode's few. One block a row walked 256 elements a thread of +// tanhf on a handful of CUs -- ~85 us at one row, --profile-ops on an R9700, for 256 KiB of f32. +// Elementwise, so the spread moves no bits. __global__ __launch_bounds__(kThreads) void logit_softcap_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { const uint32_t m = blockIdx.x; const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; - for (uint32_t i = threadIdx.x; i < n; i += kThreads) + for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads) yr[i] = f32_to_bf16(cap * tanhf(bf2f(xr[i]) / cap)); } @@ -707,10 +712,16 @@ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32( const uint32_t m = blockIdx.x; const float* __restrict__ xr = x + (size_t)m * x_ld; float* __restrict__ yr = y + (size_t)m * y_ld; - for (uint32_t i = threadIdx.x; i < n; i += kThreads) + for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads) yr[i] = cap * tanhf(xr[i] / cap); } +/* The blocks a softcap row is spread over: eight elements a thread, at most 64 blocks a row. */ +static uint32_t softcap_blocks_per_row(int n) { + uint32_t b = (uint32_t)((n + kThreads * 8 - 1) / (kThreads * 8)); + return b < 1 ? 1 : (b > 64 ? 64 : b); +} + // ---------------------------------------------------------------------------- scale // ref_scale: y = x * s, s a [1] weight broadcast over every element. THE ROW-WISE-WITH-A-PITCH // SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the residual stream at @@ -1248,7 +1259,8 @@ extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap, if (!(cap > 0.0f)) return -3; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M, softcap_blocks_per_row(n)), + dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)y, (uint32_t)n, cap, (uint32_t)x_ld, (uint32_t)y_ld); @@ -1262,7 +1274,8 @@ extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap, if (!(cap > 0.0f)) return -3; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M), dim3(kThreads), 0, + hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M, softcap_blocks_per_row(n)), + dim3(kThreads), 0, (hipStream_t)stream, (const float*)x, (float*)y, (uint32_t)n, cap, (uint32_t)x_ld, (uint32_t)y_ld); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 6e3a5094..a60835d3 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -3829,7 +3829,7 @@ static const RadKernelInfo kKernels[] = { r4d_shape_unary }, { "logit_softcap_bf16", "logit_softcap", "elem", - "cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent", + "cap * tanh(x / cap), the final-logit softcap, a row spread over up to 64 blocks", "any extent; contiguous in and out", "bf16 in and out, fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, @@ -3838,7 +3838,7 @@ static const RadKernelInfo kKernels[] = { r4d_shape_unary }, { "logit_softcap_f32", "logit_softcap", "elem", - "cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent", + "cap * tanh(x / cap), the final-logit softcap, a row spread over up to 64 blocks", "any extent; contiguous in and out", "f32 in and out — the 1.3.0 sampling chain carries the logits as f32 from the gemm", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, From e1733658236a035aed4dcc6f5f42f820f26cfba6 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 14:57:34 -0500 Subject: [PATCH 18/24] gemma4k: the sandwich joins issue every load first A barrier is a fence, so a load written after a reduction waits for it. norm_add_norm fetched the residual and both gains phase by phase, join_add_scale the residual, three or four gains and the layer scalar, so each paid a global round trip per phase on top of its reductions: --profile-ops on 4x R9700 has them at 13.2 and 17.8 us a call at decode, 30 of each a step, where a launch that does nothing costs ~7. Now every operand of the row is in flight at once before the first reduction, the two arm norms share one barrier pair (block_sum2: each value takes block_sum's butterfly and wave order), and a thread holds 12 elements where the row fits -- n <= 3072, Gemma 4 26B's 2816 among them -- and kMaxPer's 24 past that, instead of 24 always. The arithmetic is the same expressions in the same order; a sum's terms past n were +0 and are gone. g4k_emu: both joins at the edge between the two widths (3072, 3073), with and without the next norm, bit for bit against the chain as every other case. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- gemma4k/g4k_norm.hip | 127 +++++++++++++++++++++++++----------- tests/g4k_emu/test_norm.cpp | 3 + 2 files changed, 91 insertions(+), 39 deletions(-) diff --git a/gemma4k/g4k_norm.hip b/gemma4k/g4k_norm.hip index a84fde2a..66d1d0d2 100644 --- a/gemma4k/g4k_norm.hip +++ b/gemma4k/g4k_norm.hip @@ -22,7 +22,15 @@ * * One 256-thread block a row: a decode step is a handful of rows, so the row is latency-bound and * a block's three reductions beat seven launches. Values a later stage reuses stay in registers - * (kMaxPer a thread, so n <= 256 * kMaxPer; the row table says so). + * (PER a thread, 12 to n = 3072 and kMaxPer = 24 to 6144; the row table says so). + * + * EVERY LOAD IS ISSUED FIRST. A barrier is a fence, so a load written after a reduction waits for + * it: the first version fetched the gains, the residual and the layer scalar phase by phase and + * paid a global round trip for each on top of the reductions -- 17.8 us for join_add_scale and 13.2 + * for norm_add_norm at decode under --profile-ops, against ~7 for a launch that does nothing. Now + * the row's every operand is in flight at once, the two arm norms share one barrier pair, and a + * thread holds the elements it touches and no more. Nothing about the arithmetic moved: the same + * expressions in the same order, a sum's extra terms past n were +0. */ #include @@ -62,6 +70,20 @@ __device__ __forceinline__ float block_sum(float v, float* lds) { for (int w = 0; w < kWaves; ++w) s += lds[w]; return s; } +/* two block sums for one barrier pair: each value takes block_sum's butterfly and wave order */ +__device__ __forceinline__ void block_sum2(float& a, float& b, float* lds) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) { a += shfl_xor(a, d); b += shfl_xor(b, d); } + const int lane = lane_id(), wave = (int)(threadIdx.x >> 5); + __syncthreads(); + if (lane == 0) { lds[wave] = a; lds[kWaves + wave] = b; } + __syncthreads(); + float sa = 0.0f, sb = 0.0f; +#pragma unroll + for (int w = 0; w < kWaves; ++w) { sa += lds[w]; sb += lds[kWaves + w]; } + a = sa; + b = sb; +} __device__ __forceinline__ float norm_factor(float ss, int n, float eps) { return rsqrtf(ss / (float)n + eps); } @@ -82,6 +104,7 @@ struct NormArgs { }; /* t = norm(a) * w_a; x += t; y = norm(x) * w_y */ +template __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { __shared__ float lds[kWaves]; const int tid = (int)threadIdx.x, n = A.n; @@ -90,82 +113,96 @@ __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { uint16_t* xr = A.x + m * A.x_ld; uint16_t* yr = A.y + m * A.y_ld; - float av[kMaxPer], xv[kMaxPer]; + /* every operand of the row in flight at once: the block output, the residual, both gains */ + float av[PER], xv[PER], wa[PER], wy[PER]; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + const bool in = i < n; + av[k] = in ? bf2f(ar[i]) : 0.0f; + xv[k] = in ? bf2f(xr[i]) : 0.0f; + wa[k] = in ? A.w0[i] : 0.0f; + wy[k] = in ? A.w1[i] : 0.0f; + } float ss = 0.0f; #pragma unroll - for (int k = 0; k < kMaxPer; ++k) { - const int i = tid + k * kThreads; - av[k] = i < n ? bf2f(ar[i]) : 0.0f; - ss += av[k] * av[k]; - } + for (int k = 0; k < PER; ++k) ss += av[k] * av[k]; const float sa = norm_factor(block_sum(ss, lds), n, A.eps); ss = 0.0f; #pragma unroll - for (int k = 0; k < kMaxPer; ++k) { + for (int k = 0; k < PER; ++k) { const int i = tid + k * kThreads; if (i < n) { - const float t = rbf((av[k] * sa) * A.w0[i]); - xv[k] = rbf(bf2f(xr[i]) + t); + const float t = rbf((av[k] * sa) * wa[k]); + xv[k] = rbf(xv[k] + t); xr[i] = f2bf(xv[k]); - } else { - xv[k] = 0.0f; } ss += xv[k] * xv[k]; } const float sx = norm_factor(block_sum(ss, lds), n, A.eps); #pragma unroll - for (int k = 0; k < kMaxPer; ++k) { + for (int k = 0; k < PER; ++k) { const int i = tid + k * kThreads; - if (i < n) yr[i] = f2bf((xv[k] * sx) * A.w1[i]); + if (i < n) yr[i] = f2bf((xv[k] * sx) * wy[k]); } } /* x = (x + norm(norm(d) * w_d + norm(r) * w_r) * w_j) * s, and with NEXT y = norm(x) * w_n: the * next layer's input norm taken over the bf16 x this stores, which is what that norm would read. */ -template +template __global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { - __shared__ float lds[kWaves]; + __shared__ float lds[2 * kWaves]; const int tid = (int)threadIdx.x, n = A.n; const long long m = (long long)blockIdx.x; const uint16_t* dr = A.d + m * A.d_ld; const uint16_t* rr = A.r + m * A.r_ld; uint16_t* xr = A.x + m * A.x_ld; - float dv[kMaxPer], rv[kMaxPer]; + /* every operand of the row in flight at once: both arms, the residual, the three gains (four + * with the next norm's) and the layer scalar */ + float dv[PER], rv[PER], xo[PER], wd[PER], wr[PER], wj[PER], wn[NEXT ? PER : 1]; + const float sc = bf2f(*A.s); +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + const bool in = i < n; + dv[k] = in ? bf2f(dr[i]) : 0.0f; + rv[k] = in ? bf2f(rr[i]) : 0.0f; + xo[k] = in ? bf2f(xr[i]) : 0.0f; + wd[k] = in ? A.w0[i] : 0.0f; + wr[k] = in ? A.w1[i] : 0.0f; + wj[k] = in ? A.w2[i] : 0.0f; + if constexpr (NEXT) wn[k] = in ? A.w3[i] : 0.0f; + } float sd2 = 0.0f, sr2 = 0.0f; #pragma unroll - for (int k = 0; k < kMaxPer; ++k) { - const int i = tid + k * kThreads; - dv[k] = i < n ? bf2f(dr[i]) : 0.0f; - rv[k] = i < n ? bf2f(rr[i]) : 0.0f; + for (int k = 0; k < PER; ++k) { sd2 += dv[k] * dv[k]; sr2 += rv[k] * rv[k]; } - const float sd = norm_factor(block_sum(sd2, lds), n, A.eps); - const float sr = norm_factor(block_sum(sr2, lds), n, A.eps); + block_sum2(sd2, sr2, lds); + const float sd = norm_factor(sd2, n, A.eps); + const float sr = norm_factor(sr2, n, A.eps); /* the join, kept in dv */ float ss = 0.0f; #pragma unroll - for (int k = 0; k < kMaxPer; ++k) { + for (int k = 0; k < PER; ++k) { const int i = tid + k * kThreads; if (i < n) { - const float u = rbf((dv[k] * sd) * A.w0[i]); - const float v = rbf((rv[k] * sr) * A.w1[i]); + const float u = rbf((dv[k] * sd) * wd[k]); + const float v = rbf((rv[k] * sr) * wr[k]); dv[k] = rbf(u + v); - } else { - dv[k] = 0.0f; } ss += dv[k] * dv[k]; } const float sj = norm_factor(block_sum(ss, lds), n, A.eps); - const float sc = bf2f(*A.s); ss = 0.0f; #pragma unroll - for (int k = 0; k < kMaxPer; ++k) { + for (int k = 0; k < PER; ++k) { const int i = tid + k * kThreads; if (i < n) { - const float j = rbf((dv[k] * sj) * A.w2[i]); - const float x1 = rbf(bf2f(xr[i]) + j); + const float j = rbf((dv[k] * sj) * wj[k]); + const float x1 = rbf(xo[k] + j); const uint16_t xn = f2bf(x1 * sc); xr[i] = xn; rv[k] = bf2f(xn); /* the new x, kept for the next norm */ @@ -178,9 +215,9 @@ __global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { const float sn = norm_factor(block_sum(ss, lds), n, A.eps); uint16_t* yr = A.y + m * A.y_ld; #pragma unroll - for (int k = 0; k < kMaxPer; ++k) { + for (int k = 0; k < PER; ++k) { const int i = tid + k * kThreads; - if (i < n) yr[i] = f2bf((rv[k] * sn) * A.w3[i]); + if (i < n) yr[i] = f2bf((rv[k] * sn) * wn[k]); } } } @@ -234,7 +271,12 @@ int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream stream) { P.y = (uint16_t*)Y->data; P.y_ld = ly; P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data; P.n = (int)n; P.eps = eps; - G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + if (n <= (int64_t)kThreads * 12) + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel<12>), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); + else + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } @@ -270,12 +312,19 @@ int g4k_join_add_scale_bf16(const RadArgs* a, RadStream stream) { P.s = (const uint16_t*)Sc->data; if (Y) { P.w3 = (const float*)Wn->data; P.y = (uint16_t*)Y->data; P.y_ld = ly; } P.n = (int)n; P.eps = eps; - if (Y) - G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), + const bool narrow = n <= (int64_t)kThreads * 12; + if (narrow && Y) + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel<12, true>), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + else if (narrow) + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel<12, false>), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); + else if (Y) + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), + dim3(kThreads), (hipStream_t)stream, P); else - G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), - (hipStream_t)stream, P); + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), + dim3(kThreads), (hipStream_t)stream, P); return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } diff --git a/tests/g4k_emu/test_norm.cpp b/tests/g4k_emu/test_norm.cpp index 7e09c672..38f1598a 100644 --- a/tests/g4k_emu/test_norm.cpp +++ b/tests/g4k_emu/test_norm.cpp @@ -194,6 +194,9 @@ int main() { fails += case_nan(3, 1000, 24, 1) + case_jas(3, 1000, 24, 1); fails += case_nan(2, 6144, 0, 0) + case_jas(2, 6144, 16, 0); fails += case_nan(5, 256, 8, 1) + case_jas(5, 5376, 0, 1); + /* the edge between the 12-a-thread kernels and the 24: 3072 the last of the first */ + fails += case_nan(2, 3072, 0, 1) + case_nan(2, 3073, 8, 1); + fails += case_jas(2, 3072, 0, 1, true) + case_jas(2, 3073, 8, 1, true) + case_jas(3, 3073, 0, 1); /* and with the next layer's input norm folded in */ for (int M : Ms) fails += case_jas(M, 2816, M % 2 ? 64 : 0, 2, true); fails += case_jas(3, 1000, 24, 1, true) + case_jas(2, 6144, 16, 0, true); From 73c3dc38bef34994cd1bb95c238bf87704a22645 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 15:23:48 -0500 Subject: [PATCH 19/24] gemma4k, arch/gemma4: attn_paged_qrow -- q in the fused row only where gemma4k reads it 8772d5b handed the sliding layers' attn_paged q as a column slice of the fused [q|k|v] row. gemma4k reads that; libr4d's paged attention reads q only dense and refuses the slice with RAD_E_STRIDE, which stops the engine at the first step. Under attn_paged the first library in --kernels wins, so the slice was only safe with gemma4k ahead of libr4d -- and the deploy script's default order (libr4d,gemma4k,libavx) took the server down at layer 0's attention on both profile runs. gemma4k now declares the same kernels a second time under attn_paged_qrow: attn_paged's schema field for field, with q read at its own row pitch. Only gemma4k declares it, so it resolves there or nowhere. The sliding layers ask for it once; where it resolves they read q in place (no lift), and where it does not -- a hierarchy without gemma4k, or RADIANCE_GEMMA4_FUSE=0 -- q is lifted into a dense block by a `cast` again and attn_paged reads that, which every attention library takes. The lift's buffer is declared only then, since an unnamed buffer is live for the whole program. A miss is the swa group's first op carrying a block_size, and answers rad_kv_block_size with the RAD_KV_BLOCK it declares, as attn_paged would. No libref row, as the joins. The kernel order still matters for speed -- gemma4k first is the order this model was measured with (ARCHITECTURES.md) -- but no longer for whether the server runs. A startup note says which form was taken. arch_test: the slice reaches attn_paged_qrow and never attn_paged; refused, every sliding layer lifts q for attn_paged; a decode step issues either form; and the three older gemma4 tests count the sliding layers' attention under its new name. docs: OPS.md's row and paragraph (and a line of the joins' text reflowed to the width, as one of gemma4.cpp's), ARCHITECTURES.md's kernel paragraph, which now names expert_scale too, and GUIDE's FUSE row. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 53 ++++++++++++++++++++++++-------- docs/ARCHITECTURES.md | 11 ++++--- docs/GUIDE.md | 2 +- docs/OPS.md | 21 ++++++++++--- gemma4k/g4k_rows.cpp | 53 ++++++++++++++++++++++++++++++++ tests/arch_test.cpp | 69 +++++++++++++++++++++++++++++++----------- 6 files changed, 168 insertions(+), 41 deletions(-) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index aea10675..f258f44c 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -217,7 +217,7 @@ struct Layer { int full = 0; /* attention */ rad_weight w_anorm = 0, w_qkv = 0, w_q = 0, w_k = 0, w_qn = 0, w_kn = 0, w_o = 0, w_apost = 0; - rad_op op_anorm = 0, op_qkv = 0, op_qknr = 0; + rad_op op_anorm = 0, op_qkv = 0, op_qknr = 0, op_lift = 0; rad_op op_q = 0, op_k = 0, op_vnorm = 0, op_qn = 0, op_kn = 0, op_qrope = 0, op_krope = 0; rad_op op_store = 0, op_attn = 0, op_o = 0, op_ar_o = 0, op_apost = 0, op_add_a = 0; /* dense arm */ @@ -269,7 +269,8 @@ struct Model { double escale = 1.0, softcap = 0.0; rad_buf b_x = 0, b_h = 0, b_o = 0; - rad_buf b_qkv = 0, b_atts = 0; /* sliding */ + rad_buf b_qkv = 0, b_qs = 0, b_atts = 0; /* sliding; q_s where q is lifted */ + int qrow = -1; /* attn_paged_qrow resolved: -1 not asked yet, then 0 or 1 */ rad_buf b_qf = 0, b_kf = 0, b_vf = 0, b_attf = 0; /* full */ rad_buf b_ff2 = 0, b_gu = 0, b_act = 0; /* the arms' join; the dense arm */ rad_buf b_rn = 0, b_logit = 0, b_ids = 0, b_ew = 0, b_es = 0, b_hx = 0; @@ -977,8 +978,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_NOWEIGHTS), {buf}, {buf}); }; - auto attn = [&](const Kind& k, rad_buf q, rad_buf out) { - return rw(b, RAD_OP(b, "attn_paged", + auto attn = [&](const Kind& k, rad_buf q, rad_buf out, const char* op = "attn_paged") { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", k.hd), RAD_INT("gqa", k.nh / k.nkv), RAD_INT("causal", 1), RAD_INT("window", k.window), RAD_INT("n_head", k.nh), @@ -1001,7 +1002,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* THE SANDWICH JOINS: asked of the kernel libraries as one op each (gemma4k serves them) and * declared as the chain where nothing does -- or where RADIANCE_GEMMA4_FUSE=0 asks for the - * chain, the A/B switch, which turns off gemma4k's `expert_scale` with them. The fused kernels round where the chain rounds (gemma4k/g4k_norm.hip). + * chain, the A/B switch, which turns off gemma4k's `expert_scale` and `attn_paged_qrow` with + * them. The fused kernels round where the chain rounds (gemma4k/g4k_norm.hip). * libref has no row for the joins on purpose, so "nothing serves them" stays reachable. */ const char* fuse_env = std::getenv("RADIANCE_GEMMA4_FUSE"); const bool fuse_joins = !(fuse_env && fuse_env[0] == '0'); @@ -1089,12 +1091,30 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_F64("wadd", 0.0), RAD_INT("v_norm", 1)), RAD_WEIGHTS(y.w_qn, y.w_kn)), {m.b_qkv}, {m.b_qkv}); - /* Q IS READ WHERE THE PROJECTION LEFT IT, a column slice of the fused [q|k|v] row: - * gemma4k's attention takes q at any row pitch, so there is no copy into a dense block - * -- a launch and a [T, q] round trip a sliding layer. libr4d's attention reads q only - * dense and refuses the slice by name (RAD_E_STRIDE), which is one more reason the - * order is `--kernels gemma4k,libr4d` for this model. */ - y.op_attn = attn(k, m.b_qkv, m.b_atts); + /* Q IS READ WHERE THE PROJECTION LEFT IT, a column slice of the fused [q|k|v] row, by + * `attn_paged_qrow` -- attn_paged with q at its own row pitch -- which only gemma4k + * declares, so no `--kernels` order can hand the slice to a library that reads q only + * dense (libr4d's refuses it with RAD_E_STRIDE, which stops the engine). That saves the + * lift: a launch and a [T, q] round trip a sliding layer. Where the op does not + * resolve, or RADIANCE_GEMMA4_FUSE=0 asks for the chain, q is lifted into a dense block + * for attn_paged, which every attention library takes. Asked once, because every + * sliding layer asks the same question; a miss is still the group's first op carrying + * a block_size, and answers rad_kv_block_size with the RAD_KV_BLOCK it declares. */ + if (fuse_joins && m.qrow != 0) { + y.op_attn = attn(k, m.b_qkv, m.b_atts, "attn_paged_qrow"); + m.qrow = y.op_attn ? 1 : 0; + } + if (!y.op_attn) { + /* declared here, not with the others: a buffer no op names is live for the whole + * program, and where q is read in place nothing names this one */ + if (!m.b_qs) m.b_qs = decl_b(b, nm.f("q_s"), RAD_BF16, {T, k.q()}); + y.op_lift = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", k.q()), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {m.b_qkv}, {m.b_qs}); + y.op_attn = attn(k, m.b_qs, m.b_atts); + } y.op_store = kv_store(k, m.b_qkv, m.b_qkv); y.op_o = gemm(T, E, k.q(), y.w_o, m.b_atts, m.b_o); } else { @@ -1467,6 +1487,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c n_joins, (long long)(m.moe ? 2 * m.n_layer : m.n_layer), !fuse_joins ? " -- RADIANCE_GEMMA4_FUSE=0, the rmsnorm / add / mul_weight chain" : n_joins == 0 ? " -- not served (load gemma4k), the rmsnorm / add / mul_weight chain" : ""); + if (m.ks.nh > 0) + rad_note(b, "sliding attention: q %s", m.qrow == 1 + ? "read in the fused qkv row (gemma4k attn_paged_qrow)" + : "lifted into a dense block for attn_paged (attn_paged_qrow not served, or " + "RADIANCE_GEMMA4_FUSE=0)"); if (m.moe) { auto how = [&](int n_fp8) { return n_fp8 == m.n_layer ? "block fp8" : n_fp8 == 0 ? "bf16" : "mixed"; @@ -1625,8 +1650,10 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_ISSUE(c, y.op_qknr, brows(m.b_qkv, T), pos, RAD_W(y.w_qn), RAD_W(y.w_kn)); RAD_ISSUE(c, y.op_store, bcol(m.b_qkv, qd, kvd, T), bcol(m.b_qkv, qd + kvd, kvd, T), praw(slot, RAD_I32, T), kv_cache(k.kv, (int)li)); - RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, bcol(m.b_qkv, 0, qd, T), kv_cache(k.kv, (int)li), - bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_atts, T)); + if (y.op_lift) RAD_ISSUE(c, y.op_lift, bcol(m.b_qkv, 0, qd, T), brows(m.b_qs, T)); + RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, + y.op_lift ? brows(m.b_qs, T) : bcol(m.b_qkv, 0, qd, T), + kv_cache(k.kv, (int)li), bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_atts, T)); RAD_ISSUE(c, y.op_o, brows(m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T)); } else { RAD_ISSUE(c, y.op_q, brows(m.b_h, T), RAD_W(y.w_q), brows(m.b_qf, T)); diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 867b2ea3..360b9131 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -520,10 +520,13 @@ expert parity, so a rank holds an even number of experts. **Kernels.** `--kernels gemma4k,libr4d,libavx`, **gemma4k first.** It serves all of the trunk's attention -- the sliding layers (h256, gqa 2) and the full layers at gqa 8, 4 and 2 (one or two, -four, eight ranks) -- plus `pair_argmax` and the two sandwich-norm joins (`norm_add_norm`, -`join_add_scale`), which the plugin declares as the rmsnorm / add chain where nothing serves them; -the startup note says how many were fused. libr4d has h256/gqa2 and h512/gqa8 rows as well, -written for the dense 31B; with gemma4k first the 26B-A4B runs on the kernels it was measured with. +four, eight ranks) -- plus `pair_argmax` and the fusions: the two sandwich-norm joins +(`norm_add_norm`, `join_add_scale`), `expert_scale`, and `attn_paged_qrow`, the sliding layers' +attention reading q where the fused qkv projection left it. The plugin declares each one's unfused +form where nothing serves it -- the rmsnorm / add chain, `embed_lookup` + `mul`, a `cast` lifting q +for `attn_paged` -- and the startup notes say which were taken. libr4d has h256/gqa2 and h512/gqa8 +rows as well, written for the dense 31B; with gemma4k first the 26B-A4B runs on the kernels it was +measured with. Without `gemma4k` at all, the full layers have no kernel at four and eight ranks, and a drafter head sharded over more than one rank has no `pair_argmax`. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 55b39020..54b9f5c1 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1859,7 +1859,7 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct at al | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_G4K_WMMA` | `0` keeps `gemma4k`'s prefill attention on its scalar kernel instead of the WMMA one. An A/B switch and a way out if the matrix path misbehaves on a card; read once | -| `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the chains instead of `gemma4k`'s fusions: the rmsnorm / add chain for the sandwich joins (`norm_add_norm`, `join_add_scale`), and `embed_lookup` + `mul` for `expert_scale`. An A/B switch; read at declare | +| `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the chains instead of `gemma4k`'s fusions: the rmsnorm / add chain for the sandwich joins (`norm_add_norm`, `join_add_scale`), `embed_lookup` + `mul` for `expert_scale`, and a `cast` lifting q for `attn_paged` for `attn_paged_qrow`. An A/B switch; read at declare | There is also a family of instruments for engine development — `RADIANCE_DEBUG_*` (residual probes, idle scrubs, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on diff --git a/docs/OPS.md b/docs/OPS.md index 4e3ece12..ac97377f 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -294,13 +294,14 @@ rounding. -log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's torch expressions are, then rounded. -### gemma4k's fusions: the sandwich-norm joins and `expert_scale` — no reference row +### gemma4k's fusions: the sandwich-norm joins, `expert_scale`, `attn_paged_qrow` — no reference row | op | params | operands | |---|---|---| | `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` | | `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w, `w_n`w? → `y`? | | `expert_scale` | `M`(range) `n_expert` `top_k` `dtype` | `ids`, `w_e`w, `ew`:inout | +| `attn_paged_qrow` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` | Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add` and `mul_weight`. `norm_add_norm` is `t = rmsnorm(a) * w_a; x += t; y = rmsnorm(x) * w_y` -- a post-norm, the @@ -308,16 +309,26 @@ residual add, the next pre-norm. `join_add_scale` is `x = (x + rmsnorm(rmsnorm(d rmsnorm(r) * w_r) * w_j) * s` -- two arms' post-norms, their sum, its norm, the residual add and a one-element layer scalar (Gemma 4's MoE feed-forward) -- and, given `w_n` and `y` (both or neither), `y = rmsnorm(x) * w_n` over the `x` it writes: the next layer's input norm, or the final -norm after the last layer, which would otherwise be a launch of its own reading that `x` back. Every value the chain stores is rounded to -the activation dtype at the same point, so the two differ from the chain only in the order a sum -of squares is added in: with the same order they are bit-identical to it, and against a chain -summed in another block width a norm factor can differ in its last bit. +norm after the last layer, which would otherwise be a launch of its own reading that `x` back. +Every value the chain stores is rounded to the activation dtype at the same point, so the two +differ from the chain only in the order a sum of squares is added in: with the same order they are +bit-identical to it, and against a chain summed in another block width a norm factor can differ in +its last bit. `expert_scale` is `ew[t, k] = ew[t, k] * w_e[ids[t, k]]` over `[M, top_k]`, `w_e` an `[n_expert]` table and an id outside it reading 0: Gemma 4's per_expert_scale on the renormalised routing weights, in place of an `embed_lookup` of the table by the ids and a `mul` into the weights. One product rounded once, so the pair's value bit for bit. +`attn_paged_qrow` is `attn_paged` -- the same parameters, operands and values -- with `q` read at +its own row pitch: a column slice of a wider row, the q part of a fused `[q|k|v]` projection, read +where it lies instead of lifted into a dense block by a `cast` first. It is a name of its own +because an `attn_paged` kernel may refuse a pitched `q` (libr4d's do, with `RAD_E_STRIDE`, at the +first step), and under `attn_paged` whichever library is first in `--kernels` wins the op: an +architecture handing it the slice would depend on an order it cannot see. Asked for by name, the op +resolves to a library that reads the pitch or to nothing, and the architecture lifts `q` for +`attn_paged` where it is nothing. + **libref has no row for any of them, on purpose.** An architecture asks for a join and declares the chain where it does not resolve (`rad_op_resolved`), and a reference row would resolve it everywhere -- so a model loaded without the library that serves the join would resolve it to the diff --git a/gemma4k/g4k_rows.cpp b/gemma4k/g4k_rows.cpp index 14476680..47b4e2be 100644 --- a/gemma4k/g4k_rows.cpp +++ b/gemma4k/g4k_rows.cpp @@ -96,6 +96,38 @@ static const RadOperandSpec oEscale[] = { { "w_e", RAD_OPD_WEIGHT, 0 }, { "ew", RAD_OPD_INOUT, 0 }, }; +/* attn_paged_qrow is attn_paged's schema restated field for field under a name only this library + * declares. The attention kernels below take q at any row pitch, so q can be read where a fused + * [q|k|v] projection left it; libr4d's paged attention reads q only dense and refuses the slice by + * name (RAD_E_STRIDE), which stops the engine at the first step. Under attn_paged, whichever + * library comes first in `--kernels` wins the op, so an architecture handing it the slice depends + * on an order it cannot see. Under its own name it resolves to this library or to nothing, and the + * architecture falls back to the lift and attn_paged where it is nothing. No libref row, as the + * joins, for the same reason. */ +static const RadParamSpec pAttnQrow[] = { + { "q_len", RAD_P_INT, RAD_REQUIRED, 0 }, + { "head_dim", RAD_P_INT, RAD_REQUIRED, 0 }, + { "gqa", RAD_P_INT, RAD_REQUIRED, 0 }, + { "block_size", RAD_P_INT, RAD_DERIVED, 0 }, + { "causal", RAD_P_INT, RAD_REQUIRED, 0 }, + { "window", RAD_P_INT, RAD_REQUIRED, 0 }, + { "q_dtype", RAD_P_STR, RAD_REQUIRED, 0 }, + { "kv_dtype", RAD_P_STR, RAD_REQUIRED, 0 }, + { "scale", RAD_P_F64, RAD_OPTIONAL, 0 }, + { "max_ctx", RAD_P_INT, RAD_OPTIONAL, 0 }, + { "n_head", RAD_P_INT, RAD_OPTIONAL, 0 }, + { "max_seqs", RAD_P_INT, RAD_OPTIONAL, 0 }, +}; +static const RadOperandSpec oAttnQrow[] = { + { "q", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_IN, 0 }, + { "block_table", RAD_OPD_IN, 0 }, + { "seqused", RAD_OPD_IN, 0 }, + { "k_descale", RAD_OPD_IN, 1 }, + { "v_descale", RAD_OPD_IN, 1 }, + { "cu_seqlens", RAD_OPD_IN, 1 }, + { "out", RAD_OPD_OUT, 0 }, +}; static const RadOpSchema kSchemas[] = { { "pair_argmax", ROW(pPick), ROW(oPick), "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in the first " @@ -115,6 +147,10 @@ static const RadOpSchema kSchemas[] = { "ew[t, k] = ew[t, k] * w_e[ids[t, k]] over [M, top_k], w_e an [n_expert] table, an id outside " "it reading 0; one product rounded once, so the embed_lookup + mul pair's value bit for bit. " "Gemma 4's per_expert_scale on the renormalised routing weights." }, + { "attn_paged_qrow", ROW(pAttnQrow), ROW(oAttnQrow), + "attn_paged, parameter for parameter and value for value, with q read at its own row pitch: " + "a column slice of a wider row -- the q part of a fused [q|k|v] projection -- read where it " + "lies rather than lifted into a dense block first." }, }; /* ==================================================================== operand descriptions @@ -411,10 +447,25 @@ static const RadConstraint cEscale[] = { C_GE("top_k", 1), C_LE("top_k", 64), C #define G4K_ATTN_PAIR(HD, G) \ G4K_ATTN_ROW(HD, G, bf16kv, cH##HD##x##G##B, "bf16") \ G4K_ATTN_ROW(HD, G, fp8kv, cH##HD##x##G##F, "fp8-e4m3 (per-(seq,head) descales)") +/* attn_paged_qrow: the same kernel and the same constraints. NO opd_shape -- no libref row, so no + * oracle; g4k_emu's attention cases already take q as a pitched slice of a wider row. */ +#define G4K_QROW_ROW(HD, G, KVN, C, KVDOC) \ + { "attn_paged_qrow_h" #HD "_gqa" #G "_" #KVN, "attn_paged_qrow", "attn", \ + "paged attention reading q at its own row pitch, any window, causal or not", \ + "head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \ + "bf16 query (any row pitch), " KVDOC " kv cache, bf16 out, f32 partials", \ + RAD_DOMAIN_DEVICE, 10, ROW(C), NOTUNE, \ + nullptr, nullptr, g4k_attn_h##HD##_gqa##G##_##KVN, g4k_attn_h##HD##_scratch, nullptr, \ + nullptr, nullptr, nullptr, nullptr, nullptr }, +#define G4K_QROW_PAIR(HD, G) \ + G4K_QROW_ROW(HD, G, bf16kv, cH##HD##x##G##B, "bf16") \ + G4K_QROW_ROW(HD, G, fp8kv, cH##HD##x##G##F, "fp8-e4m3 (per-(seq,head) descales)") static const RadKernelInfo kKernels[] = { G4K_ATTN_PAIR(256, 1) G4K_ATTN_PAIR(256, 2) G4K_ATTN_PAIR(256, 4) G4K_ATTN_PAIR(256, 8) G4K_ATTN_PAIR(512, 1) G4K_ATTN_PAIR(512, 2) G4K_ATTN_PAIR(512, 4) G4K_ATTN_PAIR(512, 8) + G4K_QROW_PAIR(256, 1) G4K_QROW_PAIR(256, 2) G4K_QROW_PAIR(256, 4) G4K_QROW_PAIR(256, 8) + G4K_QROW_PAIR(512, 1) G4K_QROW_PAIR(512, 2) G4K_QROW_PAIR(512, 4) G4K_QROW_PAIR(512, 8) /* Described as libref describes it, so rad-kbench runs both arms against the oracle. */ { "pair_argmax_f32", "pair_argmax", "select", @@ -472,6 +523,8 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, pick_host, nullptr, nullptr, nullptr, shape_pick, nullptr, nullptr, nullptr }, }; +#undef G4K_QROW_PAIR +#undef G4K_QROW_ROW #undef G4K_ATTN_PAIR #undef G4K_ATTN_ROW diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index ee58db94..c53ac9b8 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3444,7 +3444,9 @@ TEST(a_gemma4_moe_trunk_declares_both_arms_and_the_joins) { RadBuildCtx ctx = build_ctx(); CHECK_OK(gemma4::declare(&b, &meta, &ctx)); - CHECK_EQ(count_op(b, "attn_paged"), 6); + /* five sliding layers read q in the fused row (attn_paged_qrow), the full one attn_paged */ + CHECK_EQ(count_op(b, "attn_paged_qrow"), 5); + CHECK_EQ(count_op(b, "attn_paged"), 1); CHECK_EQ(count_op(b, "kv_store"), 6); /* One join after attention and one after the two feed-forward arms, a layer. */ CHECK_EQ(count_resolved(b, "norm_add_norm"), 6); @@ -3474,11 +3476,11 @@ TEST(gemma4_moe_kv_groups_are_both_full_and_the_window_rides_the_op) { CHECK_EQ((int)g.d.kind, RAD_KV_FULL); CHECK_EQ(g.d.window, 0); } - const RecOp* sl = find_op(b, "attn_paged", 0); + const RecOp* sl = find_op(b, "attn_paged_qrow", 0); REQUIRE(sl != nullptr); CHECK_EQ(pint(sl, "head_dim"), 256); CHECK_EQ(pint(sl, "window"), 1024); - const RecOp* fu = find_op(b, "attn_paged", 5); + const RecOp* fu = find_op(b, "attn_paged", 0); REQUIRE(fu != nullptr); CHECK_EQ(pint(fu, "head_dim"), 512); CHECK_EQ(pint(fu, "gqa"), 8); @@ -3531,8 +3533,10 @@ TEST(gemma4_falls_back_to_the_chain_where_no_join_resolves) { CHECK_EQ(count_issued(fused, "join_add_scale"), 6); CHECK_EQ(count_issued(chain, "norm_add_norm"), 0); CHECK_EQ(count_issued(chain, "join_add_scale"), 0); - CHECK_EQ(count_issued(fused, "attn_paged"), 6); - CHECK_EQ(count_issued(chain, "attn_paged"), 6); + for (const auto* v : { &fused, &chain }) { + CHECK_EQ(count_issued(*v, "attn_paged_qrow"), 5); + CHECK_EQ(count_issued(*v, "attn_paged"), 1); + } /* The chain is longer, by the norms and adds the joins fold in. */ CHECK(count_issued(chain, "rmsnorm") > count_issued(fused, "rmsnorm")); CHECK(count_issued(chain, "add") > count_issued(fused, "add")); @@ -3625,20 +3629,49 @@ TEST(gemma4_dflash_taps_are_live_from_the_layer_that_writes_them) { CHECK_EQ(taps, 3); } -/* The sliding layers' attention reads q where the fused projection left it: no copy op between - * the qkv projection and the attention, and the attention's declared reads name the fused row. */ +/* The sliding layers' attention reads q where the fused projection left it -- no copy between the + * qkv projection and the attention -- where attn_paged_qrow is served, and lifts q for attn_paged + * where it is not. */ TEST(gemma4_sliding_attention_reads_q_in_the_fused_row) { - RadBuilder b; - RadModelMeta meta = gemma4_moe_meta(); - RadBuildCtx ctx = build_ctx(); - CHECK_OK(gemma4::declare(&b, &meta, &ctx)); - const int qkv = buf_named(b, "qkv_s"); - REQUIRE(qkv > 0); - CHECK_EQ(buf_named(b, "q_s"), 0); - const RecOp* at = find_op(b, "attn_paged", 0); - REQUIRE(at != nullptr); - CHECK(std::find(at->reads.begin(), at->reads.end(), (rad_buf)qkv) != at->reads.end()); - CHECK_EQ(count_op(b, "cast"), 0); /* no drafter here, so no taps either */ + /* Served, attn_paged_qrow reads the slice and nothing is lifted; refused -- a hierarchy without + * gemma4k -- q is lifted into q_s for attn_paged, and the slice reaches no attn_paged either + * way, since that op may resolve to a library that reads q only dense. */ + for (int refuse = 0; refuse < 2; ++refuse) { + RadBuilder b; + if (refuse) b.refuse.insert("attn_paged_qrow"); + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + const int qkv = buf_named(b, "qkv_s"), qs = buf_named(b, "q_s"); + REQUIRE(qkv > 0); + CHECK_EQ(qs > 0, refuse == 1); + auto reads = [](const RecOp& o, int buf) { + return buf > 0 && std::find(o.reads.begin(), o.reads.end(), (rad_buf)buf) != o.reads.end(); + }; + int qrow = 0, paged_slice = 0, paged_lifted = 0; + for (const auto& o : b.ops) { + if (!o.resolved) continue; + if (o.op == "attn_paged_qrow" && reads(o, qkv)) ++qrow; + if (o.op == "attn_paged" && reads(o, qkv)) ++paged_slice; + if (o.op == "attn_paged" && reads(o, qs)) ++paged_lifted; + } + const int sliding = refuse ? paged_lifted : qrow; + CHECK(sliding > 0); + CHECK_EQ(refuse ? qrow : paged_lifted, 0); + CHECK_EQ(paged_slice, 0); + CHECK_EQ(count_op(b, "cast"), refuse ? sliding : 0); /* the lifts; no drafter, no taps */ + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector issued = issued_ops(b, c); + CHECK_EQ(count_issued(issued, "attn_paged_qrow"), refuse ? 0 : sliding); + CHECK_EQ(count_issued(issued, "cast"), refuse ? sliding : 0); + for (const auto& o : b.ops) + if (o.resolved) CHECK(o.uses_declared); + } } /* The feed-forward join writes the next layer's input norm: with the joins served, the only From 743b7e1a6a2dfc004d9d350ebf96721019ce0de2 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 15:25:46 -0500 Subject: [PATCH 20/24] arch/gemma4: the DFlash head reads a block-fp8 copy of the table where the container holds one The drafter's head was `gemm_nt` over the target's bf16 table -- 352 MiB a rank at tp 4, every draft pass, 566 us of a 26B-A4B decode step under --profile-ops on 4x R9700: the widest read on the draft path, and the "first thing to change once the model runs" its own comment named. A container may now hold the table a second time as `dflash.draft_head.weight`, block fp8 -- one checkpoint tensor, two logical weights, as rad_block_dflash2.h does it -- made by the recipe line dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 which the three gemma4-26b-a4b -df recipes now carry. Where the copy is there, the head is quant_act_fp8 over the gathered rows and gemm_nt_q over the copy at fp8a8: half the bytes, for 176 MiB a rank more. The copy is row-sharded exactly as the table, so a rank's rows are the same vocabulary slice and row_topk's vocab_off, the all_gather and pair_argmax are unchanged. Drafts are verified, so the coarser logits change what is proposed and never what is accepted -- draft_n_accepted says whether they propose worse; there is no rerank against the bf16 table yet. Where the copy is not there -- every container converted before this, or one whose recipe made it something other than block fp8 -- the head reads the bf16 table exactly as before. The decision is the stored encoding's (weight_enc on the copy's name), and the copy's name map entry alone writes nothing: rad-convert walks the declared weights. The startup note names the head in use. The block-fp8 test moves to one helper, which the routed experts' encoding check now uses too. arch_test: with the copy's encoding block fp8, the copy is declared and the head is gemm_nt_q over it from the quantised rows; without, nothing is declared and the head is gemm_nt over the table; a draft pass issues the head once either way. ARCHITECTURES.md says so. Not yet run on the cards; it needs a container converted with the new recipe line. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 17 ++-- arch/gemma4/gemma4_dflash.h | 87 +++++++++++++++++--- data/recipes/gemma4-26b-a4b-df-bf16x.recipe | 6 ++ data/recipes/gemma4-26b-a4b-df-pad768.recipe | 6 ++ data/recipes/gemma4-26b-a4b-df.recipe | 6 ++ docs/ARCHITECTURES.md | 9 ++ tests/arch_test.cpp | 46 +++++++++++ 7 files changed, 157 insertions(+), 20 deletions(-) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index f258f44c..dcd735ba 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -293,6 +293,7 @@ struct Model { Dflash1::Wire dfw{}; rad_kvgroup kv_draft = 0; bool have_df = false; + const char* tok_src = nullptr; /* the checkpoint's table, which the fp8 draft head copies */ std::vector layers; }; @@ -515,7 +516,8 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil * pitch of `steps` -- and the engine reads it by the declaration below. */ dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {sr, 1}); - RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw)); + RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw, + m.tok_src)); m.have_df = true; RadDrafterDecl drf{}; @@ -539,11 +541,14 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld " "sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the " "trunk at %d tap(s). ONE forward over %lld rows proposes %lld tokens; the head is " - "the target's tied bf16 table, argmax %s", + "%s, argmax %s", (long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, nfull, (long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, m.n_taps, (long long)dc.block, (long long)dc.steps(), + m.df.fp8_head + ? "the container's block-fp8 copy of the target's table (dflash.draft_head)" + : "the target's tied bf16 table", Dflash1::head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary"); return RAD_OK; } @@ -561,10 +566,7 @@ static int expert_format(RadBuilder* b, const char* wn, int* fmt) { *fmt = EXP_BF16; if (!weight_enc(b, wn, &e)) return RAD_OK; if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return RAD_OK; - const RadEncPlane* sc = rad_enc_plane(&e, "scale"); - if (rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] && - e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 && - sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK) { + if (block_fp8_128(e)) { *fmt = EXP_FP8; return RAD_OK; } @@ -916,7 +918,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ---- the vocabulary edges: ONE table, row-sharded with the vocabulary, read as the embedding * by `embed_lookup` and as the head by `logits_gemm` -- Gemma ties them, so storing the head * a second time would be 1.4 GiB for nothing. */ - RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", L))); + m.tok_src = nm.ckpt("%s.embed_tokens.weight", L); + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), m.tok_src)); RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", L))); m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); diff --git a/arch/gemma4/gemma4_dflash.h b/arch/gemma4/gemma4_dflash.h index cc29dad8..348c1bdd 100644 --- a/arch/gemma4/gemma4_dflash.h +++ b/arch/gemma4/gemma4_dflash.h @@ -49,9 +49,19 @@ * `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR). * * Reading the bf16 head every draft pass is the expensive way to do it -- 262144 x 2816 x 2 bytes - * over the ranks. The cheaper way is the 2-bit copy plus an exact rerank that DFlash2 uses, and - * that needs the trunk's head in fp8 or int8, which a tied Gemma head is not. Stated rather than - * hidden: it is the first thing to change once the model runs. + * over the ranks, 566 us of a 26B-A4B decode step at tp 4 (--profile-ops, 4x R9700), the widest + * read on the draft path. So where the CONTAINER holds a block-fp8 copy of the table under a name + * of its own -- `dflash.draft_head.weight`, one checkpoint tensor and two logical weights, as + * rad_block_dflash2.h does it, made by a recipe line + * + * dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + * + * -- the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, and the argmax is taken over + * its coarser logits. Every draft is still verified, so the copy can change what is proposed and + * never what is accepted; draft_n_accepted is what says whether it proposes worse. A container + * without it, or with it in any other encoding, reads the bf16 table as before. The copy costs + * half the table's bytes again, 176 MiB a rank at tp 4. No rerank against the bf16 table yet: + * DFlash2's needs the target's head in fp8 or int8, which a tied Gemma head is not. * * ============================== THE LINEARS ARE FP8 ============================== * @@ -72,6 +82,15 @@ namespace gemma4 { using namespace rad::arch; +/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale a 128x128 block, no + * transform -- a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`. */ +inline bool block_fp8_128(const RadEncoding& e) { + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] && + e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 && + sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK; +} + struct Dflash1 { enum { MAX_LAYERS = 8 }; @@ -97,6 +116,7 @@ struct Dflash1 { rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */ /* the head, one row a draft position */ rad_buf sel_h = 0; /* [srows, n_embd] */ + rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */ rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */ rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */ rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */ @@ -114,6 +134,8 @@ struct Dflash1 { DenseFP8 w_fc{}; rad_weight w_hnorm = 0, w_norm = 0; rad_weight w_tok = 0; /* the TARGET's table: embedding AND head */ + DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */ + bool fp8_head = false; rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{}; rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}; @@ -129,7 +151,7 @@ struct Dflash1 { rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0; rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; - rad_op op_gather = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0; + rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0; /* CANDIDATES A RANK CONTRIBUTES under a sharded head. The draft needs one, but the gather moves * whole 16-byte words a row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is refused at @@ -140,7 +162,8 @@ struct Dflash1 { static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); } int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, - rad_kvgroup group, rad_weight tok_embd, const char* ck, const Wire& wire); + rad_kvgroup group, rad_weight tok_embd, const char* ck, const Wire& wire, + const char* tok_src); void context(RadCtx* c, const RadBatch* batch) const; void step(RadCtx* c, const RadBatch* batch) const; @@ -168,9 +191,9 @@ private: inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, rad_kvgroup group, rad_weight tok_embd, - const char* ck, const Wire& wire) { + const char* ck, const Wire& wire, const char* tok_src) { g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd; - if (!ck || !w_tok) return RAD_E_INVAL; + if (!ck || !w_tok || !tok_src) return RAD_E_INVAL; if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) { fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most " "%d\n", (long long)g.n_layer, MAX_LAYERS); @@ -443,11 +466,43 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), {w.h}, {w.sel_h}); - op_head = rw(b, RAD_OP(b, "gemm_nt", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), - RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_tok)), - {w.sel_h}, {w.dlog}); + /* THE FP8 COPY, where the container holds one (see the top of this file). The name map comes + * first -- it is how the encoding is looked up -- and a map whose weight is never declared is + * written by nothing: rad-convert walks the declared weights. The copy is row-sharded exactly + * as the table is, so this rank's rows are the same vocabulary slice and `vocab_off` holds. */ + const char* dhn = nm.f("dflash.draft_head.weight"); + RAD_ARCH_TRY(map_copy(b, dhn, tok_src)); + RadEncoding he{}; + fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he); + if (fp8_head) { + if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which " + "is not whole %d-row scale blocks\n", + (long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE; + w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd }, + RAD_ACCESS_PER_TOKEN, shard, grp_model()); + w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16, + { fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN, + shard, grp_model()); + if (!w_dh.w || !w_dh.s) return RAD_E_INVAL; + w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd}); + w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)}); + op_qsel = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.sel_h}, {w.selq, w.sels}); + op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog}); + } else { + op_head = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_tok)), + {w.sel_h}, {w.dlog}); + } if (sharded) { op_topk = rw(b, RAD_OP(b, "row_topk", RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), @@ -575,7 +630,13 @@ inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { const int64_t S = batch->n_out; if (S <= 0) return; RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S)); - RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S)); + if (fp8_head) { + RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S)); + RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w), + RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref()); + } else { + RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S)); + } if (sharded) { RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S), brows(w.dpair, S)); diff --git a/data/recipes/gemma4-26b-a4b-df-bf16x.recipe b/data/recipes/gemma4-26b-a4b-df-bf16x.recipe index 204ae3bb..90cd1f37 100644 --- a/data/recipes/gemma4-26b-a4b-df-bf16x.recipe +++ b/data/recipes/gemma4-26b-a4b-df-bf16x.recipe @@ -15,3 +15,9 @@ dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The drafter's head: the target's tied table again under a name of its own, block fp8, which the +# draft head reads instead of the bf16 table -- half the widest read on the draft path, for half +# the table's bytes again (176 MiB a rank at tp 4). Drafts are verified, so this changes what is +# proposed, never what is accepted. +dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/gemma4-26b-a4b-df-pad768.recipe b/data/recipes/gemma4-26b-a4b-df-pad768.recipe index f88c1dee..46749c3b 100644 --- a/data/recipes/gemma4-26b-a4b-df-pad768.recipe +++ b/data/recipes/gemma4-26b-a4b-df-pad768.recipe @@ -23,3 +23,9 @@ dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The drafter's head: the target's tied table again under a name of its own, block fp8, which the +# draft head reads instead of the bf16 table -- half the widest read on the draft path, for half +# the table's bytes again (176 MiB a rank at tp 4). Drafts are verified, so this changes what is +# proposed, never what is accepted. +dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/gemma4-26b-a4b-df.recipe b/data/recipes/gemma4-26b-a4b-df.recipe index 35bd4a3f..b296b701 100644 --- a/data/recipes/gemma4-26b-a4b-df.recipe +++ b/data/recipes/gemma4-26b-a4b-df.recipe @@ -25,3 +25,9 @@ dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The drafter's head: the target's tied table again under a name of its own, block fp8, which the +# draft head reads instead of the bf16 table -- half the widest read on the draft path, for half +# the table's bytes again (176 MiB a rank at tp 4). Drafts are verified, so this changes what is +# proposed, never what is accepted. +dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 360b9131..423f8fca 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -511,6 +511,15 @@ The drafter's head is vocab-sharded with the trunk's: each rank's top-2 are all- `pair_argmax` picks the winner (two a rank, because a row-interleaved `all_gather` moves 16-byte words and one pair is 8 bytes). +**The draft head in fp8.** The drafter's head is the widest read on the draft path: the target's +bf16 table, 352 MiB a rank at tp 4, every draft pass. A container converted with the line +`dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16` (the three `-df` recipes +carry it) stores a block-fp8 copy of the table under that name, and the head reads the copy at +fp8a8 instead -- half the bytes, for 176 MiB a rank more. Drafts are verified, so the coarser +logits can change what is proposed and never what is accepted; `draft_n_accepted` says whether +they propose worse. A container without the copy reads the bf16 table as before, and the startup +note names which head is in use. + **FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up `[1408, 2816]` is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not — the fp8 grouped GEMM reads K in diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index c53ac9b8..43c641ef 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3759,3 +3759,49 @@ TEST(gemma4_scales_the_routing_weights_in_one_launch) { if (o.resolved) CHECK(o.uses_declared); } } + +/* The drafter's head reads the container's block-fp8 copy of the target's table where it holds one + * -- `dflash.draft_head.weight` -- through quant_act_fp8 and gemm_nt_q, and the bf16 table through + * gemm_nt where it does not. The copy is declared only in the first case, so a container converted + * without the recipe line is served exactly as before. */ +TEST(gemma4_dflash_head_reads_the_fp8_copy_where_the_container_holds_one) { + const std::vector keys = g4df_keys(), vals = g4df_vals(); + for (int fp8 = 0; fp8 < 2; ++fp8) { + RadModelMeta meta = gemma4_moe_meta(); + meta.n_kv = (int)keys.size(); + meta.kv_key = keys.data(); + meta.kv_val = vals.data(); + RadBuilder b; + if (fp8) + b.encs = { { "dflash.draft_head", rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128) } }; + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + CHECK_EQ(find_w(b, "dflash.draft_head.weight") != nullptr, fp8 == 1); + + const int dlog = buf_named(b, "df_dlog"), selh = buf_named(b, "df_selh"); + REQUIRE(dlog > 0 && selh > 0); + const RecOp* head = nullptr; + for (const auto& o : b.ops) + if (o.resolved && + std::find(o.writes.begin(), o.writes.end(), (rad_buf)dlog) != o.writes.end()) + head = &o; + REQUIRE(head != nullptr); + CHECK_EQ(head->op, std::string(fp8 ? "gemm_nt_q" : "gemm_nt")); + const bool reads_selh = + std::find(head->reads.begin(), head->reads.end(), (rad_buf)selh) != head->reads.end(); + CHECK_EQ(reads_selh, fp8 == 0); + + /* and a draft pass issues it */ + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + batch.draft_pass = 1; + c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + int head_issues = 0; + for (const auto& i : c.issues) + if (b.op_of(i.op) == head) ++head_issues; + CHECK_EQ(head_issues, 1); + } +} From 34ee08ea5ebd9eadd63c1756745e5e636833afa5 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Mon, 12 Oct 2026 09:55:53 -0500 Subject: [PATCH 21/24] arch/gemma4: a prefill chunk in two slices, the all-reduces on the second lane beside the compute On gemma-4-26B-A4B at tp 4 on 4x R9700 the all-reduces were 47% of a 20K-token prefill under --profile-ops (957 of 2020 ms): a layer reduces T x E after attention and both arms' 2T x E after the feed-forward, at ~16.5 GB/s a rank on the link, against ~8 ms of compute a layer at the average chunk. Run whole, the two take turns. A chunk of two routed passes or more (4096 tokens) now runs as two slices, and every trunk all-reduce rides the runtime's second lane (rad_lane) beside the other slice's compute: slice A's attention reduction under slice B's output projection, slice B's under slice A's two arms, slice A's feed-forward reduction under slice B's arms, and slice B's under the next layer's join and projections of slice A. Attention runs whole -- it reads every row's keys. A model of the measured times puts it at up to a quarter off an unprofiled prefill; --profile-ops syncs every op and cannot show it. The same bits as the whole step: the cut is a whole number of routed passes, so the routed arm makes the passes the whole step makes, and both slices are at least one pass, above every row band the sliced kernels have (the GEMM's 16 and 64, the reduction's one-shot edge) -- core's rule four for the second lane. The slice's partials sit dense-then-routed in its own run of the join buffer, so each slice's feed-forward reduction is one message. The order: a reduction is issued on lane 1 behind a join from lane 0, its producer; lane 0 joins lane 1 back before the consumer and before the next reduction is issued, since a join orders behind everything its lane has issued. The embedding's reduction stays on lane 0, ahead of everything lane 1 is first joined behind, so the collectives keep one order on every rank. The two buffers reduced in place are named to rad_buf_concurrent. Taken where the joins are fused, the wire is exact and there is more than one rank; RADIANCE_GEMMA4_OVERLAP=0 runs every chunk whole, and the startup note says which. A decode step never takes the lane. routed() takes a run of rows and the join row its partial lands at; attention between the projections and the output projection moves into attend(), which both paths issue. arch_test records the lane of each issue and where each join sits, and a new test holds a 6-layer 26B-A4B with the DFlash taps, at tp 4: no two issues on different lanes that touch a common element go unordered (taking every operand as read and written; dropping one wait makes it count six), lane 1 carries the trunk's 4 x 6 reductions at the slices' sizes and nothing else, the slices issue the whole step's rows by op and its routed passes, a 4095-token chunk and a decode step stay on one lane. GUIDE.md has the switch, ARCHITECTURES.md the paragraph. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 299 +++++++++++++++++++++++++++++++++-------- docs/ARCHITECTURES.md | 16 ++- docs/GUIDE.md | 1 + tests/arch_test.cpp | 209 +++++++++++++++++++++++++++- 4 files changed, 466 insertions(+), 59 deletions(-) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index dcd735ba..3831efd9 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -266,6 +266,9 @@ struct Model { bool moe = false; int64_t n_expert = 0, n_local = 0, expert_base = 0, top_k = 0, n_ffe = 0; int64_t moe_rows = 0; /* tokens a routed pass */ + /* A prefill chunk of 2 * moe_rows tokens or more runs as two slices, the trunk's all-reduces + * on the second lane beside the other slice's compute (trunk_overlap). Set at declare. */ + bool overlap = false; double escale = 1.0, softcap = 0.0; rad_buf b_x = 0, b_h = 0, b_o = 0; @@ -1440,6 +1443,25 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c {m.b_x}, {m.b_dfsrc}); } + /* ---- THE PREFILL OVERLAP (trunk_overlap): where there is a reduction to hide, a routed arm + * whose passes a slice can be a whole number of, and every join fused -- the slices issue the + * fused forms only. On the exact wire alone: nothing here shows the lossy one gives a slice + * the bits it gives the whole. RADIANCE_GEMMA4_OVERLAP=0 runs every chunk whole, the A/B + * switch. The two buffers the second lane reduces in place are taken out of the arena's + * sharing, which the runtime asks of every buffer a second lane touches (rad_buf_concurrent); + * both live across the whole trunk already, so what that costs is only the sharing with the + * drafter's and the head's buffers. */ + const char* ov_env = std::getenv("RADIANCE_GEMMA4_OVERLAP"); + const bool ov_off = ov_env && ov_env[0] == '0'; + m.overlap = W > 1 && m.moe && g.wire_exact && T >= 2 * m.moe_rows && !ov_off; + for (const Layer& y : m.layers) + m.overlap = m.overlap && y.op_join_a && y.op_join_f && y.next_norm && y.op_ar_o && + y.op_ar_f; + if (m.overlap) { + RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o)); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2)); + } + if (m.layers.empty() || !m.layers.back().next_norm) m.op_onorm = rmsnorm(T, E, m.w_onorm, 1.0, m.b_x, m.b_h); m.op_gather = rw(b, RAD_OP(b, "gather_rows", @@ -1504,6 +1526,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c (long long)m.n_local, (long long)m.expert_base, (long long)m.n_expert, (long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_fp8), m.n_gu_fp8, (long long)m.n_layer, how(m.n_dn_fp8), m.n_dn_fp8, (long long)m.moe_rows); + if (W > 1) + rad_note(b, "prefill overlap: %s", m.overlap + ? "a chunk of two routed passes or more runs as two slices, each slice's " + "all-reduces on a second stream beside the other's compute" + : ov_off ? "off (RADIANCE_GEMMA4_OVERLAP=0)" + : !g.wire_exact ? "off (the lossy all-reduce wire)" + : T < 2 * m.moe_rows ? "off (a step holds fewer than two routed passes)" + : "off (the sandwich joins are not fused)"); } if (m.kf.rot_pairs < m.kf.hd / 2) rad_note(b, "full layers: PROPORTIONAL rope -- %lld of %lld frequency pairs rotate at " @@ -1515,10 +1545,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ============================================================== step */ -static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T) { +/* The routed arm over rows [first, first + rows) of a T-token step, in passes of m.moe_rows, its + * partial into rows [dst, dst + rows) of the join: [T, 2T) for a whole step, and right after the + * slice's dense rows for a slice of one (trunk_overlap). */ +static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t first, + int64_t rows, int64_t dst) { const int64_t E = m.E, K = m.top_k, NL = m.n_local, NE = m.n_expert; - for (int64_t r0 = 0; r0 < T; r0 += m.moe_rows) { - const int64_t n = (T - r0 < m.moe_rows) ? (T - r0) : m.moe_rows; + const int64_t end = first + rows; + for (int64_t r0 = first; r0 < end; r0 += m.moe_rows) { + const int64_t n = (end - r0 < m.moe_rows) ? (end - r0) : m.moe_rows; int32_t* const counts = rad_route_counts(c, (int)(&y - m.layers.data()), NL); const RadOperand ecnt = counts ? praw(counts, RAD_I32, NL) : brows(m.b_ecnt, NL); RAD_ISSUE_N(c, y.op_rnorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_rscale), @@ -1592,10 +1627,10 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T) { RAD_ISSUE_N(c, y.op_edn, n, brows(m.b_eact, n * K), RAD_WTAB(y.w_edn[0], NL), brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), brows(m.b_edn, n * K)); } - /* The routed partial into rows [T + r0, T + r0 + n) of the join. */ + /* The routed partial into its rows of the join. */ RAD_ISSUE_N(c, y.op_gather, n, brows(m.b_edn, n * K), brow_slice(m.b_ew, r0, n, K), brows(m.b_sorted, n * K), RAD_NONE, RAD_NONE, - brow_slice(m.b_ff2, T + r0, n, E)); + brow_slice(m.b_ff2, dst + (r0 - first), n, E)); if (r0 + n >= T) { RadRouting rt{}; rt.expert_ids = ids; @@ -1610,68 +1645,56 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T) { } } -static void step(RadCtx* c, const RadBatch* batch) { - const Model& m = g_model[rad_rank(c)]; - if (batch->draft_pass != 0) { - if (!m.have_df) { - rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " - "container carries no DFlash `draft.` block, or declare ran at " - "max_spec 0"); - return; - } - if (batch->draft_pass > 0) m.df.step(c, batch); - else m.df.context(c, batch); - return; - } - if (batch->enc) { - rad_step_fail(c, "gemma4 declares no encoder; serve this container with --mm-max-patches 0"); - return; - } - const int64_t T = batch->n_tok, E = m.E; - if (T <= 0) return; +/* A layer's attention between its projections and its output projection, over the whole step: + * the norms and the rotaries, the cache write, the attention. */ +static void attend(RadCtx* c, const Model& m, const Layer& y, size_t li, const RadBatch* batch) { + const int64_t T = batch->n_tok; const RadOperand pos = praw(batch->positions, RAD_I32, T); const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + const Kind& k = y.full ? m.kf : m.ks; + const RadKVGroupBatch* kvb = kv_batch(batch, k.kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + const RadOperand bt = praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0); + const RadOperand su = praw(used, RAD_I32, batch->n_seq); - RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); - if (m.op_embed_ar) - RAD_ISSUE_N(c, m.op_embed_ar, T * E, brows(m.b_x, T), RAD_NONE); + if (!y.full) { + const int64_t qd = k.q(), kvd = k.kv_dim(); + RAD_ISSUE(c, y.op_qknr, brows(m.b_qkv, T), pos, RAD_W(y.w_qn), RAD_W(y.w_kn)); + RAD_ISSUE(c, y.op_store, bcol(m.b_qkv, qd, kvd, T), bcol(m.b_qkv, qd + kvd, kvd, T), + praw(slot, RAD_I32, T), kv_cache(k.kv, (int)li)); + if (y.op_lift) RAD_ISSUE(c, y.op_lift, bcol(m.b_qkv, 0, qd, T), brows(m.b_qs, T)); + RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, + y.op_lift ? brows(m.b_qs, T) : bcol(m.b_qkv, 0, qd, T), + kv_cache(k.kv, (int)li), bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_atts, T)); + } else { + RAD_ISSUE_N(c, y.op_vnorm, T * k.nkv, brows(m.b_kf, T), RAD_NONE, brows(m.b_vf, T)); + RAD_ISSUE_N(c, y.op_qn, T * k.nh, brows(m.b_qf, T), RAD_W(y.w_qn), brows(m.b_qf, T)); + RAD_ISSUE_N(c, y.op_kn, T * k.nkv, brows(m.b_kf, T), RAD_W(y.w_kn), brows(m.b_kf, T)); + RAD_ISSUE(c, y.op_qrope, brows(m.b_qf, T), pos); + RAD_ISSUE(c, y.op_krope, brows(m.b_kf, T), pos); + RAD_ISSUE(c, y.op_store, brows(m.b_kf, T), brows(m.b_vf, T), praw(slot, RAD_I32, T), + kv_cache(k.kv, (int)li)); + RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, brows(m.b_qf, T), kv_cache(k.kv, (int)li), + bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_attf, T)); + } +} +/* The trunk over the whole step. */ +static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) { + const int64_t T = batch->n_tok, E = m.E; for (size_t li = 0; li < m.layers.size(); ++li) { const Layer& y = m.layers[li]; - const Kind& k = y.full ? m.kf : m.ks; - const RadKVGroupBatch* kvb = kv_batch(batch, k.kv); - const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; - const int32_t* table = kvb ? kvb->block_table : nullptr; - const int32_t* used = kvb ? kvb->seqused : nullptr; - const RadOperand bt = praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0); - const RadOperand su = praw(used, RAD_I32, batch->n_seq); - if (y.op_anorm) RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); if (!y.full) { - const int64_t qd = k.q(), kvd = k.kv_dim(); RAD_ISSUE(c, y.op_qkv, brows(m.b_h, T), RAD_W(y.w_qkv), brows(m.b_qkv, T)); - RAD_ISSUE(c, y.op_qknr, brows(m.b_qkv, T), pos, RAD_W(y.w_qn), RAD_W(y.w_kn)); - RAD_ISSUE(c, y.op_store, bcol(m.b_qkv, qd, kvd, T), bcol(m.b_qkv, qd + kvd, kvd, T), - praw(slot, RAD_I32, T), kv_cache(k.kv, (int)li)); - if (y.op_lift) RAD_ISSUE(c, y.op_lift, bcol(m.b_qkv, 0, qd, T), brows(m.b_qs, T)); - RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, - y.op_lift ? brows(m.b_qs, T) : bcol(m.b_qkv, 0, qd, T), - kv_cache(k.kv, (int)li), bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_atts, T)); - RAD_ISSUE(c, y.op_o, brows(m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T)); } else { RAD_ISSUE(c, y.op_q, brows(m.b_h, T), RAD_W(y.w_q), brows(m.b_qf, T)); RAD_ISSUE(c, y.op_k, brows(m.b_h, T), RAD_W(y.w_k), brows(m.b_kf, T)); - RAD_ISSUE_N(c, y.op_vnorm, T * k.nkv, brows(m.b_kf, T), RAD_NONE, brows(m.b_vf, T)); - RAD_ISSUE_N(c, y.op_qn, T * k.nh, brows(m.b_qf, T), RAD_W(y.w_qn), brows(m.b_qf, T)); - RAD_ISSUE_N(c, y.op_kn, T * k.nkv, brows(m.b_kf, T), RAD_W(y.w_kn), brows(m.b_kf, T)); - RAD_ISSUE(c, y.op_qrope, brows(m.b_qf, T), pos); - RAD_ISSUE(c, y.op_krope, brows(m.b_kf, T), pos); - RAD_ISSUE(c, y.op_store, brows(m.b_kf, T), brows(m.b_vf, T), praw(slot, RAD_I32, T), - kv_cache(k.kv, (int)li)); - RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, brows(m.b_qf, T), kv_cache(k.kv, (int)li), - bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_attf, T)); - RAD_ISSUE(c, y.op_o, brows(m.b_attf, T), RAD_W(y.w_o), brows(m.b_o, T)); } + attend(c, m, y, li, batch); + RAD_ISSUE(c, y.op_o, brows(y.full ? m.b_attf : m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T)); if (y.op_ar_o) RAD_ISSUE_N(c, y.op_ar_o, T * E, brows(m.b_o, T), RAD_NONE); if (y.op_join_a) { RAD_ISSUE(c, y.op_join_a, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T), @@ -1688,7 +1711,7 @@ static void step(RadCtx* c, const RadBatch* batch) { brows(m.b_act, T)); RAD_ISSUE(c, y.op_dn, brows(m.b_act, T), RAD_W(y.w_dn), brows(m.b_ff2, T)); if (m.moe) { - routed(c, m, y, T); + routed(c, m, y, T, 0, T, T); if (y.op_ar_f) RAD_ISSUE_N(c, y.op_ar_f, 2 * T * E, brows(m.b_ff2, 2 * T), RAD_NONE); if (y.op_join_f) { RAD_ISSUE(c, y.op_join_f, brows(m.b_ff2, T), RAD_W(y.w_fpost1), @@ -1718,6 +1741,172 @@ static void step(RadCtx* c, const RadBatch* batch) { bcol(m.b_dfsrc, (int64_t)t * E, E, T)); } } +} + +/* ============================================================== the prefill overlap */ +/* A PREFILL CHUNK IN TWO SLICES, each slice's all-reduces on the second lane (rad_lane) beside the + * other slice's compute. On gemma-4-26B-A4B at tp 4 on 4x R9700 the reductions were 47% of a + * 20K-token prefill under --profile-ops: a layer reduces T x E after attention and both arms' 2T x + * E after the feed-forward, at ~16.5 GB/s a rank on the link, against ~8 ms of compute a layer at + * the average chunk. Run whole, the two take turns. Cut in two, a slice's reduction runs while the + * other slice computes: + * + * lane 0 o(A) o(B) . nan(A) ff(A) . nan(B) ff(B) . jas(A) qkv(A) . jas(B) qkv(B) attn o(A) .. + * lane 1 ar_o(A) ar_o(B) ar_f(A) ar_f(B) + * + * ATTENTION RUNS WHOLE: it reads every row's keys, and its batch bounds describe the whole step. + * The rest is a row at a time -- the projections, the joins, both arms -- and so is the reduction, + * which folds a word in fp32 in ascending rank order whichever message carries it. + * + * THE SAME KERNELS, SO THE SAME BITS (core/runtime/ctx.h, the second lane's rule FOUR). A cut is + * a whole number of routed passes from the step's first row, so the routed arm makes exactly the + * passes the whole step makes, and both slices are at least one pass (2048 rows): above every row + * band the projections, the joins, the activation and the reduction have -- the GEMM's at 16 and + * 64, the reduction's one-shot edge at 524288 elements. None of those kernels' row results + * depends on the row count, so the step's output is the whole step's. + * + * THE ORDER. Every reduction rides lane 1 behind a join from lane 0, which holds its producer; + * lane 0 waits for lane 1 before the reduction's consumer. A join orders behind EVERYTHING its + * lane has issued, so each wait goes in after the lane-0 work that does not need it and before + * the next reduction is issued -- which is what fixes the issue order below. The embedding's + * reduction stays on lane 0, ahead of everything lane 1 is first joined behind, so the + * collectives keep one order on every rank; the runtime joins lane 1 back at the end of a step. */ + +/* The first row of slice B, or 0 for a step that runs whole: the whole number of routed passes + * nearest half the step. Both slices are then at least one pass. */ +static int64_t split_at(const Model& m, int64_t T) { + if (!m.overlap || T < 2 * m.moe_rows) return 0; + const int64_t P = m.moe_rows; + return P * ((T + P) / (2 * P)); +} + +/* Rows [r0, r0 + n) of a layer's projections: q|k|v on a sliding layer, q and k on a full one. */ +static void project(RadCtx* c, const Model& m, const Layer& y, int64_t r0, int64_t n) { + const RadOperand h = brow_slice(m.b_h, r0, n, m.E); + if (!y.full) { + RAD_ISSUE_N(c, y.op_qkv, n, h, RAD_W(y.w_qkv), + brow_slice(m.b_qkv, r0, n, m.ks.q() + 2 * m.ks.kv_dim())); + } else { + RAD_ISSUE_N(c, y.op_q, n, h, RAD_W(y.w_q), brow_slice(m.b_qf, r0, n, m.kf.q())); + RAD_ISSUE_N(c, y.op_k, n, h, RAD_W(y.w_k), brow_slice(m.b_kf, r0, n, m.kf.kv_dim())); + } +} + +/* Rows [r0, r0 + n) of the output projection. */ +static void out_proj(RadCtx* c, const Model& m, const Layer& y, int64_t r0, int64_t n) { + const int64_t q = y.full ? m.kf.q() : m.ks.q(); + RAD_ISSUE_N(c, y.op_o, n, brow_slice(y.full ? m.b_attf : m.b_atts, r0, n, q), RAD_W(y.w_o), + brow_slice(m.b_o, r0, n, m.E)); +} + +/* Rows [r0, r0 + n) from the attention join to the arms' partials, once those rows' attention + * reduction is in. The slice's partials land in rows [2 r0, 2 r0 + 2n) of the join, dense then + * routed, so its feed-forward reduction is one run. */ +static void arms(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t r0, int64_t n) { + const int64_t E = m.E, F = m.n_ff; + RAD_ISSUE_N(c, y.op_join_a, n, brow_slice(m.b_o, r0, n, E), RAD_W(y.w_apost), + brow_slice(m.b_x, r0, n, E), RAD_W(y.w_fnorm), brow_slice(m.b_h, r0, n, E)); + RAD_ISSUE_N(c, y.op_gu, n, brow_slice(m.b_h, r0, n, E), RAD_W(y.w_gu), + brow_slice(m.b_gu, r0, n, 2 * F)); + RAD_ISSUE_N(c, y.op_act, n, bcol_at(m.b_gu, r0, 2 * F, 0, F, n), + bcol_at(m.b_gu, r0, 2 * F, F, F, n), brow_slice(m.b_act, r0, n, F)); + RAD_ISSUE_N(c, y.op_dn, n, brow_slice(m.b_act, r0, n, F), RAD_W(y.w_dn), + brow_slice(m.b_ff2, 2 * r0, n, E)); + routed(c, m, y, T, r0, n, 2 * r0 + n); +} + +/* Rows [r0, r0 + n) of layer li's feed-forward join, once their reduction is in -- with the next + * norm it writes -- and the drafter's taps of those rows. */ +static void join_ff(RadCtx* c, const Model& m, size_t li, int64_t r0, int64_t n) { + const Layer& y = m.layers[li]; + const int64_t E = m.E; + RAD_ISSUE_N(c, y.op_join_f, n, brow_slice(m.b_ff2, 2 * r0, n, E), RAD_W(y.w_fpost1), + brow_slice(m.b_ff2, 2 * r0 + n, n, E), RAD_W(y.w_fpost2), RAD_W(y.w_fpost), + brow_slice(m.b_x, r0, n, E), RAD_W(y.w_scalar), RAD_W(y.w_next), + brow_slice(m.b_h, r0, n, E)); + for (int t = 0; t < m.n_taps && y.op_tap; ++t) { + if (m.tap_layer[t] != (int)li) continue; + RAD_ISSUE_N(c, y.op_tap, n, brow_slice(m.b_x, r0, n, E), + bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * E, (int64_t)t * E, E, n)); + } +} + +static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int64_t cut) { + const int64_t T = batch->n_tok, E = m.E; + const int64_t a0 = 0, an = cut, b0 = cut, bn = T - cut; + bool lanes_ok = true; + /* An all-reduce in place over `rows` rows of `buf` from `row`, on lane 1 behind everything + * lane 0 has issued -- its producer among it. */ + auto reduce = [&](rad_op op, rad_buf buf, int64_t row, int64_t rows) { + lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK; + RAD_ISSUE_N(c, op, rows * E, brow_slice(buf, row, rows, E), RAD_NONE); + lanes_ok = rad_lane(c, 0) == RAD_OK && lanes_ok; + }; + /* Lane 0 behind every reduction issued so far. */ + auto join_back = [&] { lanes_ok = rad_lane_join(c, 1, 0) == RAD_OK && lanes_ok; }; + + const size_t L = m.layers.size(); + for (size_t li = 0; li < L; ++li) { + const Layer& y = m.layers[li]; + if (li == 0) { + RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); + project(c, m, y, a0, an); + project(c, m, y, b0, bn); + } else { + join_ff(c, m, li - 1, a0, an); /* its reduction was waited for last layer */ + project(c, m, y, a0, an); + join_back(); /* the last layer's feed-forward, slice B */ + join_ff(c, m, li - 1, b0, bn); + project(c, m, y, b0, bn); + } + attend(c, m, y, li, batch); + out_proj(c, m, y, a0, an); + reduce(y.op_ar_o, m.b_o, a0, an); + out_proj(c, m, y, b0, bn); + join_back(); /* attention, slice A */ + reduce(y.op_ar_o, m.b_o, b0, bn); + arms(c, m, y, T, a0, an); + join_back(); /* attention, slice B */ + reduce(y.op_ar_f, m.b_ff2, 2 * a0, 2 * an); + arms(c, m, y, T, b0, bn); + join_back(); /* the feed-forward, slice A */ + reduce(y.op_ar_f, m.b_ff2, 2 * b0, 2 * bn); + } + join_ff(c, m, L - 1, a0, an); + join_back(); /* the last feed-forward, slice B */ + join_ff(c, m, L - 1, b0, bn); + if (!lanes_ok) + rad_step_fail(c, "gemma4: the prefill overlap could not order its second lane against " + "the first (RADIANCE_GEMMA4_OVERLAP=0 runs every chunk on one)"); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (batch->draft_pass != 0) { + if (!m.have_df) { + rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " + "container carries no DFlash `draft.` block, or declare ran at " + "max_spec 0"); + return; + } + if (batch->draft_pass > 0) m.df.step(c, batch); + else m.df.context(c, batch); + return; + } + if (batch->enc) { + rad_step_fail(c, "gemma4 declares no encoder; serve this container with --mm-max-patches 0"); + return; + } + const int64_t T = batch->n_tok, E = m.E; + if (T <= 0) return; + + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); + if (m.op_embed_ar) + RAD_ISSUE_N(c, m.op_embed_ar, T * E, brows(m.b_x, T), RAD_NONE); + + const int64_t cut = split_at(m, T); + if (cut > 0) trunk_overlap(c, m, batch, cut); + else trunk(c, m, batch); if (m.op_onorm) RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T)); if (batch->n_out > 0) { diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 423f8fca..30338aed 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -492,8 +492,8 @@ The readings that stay plausible when wrong: pre_feedforward_layernorm_2's output. `per_expert_scale` multiplies the weight AFTER the renormalised top-k. - **The arms' two post-norms are per arm**, so under tensor parallel each arm's partial sum is - reduced before its norm. The partials share one [2T, hidden] buffer, dense rows first, so one - all-reduce carries both. + reduced before its norm. The partials share one [2T, hidden] buffer, dense rows first -- each + slice's own run of it when a prefill chunk is cut in two -- so one all-reduce carries both. - **The embedding scale is sqrt(hidden) rounded to bf16**: 53.0, not 53.066. The drafter reads the same scaled embedding. - **The sliding layers' KV group is `RAD_KV_FULL`**, with the window on the attention op. A @@ -511,6 +511,18 @@ The drafter's head is vocab-sharded with the trunk's: each rank's top-2 are all- `pair_argmax` picks the winner (two a rank, because a row-interleaved `all_gather` moves 16-byte words and one pair is 8 bytes). +**The prefill overlap.** At more than one rank, a prefill chunk of two routed passes or more (4096 +tokens, at the 2048-token pass) runs as two slices, and the trunk's all-reduces ride the runtime's +second lane beside the other slice's compute: slice A's attention reduction runs under slice B's +output projection, slice B's under slice A's two arms, and so on through the layer. Attention runs +whole, since it reads every row's keys. The cut is a whole number of routed passes and both slices +are above every row band the sliced kernels have, so the step issues the same kernels over the +same rows and its output is the whole step's, bit for bit. On 4x R9700 the reductions were 47% of +a 20K-token prefill under `--profile-ops`; a model of the measured times puts the overlap at up to +a quarter off an unprofiled prefill. The per-op profile syncs every op, so it cannot show it -- +time a prefill without `--profile-ops`. `RADIANCE_GEMMA4_OVERLAP=0` runs every chunk whole, and the +startup note says which. A decode step never takes the second lane. + **The draft head in fp8.** The drafter's head is the widest read on the draft path: the target's bf16 table, 352 MiB a rank at tp 4, every draft pass. A container converted with the line `dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16` (the three `-df` recipes diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 54b9f5c1..2ff9fe8d 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1860,6 +1860,7 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct at al | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_G4K_WMMA` | `0` keeps `gemma4k`'s prefill attention on its scalar kernel instead of the WMMA one. An A/B switch and a way out if the matrix path misbehaves on a card; read once | | `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the chains instead of `gemma4k`'s fusions: the rmsnorm / add chain for the sandwich joins (`norm_add_norm`, `join_add_scale`), `embed_lookup` + `mul` for `expert_scale`, and a `cast` lifting q for `attn_paged` for `attn_paged_qrow`. An A/B switch; read at declare | +| `RADIANCE_GEMMA4_OVERLAP` | `0` runs every `arch/gemma4` prefill chunk whole, its all-reduces on the compute stream, instead of as two slices whose all-reduces ride a second stream beside the other slice's compute. An A/B switch; read at declare | There is also a family of instruments for engine development — `RADIANCE_DEBUG_*` (residual probes, idle scrubs, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 43c641ef..1a34c3ed 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -71,7 +72,10 @@ struct RecIssue { rad_op op = 0; std::vector opd; int64_t n = 0; + int lane = 0; /* the lane it was issued on (rad_lane) */ }; +/* A rad_lane_join: `to` behind everything `from` issued before issue number `at`. */ +struct RecJoin { size_t at = 0; int from = 0, to = 0; }; } /* namespace */ @@ -91,6 +95,9 @@ struct RadBuilder { /* The buffer the plugin named as this step's logits (rad_declare_logits). */ rad_buf logits = 0; + /* The buffers named to rad_buf_concurrent: the ones a second lane touches. */ + std::vector concurrent; + /* The vision tower's declaration (rad_declare_encoder), when the plugin made one, and the * audio encoder's. */ RadEncoderDecl encoder{}; @@ -113,6 +120,8 @@ struct RadCtx { std::vector issues; std::vector routed_layers; std::string step_fail; + int lane = 0; /* where the next issue goes */ + std::vector joins; }; /* -------------------------------------------------------------------- the declare-side ABI */ @@ -212,8 +221,12 @@ extern "C" int rad_declare_logits(RadBuilder* b, rad_buf logits) { return RAD_OK; } -/* Recorded as calls and nothing else: no test here reads a lane or a drafter declaration. */ -extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { (void)b; (void)buf; return RAD_OK; } +/* Recorded: the gemma4 prefill overlap names the buffers its second lane reduces in place. */ +extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { + if (!b || !buf) return RAD_E_INVAL; + b->concurrent.push_back(buf); + return RAD_OK; +} extern "C" int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) { if (!b || w == 0 || w > b->weights.size()) return RAD_E_INVAL; if (lo < 0 || hi <= lo) return RAD_E_INVAL; @@ -285,9 +298,21 @@ extern "C" int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, r.op = op; r.n = n; for (int i = 0; i < n_opd; ++i) r.opd.push_back(opd[i]); + r.lane = c->lane; c->issues.push_back(r); return RAD_OK; } +/* The second lane, recorded: the lane each issue went to, and where each join sits among them. */ +extern "C" int rad_lane(RadCtx* c, int lane) { + if (lane != 0 && lane != 1) return RAD_E_INVAL; + c->lane = lane; + return RAD_OK; +} +extern "C" int rad_lane_join(RadCtx* c, int from, int to) { + if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL; + c->joins.push_back({ c->issues.size(), from, to }); + return RAD_OK; +} /* A block that refuses the batch records the reason; the recorder is what the tests read. */ extern "C" int rad_step_fail(RadCtx* c, const char* what) { c->step_fail = what ? what : ""; @@ -3805,3 +3830,183 @@ TEST(gemma4_dflash_head_reads_the_fp8_copy_where_the_container_holds_one) { CHECK_EQ(head_issues, 1); } } + +/* ============ gemma4: the prefill overlap -- two slices, the reductions on lane 1 ============ */ + +namespace { + +/* The elements [lo, hi) of its buffer an operand can reach, whole rows at the declared width. False + * for an operand that is not a buffer. */ +bool reach(const RadBuilder& b, const RadOperand& o, rad_buf* buf, int64_t* lo, int64_t* hi) { + if (o.kind != RAD_OPK_BUF || o.handle == 0 || o.handle > b.bufs.size()) return false; + const RadBufDecl& d = b.bufs[o.handle - 1].d; + int64_t pitch = 1; + for (uint32_t i = 1; i < d.rank; ++i) pitch *= d.shape[i]; + *buf = o.handle; + *lo = o.offset - o.offset % pitch; + *hi = *lo + (o.rows > 0 ? o.rows : d.shape[0]) * pitch; + return true; +} + +/* Whether issue a runs before issue b (a < b): on one lane by issue order, across the two only + * through a join from a's lane to b's issued between them. */ +bool ordered(const RadCtx& c, size_t a, size_t b) { + const int la = c.issues[a].lane, lb = c.issues[b].lane; + if (la == lb) return true; + for (const RecJoin& j : c.joins) + if (j.from == la && j.to == lb && j.at > a && j.at <= b) return true; + return false; +} + +/* Pairs of issues on different lanes that reach a common element with nothing ordering them. + * Every operand is taken as read and written, which can only over-count. */ +int races(const RadBuilder& b, const RadCtx& c) { + int n = 0; + for (size_t i = 0; i < c.issues.size(); ++i) + for (size_t j = i + 1; j < c.issues.size(); ++j) { + if (ordered(c, i, j)) continue; + bool meet = false; + for (const RadOperand& p : c.issues[i].opd) + for (const RadOperand& q : c.issues[j].opd) { + rad_buf bp = 0, bq = 0; + int64_t pl = 0, ph = 0, ql = 0, qh = 0; + if (reach(b, p, &bp, &pl, &ph) && reach(b, q, &bq, &ql, &qh) && bp == bq && + pl < qh && ql < ph) + meet = true; + } + n += meet ? 1 : 0; + } + return n; +} + +/* One prompt of T tokens, its last sampled. */ +RadBatch one_prompt(int64_t T, const int32_t* out) { + RadBatch b{}; + b.phase = RAD_PHASE_PREFILL; + b.n_tok = T; + b.n_seq = 1; + b.max_q_len = T; + b.max_ctx_len = T; + b.n_out = 1; + b.out_ids = out; + return b; +} + +/* Rows issued, summed by op: a slice's n is its rows, a whole step's RAD_N_BATCH is T. */ +std::map rows_by_op(const RadBuilder& b, const RadCtx& c, int64_t T) { + std::map w; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + w[o ? o->op : ""] += i.n < 0 ? T : i.n; + } + return w; +} + +/* The n of each issue of one op, in issue order. */ +std::vector ns_of(const RadBuilder& b, const RadCtx& c, const char* op) { + std::vector v; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (o && o->op == op) v.push_back(i.n); + } + return v; +} + +bool noted(const RadBuilder& b, const char* text) { + for (const auto& n : b.notes) + if (n.find(text) != std::string::npos) return true; + return false; +} + +} /* namespace */ + +/* A PREFILL CHUNK IN TWO SLICES (arch/gemma4, trunk_overlap). What a recorder can check is the + * order and the work: every reduction rides lane 1 behind its producer and ahead of its consumer, + * nothing else does, the cut is a whole number of routed passes, and the slices issue exactly the + * rows the whole step issues -- the same routed passes, the drafter's taps -- which is what makes + * the output the whole step's. A chunk under two passes, and a decode step, run whole on one + * lane. */ +TEST(a_gemma4_prefill_chunk_runs_as_two_slices_with_its_reductions_on_the_second_lane) { + const std::vector keys = g4df_keys(), vals = g4df_vals(); + const int64_t E = 2816, L = 6; + auto model = [&](RadBuilder& b, bool off) { + RadModelMeta meta = gemma4_moe_meta(); + meta.n_kv = (int)keys.size(); + meta.kv_key = keys.data(); + meta.kv_val = vals.data(); + RadBuildCtx ctx = build_ctx(0, 4); + ctx.max_tok = 8192; + ctx.max_spec = 15; + if (off) setenv("RADIANCE_GEMMA4_OVERLAP", "0", 1); + const int st = gemma4::declare(&b, &meta, &ctx); + if (off) unsetenv("RADIANCE_GEMMA4_OVERLAP"); + return st; + }; + auto run = [&](RadBuilder& b, RadCtx& c, RadBatch& batch) { + c.b = &b; c.rank = 0; c.world = 4; c.batch = &batch; + gemma4::step(&c, &batch); + }; + + struct Case { int64_t T, cut; }; + for (const Case k : { Case{8192, 4096}, Case{6144, 4096}, Case{6143, 2048}, Case{4096, 2048}, + Case{4095, 0} }) { + const int32_t out[1] = { (int32_t)(k.T - 1) }; + RadBuilder b; + CHECK_OK(model(b, false)); + CHECK(noted(b, "prefill overlap: a chunk of two routed passes")); + CHECK_EQ((int)b.concurrent.size(), 2); + for (const char* name : { "o", "ff2" }) + CHECK(std::count(b.concurrent.begin(), b.concurrent.end(), + (rad_buf)buf_named(b, name)) == 1); + RadBatch batch = one_prompt(k.T, out); + RadCtx c; + run(b, c, batch); + CHECK(c.step_fail.empty()); + CHECK_EQ(c.lane, 0); + CHECK_EQ(races(b, c), 0); + + std::vector lane1; + for (const auto& i : c.issues) { + if (i.lane != 1) continue; + const RecOp* o = b.op_of(i.op); + CHECK(o && o->op == "all_reduce"); + lane1.push_back(i.n); + } + if (k.cut == 0) { + CHECK(lane1.empty()); + CHECK(c.joins.empty()); + } else { + REQUIRE(lane1.size() == (size_t)(4 * L)); + for (int64_t l = 0; l < L; ++l) { + CHECK_EQ(lane1[4 * l + 0], k.cut * E); /* attention, slice A */ + CHECK_EQ(lane1[4 * l + 1], (k.T - k.cut) * E); /* attention, slice B */ + CHECK_EQ(lane1[4 * l + 2], 2 * k.cut * E); /* both arms, slice A */ + CHECK_EQ(lane1[4 * l + 3], 2 * (k.T - k.cut) * E); /* both arms, slice B */ + } + } + + /* The whole step, with the switch off: the same rows by op, the same routed passes. */ + RadBuilder w; + CHECK_OK(model(w, true)); + CHECK(noted(w, "prefill overlap: off (RADIANCE_GEMMA4_OVERLAP=0)")); + CHECK(w.concurrent.empty()); + RadBatch wbatch = one_prompt(k.T, out); + RadCtx wc; + run(w, wc, wbatch); + CHECK(wc.step_fail.empty()); + CHECK(wc.joins.empty()); + CHECK(rows_by_op(b, c, k.T) == rows_by_op(w, wc, k.T)); + CHECK(ns_of(b, c, "moe_gather") == ns_of(w, wc, "moe_gather")); + CHECK_EQ((int)ns_of(b, c, "cast").size(), k.cut ? 6 : 3); /* three taps, a slice each */ + } + + /* A decode step never leaves lane 0. */ + RadBuilder b; + CHECK_OK(model(b, false)); + RadBatch d = decode_batch(); + RadCtx c; + run(b, c, d); + CHECK(c.step_fail.empty()); + CHECK(c.joins.empty()); + for (const auto& i : c.issues) CHECK_EQ(i.lane, 0); +} From efff69be1da224fce2c8d3ae446e175693d69f46 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Mon, 12 Oct 2026 09:59:38 -0500 Subject: [PATCH 22/24] arch/gemma4: the drafter's residual add, norm and quantiser in one rmsnorm_quant_fp8 launch Every input of a drafter layer was three launches after its all-reduce: `add` (x += h), `rmsnorm` (x -> h) and `quant_act_fp8` (h -> hq | hs), ~8 us each under --profile-ops on 4x R9700 and a few unprofiled, twice a layer -- thirty a draft pass, every decode step. libr4d's `rmsnorm_quant_fp8` is that chain in one pass where it takes the residual operand (the fused_add_rms_norm form): the norm of the bf16-rounded sum, the codes of the bf16-rounded norm, which its row states is the chain's function. The drafter now issues it for both inputs of every layer, the attention input of layer 0 with no residual -- x as the embedding left it -- and the last layer's trailing add stays, ahead of the final norm, which no quantiser follows. Nineteen launches fewer a draft pass. Where nothing serves the op the chain is declared and issued as before. A draft is verified whatever it is, so this cannot change what is accepted. arch_test: a draft pass issues ten rmsnorm_quant_fp8 and one add, the residual operand x and the delta h past layer 0 and x alone at it; refused, the chain's ten adds and fifteen quantisers. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4_dflash.h | 47 ++++++++++++++++++++++++++++++------ docs/ARCHITECTURES.md | 8 ++++--- tests/arch_test.cpp | 48 +++++++++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 10 deletions(-) diff --git a/arch/gemma4/gemma4_dflash.h b/arch/gemma4/gemma4_dflash.h index 348c1bdd..fc93303b 100644 --- a/arch/gemma4/gemma4_dflash.h +++ b/arch/gemma4/gemma4_dflash.h @@ -146,6 +146,11 @@ struct Dflash1 { rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0; rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}; + /* THE RESIDUAL ADD, THE NORM AND THE QUANTISER IN ONE LAUNCH where `rmsnorm_quant_fp8` is + * served (libr4d): op_anq[i] the attention input's -- layer 0's with no add, x as the + * embedding left it -- and op_fnq[i] the feed-forward input's. Zero where it is not, and the + * `add` / `rmsnorm` / `quant_act_fp8` chain is issued instead. */ + rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {}; rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}; rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; @@ -361,6 +366,19 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_NOWEIGHTS), {w.ffn}, {w.ffq, w.ffs}); + /* x's norm under `gain`, quantised into hq|hs, in one launch; with `add` the fused_add_rms_norm + * form, x += h first. The row is the chain's function exactly -- the norm of the bf16-rounded + * sum, the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp) -- and a draft is verified + * whatever it is. */ + auto norm_quant = [&](rad_weight gain, bool add) -> rad_op { + const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)), + RAD_WEIGHTS(gain)); + return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs}); + }; + for (int64_t l = 0; l < g.n_layer; ++l) { const int i = (int)l; op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm", @@ -369,6 +387,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_anorm[i])), {w.x}, {w.h}); + op_anq[i] = norm_quant(w_anorm[i], l > 0); op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q}); op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k}); op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v}); @@ -391,6 +410,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_fnorm[i])), {w.x}, {w.h}); + op_fnq[i] = norm_quant(w_fnorm[i], true); op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up}); /* The gate_up|silu|quant fold where it resolves, the pair where it does not -- * rad_block_dflash2.h's rule, band included. */ @@ -582,8 +602,15 @@ inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { const int i = (int)l; const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa; - RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); - RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + /* The attention input, with the last layer's residual add where one launch takes both. */ + if (op_anq[i]) { + RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T), + l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T), + brows(w.hs, T), RAD_NONE); + } else { + RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); + RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + } RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T), RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref()); RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T), @@ -605,10 +632,14 @@ inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T), RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref()); if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); - - RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); - RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + if (op_fnq[i]) { + RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]), + brows(w.hq, T), brows(w.hs, T), RAD_NONE); + } else { + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); + RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + } if (op_gug[i] && T <= gated_rows) { RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T), @@ -623,7 +654,9 @@ inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T), RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref()); if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + /* the residual add, unless the next layer's input norm takes it */ + if (l + 1 == g.n_layer || !op_anq[i + 1]) + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); } RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 30338aed..065ed250 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -545,9 +545,11 @@ four, eight ranks) -- plus `pair_argmax` and the fusions: the two sandwich-norm (`norm_add_norm`, `join_add_scale`), `expert_scale`, and `attn_paged_qrow`, the sliding layers' attention reading q where the fused qkv projection left it. The plugin declares each one's unfused form where nothing serves it -- the rmsnorm / add chain, `embed_lookup` + `mul`, a `cast` lifting q -for `attn_paged` -- and the startup notes say which were taken. libr4d has h256/gqa2 and h512/gqa8 -rows as well, written for the dense 31B; with gemma4k first the 26B-A4B runs on the kernels it was -measured with. +for `attn_paged` -- and the startup notes say which were taken. The drafter's residual add, norm +and fp8 quantiser of x are one libr4d `rmsnorm_quant_fp8` launch an input (ten a draft pass), and +the `add` / `rmsnorm` / `quant_act_fp8` chain where nothing serves it. libr4d has h256/gqa2 and +h512/gqa8 rows as well, written for the dense 31B; with gemma4k first the 26B-A4B runs on the +kernels it was measured with. Without `gemma4k` at all, the full layers have no kernel at four and eight ranks, and a drafter head sharded over more than one rank has no `pair_argmax`. diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 1a34c3ed..4a01dd66 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3831,6 +3831,54 @@ TEST(gemma4_dflash_head_reads_the_fp8_copy_where_the_container_holds_one) { } } +/* THE DRAFTER'S RESIDUAL ADD, NORM AND QUANTISER IN ONE LAUNCH (`rmsnorm_quant_fp8`): ten a draft + * pass over five layers, each layer's two inputs, layer 0's attention input taking x as the + * embedding left it -- and one `add` left, the last layer's, ahead of the final norm. Refused, the + * chain: two adds and two quantisers of x a layer. */ +TEST(gemma4_dflash_folds_the_residual_add_norm_and_quantiser_into_one_launch) { + const std::vector keys = g4df_keys(), vals = g4df_vals(); + for (int refuse = 0; refuse < 2; ++refuse) { + RadModelMeta meta = gemma4_moe_meta(); + meta.n_kv = (int)keys.size(); + meta.kv_key = keys.data(); + meta.kv_val = vals.data(); + RadBuilder b; + if (refuse) b.refuse.insert("rmsnorm_quant_fp8"); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + batch.draft_pass = 1; + c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + CHECK_EQ(count_issued(ops, "rmsnorm_quant_fp8"), refuse ? 0 : 10); + CHECK_EQ(count_issued(ops, "add"), refuse ? 10 : 1); + /* x's quantiser twice a layer in the chain; the attention output's once a layer always */ + CHECK_EQ(count_issued(ops, "quant_act_fp8"), refuse ? 15 : 5); + if (refuse) continue; + + /* the delta then the residual x past layer 0; layer 0 reads x and adds nothing */ + const uint32_t x = (uint32_t)buf_named(b, "df_x"), h = (uint32_t)buf_named(b, "df_h"); + int k = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (!o || o->op != "rmsnorm_quant_fp8") continue; + REQUIRE(i.opd.size() == 6); + if (k++ == 0) { + CHECK_EQ(i.opd[0].handle, x); + CHECK_EQ((int)i.opd[1].kind, (int)RAD_OPK_NONE); + } else { + CHECK_EQ(i.opd[0].handle, h); + CHECK_EQ(i.opd[1].handle, x); + } + } + } +} + /* ============ gemma4: the prefill overlap -- two slices, the reductions on lane 1 ============ */ namespace { From 7a1ae226909861f64b88f47d74d74a9236dd504b Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Mon, 12 Oct 2026 10:23:24 -0500 Subject: [PATCH 23/24] gemma4k, arch/gemma4: norm_add_norm_route -- the attention join writes the routed arm's inputs The 26B-A4B's router reads rmsnorm(x) * w_r * hidden^-0.5 and its experts rmsnorm(x) * w_e, quantised to E4M3 for the fp8 gate_up: an `rmsnorm` and an `rmsnorm_quant_fp8` a layer, each reading back the x norm_add_norm has just written and taking the sum of squares it has just taken. At decode that is 60 launches a step (8.3 and 7.8 us under --profile-ops on 4x R9700); at a prefill, eleven passes of each a layer per 20K-token request. norm_add_norm_route is norm_add_norm, then from the norm factor it already holds the router's row by rmsnorm's expression, ((x * s) * w_r) * mult, and the experts' codes as rmsnorm_quant_fp8 writes them: the bf16-rounded norm, a scale of amax * (1 / 448) a 128 columns (1 for an all-zero group), the value times its reciprocal clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256 at slot i / 256, so a group is four waves at one slot -- a wave's max, then the four through LDS. Its own name rather than optional operands on norm_add_norm: the codes need whole 128-column groups, which the plain join does not, and the arch falls back cleanly where it does not resolve. A device row and a host arm (one helper with norm_add_norm's), the schema, OPS.md. arch/gemma4 asks for it on every layer whose gate_up is block fp8 -- the user's fp8gu container, every layer -- and then issues neither op_rnorm nor op_enorm; it declares both still, and norm_add_norm and the chain behind it, for where it does not resolve. The routed arm's two norm gains are declared ahead of the attention join now, which names them. The overlap takes either join. A startup note counts the layers that take it. The same rounding as the chain, but for the order a sum of squares is added in, as every join here: g4k_emu holds the kernel to a chain summed in its block order bit for bit -- x, y, the router's row, every code and scale -- at the 26B-A4B's 2816 at four heights, at 128, 3072, 3200 and 6144, and with an all-zero group; against the host arm, no code more than a step off. The emulator gains v_cvt_pk_fp8_f32, through the project's saturating encoder. arch_test: with fp8 gate_up experts the route op resolves on all six layers, a decode step issues it and no rmsnorm_quant_fp8 and one rmsnorm fewer a layer; refused, norm_add_norm and both launches; a tp-4 prefill through the overlap issues it a slice and keeps every reduction ordered. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 79 +++++++++++++----- docs/ARCHITECTURES.md | 11 ++- docs/GUIDE.md | 2 +- docs/OPS.md | 9 ++ gemma4k/g4k.h | 6 +- gemma4k/g4k_norm.hip | 123 +++++++++++++++++++++++++--- gemma4k/g4k_rows.cpp | 101 +++++++++++++++++++++-- tests/arch_test.cpp | 60 ++++++++++++++ tests/g4k_emu/emu/emu.cpp | 6 ++ tests/g4k_emu/emu/hip/hip_runtime.h | 5 ++ tests/g4k_emu/test_norm.cpp | 90 +++++++++++++++++++- 11 files changed, 449 insertions(+), 43 deletions(-) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index 3831efd9..7dba1b8f 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -248,6 +248,10 @@ struct Layer { * routed layer's fpost1 + fpost2 + fsum + fpost + add_f + scale. Zero where not served, and * then the chain above is declared and issued instead. */ rad_op op_join_a = 0, op_join_f = 0; + /* op_join_r: op_join_a writing the routed arm's two inputs as well -- the router's norm into + * b_rn and the experts' fp8 codes into b_hq / b_hqs (gemma4k norm_add_norm_route) -- where the + * layer's gate_up is block fp8. op_rnorm and op_enorm are then declared and not issued. */ + rad_op op_join_r = 0; /* op_join_f also writes the NEXT norm -- the following layer's input norm, or the final norm * after the last layer -- into `h`, with that norm's gain `w_next`; the norm it replaces is * then neither declared nor issued. */ @@ -1013,7 +1017,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * libref has no row for the joins on purpose, so "nothing serves them" stays reachable. */ const char* fuse_env = std::getenv("RADIANCE_GEMMA4_FUSE"); const bool fuse_joins = !(fuse_env && fuse_env[0] == '0'); - int n_joins = 0; + int n_joins = 0, n_route = 0; const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE; /* EVERY LAYER'S INPUT NORM GAIN, AHEAD OF THE LAYERS: a feed-forward join writes the next @@ -1157,13 +1161,37 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* bf16 and one element: the reference multiplies the bf16 stream by it. */ y.w_scalar = decl_w(b, nm.f("blk.%lld.layer_scalar", ll), RAD_BF16, {1}, A, N, gl); - if (fuse_joins) + /* The routed arm's two input norms -- the router's gain and the experts' pre-norm -- are + * declared here, ahead of the attention join, which writes both inputs where gemma4k + * serves `norm_add_norm_route` and an op names its weights after they are declared. */ + if (m.moe) { + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), + src("pre_feedforward_layernorm_2.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), src("router.scale"))); + y.w_enorm = decl_w(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), RAD_F32, {E}, A, N, + gl); + y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl); + } + + /* THE ATTENTION JOIN, and on a layer whose gate_up is block fp8 the routed arm's two + * inputs with it: the router's norm (rmsnorm's expression, its mult hidden^-0.5) and the + * experts' E4M3 codes (rmsnorm_quant_fp8's) from the norm of x the join already takes -- + * two launches a layer fewer, and two reads of x. Then norm_add_norm, then the chain. */ + if (fuse_joins && m.moe && y.gu_fp8) + y.op_join_r = rw(b, RAD_OP(b, "norm_add_norm_route", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16"), + RAD_F64("mult", 1.0 / std::sqrt((double)E)), + RAD_INT("group", RAD_FP8_BLOCK)), + RAD_WEIGHTS(y.w_apost, y.w_fnorm, y.w_rscale, y.w_enorm)), + {m.b_o, m.b_x}, {m.b_x, m.b_h, m.b_rn, m.b_hq, m.b_hqs}); + if (fuse_joins && !y.op_join_r) y.op_join_a = rw(b, RAD_OP(b, "norm_add_norm", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(y.w_apost, y.w_fnorm)), {m.b_o, m.b_x}, {m.b_x, m.b_h}); - if (!y.op_join_a) { + if (!y.op_join_a && !y.op_join_r) { y.op_apost = rmsnorm(T, E, y.w_apost, 1.0, m.b_o, m.b_o); y.op_add_a = binop("add", T, E, m.b_x, m.b_o, m.b_x); y.op_fnorm = rmsnorm(T, E, y.w_fnorm, 1.0, m.b_x, m.b_h); @@ -1180,19 +1208,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c src("post_feedforward_layernorm_1.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_post_norm2.weight", ll), src("post_feedforward_layernorm_2.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), - src("pre_feedforward_layernorm_2.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.weight", ll), src("router.proj.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), src("router.scale"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_exp_scale", ll), src("router.per_expert_scale"))); y.w_fpost1 = decl_w(b, nm.f("blk.%lld.ffn_post_norm1.weight", ll), RAD_F32, {E}, A, N, gl); y.w_fpost2 = decl_w(b, nm.f("blk.%lld.ffn_post_norm2.weight", ll), RAD_F32, {E}, A, N, gl); - y.w_enorm = decl_w(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), RAD_F32, {E}, A, N, gl); /* THE ROUTER IS REPLICATED (rad_block_moe_fp8.h argues it): every rank routes every * token the same way from the same residual stream. */ y.w_router = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.weight", ll), RAD_BF16, {m.n_expert, E}, A, N, gl); - y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl); y.w_escale = decl_w(b, nm.f("blk.%lld.ffn_exp_scale", ll), RAD_BF16, {m.n_expert}, A, N, gl); /* THE EXPERTS: whole experts, this rank's run of them (their name maps and encodings @@ -1425,7 +1448,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_WEIGHTS(y.w_scalar)), {m.b_x}, {m.b_x}); } - n_joins += (y.op_join_a ? 1 : 0) + (y.op_join_f ? 1 : 0); + n_joins += (y.op_join_a || y.op_join_r ? 1 : 0) + (y.op_join_f ? 1 : 0); + n_route += y.op_join_r ? 1 : 0; /* THE TAP: a row copy of the layer's output into the column slice a tap owns, DECLARED * HERE, after the layer's last op, because that is where step() issues it. The buffer @@ -1455,8 +1479,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c const bool ov_off = ov_env && ov_env[0] == '0'; m.overlap = W > 1 && m.moe && g.wire_exact && T >= 2 * m.moe_rows && !ov_off; for (const Layer& y : m.layers) - m.overlap = m.overlap && y.op_join_a && y.op_join_f && y.next_norm && y.op_ar_o && - y.op_ar_f; + m.overlap = m.overlap && (y.op_join_a || y.op_join_r) && y.op_join_f && y.next_norm && + y.op_ar_o && y.op_ar_f; if (m.overlap) { RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o)); RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2)); @@ -1512,6 +1536,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c n_joins, (long long)(m.moe ? 2 * m.n_layer : m.n_layer), !fuse_joins ? " -- RADIANCE_GEMMA4_FUSE=0, the rmsnorm / add / mul_weight chain" : n_joins == 0 ? " -- not served (load gemma4k), the rmsnorm / add / mul_weight chain" : ""); + if (m.moe && m.n_gu_fp8 > 0) + rad_note(b, "routed inputs: %d of %d fp8 layers take the router's norm and the experts' " + "codes from the attention join (gemma4k norm_add_norm_route)%s", + n_route, m.n_gu_fp8, + n_route ? "" : " -- the rmsnorm and rmsnorm_quant_fp8 launches instead"); if (m.ks.nh > 0) rad_note(b, "sliding attention: q %s", m.qrow == 1 ? "read in the fused qkv row (gemma4k attn_paged_qrow)" @@ -1556,8 +1585,9 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t const int64_t n = (end - r0 < m.moe_rows) ? (end - r0) : m.moe_rows; int32_t* const counts = rad_route_counts(c, (int)(&y - m.layers.data()), NL); const RadOperand ecnt = counts ? praw(counts, RAD_I32, NL) : brows(m.b_ecnt, NL); - RAD_ISSUE_N(c, y.op_rnorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_rscale), - brow_slice(m.b_rn, r0, n, E)); + if (!y.op_join_r) /* the attention join wrote the router's input otherwise */ + RAD_ISSUE_N(c, y.op_rnorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_rscale), + brow_slice(m.b_rn, r0, n, E)); /* One launch, two or three: the router, its top-k and the sort (see declare). */ const bool rfused = y.op_router_fused && n <= y.router_fused_rows; const bool pair = !rfused && y.op_topk_scatter && n <= y.topk_scatter_rows; @@ -1589,12 +1619,13 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t RAD_ISSUE_N(c, y.op_emul, n, brow_slice(m.b_ew, r0, n, K), brow_slice(m.b_es, r0, n, K), brow_slice(m.b_ew, r0, n, K)); } - /* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent). */ - if (y.gu_fp8) + /* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent) -- + * where the attention join did not write the codes already. */ + if (y.gu_fp8 && !y.op_join_r) RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm), brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK), RAD_NONE); - else + else if (!y.gu_fp8) RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_enorm), brow_slice(m.b_hx, r0, n, E)); if (!rfused && !pair) @@ -1696,7 +1727,11 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) { attend(c, m, y, li, batch); RAD_ISSUE(c, y.op_o, brows(y.full ? m.b_attf : m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T)); if (y.op_ar_o) RAD_ISSUE_N(c, y.op_ar_o, T * E, brows(m.b_o, T), RAD_NONE); - if (y.op_join_a) { + if (y.op_join_r) { + RAD_ISSUE(c, y.op_join_r, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T), + RAD_W(y.w_fnorm), brows(m.b_h, T), RAD_W(y.w_rscale), brows(m.b_rn, T), + RAD_W(y.w_enorm), brows(m.b_hq, T), brows(m.b_hqs, T)); + } else if (y.op_join_a) { RAD_ISSUE(c, y.op_join_a, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T), RAD_W(y.w_fnorm), brows(m.b_h, T)); } else { @@ -1804,8 +1839,14 @@ static void out_proj(RadCtx* c, const Model& m, const Layer& y, int64_t r0, int6 * routed, so its feed-forward reduction is one run. */ static void arms(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t r0, int64_t n) { const int64_t E = m.E, F = m.n_ff; - RAD_ISSUE_N(c, y.op_join_a, n, brow_slice(m.b_o, r0, n, E), RAD_W(y.w_apost), - brow_slice(m.b_x, r0, n, E), RAD_W(y.w_fnorm), brow_slice(m.b_h, r0, n, E)); + if (y.op_join_r) + RAD_ISSUE_N(c, y.op_join_r, n, brow_slice(m.b_o, r0, n, E), RAD_W(y.w_apost), + brow_slice(m.b_x, r0, n, E), RAD_W(y.w_fnorm), brow_slice(m.b_h, r0, n, E), + RAD_W(y.w_rscale), brow_slice(m.b_rn, r0, n, E), RAD_W(y.w_enorm), + brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK)); + else + RAD_ISSUE_N(c, y.op_join_a, n, brow_slice(m.b_o, r0, n, E), RAD_W(y.w_apost), + brow_slice(m.b_x, r0, n, E), RAD_W(y.w_fnorm), brow_slice(m.b_h, r0, n, E)); RAD_ISSUE_N(c, y.op_gu, n, brow_slice(m.b_h, r0, n, E), RAD_W(y.w_gu), brow_slice(m.b_gu, r0, n, 2 * F)); RAD_ISSUE_N(c, y.op_act, n, bcol_at(m.b_gu, r0, 2 * F, 0, F, n), diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 065ed250..21daa5d8 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -542,10 +542,13 @@ expert parity, so a rank holds an even number of experts. **Kernels.** `--kernels gemma4k,libr4d,libavx`, **gemma4k first.** It serves all of the trunk's attention -- the sliding layers (h256, gqa 2) and the full layers at gqa 8, 4 and 2 (one or two, four, eight ranks) -- plus `pair_argmax` and the fusions: the two sandwich-norm joins -(`norm_add_norm`, `join_add_scale`), `expert_scale`, and `attn_paged_qrow`, the sliding layers' -attention reading q where the fused qkv projection left it. The plugin declares each one's unfused -form where nothing serves it -- the rmsnorm / add chain, `embed_lookup` + `mul`, a `cast` lifting q -for `attn_paged` -- and the startup notes say which were taken. The drafter's residual add, norm +(`norm_add_norm`, `join_add_scale`), `norm_add_norm_route` -- on a layer whose gate_up is block +fp8, the attention join writing the router's input and the experts' fp8 codes from the norm it +already takes, in place of an `rmsnorm` and an `rmsnorm_quant_fp8` -- `expert_scale`, and +`attn_paged_qrow`, the sliding layers' attention reading q where the fused qkv projection left it. +The plugin declares each one's unfused form where nothing serves it -- the rmsnorm / add chain, +`embed_lookup` + `mul`, a `cast` lifting q for `attn_paged` -- and the startup notes say which +were taken. The drafter's residual add, norm and fp8 quantiser of x are one libr4d `rmsnorm_quant_fp8` launch an input (ten a draft pass), and the `add` / `rmsnorm` / `quant_act_fp8` chain where nothing serves it. libr4d has h256/gqa2 and h512/gqa8 rows as well, written for the dense 31B; with gemma4k first the 26B-A4B runs on the diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 2ff9fe8d..cc9b1ba9 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1859,7 +1859,7 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct at al | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_G4K_WMMA` | `0` keeps `gemma4k`'s prefill attention on its scalar kernel instead of the WMMA one. An A/B switch and a way out if the matrix path misbehaves on a card; read once | -| `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the chains instead of `gemma4k`'s fusions: the rmsnorm / add chain for the sandwich joins (`norm_add_norm`, `join_add_scale`), `embed_lookup` + `mul` for `expert_scale`, and a `cast` lifting q for `attn_paged` for `attn_paged_qrow`. An A/B switch; read at declare | +| `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the chains instead of `gemma4k`'s fusions: the rmsnorm / add chain for the sandwich joins (`norm_add_norm`, `norm_add_norm_route`, `join_add_scale`), `embed_lookup` + `mul` for `expert_scale`, and a `cast` lifting q for `attn_paged` for `attn_paged_qrow`. An A/B switch; read at declare | | `RADIANCE_GEMMA4_OVERLAP` | `0` runs every `arch/gemma4` prefill chunk whole, its all-reduces on the compute stream, instead of as two slices whose all-reduces ride a second stream beside the other slice's compute. An A/B switch; read at declare | There is also a family of instruments for engine development — `RADIANCE_DEBUG_*` (residual probes, diff --git a/docs/OPS.md b/docs/OPS.md index ac97377f..cf34483c 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -299,6 +299,7 @@ rounding. | op | params | operands | |---|---|---| | `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` | +| `norm_add_norm_route` | `M`(range) `n` `eps`:f64 `dtype` `mult`:f64 `group` | `a`, `w_a`w, `x`:inout, `w_y`w → `y`; `w_r`w → `r`; `w_e`w → `q`, `qs` | | `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w, `w_n`w? → `y`? | | `expert_scale` | `M`(range) `n_expert` `top_k` `dtype` | `ids`, `w_e`w, `ew`:inout | | `attn_paged_qrow` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` | @@ -315,6 +316,14 @@ differ from the chain only in the order a sum of squares is added in: with the s bit-identical to it, and against a chain summed in another block width a norm factor can differ in its last bit. +`norm_add_norm_route` is `norm_add_norm` and, from the same norm of the `x` it writes, a MoE +layer's two routed inputs: `r = rmsnorm(x) * w_r * mult` -- `rmsnorm`'s expression with `mult` -- +and `q`, `qs` = `rmsnorm_quant_fp8` of `x` under `w_e`: E4M3 codes of the bf16-rounded norm, an +f32 scale per (row, `group` columns) of `amax / 448` (1 for an all-zero group), the value over it +clamped to +-448. `n` is whole groups and `group` 128. In Gemma 4 it replaces the router's +`rmsnorm` and the experts' `rmsnorm_quant_fp8`, two launches a layer that read back the `x` the +join had just written. + `expert_scale` is `ew[t, k] = ew[t, k] * w_e[ids[t, k]]` over `[M, top_k]`, `w_e` an `[n_expert]` table and an id outside it reading 0: Gemma 4's per_expert_scale on the renormalised routing weights, in place of an `embed_lookup` of the table by the ids and a `mul` into the weights. One diff --git a/gemma4k/g4k.h b/gemma4k/g4k.h index 8350d8be..3ae85a65 100644 --- a/gemma4k/g4k.h +++ b/gemma4k/g4k.h @@ -27,9 +27,11 @@ int64_t g4k_attn_h512_scratch(const RadArgs* a); int g4k_pair_argmax_f32(const RadArgs* a, RadStream s); /* Gemma 4's sandwich-norm joins, one kernel each (g4k_norm.hip): - * norm_add_norm operands a, w_a, x (inout), w_y, y - * join_add_scale operands d, w_d, r, w_r, w_j, x (inout), s */ + * norm_add_norm operands a, w_a, x (inout), w_y, y + * norm_add_norm_route the same, then w_r, r, w_e, q, qs: the routed arm's two inputs + * join_add_scale operands d, w_d, r, w_r, w_j, x (inout), s */ int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream s); +int g4k_norm_add_norm_route_bf16(const RadArgs* a, RadStream s); /* expert_scale: each routing weight times its expert's scale, in place (g4k_escale.hip): * operands ids, w_e, ew (inout) */ diff --git a/gemma4k/g4k_norm.hip b/gemma4k/g4k_norm.hip index 66d1d0d2..fc58bc69 100644 --- a/gemma4k/g4k_norm.hip +++ b/gemma4k/g4k_norm.hip @@ -20,6 +20,16 @@ * and, rarely, a bf16 output by one ulp. The arch plugin asks for these first and falls back to * the chain where nothing serves them (gemma4.cpp). * + * AND THE ROUTED ARM'S TWO INPUTS (norm_add_norm_route). The 26B-A4B's router reads norm(x) * w_r * + * hidden^-0.5 and its experts norm(x) * w_e, quantised to E4M3 -- two more launches a layer + * (`rmsnorm`, `rmsnorm_quant_fp8`), each reading back the x norm_add_norm has just written and + * taking the sum of squares norm_add_norm has just taken. The route form writes both from the norm + * factor it holds: the router's row by libr4d's rmsnorm expression, ((x * s) * w) * mult, and the + * experts' codes as libr4d's rmsnorm_quant_fp8 writes them -- the bf16-rounded norm, a scale of + * amax * (1 / 448) a 128 columns (1 where the group is all zero), the value times its reciprocal + * clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256 at slot i / 256, so a group + * is four waves at one slot: a wave's max, then the four. + * * One 256-thread block a row: a decode step is a handful of rows, so the row is latency-bound and * a block's three reductions beat seven launches. Values a later stage reuses stay in registers * (PER a thread, 12 to n = 3072 and kMaxPer = 24 to 6144; the row table says so). @@ -99,22 +109,30 @@ struct NormArgs { const float* w2; /* w_j */ const float* w3; /* w_n, the next norm's gain (or null) */ const uint16_t* s; /* the layer scalar, bf16, one element */ + /* norm_add_norm_route: the router's input, the experts' codes and their scales; the router's + * gain is w2 and the experts' w3 */ + uint16_t* rt; long long rt_ld; + uint8_t* q; long long q_ld; + float* qs; long long qs_ld; + float mult; int n; float eps; }; -/* t = norm(a) * w_a; x += t; y = norm(x) * w_y */ -template +/* t = norm(a) * w_a; x += t; y = norm(x) * w_y -- and with ROUTE, from the same norm of x, the + * router's input norm(x) * w_r * mult and the experts' norm(x) * w_e as E4M3 codes and scales */ +template __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { __shared__ float lds[kWaves]; + __shared__ float gmax[ROUTE ? PER * kWaves : 1]; const int tid = (int)threadIdx.x, n = A.n; const long long m = (long long)blockIdx.x; const uint16_t* ar = A.a + m * A.a_ld; uint16_t* xr = A.x + m * A.x_ld; uint16_t* yr = A.y + m * A.y_ld; - /* every operand of the row in flight at once: the block output, the residual, both gains */ - float av[PER], xv[PER], wa[PER], wy[PER]; + /* every operand of the row in flight at once: the block output, the residual, the gains */ + float av[PER], xv[PER], wa[PER], wy[PER], wr[ROUTE ? PER : 1], we[ROUTE ? PER : 1]; #pragma unroll for (int k = 0; k < PER; ++k) { const int i = tid + k * kThreads; @@ -123,6 +141,10 @@ __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { xv[k] = in ? bf2f(xr[i]) : 0.0f; wa[k] = in ? A.w0[i] : 0.0f; wy[k] = in ? A.w1[i] : 0.0f; + if constexpr (ROUTE) { + wr[k] = in ? A.w2[i] : 0.0f; + we[k] = in ? A.w3[i] : 0.0f; + } } float ss = 0.0f; #pragma unroll @@ -140,10 +162,45 @@ __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { ss += xv[k] * xv[k]; } const float sx = norm_factor(block_sum(ss, lds), n, A.eps); + uint16_t* rr = ROUTE ? A.rt + m * A.rt_ld : nullptr; #pragma unroll for (int k = 0; k < PER; ++k) { const int i = tid + k * kThreads; - if (i < n) yr[i] = f2bf((xv[k] * sx) * wy[k]); + if (i < n) { + yr[i] = f2bf((xv[k] * sx) * wy[k]); + if constexpr (ROUTE) { + rr[i] = f2bf(((xv[k] * sx) * wr[k]) * A.mult); + av[k] = rbf((xv[k] * sx) * we[k]); /* the experts' row, as quantised */ + } + } else if constexpr (ROUTE) { + av[k] = 0.0f; + } + } + if constexpr (ROUTE) { + /* group 2k + tid / 128 at slot k is waves 0..3 or 4..7: each wave's max, then its four */ + const int wave = tid >> 5, half = tid >> 7; +#pragma unroll + for (int k = 0; k < PER; ++k) { + float mx = fabsf(av[k]); +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) mx = fmaxf(mx, shfl_xor(mx, d)); + if (lane_id() == 0) gmax[k * kWaves + wave] = mx; + } + __syncthreads(); + uint8_t* qr = A.q + m * A.q_ld; + float* sr = A.qs + m * A.qs_ld; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + if (i >= n) continue; /* n is whole groups: a group is in or out */ + const float* g = gmax + k * kWaves + 4 * half; + const float am = fmaxf(fmaxf(g[0], g[1]), fmaxf(g[2], g[3])); + const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f; + const float inv = 1.0f / sc; + const float v = fminf(fmaxf(av[k] * inv, -448.0f), 448.0f); + qr[i] = (uint8_t)(__builtin_amdgcn_cvt_pk_fp8_f32(v, v, 0, false) & 0xff); + if ((tid & 127) == 0) sr[i >> 7] = sc; + } } } @@ -224,14 +281,17 @@ __global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { /* ------------------------------------------------------------------ host: the launch adapters */ -/* [rows..., n] with a dense last axis: its row count and pitch, or false */ -static bool rows_of(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) { - if (!t || t->dtype != RAD_BF16 || t->rank < 1) return false; +/* [rows..., n] of `dt` with a dense last axis: its row count and pitch, or false */ +static bool rows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != dt || t->rank < 1) return false; if (rad_tensor_lastdim(t) != n || (t->stride[t->rank - 1] != 1)) return false; *rows = rad_tensor_rows(t); *ld = rad_tensor_row_pitch(t); return *ld >= n || *rows <= 1; } +static bool rows_of(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) { + return rows_as(t, RAD_BF16, n, rows, ld); +} static bool gain(const RadTensor* w, int64_t n) { return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n && (w->rank == 0 || w->stride[w->rank - 1] == 1); @@ -272,11 +332,54 @@ int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream stream) { P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data; P.n = (int)n; P.eps = eps; if (n <= (int64_t)kThreads * 12) - G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel<12>), dim3((unsigned)M), dim3(kThreads), + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel<12, false>), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); else - G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel), dim3((unsigned)M), dim3(kThreads), + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel), dim3((unsigned)M), + dim3(kThreads), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +/* operands: a, w_a, x (inout), w_y, y, w_r, r, w_e, q, qs */ +int g4k_norm_add_norm_route_bf16(const RadArgs* a, RadStream stream) { + using namespace g4kn; + if (!a || a->n_t < 10) return RAD_E_INVAL; + int64_t n = 0; + float eps = 0.0f; + if (int rc = params(a, &n, &eps)) return rc; + if (n % 128 || rad_args_geti_or(a, "group", 0) != 128) return RAD_E_SHAPE; + const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), + *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4), *Wr = rad_arg_in(a, 5), + *R = rad_arg_in(a, 6), *We = rad_arg_in(a, 7), *Q = rad_arg_in(a, 8), + *S = rad_arg_in(a, 9); + if (!A_ || !X || !Y || !R || !Q || !S) return RAD_E_INVAL; + if (!gain(Wa, n) || !gain(Wy, n) || !gain(Wr, n) || !gain(We, n)) return RAD_E_DTYPE; + int64_t ra = 0, la = 0, rx = 0, lx = 0, ry = 0, ly = 0, rr = 0, lr = 0, rq = 0, lq = 0, + rs = 0, ls = 0; + if (!rows_of(A_, n, &ra, &la) || !rows_of(X, n, &rx, &lx) || !rows_of(Y, n, &ry, &ly) || + !rows_of(R, n, &rr, &lr) || !rows_as(Q, RAD_F8E4M3, n, &rq, &lq) || + !rows_as(S, RAD_F32, n / 128, &rs, &ls)) + return RAD_E_SHAPE; + const int64_t M = rx; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (ra < M || ry < M || rr < M || rq < M || rs < M || M > 0x7fffffff) return RAD_E_SHAPE; + NormArgs P{}; + P.a = (const uint16_t*)A_->data; P.a_ld = la; + P.x = (uint16_t*)X->data; P.x_ld = lx; + P.y = (uint16_t*)Y->data; P.y_ld = ly; + P.rt = (uint16_t*)R->data; P.rt_ld = lr; + P.q = (uint8_t*)Q->data; P.q_ld = lq; + P.qs = (float*)S->data; P.qs_ld = ls; + P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data; + P.w2 = (const float*)Wr->data; P.w3 = (const float*)We->data; + P.mult = (float)rad_args_getf_or(a, "mult", 1.0); + P.n = (int)n; P.eps = eps; + if (n <= (int64_t)kThreads * 12) + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel<12, true>), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + else + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel), dim3((unsigned)M), + dim3(kThreads), (hipStream_t)stream, P); return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } diff --git a/gemma4k/g4k_rows.cpp b/gemma4k/g4k_rows.cpp index 47b4e2be..72dc4907 100644 --- a/gemma4k/g4k_rows.cpp +++ b/gemma4k/g4k_rows.cpp @@ -11,6 +11,8 @@ * norm_add_norm and join_add_scale, ops this library DEFINES: Gemma 4's two sandwich-norm joins, * each one kernel in place of a chain of rmsnorm / add / mul_weight launches, rounding where the * chain rounds (g4k_norm.hip). The arch plugin asks for them and falls back to the chain. + * norm_add_norm_route is the attention join writing the routed arm's two inputs as well -- the + * router's norm and the experts' fp8 codes -- in place of an rmsnorm and an rmsnorm_quant_fp8. * * Put it AHEAD of libr4d for Gemma 4 (`--kernels gemma4k,libr4d,...`). The hierarchy is absolute, * and libr4d has rows at h256/gqa2 and h512/gqa8 too -- written for the dense 31B, which has no @@ -40,6 +42,7 @@ #define C_GE(k, v) { (k), RAD_C_GE, (long long)(v), nullptr } #define C_LE(k, v) { (k), RAD_C_LE, (long long)(v), nullptr } #define C_IN(k, s) { (k), RAD_C_IN, 0, (s) } +#define C_DIV(k, v) { (k), RAD_C_DIV, (long long)(v), nullptr } namespace { @@ -74,6 +77,26 @@ static const RadOperandSpec oNan[] = { { "w_y", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +static const RadParamSpec pRoute[] = { + { "M", RAD_P_INT, RAD_REQUIRED, 0 }, + { "n", RAD_P_INT, RAD_REQUIRED, 0 }, + { "eps", RAD_P_F64, RAD_REQUIRED, 0 }, + { "dtype", RAD_P_STR, RAD_REQUIRED, 0 }, + { "mult", RAD_P_F64, RAD_REQUIRED, 0 }, + { "group", RAD_P_INT, RAD_REQUIRED, 0 }, +}; +static const RadOperandSpec oRoute[] = { + { "a", RAD_OPD_IN, 0 }, + { "w_a", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_INOUT, 0 }, + { "w_y", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, + { "w_r", RAD_OPD_WEIGHT, 0 }, + { "r", RAD_OPD_OUT, 0 }, + { "w_e", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "qs", RAD_OPD_OUT, 0 }, +}; static const RadOperandSpec oJas[] = { { "d", RAD_OPD_IN, 0 }, { "w_d", RAD_OPD_WEIGHT, 0 }, @@ -138,6 +161,11 @@ static const RadOpSchema kSchemas[] = { "t = rmsnorm(a) * w_a; x = x + t; y = rmsnorm(x) * w_y, over [M, n] rows; every value the " "unfused rmsnorm, add, rmsnorm chain stores is rounded to the activation dtype at the same " "point. A post-norm, the residual add and the next pre-norm (Gemma's sandwich)." }, + { "norm_add_norm_route", ROW(pRoute), ROW(oRoute), + "norm_add_norm, then from the same rmsnorm of the x it writes r = rmsnorm(x) * w_r * mult " + "and the E4M3 codes q of rmsnorm(x) * w_e with an f32 scale qs per (row, `group` columns): " + "rmsnorm_quant_fp8's codes, taken over the bf16-rounded norm. A MoE layer's router input and " + "its experts' fp8 input, written by the attention join that already holds the norm." }, { "join_add_scale", ROW(pJoin), ROW(oJas), "x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s, over [M, n] rows, s one " "element; and with w_n and y, y = rmsnorm(x) * w_n over the x written. Rounding where the " @@ -301,17 +329,36 @@ static bool hgain(const RadTensor* w, int64_t n) { return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n; } -int norm_add_norm_host(const RadArgs* a, RadStream) { - if (!a || a->n_t < 5) return RAD_E_INVAL; +/* [rows..., n] of `dt`, dense last axis, for the route form's fp8 codes and f32 scales */ +static bool hrows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != dt || t->rank < 1 || rad_tensor_lastdim(t) != n) return false; + if (t->stride[t->rank - 1] != 1) return false; + *rows = rad_tensor_rows(t); + *ld = rad_tensor_row_pitch(t); + return true; +} + +/* norm_add_norm, and with `route` norm_add_norm_route's three more outputs */ +static int nan_host(const RadArgs* a, bool route) { + if (!a || a->n_t < (route ? 10 : 5)) return RAD_E_INVAL; const int64_t n = rad_args_geti_or(a, "n", 0); const double eps = rad_args_getf_or(a, "eps", 1e-6); + const float mult = (float)rad_args_getf_or(a, "mult", 1.0); const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4); - if (n <= 0 || !A_ || !X || !Y) return RAD_E_INVAL; - if (!hgain(Wa, n) || !hgain(Wy, n)) return RAD_E_DTYPE; - int64_t ra, la, rx, lx, ry, ly; + const RadTensor *Wr = route ? rad_arg_in(a, 5) : nullptr, *R = route ? rad_arg_in(a, 6) : nullptr; + const RadTensor *We = route ? rad_arg_in(a, 7) : nullptr, *Q = route ? rad_arg_in(a, 8) : nullptr; + const RadTensor *S = route ? rad_arg_in(a, 9) : nullptr; + if (n <= 0 || !A_ || !X || !Y || (route && (!R || !Q || !S))) return RAD_E_INVAL; + if (route && (n % 128 || rad_args_geti_or(a, "group", 0) != 128)) return RAD_E_SHAPE; + if (!hgain(Wa, n) || !hgain(Wy, n) || (route && (!hgain(Wr, n) || !hgain(We, n)))) + return RAD_E_DTYPE; + int64_t ra, la, rx, lx, ry, ly, rr = 0, lr = 0, rq = 0, lq = 0, rs = 0, ls = 0; if (!hrows(A_, n, &ra, &la) || !hrows(X, n, &rx, &lx) || !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE; - if (ra < rx || ry < rx) return RAD_E_SHAPE; + if (route && (!hrows(R, n, &rr, &lr) || !hrows_as(Q, RAD_F8E4M3, n, &rq, &lq) || + !hrows_as(S, RAD_F32, n / 128, &rs, &ls))) + return RAD_E_SHAPE; + if (ra < rx || ry < rx || (route && (rr < rx || rq < rx || rs < rx))) return RAD_E_SHAPE; const float *wa = (const float*)Wa->data, *wy = (const float*)Wy->data; std::vector v((size_t)n), xv((size_t)n); for (int64_t m = 0; m < rx; ++m) { @@ -327,9 +374,33 @@ int norm_add_norm_host(const RadArgs* a, RadStream) { } const float sx = hnorm(xv.data(), n, eps); for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((xv[(size_t)i] * sx) * wy[i]); + if (!route) continue; + /* the router's row, and the experts' as rmsnorm_quant_fp8 writes it (v holds it) */ + const float *wr = (const float*)Wr->data, *we = (const float*)We->data; + uint16_t* rrow = (uint16_t*)R->data + m * lr; + uint8_t* qrow = (uint8_t*)Q->data + m * lq; + float* srow = (float*)S->data + m * ls; + for (int64_t i = 0; i < n; ++i) { + rrow[i] = hf2b(((xv[(size_t)i] * sx) * wr[i]) * mult); + v[(size_t)i] = hrbf((xv[(size_t)i] * sx) * we[i]); + } + for (int64_t g = 0; g < n / 128; ++g) { + float am = 0.0f; + for (int64_t i = g * 128; i < g * 128 + 128; ++i) + am = std::fmax(am, std::fabs(v[(size_t)i])); + const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f; + const float inv = 1.0f / sc; + srow[g] = sc; + for (int64_t i = g * 128; i < g * 128 + 128; ++i) { + const float c = std::fmin(std::fmax(v[(size_t)i] * inv, -448.0f), 448.0f); + qrow[i] = rad_f32_to_fp8e4m3(c); + } + } } return RAD_OK; } +int norm_add_norm_host(const RadArgs* a, RadStream) { return nan_host(a, false); } +int norm_add_norm_route_host(const RadArgs* a, RadStream) { return nan_host(a, true); } int join_add_scale_host(const RadArgs* a, RadStream) { if (!a || a->n_t < 7) return RAD_E_INVAL; @@ -431,6 +502,10 @@ G4K_ATTN_C(cH512x8B, 512, 8, "bf16", 0) G4K_ATTN_C(cH512x8F, 512, 8, "fp8_e4m3", /* the device kernels hold 24 elements a thread over a 256-thread block */ static const RadConstraint cJoin[] = { C_GE("n", 1), C_LE("n", 6144), C_IN("dtype", "bf16") }; static const RadConstraint cJoinHost[] = { C_GE("n", 1), C_IN("dtype", "bf16") }; +static const RadConstraint cRoute[] = { C_GE("n", 128), C_LE("n", 6144), C_DIV("n", 128), + C_EQ("group", 128), C_IN("dtype", "bf16") }; +static const RadConstraint cRouteHost[] = { C_GE("n", 128), C_DIV("n", 128), C_EQ("group", 128), + C_IN("dtype", "bf16") }; static const RadConstraint cPick[] = { C_GE("n", 1), C_IN("dtype", "f32 fp32") }; static const RadConstraint cEscale[] = { C_GE("top_k", 1), C_LE("top_k", 64), C_GE("n_expert", 1), C_IN("dtype", "bf16") }; @@ -490,6 +565,20 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_HOST, 10, ROW(cJoinHost), NOTUNE, nullptr, nullptr, norm_add_norm_host, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }, + { "norm_add_norm_route_bf16", "norm_add_norm_route", "norm", + "norm_add_norm, and the routed arm's router input and fp8 expert input from the same norm", + "n <= 6144 in whole 128-column groups, any M, row pitches honoured", + "bf16 activations, f32 gains; E4M3 codes with an f32 scale a 128 columns", + RAD_DOMAIN_DEVICE, 10, ROW(cRoute), NOTUNE, + nullptr, nullptr, g4k_norm_add_norm_route_bf16, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "norm_add_norm_route_bf16_host", "norm_add_norm_route", "norm", + "norm_add_norm, and the routed arm's router input and fp8 expert input from the same norm", + "any [M, n] in whole 128-column groups", + "bf16 activations, f32 gains; E4M3 codes with an f32 scale a 128 columns", + RAD_DOMAIN_HOST, 10, ROW(cRouteHost), NOTUNE, + nullptr, nullptr, norm_add_norm_route_host, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, { "join_add_scale_bf16", "join_add_scale", "norm", "two arms' post-norms, sum, norm, residual add, layer scalar: one block a row", "n <= 6144, any M, row pitches honoured", "bf16 activations, f32 gains, bf16 scalar", diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 4a01dd66..2ab1ac44 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -4058,3 +4058,63 @@ TEST(a_gemma4_prefill_chunk_runs_as_two_slices_with_its_reductions_on_the_second CHECK(c.joins.empty()); for (const auto& i : c.issues) CHECK_EQ(i.lane, 0); } + +/* THE ATTENTION JOIN WRITES THE ROUTED ARM'S INPUTS on a layer whose gate_up is block fp8 + * (gemma4k norm_add_norm_route): the router's norm into moe_rn and the experts' codes into + * moe_hq / moe_hqs, so a step issues neither the router's rmsnorm nor rmsnorm_quant_fp8. Refused, + * norm_add_norm and the two launches. A tp-4 prefill through the overlap keeps every reduction + * ordered with the route form too. */ +TEST(gemma4_attention_join_writes_the_routed_inputs_on_fp8_experts) { + const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); + std::map issued[2]; + for (int refuse = 0; refuse < 2; ++refuse) { + RadBuilder b; + b.encs = { { "ffn_gate_up_exps", fp8 } }; + if (refuse) b.refuse.insert("norm_add_norm_route"); + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + CHECK_EQ(count_resolved(b, "norm_add_norm_route"), refuse ? 0 : 6); + CHECK_EQ(count_resolved(b, "norm_add_norm"), refuse ? 6 : 0); + CHECK(noted(b, refuse ? "routed inputs: 0 of 6" : "routed inputs: 6 of 6")); + if (!refuse) { + const RecOp* r = find_op(b, "norm_add_norm_route"); + REQUIRE(r != nullptr); + for (const char* name : { "moe_rn", "moe_hq", "moe_hqs", "x", "h" }) + CHECK(std::count(r->writes.begin(), r->writes.end(), + (rad_buf)buf_named(b, name)) == 1); + } + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + for (const auto& n : issued_ops(b, c)) ++issued[refuse][n]; + } + CHECK_EQ(issued[0]["norm_add_norm_route"], 6); + CHECK_EQ(issued[0]["norm_add_norm"], 0); + CHECK_EQ(issued[0]["rmsnorm_quant_fp8"], 0); + CHECK_EQ(issued[1]["norm_add_norm_route"], 0); + CHECK_EQ(issued[1]["norm_add_norm"], 6); + CHECK_EQ(issued[1]["rmsnorm_quant_fp8"], 6); + CHECK_EQ(issued[1]["rmsnorm"] - issued[0]["rmsnorm"], 6); /* the router's input norm */ + CHECK_EQ(issued[0]["moe_gemm_q"], 6); + + /* tp 4, an 8192-token chunk in two slices */ + RadBuilder b; + b.encs = { { "ffn_gate_up_exps", fp8 } }; + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(0, 4); + ctx.max_tok = 8192; + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + CHECK(noted(b, "prefill overlap: a chunk of two routed passes")); + const int32_t out[1] = { 8191 }; + RadBatch batch = one_prompt(8192, out); + RadCtx c; c.b = &b; c.rank = 0; c.world = 4; c.batch = &batch; + gemma4::step(&c, &batch); + CHECK(c.step_fail.empty()); + CHECK_EQ(races(b, c), 0); + CHECK_EQ(count_issued(issued_ops(b, c), "norm_add_norm_route"), 12); + CHECK_EQ(count_issued(issued_ops(b, c), "rmsnorm_quant_fp8"), 0); +} diff --git a/tests/g4k_emu/emu/emu.cpp b/tests/g4k_emu/emu/emu.cpp index f3f70c19..f35435a3 100644 --- a/tests/g4k_emu/emu/emu.cpp +++ b/tests/g4k_emu/emu/emu.cpp @@ -1,4 +1,5 @@ #include "hip/hip_runtime.h" +#include "rad_plugin.h" #include #include @@ -102,6 +103,11 @@ int emu_bpermute(int addr, int v) { return S.slot[w][par][(addr >> 2) & 31]; } int emu_readlane(int v, int lane) { return emu_bpermute(lane << 2, v); } +int emu_cvt_pk_fp8(float a, float b, int old, bool hi) { + const unsigned pk = (unsigned)rad_f32_to_fp8e4m3(a) | ((unsigned)rad_f32_to_fp8e4m3(b) << 8); + const unsigned o = (unsigned)old; + return (int)(hi ? ((o & 0xffffu) | (pk << 16)) : ((o & 0xffff0000u) | pk)); +} static short g_wa[64][2][32][8], g_wb[64][2][32][8]; emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c) { const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31; diff --git a/tests/g4k_emu/emu/hip/hip_runtime.h b/tests/g4k_emu/emu/hip/hip_runtime.h index d17a081f..af77b8d6 100644 --- a/tests/g4k_emu/emu/hip/hip_runtime.h +++ b/tests/g4k_emu/emu/hip/hip_runtime.h @@ -45,6 +45,11 @@ emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c); typedef _Float16 emu_v8h __attribute__((ext_vector_type(8))); emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c); #define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c)) +/* v_cvt_pk_fp8_f32 (gfx12, OCP E4M3): a and b as two codes into the low half of `old` (hi false) + * or its high half, the other half kept; round to nearest even. The project's saturating encoder, + * rad_f32_to_fp8e4m3, is the same function on the +-448 a kernel clamps to first. */ +int emu_cvt_pk_fp8(float a, float b, int old, bool hi); +#define __builtin_amdgcn_cvt_pk_fp8_f32(a, b, old, hi) emu_cvt_pk_fp8((a), (b), (old), (hi)) extern int emu_last_block; /* threads a block of the last grid had: which kernel ran */ struct alignas(8) uint2 { unsigned x, y; }; diff --git a/tests/g4k_emu/test_norm.cpp b/tests/g4k_emu/test_norm.cpp index 38f1598a..c63a1397 100644 --- a/tests/g4k_emu/test_norm.cpp +++ b/tests/g4k_emu/test_norm.cpp @@ -6,7 +6,9 @@ * BIT, which is the claim that fusing changes nothing but the launch count. The HOST ARM sums in * index order -- what a different libr4d block width does too -- and may differ by a flipped * rounding, measured against the row's scale (see cmp). Padding columns and rows past M must be - * left alone. */ + * left alone. The route form's chain adds the router's rmsnorm (with its mult) and libr4d's + * rmsnorm_quant_fp8 of the experts' norm -- amax * (1 / 448) a group, the clamped value encoded by + * the emulator's v_cvt_pk_fp8_f32, the saturating encoder every fp8 cast here uses. */ #include "rad_abi.h" #include "rad_plugin.h" #include "g4k.h" @@ -135,6 +137,87 @@ static int case_nan(int M, int n, int pad, int extra_rows) { return ok ? 0 : 1; } +/* norm_add_norm_route: norm_add_norm, then the router's row r = norm(x) * w_r * mult and the experts' + * E4M3 codes q and scales qs of norm(x) * w_e. `zero_group`: w_e zero over the second 128 columns, + * so that group's amax is 0 and its scale the quantiser's 1. */ +static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = false) { + const int ld = n + pad, R = M + extra_rows, G = n / 128, ldq = n + pad, lds = G + 3; + const float eps = 1e-6f, mult = 1.0f / std::sqrt((float)n); + auto a = randb((size_t)R * ld, 3.f), x = randb((size_t)R * ld, 1.f), y0 = randb((size_t)R * ld, 1.f); + auto r0 = randb((size_t)R * ld, 1.f); + auto wa = gains(n), wy = gains(n), wr = gains(n), we = gains(n); + if (zero_group && n >= 256) for (int i = 128; i < 256; ++i) we[(size_t)i] = 0.0f; + std::vector q0((size_t)R * ldq); + std::vector s0((size_t)R * lds); + for (auto& v : q0) v = (uint8_t)(rng() & 0xff); + for (auto& v : s0) v = -7.0f; + auto xd = x, yd = y0, rd = r0, xh = x, yh = y0, rh = r0; + auto qd = q0, qh = q0; + auto sd = s0, sh = s0; + RadTensor t[10] = { rows(a.data(), RAD_BF16, M, n, ld), vec(wa.data(), RAD_F32, n), + rows(xd.data(), RAD_BF16, M, n, ld), vec(wy.data(), RAD_F32, n), + rows(yd.data(), RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n), + rows(rd.data(), RAD_BF16, M, n, ld), vec(we.data(), RAD_F32, n), + rows(qd.data(), RAD_F8E4M3, M, n, ldq), rows(sd.data(), RAD_F32, M, G, lds) }; + RadParam p[6]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n}; + p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16"; + p[4].key = "mult"; p[4].kind = RAD_P_F64; p[4].dval = mult; p[5] = {"group", RAD_P_INT, 128}; + RadArgs ar{}; ar.t = t; ar.n_t = 10; ar.p = p; ar.n_p = 6; + if (g4k_norm_add_norm_route_bf16(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm_route: device launch failed"); return 1; } + t[2].data = xh.data(); t[4].data = yh.data(); t[6].data = rh.data(); t[8].data = qh.data(); t[9].data = sh.data(); + if (host_row("norm_add_norm_route")->launch(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm_route: host launch failed"); return 1; } + Tally tx, ty, tr; + long q_chain = 0, s_chain = 0, q_host_bad = 0, touched = 0; + for (int m = 0; m < R; ++m) { + const size_t o = (size_t)m * ld, oq = (size_t)m * ldq, os = (size_t)m * lds; + if (m >= M) { + for (int i = 0; i < ld; ++i) touched += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]) + (rd[o + i] != r0[o + i]); + for (int i = 0; i < ldq; ++i) touched += qd[oq + i] != q0[oq + i]; + for (int i = 0; i < lds; ++i) touched += sd[os + i] != s0[os + i]; + continue; + } + for (int i = n; i < ld; ++i) touched += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]) + (rd[o + i] != r0[o + i]); + for (int i = n; i < ldq; ++i) touched += qd[oq + i] != q0[oq + i]; + for (int i = G; i < lds; ++i) touched += sd[os + i] != s0[os + i]; + std::vector av((size_t)n), xv((size_t)n); + for (int i = 0; i < n; ++i) av[(size_t)i] = b2f(a[o + i]); + const auto t1 = chain_norm(av, wa.data(), n, eps); /* rmsnorm */ + std::vector cx((size_t)n), cy((size_t)n), cr((size_t)n); + for (int i = 0; i < n; ++i) { xv[(size_t)i] = rb(b2f(x[o + i]) + t1[(size_t)i]); cx[(size_t)i] = f2b(xv[(size_t)i]); } /* add */ + const float f = block_factor(xv, n, eps); + for (int i = 0; i < n; ++i) { + cy[(size_t)i] = f2b((xv[(size_t)i] * f) * wy[(size_t)i]); /* rmsnorm */ + cr[(size_t)i] = f2b(((xv[(size_t)i] * f) * wr[(size_t)i]) * mult); /* the router's */ + } + cmp(&xd[o], cx.data(), &xh[o], n, tx); + cmp(&yd[o], cy.data(), &yh[o], n, ty); + cmp(&rd[o], cr.data(), &rh[o], n, tr); + for (int g = 0; g < G; ++g) { /* rmsnorm_quant_fp8 */ + float h[128], am = 0.0f; + for (int j = 0; j < 128; ++j) { h[j] = rb((xv[(size_t)(g * 128 + j)] * f) * we[(size_t)(g * 128 + j)]); am = std::fmax(am, std::fabs(h[j])); } + const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f, inv = 1.0f / sc; + s_chain += sd[os + g] != sc; + if (zero_group && g == 1 && sd[os + g] != 1.0f) ++s_chain; + for (int j = 0; j < 128; ++j) { + const int i = g * 128 + j; + q_chain += qd[oq + i] != rad_f32_to_fp8e4m3(std::fmin(std::fmax(h[j] * inv, -448.0f), 448.0f)); + /* vs the host arm: one code step is an eighth of its value at most, which is no + * more than an eighth of the group's amax; a scale an ulp off moves less */ + const double dv = std::fabs((double)rad_fp8e4m3_to_f32(qd[oq + i]) * sd[os + g] - + (double)rad_fp8e4m3_to_f32(qh[oq + i]) * sh[os + g]); + if (dv > (double)am / 8 + 1e-30) ++q_host_bad; + } + } + } + const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tr.chain_bad == 0 && q_chain == 0 && s_chain == 0 && + tx.host_bad == 0 && ty.host_bad == 0 && tr.host_bad == 0 && q_host_bad == 0 && touched == 0; + std::printf("norm_add_norm_route M %3d n %4d pitch %4d%s: vs chain x %ld y %ld r %ld q %ld scale %ld differ; vs host " + "arm %ld/%ld/%ld differ, %ld codes past a step; padding touched %ld -> %s\n", M, n, ld, + zero_group ? " (a zero group)" : "", tx.chain_bad, ty.chain_bad, tr.chain_bad, q_chain, s_chain, + tx.host_diff, ty.host_diff, tr.host_diff, q_host_bad, touched, ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} + /* `next`: also the next layer's input norm, y = norm(x) * w_n over the x the join writes */ static int case_jas(int M, int n, int pad, int extra_rows, bool next = false) { const int ld = n + pad, R = M + extra_rows; @@ -200,6 +283,11 @@ int main() { /* and with the next layer's input norm folded in */ for (int M : Ms) fails += case_jas(M, 2816, M % 2 ? 64 : 0, 2, true); fails += case_jas(3, 1000, 24, 1, true) + case_jas(2, 6144, 16, 0, true); + /* the route form: the 26B-A4B's width at decode, verify and prefill heights, the edge between the + * 12- and 24-a-thread kernels, one group, the limit, and a group whose norm is all zero */ + for (int M : Ms) fails += case_route(M, 2816, M % 2 ? 64 : 0, 2); + fails += case_route(2, 3072, 0, 1) + case_route(2, 3200, 16, 1) + case_route(3, 128, 8, 1); + fails += case_route(2, 6144, 0, 0) + case_route(4, 2816, 0, 1, true); std::printf("norm joins: %d failure(s)\n", fails); return fails ? 1 : 0; } From c5278632485e7000becf2b40063f4c0c339fe7e4 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Mon, 12 Oct 2026 10:28:43 -0500 Subject: [PATCH 24/24] arch/gemma4: the dense arm on the second lane beside the routed arm, in a step that runs whole The two feed-forward arms of a Gemma 4 MoE layer read the same normed residual and meet only at the feed-forward join; issued one after the other, the dense arm's three launches -- gate_up, act_mul, down, ~36 us under --profile-ops at a 26B-A4B decode step on 4x R9700 -- wait behind the routed arm's ~120 every layer. At a few rows its GEMMs are latency-bound, nowhere near the bandwidth the experts' GEMMs take. In a step that runs whole -- every decode and verify step, and a prefill chunk too short to cut -- the dense arm now rides the second lane: issued behind a join from lane 0 (the attention join is its producer), beside the routed arm on lane 0, and joined back before the feed-forward reduction reads both. Its rows of the join buffer and the routed arm's are disjoint. No collective rides it, so the reductions keep lane 0 here and lane 1 in a cut prefill chunk, and a step's collectives are on one lane as before. h, gate_up, ffn and ff2 are named to rad_buf_concurrent. Off with the overlap's switch, RADIANCE_GEMMA4_OVERLAP=0, which now keeps every step on one stream; a startup note says which. arch_test: a decode step issues the dense arm's three launches a layer on lane 1 and every all-reduce on lane 0, two joins a layer, and nothing on the two lanes that touches a common element unordered; a 4095-token chunk the same; the cut chunks keep lane 1 for their reductions alone. GUIDE.md's switch and ARCHITECTURES.md say so. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 35 +++++++++++++++++++++++++++++------ docs/ARCHITECTURES.md | 7 +++++-- docs/GUIDE.md | 2 +- tests/arch_test.cpp | 40 +++++++++++++++++++++++++++++----------- 4 files changed, 64 insertions(+), 20 deletions(-) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index 7dba1b8f..be3af261 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -273,6 +273,9 @@ struct Model { /* A prefill chunk of 2 * moe_rows tokens or more runs as two slices, the trunk's all-reduces * on the second lane beside the other slice's compute (trunk_overlap). Set at declare. */ bool overlap = false; + /* In a step that runs whole -- every decode and verify step -- the dense arm rides the second + * lane beside the routed arm (trunk). Set at declare. */ + bool arms = false; double escale = 1.0, softcap = 0.0; rad_buf b_x = 0, b_h = 0, b_o = 0; @@ -1481,10 +1484,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c for (const Layer& y : m.layers) m.overlap = m.overlap && (y.op_join_a || y.op_join_r) && y.op_join_f && y.next_norm && y.op_ar_o && y.op_ar_f; - if (m.overlap) { - RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o)); - RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2)); - } + /* ---- THE TWO ARMS SIDE BY SIDE (trunk), in a step that runs whole: the dense arm on the + * second lane beside the routed arm, which needs nothing of it until the feed-forward join. At a + * decode step on 4x R9700 the dense arm is three launches, ~36 us under --profile-ops, behind + * the routed arm's ~120 in a layer, and its GEMMs at a few rows are latency-bound -- far from + * the bandwidth the experts take. No collective rides it, so the reductions keep lane 0. Off + * with the overlap's switch. The buffers the dense arm touches leave the arena's sharing. */ + m.arms = m.moe && !ov_off; + if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o)); + if (m.overlap || m.arms) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2)); + if (m.arms) + for (rad_buf bb : { m.b_h, m.b_gu, m.b_act }) RAD_ARCH_TRY(rad_buf_concurrent(b, bb)); if (m.layers.empty() || !m.layers.back().next_norm) m.op_onorm = rmsnorm(T, E, m.w_onorm, 1.0, m.b_x, m.b_h); @@ -1563,6 +1573,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c : !g.wire_exact ? "off (the lossy all-reduce wire)" : T < 2 * m.moe_rows ? "off (a step holds fewer than two routed passes)" : "off (the sandwich joins are not fused)"); + rad_note(b, "the two arms: %s", m.arms + ? "in a step that runs whole, the dense arm on a second stream beside the " + "routed" + : "one after the other (RADIANCE_GEMMA4_OVERLAP=0)"); } if (m.kf.rot_pairs < m.kf.hd / 2) rad_note(b, "full layers: PROPORTIONAL rope -- %lld of %lld frequency pairs rotate at " @@ -1712,9 +1726,10 @@ static void attend(RadCtx* c, const Model& m, const Layer& y, size_t li, const R } } -/* The trunk over the whole step. */ +/* The trunk over the whole step, the dense arm beside the routed one where the model says so. */ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) { const int64_t T = batch->n_tok, E = m.E; + bool lanes_ok = true; for (size_t li = 0; li < m.layers.size(); ++li) { const Layer& y = m.layers[li]; if (y.op_anorm) RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); @@ -1740,13 +1755,18 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) { RAD_ISSUE(c, y.op_fnorm, brows(m.b_x, T), RAD_W(y.w_fnorm), brows(m.b_h, T)); } - /* dense arm -> rows [0, T) of the join */ + /* dense arm -> rows [0, T) of the join: on lane 1 behind the attention join, where the arms + * run side by side, and lane 0 joins it back before the reduction reads them */ + if (m.arms) + lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK; RAD_ISSUE(c, y.op_gu, brows(m.b_h, T), RAD_W(y.w_gu), brows(m.b_gu, T)); RAD_ISSUE(c, y.op_act, bcol(m.b_gu, 0, m.n_ff, T), bcol(m.b_gu, m.n_ff, m.n_ff, T), brows(m.b_act, T)); RAD_ISSUE(c, y.op_dn, brows(m.b_act, T), RAD_W(y.w_dn), brows(m.b_ff2, T)); + if (m.arms) lanes_ok = rad_lane(c, 0) == RAD_OK && lanes_ok; if (m.moe) { routed(c, m, y, T, 0, T, T); + if (m.arms) lanes_ok = rad_lane_join(c, 1, 0) == RAD_OK && lanes_ok; if (y.op_ar_f) RAD_ISSUE_N(c, y.op_ar_f, 2 * T * E, brows(m.b_ff2, 2 * T), RAD_NONE); if (y.op_join_f) { RAD_ISSUE(c, y.op_join_f, brows(m.b_ff2, T), RAD_W(y.w_fpost1), @@ -1776,6 +1796,9 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) { bcol(m.b_dfsrc, (int64_t)t * E, E, T)); } } + if (!lanes_ok) + rad_step_fail(c, "gemma4: the dense arm's second lane could not be ordered against the " + "first (RADIANCE_GEMMA4_OVERLAP=0 keeps one)"); } /* ============================================================== the prefill overlap */ diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 21daa5d8..ff7c5cab 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -520,8 +520,11 @@ are above every row band the sliced kernels have, so the step issues the same ke same rows and its output is the whole step's, bit for bit. On 4x R9700 the reductions were 47% of a 20K-token prefill under `--profile-ops`; a model of the measured times puts the overlap at up to a quarter off an unprofiled prefill. The per-op profile syncs every op, so it cannot show it -- -time a prefill without `--profile-ops`. `RADIANCE_GEMMA4_OVERLAP=0` runs every chunk whole, and the -startup note says which. A decode step never takes the second lane. +time a prefill without `--profile-ops`. A step that runs whole -- every decode and verify step -- +takes the second lane for the dense arm instead, beside the routed arm, which needs nothing of it +until the feed-forward join: at decode the dense arm's GEMMs are a few rows, latency-bound and far +from the bandwidth the experts take, and its reductions stay on lane 0. `RADIANCE_GEMMA4_OVERLAP=0` +keeps every step on one stream, and the startup notes say which. **The draft head in fp8.** The drafter's head is the widest read on the draft path: the target's bf16 table, 352 MiB a rank at tp 4, every draft pass. A container converted with the line diff --git a/docs/GUIDE.md b/docs/GUIDE.md index cc9b1ba9..1fee7b8a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1860,7 +1860,7 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct at al | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_G4K_WMMA` | `0` keeps `gemma4k`'s prefill attention on its scalar kernel instead of the WMMA one. An A/B switch and a way out if the matrix path misbehaves on a card; read once | | `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the chains instead of `gemma4k`'s fusions: the rmsnorm / add chain for the sandwich joins (`norm_add_norm`, `norm_add_norm_route`, `join_add_scale`), `embed_lookup` + `mul` for `expert_scale`, and a `cast` lifting q for `attn_paged` for `attn_paged_qrow`. An A/B switch; read at declare | -| `RADIANCE_GEMMA4_OVERLAP` | `0` runs every `arch/gemma4` prefill chunk whole, its all-reduces on the compute stream, instead of as two slices whose all-reduces ride a second stream beside the other slice's compute. An A/B switch; read at declare | +| `RADIANCE_GEMMA4_OVERLAP` | `0` keeps every `arch/gemma4` step on one stream: a prefill chunk runs whole, its all-reduces on the compute stream, instead of as two slices whose all-reduces ride a second stream beside the other slice's compute; and a decode step runs the dense arm after the routed arm instead of beside it. An A/B switch; read at declare | There is also a family of instruments for engine development — `RADIANCE_DEBUG_*` (residual probes, idle scrubs, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 2ab1ac44..a1f0adf9 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3972,8 +3972,9 @@ bool noted(const RadBuilder& b, const char* text) { * order and the work: every reduction rides lane 1 behind its producer and ahead of its consumer, * nothing else does, the cut is a whole number of routed passes, and the slices issue exactly the * rows the whole step issues -- the same routed passes, the drafter's taps -- which is what makes - * the output the whole step's. A chunk under two passes, and a decode step, run whole on one - * lane. */ + * the output the whole step's. A chunk under two passes, and a decode step, run whole: their + * reductions on lane 0 and the dense arm on lane 1 beside the routed arm (trunk), with nothing + * unordered either. */ TEST(a_gemma4_prefill_chunk_runs_as_two_slices_with_its_reductions_on_the_second_lane) { const std::vector keys = g4df_keys(), vals = g4df_vals(); const int64_t E = 2816, L = 6; @@ -4002,8 +4003,8 @@ TEST(a_gemma4_prefill_chunk_runs_as_two_slices_with_its_reductions_on_the_second RadBuilder b; CHECK_OK(model(b, false)); CHECK(noted(b, "prefill overlap: a chunk of two routed passes")); - CHECK_EQ((int)b.concurrent.size(), 2); - for (const char* name : { "o", "ff2" }) + CHECK_EQ((int)b.concurrent.size(), 5); + for (const char* name : { "o", "ff2", "h", "gate_up", "ffn" }) CHECK(std::count(b.concurrent.begin(), b.concurrent.end(), (rad_buf)buf_named(b, name)) == 1); RadBatch batch = one_prompt(k.T, out); @@ -4013,17 +4014,20 @@ TEST(a_gemma4_prefill_chunk_runs_as_two_slices_with_its_reductions_on_the_second CHECK_EQ(c.lane, 0); CHECK_EQ(races(b, c), 0); - std::vector lane1; + std::vector lane1; /* the reductions on lane 1 */ + int dense1 = 0; /* and the dense arm's launches */ for (const auto& i : c.issues) { if (i.lane != 1) continue; const RecOp* o = b.op_of(i.op); - CHECK(o && o->op == "all_reduce"); - lane1.push_back(i.n); + REQUIRE(o != nullptr); + if (o->op == "all_reduce") lane1.push_back(i.n); + else ++dense1; } if (k.cut == 0) { CHECK(lane1.empty()); - CHECK(c.joins.empty()); + CHECK_EQ(dense1, 3 * (int)L); /* gate_up, act_mul, down: beside the routed arm */ } else { + CHECK_EQ(dense1, 0); REQUIRE(lane1.size() == (size_t)(4 * L)); for (int64_t l = 0; l < L; ++l) { CHECK_EQ(lane1[4 * l + 0], k.cut * E); /* attention, slice A */ @@ -4048,15 +4052,29 @@ TEST(a_gemma4_prefill_chunk_runs_as_two_slices_with_its_reductions_on_the_second CHECK_EQ((int)ns_of(b, c, "cast").size(), k.cut ? 6 : 3); /* three taps, a slice each */ } - /* A decode step never leaves lane 0. */ + /* A decode step: the reductions on lane 0, the dense arm on lane 1 joined in before the + * feed-forward's, nothing unordered. */ RadBuilder b; CHECK_OK(model(b, false)); + CHECK(noted(b, "the two arms: in a step that runs whole")); RadBatch d = decode_batch(); RadCtx c; run(b, c, d); CHECK(c.step_fail.empty()); - CHECK(c.joins.empty()); - for (const auto& i : c.issues) CHECK_EQ(i.lane, 0); + CHECK_EQ(c.lane, 0); + CHECK_EQ(races(b, c), 0); + int dense1 = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + REQUIRE(o != nullptr); + if (o->op == "all_reduce") CHECK_EQ(i.lane, 0); + if (i.lane == 1) { + ++dense1; + CHECK(o->op == "gemm_nt" || o->op == "act_mul"); + } + } + CHECK_EQ(dense1, 3 * (int)L); + CHECK_EQ((int)c.joins.size(), 2 * (int)L); } /* THE ATTENTION JOIN WRITES THE ROUTED ARM'S INPUTS on a layer whose gate_up is block fp8