From 015cba8837dc2618cdb5782ad295ee568dd8cfd6 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 14:54:47 -0500 Subject: [PATCH] libr4d, arch: the 31B and DFlash2 with fewer launches a step, same bytes Attention reads q and the gqa-8 drafter's KV in place (attn_paged_qrow); the 31B's attention prologue stores k and v itself (qkv_norm_rope_kv_store); DFlash2's norm/rope/cache-store chains and add-then-norm pairs run as one launch each. Carries the launch-cliff padding until that PR merges. Squashed from: - libr4d: attn_paged_qrow on the split-KV decode kernel -- h256/gqa2, and h128/gqa8 by two groups a kv head - arch: the 31B's sliding layers and its drafter read through attn_paged_qrow where a card serves it - libr4d: step past the full-card launch cliff in qkv_norm_rope and the row norms - libr4d: qkv_norm_rope describes its operands, so rad-kbench and rad-tune can time it - libr4d, arch/gemma4_bf16: qkv_norm_rope_kv_store -- the 31B's prologue stores k and v itself - libr4d, arch/common: qkv_norm_rope takes v_norm; DFlash2's query pass folds its q/k chain - libr4d, arch/common: qkv_norm_rope takes n_head 0; DFlash2's context pass folds its key chain - libr4d, arch/common: add_rmsnorm; DFlash2 issues each residual add with the norm after it Co-Authored-By: Claude Opus 5.5 --- arch/common/rad_block_dflash2.h | 139 ++++++++++++++++-- arch/common/rad_gemma4_dflash.h | 49 ++++++- arch/gemma4_bf16/gemma4_bf16.cpp | 114 ++++++++++----- docs/ARCHITECTURES.md | 23 ++- docs/OPS.md | 32 ++++- libr4d/r4d.h | 20 +++ libr4d/r4d_attn_args.h | 24 +++- libr4d/r4d_attn_decode_h256_gqa6.hip | 37 +++-- libr4d/r4d_attn_paged_gqa8.hip | 2 +- libr4d/r4d_attn_paged_h128_gqa4.hip | 8 ++ libr4d/r4d_attn_paged_h256_gqa2.hip | 8 ++ libr4d/r4d_attn_paged_h256_gqa6.hip | 62 +++++++- libr4d/r4d_fuse.cpp | 65 +++++++++ libr4d/r4d_model_bf16.hip | 79 +++++++++++ libr4d/r4d_plugin.h | 15 ++ libr4d/r4d_qkv_norm_rope.hip | 194 +++++++++++++++++++++---- libr4d/r4d_rows.cpp | 166 +++++++++++++++++++++- libr4d/r4d_selftest.cpp | 202 +++++++++++++++++++++++++-- libr4d/r4d_shapes.cpp | 56 ++++++++ tests/arch_test.cpp | 201 ++++++++++++++++++++------ 20 files changed, 1332 insertions(+), 164 deletions(-) diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h index 800f5790..823940f7 100644 --- a/arch/common/rad_block_dflash2.h +++ b/arch/common/rad_block_dflash2.h @@ -233,6 +233,9 @@ struct Dflash2 { rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0; rad_op op_cgath = 0; /* the split fc's all-gather */ rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; + /* The k norm, the k rotary and the cache store as one launch a layer (qkv_norm_rope_kv_store + * with n_head 0 and v_norm 0), issued in place of those three where it resolves. */ + rad_op op_cqkr[MAX_LAYERS] = {}; /* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration * serves every layer; ops with weights are per layer because a weight's prefetch interval @@ -248,11 +251,19 @@ struct Dflash2 { rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; rad_op op_op[MAX_LAYERS] = {}; rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}; + /* The q and k norms, both rotaries and the cache store as one launch a layer + * (qkv_norm_rope_kv_store with v_norm 0), issued in place of those five where it resolves. */ + rad_op op_qkr[MAX_LAYERS] = {}; rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */ rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {}; rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0; rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; + /* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and + * that norm where it resolves: op_afn[i] after layer i's attention (its feed-forward norm), + * op_aan[i] after layer i-1's feed-forward (layer i's attention norm, i >= 1), op_afinal after + * the last layer's (the final norm). All or none. */ + rad_op op_afn[MAX_LAYERS] = {}, op_aan[MAX_LAYERS] = {}, op_afinal = 0; /* head and selector */ rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0; @@ -684,6 +695,62 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_STR("kv_dtype", g.kv_dtype)), RAD_NOWEIGHTS), {w.k, w.v}, {}); + /* The query pass's q/k norms, rotaries and store as one launch a layer where a library + * serves it: qkv_norm_rope_kv_store with v_norm 0 (v stored as it is), byte-identical to the + * two rmsnorms, the two ropes and kv_store (docs/OPS.md), which stay declared beside it for + * a library that does not. No YaRN (the fold takes none). */ + { + /* Only for a shape a library serves: an op declared for one that resolves to no device + * kernel is a hole that refuses startup (Program::device_holes), whether or not it is + * issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in + * steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim + * 128) keeps the chain. */ + const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 && + !std::strcmp(g.dtype, "bf16") && + (!std::strcmp(g.kv_dtype, "fp8_e4m3") || + !std::strcmp(g.kv_dtype, "bf16")); + if (fold_shape && g.yarn.factor == 0.0f && + rad_op_declared(b, "qkv_norm_rope_kv_store")) { + const int64_t bsz = rad_kv_block_size(b, kv); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_qkr[i] = RAD_OP(b, "qkv_norm_rope_kv_store", + 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", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"), + RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype), + RAD_INT("v_norm", 0), RAD_INT("block_size", bsz), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_WEIGHTS(w_qn[i], w_kn[i])); + if (!op_qkr[i] || !rad_op_resolved(b, op_qkr[i])) { + for (int j = 0; j <= i; ++j) op_qkr[j] = 0; + break; + } + op_qkr[i] = rw(b, op_qkr[i], {w.q, w.k, w.v}, {w.q, w.k, w.v}); + } + /* The context pass's keys the same way: no q (n_head 0, `q` passed as k's buffer and + * `q_w` as k's norm, neither read), the context rows' slots. */ + for (int64_t l = 0; op_qkr[0] && l < g.n_layer; ++l) { + const int i = (int)l; + op_cqkr[i] = RAD_OP(b, "qkv_norm_rope_kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", 0), RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"), + RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype), + RAD_INT("v_norm", 0), RAD_INT("block_size", bsz), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_WEIGHTS(w_kn[i], w_kn[i])); + if (!op_cqkr[i] || !rad_op_resolved(b, op_cqkr[i])) { + for (int j = 0; j <= i; ++j) op_cqkr[j] = 0; + break; + } + op_cqkr[i] = rw(b, op_cqkr[i], {w.ck, w.cv}, {w.ck}); + } + } + } 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)), @@ -708,6 +775,30 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_norm)), {w.x}, {w.h}); + /* Each residual add and the norm after it as one launch where a library serves add_rmsnorm + * (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only + * where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run + * otherwise. */ + if (rad_op_declared(b, "add_rmsnorm")) { + auto an = [&](rad_weight wt) -> rad_op { + const rad_op h = RAD_OP(b, "add_rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(wt)); + return h && rad_op_resolved(b, h) ? rw(b, h, {w.x, w.h2}, {w.x, w.h}) : (rad_op)0; + }; + bool all = true; + for (int64_t l = 0; all && l < g.n_layer; ++l) { + const int i = (int)l; + op_afn[i] = an(w_fnorm[i]); + if (l > 0) op_aan[i] = an(w_anorm[i]); + all = op_afn[i] && (l == 0 || op_aan[i]); + } + op_afinal = all ? an(w_norm) : 0; + if (!op_afinal) + for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0; + } /* ---------------------------------------------------------------- the head and the selector * @@ -839,6 +930,12 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const { 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()); + if (op_cqkr[i]) { + RAD_ISSUE_N(c, op_cqkr[i], T, brows(w.ck, T), brows(w.ck, T), brows(w.cv, T), + praw(batch->positions, RAD_I32, T), RAD_W(w_kn[i]), RAD_W(w_kn[i]), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + continue; + } 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)); @@ -864,11 +961,23 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE); + /* x += h2 waits for the norm after it, which takes it in (add_rmsnorm) where declared */ + bool add_pending = false; + auto norm = [&](rad_op plain, rad_op folded, rad_weight wt) { + if (add_pending && folded) { + RAD_ISSUE_N(c, folded, T, brows(w.x, T), brows(w.h2, T), RAD_W(wt), brows(w.h, T)); + } else { + if (add_pending) RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T)); + RAD_ISSUE_N(c, plain, T, brows(w.x, T), RAD_W(wt), brows(w.h, T)); + } + add_pending = false; + }; + for (int64_t l = 0; l < g.n_layer; ++l) { const int i = (int)l; /* ---- attention, wrapped in the two halves of one convolution */ - RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); + norm(op_anorm[i], op_aan[i], w_anorm[i]); RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T)); RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T), wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T)); @@ -880,13 +989,19 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { 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.h2q, T), brows(w.h2s, 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)); + if (op_qkr[i]) { + RAD_ISSUE_N(c, op_qkr[i], T, brows(w.q, T), brows(w.k, T), brows(w.v, T), + praw(batch->positions, RAD_I32, T), RAD_W(w_qn[i]), RAD_W(w_kn[i]), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + } else { + 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), @@ -903,10 +1018,10 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T), wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T)); - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T)); + add_pending = true; /* ---- the feed-forward, wrapped in the other convolution */ - RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); + norm(op_fnorm[i], op_afn[i], w_fnorm[i]); RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T)); RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T), wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T)); @@ -926,10 +1041,10 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T), wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T)); - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T)); + add_pending = true; } - RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + norm(op_final, op_afinal, w_norm); /* The predicting rows, `steps` per sequence, named by the scheduler through out_ids. */ const int64_t S = batch->n_out; diff --git a/arch/common/rad_gemma4_dflash.h b/arch/common/rad_gemma4_dflash.h index d962ac9b..cdf3ecff 100644 --- a/arch/common/rad_gemma4_dflash.h +++ b/arch/common/rad_gemma4_dflash.h @@ -219,21 +219,45 @@ struct Dflash1 { 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 kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */ + bool qrow = false; /* attention at the drafter's own gqa via attn_paged_qrow */ int64_t steps() const { return block - 1; } }; /* The attention's queries per kv head. libr4d serves the drafter's head-128 attention, causal * over a window and non-causal alike, on one kernel that takes 4 queries per kv head and * q_len * gqa <= 64, so a block of 16 at 4. The 26B's drafter is gqa 4. The 31B's is 64 heads - * over 8 kv heads, gqa 8 at every rank count, which no kernel serves at a block of 16: its - * cache holds each kv head twice, and attention sees 4 queries per copy. That is exact (query - * head q still reads kv head q / 8), and costs a copy of k and v per layer and a cache twice the - * size, a few MiB at the drafter's width. */ + * over 8 kv heads, gqa 8 at every rank count, which no attn_paged kernel serves at a block of + * 16: unless attn_paged_qrow does (qrow_serves), its cache holds each kv head twice, and + * attention sees 4 queries per copy. That is exact (query head q still reads kv head q / 8), + * and costs a copy of k and v per head and layer and a cache twice the size, a few MiB at the + * drafter's width. */ static constexpr int64_t kAttnGqa = 4; static int64_t kv_rep_for(const Geom& g) { const int64_t gqa = g.gqa(); return gqa > kAttnGqa && gqa % kAttnGqa == 0 ? gqa / kAttnGqa : 1; } + /* libr4d also serves gqa 8 at head_dim 128 under attn_paged_qrow: that kernel with each kv head + * read by two query groups, so the cache holds each head once and nothing is copied. No host + * library declares attn_paged_qrow, so it resolves only to a card's kernel; asked first, it + * decides the cache's head count (declare_drafter). The asking ops take no buffers and are not + * issued; the attention the drafter issues is declared after its KV group, which takes its + * block size from it. */ + static bool qrow_serves(RadBuilder* b, const Geom& g, const Config& c) { + bool any_full = false, any_swa = false; + for (int64_t l = 0; l < g.n_layer; ++l) (c.full[l] ? any_full : any_swa) = true; + auto ask = [&](int causal, int64_t window) { + const rad_op h = RAD_OP(b, "attn_paged_qrow", + RAD_PARAMS(RAD_RANGE("q_len", 1, c.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); + return h != RAD_NULL_HANDLE && rad_op_resolved(b, h); + }; + return (!any_swa || ask(1, c.window)) && (!any_full || ask(0, 0)); + } /* What the trunk hands the drafter (declare_drafter). */ struct Trunk { @@ -577,8 +601,17 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta, * 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 separate window group * for the sliding layers would save memory. */ - /* The cache holds kv_rep copies of each of this rank's kv heads (kv_rep_for). */ + /* The cache holds kv_rep copies of each of this rank's kv heads (kv_rep_for), or each once where + * a card serves the drafter's own gqa (qrow_serves). */ dc.kv_rep = kv_rep_for(dg); + if (dc.kv_rep > 1 && rad_op_declared(b, "attn_paged_qrow")) { + Geom pg = dg; + pg.kv_dtype = rad_dtype_name(rad_kv_cache_dtype(ctx, RAD_BF16)); /* as the group takes it */ + if (qrow_serves(b, pg, dc)) { + dc.kv_rep = 1; + dc.qrow = true; + } + } { Geom cg = dg; cg.n_head_kv *= dc.kv_rep; @@ -628,6 +661,10 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta, "kernel serves at a block of %lld (gqa %lld otherwise)", (long long)dg.n_head_kv, (long long)dc.kv_rep, (long long)kAttnGqa, (long long)dg.head_dim, (long long)dc.block, (long long)dg.gqa()); + else if (dc.qrow) + rad_note(b, "the DFlash drafter attends at %lld queries per kv head through attn_paged_qrow, " + "its cache holding each of its %lld kv head(s) a rank once", + (long long)dg.gqa(), (long long)dg.n_head_kv); return RAD_OK; } @@ -778,7 +815,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co * Declared before either kv_store, which reads `block_size` back from 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", + return rw(b, RAD_OP(b, cfg.qrow ? "attn_paged_qrow" : "attn_paged", RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa() / rep), RAD_INT("causal", causal), RAD_INT("window", window), RAD_INT("n_head", g.n_head), diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 578afa43..a83f3982 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -276,11 +276,16 @@ struct Gemma4Attn { op_rq = 0, op_rk = 0, op_attn = 0, op_kv = 0, op_post = 0, op_ar = 0, op_add = 0; /* the five prologue ops (v norm, q norm, k norm, two rotaries) as one, where it resolves */ rad_op op_qnr = 0; + /* ...and that with kv_store folded in (qkv_norm_rope_kv_store), issued in place of op_qnr and + * op_kv where it resolves; op_kv is then not declared */ + rad_op op_qnr_kv = 0; /* Fused only: attention reading q where it lies in the row (attn_paged_qrow), where it resolves - * to the kernel attn_paged would take anyway; else the copy of q into its own rows (`cast`) that - * a step of more than one row issues ahead of attn_paged. Without qkv_norm_rope the copies of - * k and v too, ahead of the unfused prologue, which reads them dense. */ - rad_op op_attn_row = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0; + * to the kernel attn_paged would take anyway -- at every height (op_attn_row), or at decode + * heights up to dec_hi query rows a sequence (op_attn_dec); else the copy of q into its own rows + * (`cast`) that a step of more than one row issues ahead of attn_paged. Without qkv_norm_rope + * the copies of k and v too, ahead of the unfused prologue, which reads them dense. */ + rad_op op_attn_row = 0, op_attn_dec = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0; + int64_t dec_hi = 0; /* The linear whose int8 pair a junction writes, and whether every projection reads it. */ const G4Linear& ln_in() const { return fused ? ln_qkv : ln_q; } @@ -426,9 +431,10 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const /* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM * use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim), * so 1.0 is passed explicitly. */ - auto attn = [&](const char* op, std::initializer_list rd) { + auto attn = [&](const char* op, std::initializer_list rd, int64_t q_hi = 0) { return rw(b, RAD_OP(b, op, - RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_PARAMS(RAD_RANGE("q_len", 1, q_hi > 0 ? q_hi : g.max_tok), + RAD_INT("head_dim", cls.head_dim), RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head), RAD_INT("block_size", RAD_KV_BLOCK), @@ -445,6 +451,14 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const * keeps the five, as does an engine whose libraries do not declare it (CPU-only), where asking * for it would stop the declare. It reads q, k and v at their own row pitches, so on a fused * layer it works in place on the row's column slices. */ + /* What the prologue reads and writes, either form. A k_eq_v class derives v from the raw k: + * v is written, never read. */ + auto qnr_rw = [&](rad_op op) { + if (fused) + return cls.has_v ? rw(b, op, {w.qkv}, {w.qkv}) : rw(b, op, {w.qkv}, {w.qkv, w.v}); + return cls.has_v ? rw(b, op, {w.q, w.k, w.v}, {w.q, w.k, w.v}) + : rw(b, op, {w.q, w.k}, {w.q, w.k, w.v}); + }; auto decl_qnr = [&]() { if (g.rope_mc || g.yarn.factor != 0.0f || !rad_op_declared(b, "qkv_norm_rope")) return; op_qnr = RAD_OP(b, "qkv_norm_rope", @@ -457,13 +471,7 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const RAD_F64("wadd", g.wadd_qk), RAD_INT("v_from_k", cls.has_v ? 0 : 1), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_qn, w_kn)); - /* A k_eq_v class derives v from the raw k: v is written, never read. */ - if (fused) - op_qnr = cls.has_v ? rw(b, op_qnr, {w.qkv}, {w.qkv}) - : rw(b, op_qnr, {w.qkv}, {w.qkv, w.v}); - else - op_qnr = cls.has_v ? rw(b, op_qnr, {w.q, w.k, w.v}, {w.q, w.k, w.v}) - : rw(b, op_qnr, {w.q, w.k}, {w.q, w.k, w.v}); + op_qnr = qnr_rw(op_qnr); }; /* A column slice of the fused row copied into its own rows (`cast`, bf16 to bf16, which every @@ -489,29 +497,60 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const } /* With it attention reads q in the row where that costs nothing. libr4d's dedicated paged * kernels stop at head_dim 256; at 512 (the global class) attn_paged takes the windowed - * kernel, which is the kernel attn_paged_qrow takes, so the row is read in place. At 256 the - * dedicated h256 kernels serve attn_paged in 0.26-0.71 of the windowed kernel's time - * (libr4d/r4d_plugin.h, R4D_PRIO_ATTN_WINDOW), so the sliding class keeps attn_paged: a step - * of one row reads q in place (one row of a slice is dense), a taller one copies q out. */ - if (op_qnr && cls.head_dim > 256 && rad_op_declared(b, "attn_paged_qrow")) + * kernel, which is the kernel attn_paged_qrow takes, so the row is read in place at every + * height. At 256 the dedicated h256 kernels serve attn_paged in 0.26-0.71 of the windowed + * kernel's time (libr4d/r4d_plugin.h, R4D_PRIO_ATTN_WINDOW). Their split-KV decode reads q + * at a pitch under attn_paged_qrow too, over its band (q_len * gqa <= 64: 32 query rows a + * sequence at the sliding class's gqa 2), so the sliding class reads the row there -- a + * verify step included -- and keeps attn_paged above it, a prefill copying q out first. */ + const bool qrow = op_qnr && rad_op_declared(b, "attn_paged_qrow"); + if (qrow && cls.head_dim > 256) { op_attn_row = attn("attn_paged_qrow", {w.qkv}); + } else if (qrow) { + dec_hi = std::min(g.max_tok, 64 / cls.gqa()); + op_attn_dec = attn("attn_paged_qrow", {w.qkv}, dec_hi); + if (!op_attn_dec) dec_hi = 0; + } if (!op_attn_row) { op_lift_q = lift(qd, w.q); op_attn = attn("attn_paged", {w.q, w.qkv}); } } + /* With the cache store folded into the prologue where a library serves it + * (qkv_norm_rope_kv_store: the same prologue, then kv_store of the finished k and v from the + * same launch, byte for byte), one launch a layer fewer. Declared after the attention ops, + * since its block_size comes off the resolved attention kernel (rad_kv_block_size), and + * issued in place of op_qnr and op_kv. */ + if (op_qnr && rad_op_declared(b, "qkv_norm_rope_kv_store")) { + op_qnr_kv = RAD_OP(b, "qkv_norm_rope_kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", cls.n_head_kv), + RAD_F64("theta", cls.theta), RAD_F64("eps", g.eps), + RAD_F64("scale", cls.scale), RAD_STR("mode", "neox"), + RAD_INT("rotary_dim", cls.n_rot), + RAD_STR("ladder", cls.head_ladder ? "head" : "rotary"), + RAD_F64("wadd", g.wadd_qk), RAD_INT("v_from_k", cls.has_v ? 0 : 1), + RAD_STR("dtype", g.dtype), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_WEIGHTS(w_qn, w_kn)); + if (op_qnr_kv) op_qnr_kv = qnr_rw(op_qnr_kv); + } /* On a fused layer with the one-op prologue, k and v are stored from the row (kv_store takes - * them at their own pitches); a k_eq_v class's v is its own buffer either way. */ - op_kv = RAD_OP(b, "kv_store", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), - RAD_INT("n_head_kv", cls.n_head_kv), - RAD_INT("block_size", rad_kv_block_size(b, kv)), - RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS); - if (!(fused && op_qnr)) op_kv = rw(b, op_kv, {w.k, w.v}, {}); - else if (cls.has_v) op_kv = rw(b, op_kv, {w.qkv}, {}); - else op_kv = rw(b, op_kv, {w.qkv, w.v}, {}); + * them at their own pitches); a k_eq_v class's v is its own buffer either way. Not declared + * where the prologue stores them itself. */ + if (!op_qnr_kv) { + op_kv = RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head_kv", cls.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS); + if (!(fused && op_qnr)) op_kv = rw(b, op_kv, {w.k, w.v}, {}); + else if (cls.has_v) op_kv = rw(b, op_kv, {w.qkv}, {}); + else op_kv = rw(b, op_kv, {w.qkv, w.v}, {}); + } /* o_proj is column-sharded: the rank's partial sum is reduced first, then normed. */ if (g.world > 1) @@ -593,7 +632,10 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const { const RadOperand K = row ? bcol(w.qkv, qd, kvd, T) : brows(w.k, T); const RadOperand V = row && cls.has_v ? bcol(w.qkv, qd + kvd, kvd, T) : brows(w.v, T); - if (op_qnr) { + if (op_qnr_kv) { + RAD_ISSUE(c, op_qnr_kv, Q, K, V, rope_posmc(g, batch, T), RAD_W(w_qn), RAD_W(w_kn), + praw(slot, RAD_I32, T), kv_cache(kv, layer)); + } else if (op_qnr) { RAD_ISSUE(c, op_qnr, Q, K, V, rope_posmc(g, batch, T), RAD_W(w_qn), RAD_W(w_kn)); } else { if (fused) { /* the unfused five read q, k and v dense */ @@ -610,7 +652,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const { RAD_ISSUE(c, op_rk, brows(w.k, T), rope_posmc(g, batch, T)); } - RAD_ISSUE(c, op_kv, K, V, praw(slot, RAD_I32, T), kv_cache(kv, layer)); + if (op_kv) RAD_ISSUE(c, op_kv, K, V, praw(slot, RAD_I32, T), kv_cache(kv, layer)); /* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */ rad_op a_op = op_attn; @@ -618,6 +660,9 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const { if (op_attn_row) { a_op = op_attn_row; a_q = Q; + } else if (op_attn_dec && batch->max_q_len <= dec_hi) { + a_op = op_attn_dec; + a_q = Q; } else if (row) { if (T == 1) a_q = Q; else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T)); @@ -1934,15 +1979,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c (long long)(g.n_layer - n_global), (long long)sliding_win, (long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g); { - int64_t n_fused = 0, n_row = 0; + int64_t n_fused = 0, n_row = 0, n_dec = 0, dec_hi = 0; for (const Layer& lay : m.layers) { n_fused += lay.attn.fused ? 1 : 0; n_row += lay.attn.op_attn_row ? 1 : 0; + if (lay.attn.op_attn_dec) { ++n_dec; dec_hi = lay.attn.dec_hi; } } if (n_fused) rad_note(b, "q, k and v as one linear (blk.*.attn_qkv) on %lld of %lld layers; attention " - "reads q in the row on %lld, copies it out above one row on the rest", - (long long)n_fused, (long long)m.layers.size(), (long long)n_row); + "reads q in the row at every height on %lld, up to %lld query rows a " + "sequence on %lld, and copies it out above that or one row", + (long long)n_fused, (long long)m.layers.size(), (long long)n_row, + (long long)dec_hi, (long long)n_dec); else rad_note(b, "q, k and v as three linears (a container converted before attn_qkv, or " "bf16 weights): convert with a recipe naming blk.*.attn_qkv.weight for one"); diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index b242ead9..58e8f307 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -764,13 +764,22 @@ The grid's groups never cross a row, so the codes are those of three separate ru the replies are too. On libr4d the skinny GEMM picks its in-block K split from N (k and v alone split K in two, the fused GEMM does not), so k and v can round differently in the last bit and a long greedy reply can part from the old container's late. `qkv_norm_rope` and `kv_store` work on -the row's column slices in place. A global layer's -attention reads q in the row (`attn_paged_qrow`, the windowed kernel that serves head_dim 512 under -`attn_paged` too); a sliding layer's reads it there in a one-row step, and a taller step copies q -out with a `cast` for libr4d's h256/gqa2 kernels, which take 0.26-0.71 of the windowed kernel's -time. Without `qkv_norm_rope` (a CPU-only engine) q, k and v are copied out for the unfused -prologue. A container that holds the three apart serves as before: the plugin asks the weight's -encoding, which rad-convert answers from the recipe and a container from its entries. +the row's column slices in place. Attention reads q in the row through `attn_paged_qrow`: a global +layer at every height (the windowed kernel, which serves head_dim 512 under `attn_paged` too), a +sliding layer up to 32 query rows a sequence (libr4d's h256/gqa2 split-KV decode with q at a pitch, +so a verify step included); a taller sliding step (a prefill) copies q out with a `cast` for the +h256/gqa2 prefill kernel, which takes 0.43-0.67 of the windowed kernel's time. Without +`qkv_norm_rope` (a CPU-only engine) q, k and v are copied out for the unfused prologue. A container +that holds the three apart serves as before: the plugin asks the weight's encoding, which +rad-convert answers from the recipe and a container from its entries. + +**The 31B's drafter at gqa 8.** z-lab's 31B drafter is 64 heads over 8 kv heads. Where a card +serves `attn_paged_qrow` at head_dim 128, gqa 8 and q_len 16 (libr4d's gqa-4 split-KV decode with +each kv head read by two query groups), the drafter's cache holds each kv head once and attention +runs at gqa 8. The op has no host rows, so the plugin asks it before the drafter's KV group, whose +head count follows the answer. Elsewhere the cache holds each kv head twice and attention runs at +gqa 4, the kv heads copied into place with a `cast` a head and copy (80 launches a draft step at +tp 4). **The 31B with a DFlash2 drafter.** RedHatAI's `gemma-4-31B-it-speculator.dflash2` is z-lab's DFlash2 architecture trained with vLLM's speculators library: five Qwen3-shaped layers at 5376 (32 diff --git a/docs/OPS.md b/docs/OPS.md index e207e32f..5621f5cb 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -449,7 +449,11 @@ dense block by a `cast`. It has its own name because other `attn_paged` kernels (libr4d's with `RAD_E_STRIDE`, at the first step), and under `attn_paged` the first library in `--kernels` wins the op, an order the architecture cannot see. Asked for by name, the op resolves to a library that reads the pitch or to nothing, and the architecture copies `q` for `attn_paged` in -the second case. +the second case. In libr4d the windowed kernels serve it at every height; the split-KV decode kernel +serves it at h256/gqa2 over its decode band (q_len up to 32, ahead of the windowed rows there), and +at h128/gqa8 up to q_len 16 by reading each kv head for two query groups of 4 (a drafter's cache +then holds each kv head once). Since no host library declares the op, a plugin that asks for it +learns whether a card serves the geometry. libref has no row for any of them, deliberately. An architecture asks for a fusion and declares the chain where it does not resolve (`rad_op_resolved`); a reference row would make it resolve @@ -821,6 +825,7 @@ bytes). | `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | | `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? | | `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `v_norm`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | +| `qkv_norm_rope_kv_store` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` `v_norm`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w, `slot_mapping`, `kv_cache`:inout | **`attn_paged`**'s band is `q_len`, not `M`: one query row at decode, `1 + n_spec` at a speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each band. @@ -937,9 +942,19 @@ the same reason: its angles must stay `rope`'s exactly. **`qkv_norm_rope`** (device-only) is the same prologue over separate `q`, `k` and `v` projections (Gemma 4's text attention, three GEMMs): the q and k norms, the unit-gain value norm and the rotary -in one dispatch. `v_from_k` 1 takes v from the raw k before the k norm (the k == v global class). +in one dispatch. `v_from_k` 1 takes v from the raw k before the k norm (the k == v global class); +`v_norm` 0 leaves v unnormed (a Qwen3-shaped layer: two norms and two rotaries). `n_head` 0 is the +k (and v) heads alone, `q` and `q_w` passed but neither read nor written: a pass that writes only +keys and values (a block drafter's context pass). The rotary parameters are `rope`'s, `ladder` included. Byte-identical to `rmsnorm_p`, two -`rmsnorm`s and two `rope`s. +`rmsnorm`s and two `rope`s (one each at `n_head` 0). + +**`qkv_norm_rope_kv_store`** (device-only) is `qkv_norm_rope` followed by `kv_store` in one launch: +the block of each k head (and of each v head, or under `v_from_k` the k head's block for both) ends +holding its token's finished head, so it also writes it into the paged cache at the token's slot. +Its parameters are the two ops' own, its operands the prologue's followed by `slot_mapping` and +`kv_cache`. Byte-identical to the pair at either cache width: the store converts each element as +`kv_store` does, and q, k and v are still written in place as the prologue leaves them. | op | params | operands | |---|---|---| @@ -2829,6 +2844,17 @@ Blocks are `block_size` rows starting at row 0, so a tap never reaches into the `[T, 2, taps, NG]` coefficient projection. `out` must not alias `x`. libr4d's kernel serves `taps` 2, `group_size` 16 and a power-of-two `block_size`; libref and libavx any. +`add_rmsnorm` (device-only) is the drafter's residual add and the norm after it in one pass: + +| op | params | operands | +|---|---|---| +| `add_rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`:inout, `a`, `w`w → `y` | + +It writes `x + a` into `x`, rounded as `add` rounds it, then `y = rmsnorm(x) * (w + wadd) * mult` +over the `x` it wrote, at `rmsnorm`'s width and column partition: byte-identical to `add` followed +by `rmsnorm`, on both outputs. That is where it differs from `rmsnorm_add`, which normalises the +unrounded sum: a drafter whose trained graph is the pair keeps its bits. + `dflash_select` is the greedy walk over the candidate lattice: `cand`/`unary` are `row_topk`'s two output planes at one row per draft position, `hp` the selector's rank-256 query, and `anchor` the step's own token ids (`anchor_stride` is the block width, because a draft pass carries `block` ids a diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 5489e7dc..c159bfd3 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -65,6 +65,20 @@ struct R4DArgs { // null. const int* cu_q; // (num_seqs+1,) int32 device, or null for a uniform q_len int total_q; // rows of q/out; ignored unless cu_q is set + + // ---- Views the split-KV decode kernel reads (r4d_attn_decode_h256_gqa6.hip); every other + // kernel leaves them at zero and reads q dense with one cache head per query group. + // + // `q_ld` is the element distance between q rows, 0 for dense (q_heads * head_dim): the q part + // of a fused [q|k|v] projection read where it lies (attn_paged_qrow). A multiple of 4. + // + // `kv_rep` maps query groups onto cache heads: group g (q heads g*GQA .. g*GQA+GQA-1) reads + // cache head g / kv_rep, and the descales are per cache head. kv_heads then counts the groups + // (q_heads / GQA) and the cache holds kv_heads / kv_rep heads. 0 or 1 is one head a group. It + // runs a gqa of GQA * kv_rep on the kernel compiled for GQA, whose workgroup holds at most 64 + // rows of q_len * GQA: the 31B's DFlash drafter, gqa 8 at a block of 16, on the gqa-4 kernel. + long q_ld; + int kv_rep; }; // Rows of q and out. The split-KV scratch is laid out by dense query row, so the host sizing hook @@ -89,6 +103,9 @@ int r4d_attn_decode_h256_gqa6_bf16kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h128_gqa4_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h128_gqa4_bf16kv (const R4DArgs* a, hipStream_t stream); long r4d_attn_decode_h128_gqa4_scratch_bytes(const R4DArgs* a); +// ...with R4DArgs::kv_rep and q_ld read: a gqa of 4 * kv_rep over a cache of kv_heads / kv_rep. +int r4d_attn_decode_h128_gqa4_rep_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h128_gqa4_rep_bf16kv (const R4DArgs* a, hipStream_t stream); // Bytes of split-KV partial buffer one decode launch of this shape needs. Independent of the cache // dtype: the partials are f16 either way. long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a); @@ -106,6 +123,9 @@ int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h128_gqa2w_bf16kv (const R4DArgs* a, hipStream_t stream); long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a); +// ...with q at R4DArgs::q_ld (attn_paged_qrow). +int r4d_attn_decode_h256_gqa2_qld_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h256_gqa2_qld_bf16kv (const R4DArgs* a, hipStream_t stream); // The geometry the attention kernels above are compiled for, so a caller can check a model // before the first launch. void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows); diff --git a/libr4d/r4d_attn_args.h b/libr4d/r4d_attn_args.h index b171226c..7814715a 100644 --- a/libr4d/r4d_attn_args.h +++ b/libr4d/r4d_attn_args.h @@ -39,10 +39,14 @@ enum { AP_Q = 0, AP_KV, AP_BT, AP_SEQ, AP_KDS, AP_VDS, AP_CU, AP_OUT }; * would abort the engine. So cu_seqlens is used whenever present, and the uniform arithmetic * (q_len = total_q / num_seqs) only when it is not. In the ragged case q_len is the batch maximum, * taken from the parameter the arch block issued the op with (batch->max_q_len). + * + * `q_pitched`: q may be a column slice of a wider row (attn_paged_qrow), its pitch in r->q_ld. Only + * the split-KV decode kernel reads q_ld; every other caller leaves this off. */ /* `row` is a token's bytes (elements for a 16-bit cache) in a (block, head) page: 2 * head_dim, * or 25 * head_dim / 16 for the fp8_v4 cache (E4M3 K, int4 V, f16 group scales). */ -static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_dim, long long row) { +static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_dim, long long row, + bool q_pitched = false) { const RadTensor* q = r4d_opt(a, AP_Q); const RadTensor* kv = r4d_opt(a, AP_KV); const RadTensor* bt = r4d_opt(a, AP_BT); @@ -74,8 +78,16 @@ static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_d } /* q and out are indexed as one dense [total_q, q_heads, head_dim] block; the kernel has no - * pitch argument for either. */ - if (!r4d_contig(q) || !r4d_contig(o)) return R4D_NO(RAD_E_STRIDE); + * pitch argument for either -- except q under q_pitched, whose rows may be apart: dense inside + * a row, a pitch in whole 8-byte loads (the kernel reads q four elements at a time). */ + long long q_ld = 0; + if (q_pitched && !r4d_contig(q)) { + q_ld = r4d_row_pitch(q); + if (q_ld < q_heads * head_dim || q_ld % 4) return R4D_NO(RAD_E_STRIDE); + } else if (!r4d_contig(q)) { + return R4D_NO(RAD_E_STRIDE); + } + if (!r4d_contig(o)) return R4D_NO(RAD_E_STRIDE); if (o->shape[0] != total_q || r4d_numel(o) != total_q * q_heads * head_dim) return R4D_NO(RAD_E_SHAPE); if (su->shape[0] != num_seqs) return R4D_NO(RAD_E_SHAPE); @@ -104,6 +116,7 @@ static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_d r->k_descale = kds ? (const float*)kds->data : nullptr; r->v_descale = vds ? (const float*)vds->data : nullptr; r->q_descale = nullptr; /* the query is bf16 in every variant */ + r->q_ld = (long)q_ld; /* 0: dense */ r->scratch = a->scratch; r->num_seqs = (int)num_seqs; r->cu_q = ragged ? (const int*)cu->data : nullptr; @@ -152,8 +165,9 @@ static inline int split_of(const RadArgs* a) { } -static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) { - return fill_paged_row(a, r, expect_head_dim, 2LL * expect_head_dim); +static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim, + bool q_pitched = false) { + return fill_paged_row(a, r, expect_head_dim, 2LL * expect_head_dim, q_pitched); } #endif /* R4D_ATTN_ARGS_H */ diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index aaacdc36..228fe7de 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -56,6 +56,13 @@ // k6_v4 cache (int6 K, int4 V); a token's row layout is RadBuildCtx::kv_quant's (abi/rad_builder.h). #define O_V4 33554432 #define O_K6 67108864 +// The two views of R4DArgs (r4d.h), compiled in only where a row asks for them, since the h256 +// instances sit at the 256-VGPR bound and a runtime pitch and head map spill there: +// QLD q rows at R4DArgs::q_ld (attn_paged_qrow), not dense. +// KVREP query group g reads cache head g / R4DArgs::kv_rep, descales per cache head. +// Neither changes the arithmetic. +#define O_QLD 134217728 +#define O_KVREP 268435456 __host__ __device__ __forceinline__ int r4d_attn_tiles(int ctx, int tile) { return (ctx + tile - 1) / tile; } __host__ __device__ __forceinline__ int r4d_attn_tps(int ctx, int tile, int splits) { int t = r4d_attn_tiles(ctx, tile); return (t + splits - 1) / splits; @@ -103,6 +110,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) static_assert(!K6 || (!KLDS && (OPT & O_CONTIG) && !KRAW), "k6_v4 K is widened from the paged cache, a lane's eight dims contiguous"); static_assert(!V4 || (OPT & O_F16), "fp8_v4 widens to f16"); + constexpr int QLD = (OPT & O_QLD) ? 1 : 0; + constexpr int KVREP = (OPT & O_KVREP) ? 1 : 0; typedef DT16 D; typedef typename D::frag frag16; @@ -133,6 +142,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) const int c = lane & 15, h = lane >> 4; const int sp = blockIdx.x, kvh = blockIdx.y, seq = blockIdx.z; + // kvh is the query group; under KVREP the cache head it reads is kvh / kv_rep + const int kvc = KVREP ? kvh / a.kv_rep : kvh; const int ctx = a.seqused_k[seq]; if (ctx <= 0) return; @@ -161,13 +172,17 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) const int qhead = kvh * GQA + hi; const int* __restrict__ bt = a.block_table + (size_t)seq * a.max_blocks; - const float kdesc = a.k_descale ? a.k_descale[seq * a.kv_heads + kvh] : 1.0f; + const float kdesc = a.k_descale + ? a.k_descale[seq * (KVREP ? a.kv_heads / a.kv_rep : a.kv_heads) + kvc] + : 1.0f; const float mul = a.scale * kdesc * 1.44269504089f; frag16 qf[NKS]; { - const uint16_t* qp = (const uint16_t*)a.q - + ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM; + const uint16_t* qp = QLD ? (const uint16_t*)a.q + (size_t)(qoff + qrow) * a.q_ld + + (size_t)qhead * HEAD_DIM + : (const uint16_t*)a.q + + ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM; #pragma unroll for (int t = 0; t < NKS; ++t) { const uint2 l0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h : 4 * h)); @@ -267,7 +282,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) const int d0 = dg * (KVP ? 32 : 64) + vg * (KVP ? 8 : 16); const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS]; const size_t o = (size_t)blk * a.kv_block_stride - + (size_t)kvh * a.kv_head_stride + + (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB + HEAD_DIM + d0; const void* p = KVP ? (const void*)((const uint16_t*)a.kv + o) : (const void*)((const uint8_t*)a.kv + o); @@ -345,7 +360,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) if (WIN && kk < wlo0) kk = wlo0; const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS]; const size_t o = (size_t)kb * a.kv_block_stride - + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB; + + (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB; uint16_t* kd = &sK[key * KSTR]; uint32_t w4[4]; if (KVP) { @@ -372,7 +387,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) if (WIN && kk < wlo0) kk = wlo0; const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS]; grow = (const uint8_t*)a.kv + ((size_t)kb * a.kv_block_stride - + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB) + + (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB) * (KVP ? 2 : 1); } // A fragment's raw K: 8 elements of 1 byte (fp8) or 2 (bf16). @@ -730,8 +745,9 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG } } - const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); - const float vd = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f; + const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); /* the query group */ + const int krep = a.kv_rep > 1 ? a.kv_rep : 1; /* its cache head: kvh / krep */ + const float vd = a.v_descale ? a.v_descale[seq * (a.kv_heads / krep) + kvh / krep] : 1.0f; uint16_t ob[DPL]; #pragma unroll for (int j = 0; j < DPL; ++j) { @@ -873,8 +889,9 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ #pragma unroll for (int i = 0; i < CHAINS; ++i) av += ch[i]; - const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); - const float vd = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f; + const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); /* the query group */ + const int krep = a.kv_rep > 1 ? a.kv_rep : 1; /* its cache head: kvh / krep */ + const float vd = a.v_descale ? a.v_descale[seq * (a.kv_heads / krep) + kvh / krep] : 1.0f; finish(f32_to_bf16(tot > 0.0f ? av * vd / tot : 0.0f)); } diff --git a/libr4d/r4d_attn_paged_gqa8.hip b/libr4d/r4d_attn_paged_gqa8.hip index ab6bbb27..10d1cea9 100644 --- a/libr4d/r4d_attn_paged_gqa8.hip +++ b/libr4d/r4d_attn_paged_gqa8.hip @@ -106,7 +106,7 @@ extern "C" long GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(const R4DArgs* a) { } template -/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (168 +/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (184 * bytes) like any other kernel argument. Non-null `gq` adds the output gate and quantiser to the * combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). `XOPT` adds * option bits to the attention kernel's (O_V4, O_K6: the cache layout). */ diff --git a/libr4d/r4d_attn_paged_h128_gqa4.hip b/libr4d/r4d_attn_paged_h128_gqa4.hip index d48d88e1..84dbb930 100644 --- a/libr4d/r4d_attn_paged_h128_gqa4.hip +++ b/libr4d/r4d_attn_paged_h128_gqa4.hip @@ -37,3 +37,11 @@ extern "C" int r4d_attn_decode_h128_gqa4_fp8kv(const R4DArgs* a, hipStream_t s) extern "C" int r4d_attn_decode_h128_gqa4_bf16kv(const R4DArgs* a, hipStream_t s) { return r4d_decode_launch_win(a, s); } +// The same over a cache holding each kv head once for kv_rep query groups (O_KVREP), q at +// R4DArgs::q_ld (O_QLD): gqa 8 on this gqa-4 kernel, under attn_paged_qrow. +extern "C" int r4d_attn_decode_h128_gqa4_rep_fp8kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} +extern "C" int r4d_attn_decode_h128_gqa4_rep_bf16kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} diff --git a/libr4d/r4d_attn_paged_h256_gqa2.hip b/libr4d/r4d_attn_paged_h256_gqa2.hip index 297dd4ec..77ee867f 100644 --- a/libr4d/r4d_attn_paged_h256_gqa2.hip +++ b/libr4d/r4d_attn_paged_h256_gqa2.hip @@ -36,6 +36,14 @@ extern "C" int r4d_attn_decode_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s) extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) { return r4d_decode_launch_win(a, s); } +// The same with q at R4DArgs::q_ld (O_QLD), for attn_paged_qrow; its own instances, so the dense +// ones above keep their registers. +extern "C" int r4d_attn_decode_h256_gqa2_qld_fp8kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} +extern "C" int r4d_attn_decode_h256_gqa2_qld_bf16kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} // ---- prefill --------------------------------------------------------------------------------- // The h256/gqa6 prefill option set but at K prefetch 4 (P_OPT there is 3954187); O_KWIDE is valid diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index 441a657d..0d3ead43 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -219,7 +219,11 @@ static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) { return (int64_t)r4d_attn_decode_h256_gqa6_scratch_bytes(r); } -static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long long row = 0) { +/* `row`: a token's bytes in a (block, head) page (fill_paged_row), 0 for 2 * head_dim; `rep`: the + * launch maps each kv head onto `rep` query groups (R4DArgs::kv_rep), so the split law counts + * groups, gqa / rep of them a kv head; `q_pitched`: q may be a slice (attn_paged_qrow). */ +static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long long row = 0, + int rep = 1, bool q_pitched = false) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); @@ -231,7 +235,8 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo r.head_dim = head_dim; r.q_heads = (int)n_head; const long long gqa = r4d_geti_or(a, "gqa", 1); - r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head); + r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head) * rep; + r.kv_rep = rep; r.num_seqs = (int)max_seqs; r.q_len = (int)r4d_geti_or(a, "q_len", 1); r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0); @@ -249,8 +254,10 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo return worst; } - int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim); + int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim, q_pitched); if (rc != RAD_OK) return rc; + r.kv_heads *= rep; + r.kv_rep = rep; r.splits = sp; return decode_scratch_bytes_of(&r, which); } @@ -263,11 +270,17 @@ extern "C" int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs* a) { return decode_scratch(a, 128, 1); } -static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which, long long row = 0) { +static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which, long long row = 0, + int rep = 1, bool q_pitched = false) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); - int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim); + int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim, q_pitched); if (rc != RAD_OK) return rc; + /* a QLD instance reads q_ld whatever q is: dense is the pitch q_heads * head_dim */ + if (q_pitched && r->q_ld == 0) r->q_ld = (long)r->q_heads * head_dim; + /* each cache head serves `rep` query groups: the kernel's grid and its gqa check count groups */ + r->kv_heads *= rep; + r->kv_rep = rep; r->splits = sp; const int64_t need = decode_scratch_bytes_of(r, which); if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH); @@ -389,3 +402,42 @@ extern "C" int r4d_rad_attn_decode_h128_gqa2w_bf16(const RadArgs* a, RadStream s if (rc != RAD_OK) return rc; return r4d_attn_decode_h128_gqa2w_bf16kv(&r, (hipStream_t)s); } + +/* The same decode under attn_paged_qrow: q read at its own row pitch (R4DArgs::q_ld), the sliding + * layers' q where Gemma 4 31B's fused q|k|v projection left it. Same kernel, same arithmetic. */ +extern "C" int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs* a) { + return decode_scratch(a, 256, 2, 0, 1, true); +} +extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 256, 2, 0, 1, true); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h256_gqa2_qld_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 256, 2, 0, 1, true); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h256_gqa2_qld_bf16kv(&r, (hipStream_t)s); +} + +/* Head_dim 128 at 8 queries per kv head, any window, causal or not, q_len up to 16, under + * attn_paged_qrow: the gqa-4 kernel with each kv head mapped onto two query groups + * (R4DArgs::kv_rep = 2), the 31B's DFlash drafter's attention over a cache that holds each kv head + * once. The workgroup holds q_len * 4 rows, so a block of 16 fits where gqa 8 (128 rows) does not; + * the two groups of a kv head read its blocks twice, as the copies they replace did. */ +extern "C" int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs* a) { + return decode_scratch(a, 128, 1, 0, 2, true); +} +extern "C" int r4d_rad_attn_qrow_h128_gqa8_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 128, 1, 0, 2, true); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h128_gqa4_rep_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_qrow_h128_gqa8_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 128, 1, 0, 2, true); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h128_gqa4_rep_bf16kv(&r, (hipStream_t)s); +} diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index bc176795..dfa95d2a 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -586,6 +586,71 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u } } +/* ========================================================================================== + * qkv_norm_rope_kv_store -- qkv_norm_rope, then kv_store of its finished k and v. + * (rows: qkv_norm_rope_kv_store_fp8 and _bf16; kernel: libr4d/r4d_qkv_norm_rope.hip, + * qkv_norm_rope_kernel under KV) + * + * Operands: [0] q [1] k [2] v [3] positions [4] q_w [5] k_w [6] slot_mapping [7] kv_cache + * + * No temporaries: the prologue rewrites q, k and v in place and the store reads k and v as the + * prologue left them, which is what the kernel stores. */ +extern "C" int r4d_fuse_qkv_norm_rope_kv_store(const RadParam* p, int n_p, uint64_t present, + int step, RadFuseStep* out) { + (void)present; + if (!out) return RAD_E_INVAL; + switch (step) { + case 0: { + Step s(out, "qkv_norm_rope"); + s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head") + .mirror(p, n_p, "n_head_kv").mirror(p, n_p, "theta").mirror(p, n_p, "eps") + .mirror_opt(p, n_p, "scale").mirror_opt(p, n_p, "mode").mirror_opt(p, n_p, "rotary_dim") + .mirror_opt(p, n_p, "ladder").mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "v_from_k") + .mirror(p, n_p, "dtype").mirror_opt(p, n_p, "v_norm"); + return s.wire({ 0, 1, 2, 3, 4, 5 }); + } + case 1: { + Step s(out, "kv_store"); + s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head_kv") + .mirror(p, n_p, "block_size").mirror(p, n_p, "kv_dtype") + .mirror_opt(p, n_p, "k_scale").mirror_opt(p, n_p, "v_scale"); + /* k, v, slot_mapping, kv_cache */ + return s.wire({ 1, 2, 6, 7 }); + } + default: + return RAD_E_NOTFOUND; + } +} + +/* ========================================================================================== + * add_rmsnorm -- add (x += a), then rmsnorm of the x it wrote. + * (row: add_rmsnorm_bf16; kernel: libr4d/r4d_model_bf16.hip, add_rmsnorm_kernel) + * + * Operands: [0] x [1] a [2] w [3] y + * + * No temporaries: the add writes x in place and the norm reads it. */ +extern "C" int r4d_fuse_add_rmsnorm(const RadParam* p, int n_p, uint64_t present, int step, + RadFuseStep* out) { + (void)present; + if (!out) return RAD_E_INVAL; + switch (step) { + case 0: { + Step s(out, "add"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype"); + /* a = x, b = the addend, y = x */ + return s.wire({ 0, 1, 0 }); + } + case 1: { + Step s(out, "rmsnorm"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "eps").mirror(p, n_p, "dtype") + .mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "mult"); + return s.wire({ 0, 2, 3 }); + } + default: + return RAD_E_NOTFOUND; + } +} + /* ========================================================================================== * attn_paged_gate_quant -- attn_paged, then gate_quant_fp8 over its output. * (row: attn_decode_gq_h256_gqa12_fp8kv; kernels: libr4d/r4d_attn_decode_h256_gqa6.hip, the diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index d1952c80..e41f1f73 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -226,6 +226,38 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel( } } +// ---------------------------------------------------------------------------- add_rmsnorm +// x = x + a, rounded as `add` rounds it, then y = rmsnorm(x) over the x just written, computed as +// rmsnorm_kernel computes it: the same width (r4d_act_threads), the same columns a thread, the same +// block_sum. A thread re-reads only the x it wrote itself, so no barrier separates the passes. +// Byte-identical to `add` followed by `rmsnorm`, on x and on y. +template +__global__ __launch_bounds__(THR) void add_rmsnorm_kernel( + uint16_t* __restrict__ x, const uint16_t* __restrict__ a, const void* __restrict__ w, + uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, + uint32_t a_ld, uint32_t y_ld, uint32_t M) { + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + if (m >= M) return; // a row the launch added past the full-card cliff (r4d_cliff_rows) + uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + const uint16_t* __restrict__ ar = a + (size_t)m * a_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const uint16_t h = f32_to_bf16(bf16_to_f32(xr[i]) + bf16_to_f32(ar[i])); + xr[i] = h; + const float v = bf16_to_f32(h); + ss += v * v; + } + ss = block_sum(ss, lds); + const float s = rsqrtf(ss / (float)n + eps); + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]); + yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * s * (g + wadd) * mult); + } +} + // ---------------------------------------------------------------------------- rmsnorm_p // ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps), rmsnorm with no gain. Gemma's attention applies // it to V (llama.cpp's ggml_rms_norm(V, eps)), which has no checkpoint gain. Accumulates exactly as @@ -1420,6 +1452,53 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { : RAD_E_DEVICE; } +/* ------------------------------------------------------------------ add_rmsnorm */ + +enum { AN_X = 0, AN_A, AN_W, AN_Y }; + +extern "C" int r4d_rad_add_rmsnorm(const RadArgs* a, RadStream s) { + int emit_rc = RAD_OK; + const RadTensor* x = r4d_opt(a, AN_X); + const RadTensor* ad = r4d_opt(a, AN_A); + const RadTensor* w = r4d_opt(a, AN_W); + const RadTensor* y = r4d_opt(a, AN_Y); + if (!x || !ad || !w || !y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(x)); + R4D_NEED(dt_bf16(ad)); + R4D_NEED(dt_bf16(y)); + if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE); + if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + const bool w_f32 = w->dtype == RAD_F32; + const long long n = r4d_geti_or(a, "n", r4d_dim(w, (int)w->rank - 1)); + if (n <= 0 || r4d_numel(w) < n) return R4D_NO(RAD_E_SHAPE); + long long M = 0, Ma = 0, My = 0; + const long long x_ld = r4d_rows_pitch(x, n, &M); + const long long a_ld = r4d_rows_pitch(ad, n, &Ma); + const long long y_ld = r4d_rows_pitch(y, n, &My); + if (x_ld < 0 || a_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || Ma < M || My < M) return R4D_NO(RAD_E_SHAPE); + const float eps = (float)r4d_getf(a, "eps", 1e-6); + const float wadd = (float)r4d_getf(a, "wadd", 0.0); + const float mult = (float)r4d_getf(a, "mult", 1.0); + /* rmsnorm's width, from the same table (see r4d_rmsnorm_mult_bf16) */ + const int thr = r4d_act_threads((int)M, (int)n); +#define R4D_AN_T(wf, T) \ + emit_rc = R4D_EMIT(s, (add_rmsnorm_kernel), \ + dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \ + (uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \ + (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \ + (uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M) +#define R4D_AN(wf) \ + do { if (thr == 1024) R4D_AN_T(wf, 1024); \ + else if (thr == 512) R4D_AN_T(wf, 512); \ + else R4D_AN_T(wf, 256); } while (0) + if (w_f32) R4D_AN(true); + else R4D_AN(false); +#undef R4D_AN +#undef R4D_AN_T + return emit_rc; +} + /* ------------------------------------------------------------------ rmsnorm_p */ extern "C" int r4d_rad_rmsnorm_p(const RadArgs* a, RadStream s) { diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 337717be..8e7fbafe 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -117,6 +117,14 @@ int r4d_rad_attn_prefill_h128_gqa2w_bf16 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_gqa2w_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_gqa2w_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs*); +/* attn_paged_qrow on the split-KV decode kernel: the h256/gqa2 decode with q at its own pitch, and + * head_dim 128 at gqa 8 as the gqa-4 kernel with two query groups a kv head (R4DArgs::kv_rep). */ +int r4d_rad_attn_qrow_decode_h256_gqa2_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_qrow_decode_h256_gqa2_bf16 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs*); +int r4d_rad_attn_qrow_h128_gqa8_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_qrow_h128_gqa8_bf16 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs*); /* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not * (r4d_attn_paged_window.hip): one entry point per geometry and cache dtype, every q_len and any q * row pitch, so they serve both attn_paged and attn_paged_qrow. */ @@ -461,6 +469,8 @@ int64_t r4d_rad_moe_gather_scratch (const RadArgs*); /* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */ int r4d_rad_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream); +int r4d_rad_add_rmsnorm (const RadArgs*, RadStream); +int r4d_rad_qkv_norm_rope_kv_store(const RadArgs*, RadStream); int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream); int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream); int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs*, RadStream); @@ -781,6 +791,9 @@ int r4d_shape_attn_paged (const RadParam*, int, int operand, RadOpdDesc*) int r4d_shape_attn_paged_gate_quant(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qk_norm_rope_gate (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_qkv_norm_rope (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_qkv_norm_rope_kv_store(const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_add_rmsnorm(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_rope_table (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gdn_gated_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*); @@ -853,6 +866,8 @@ int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseSt int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_add_rmsnorm(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_ar_gather_hc_write (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_attn_paged_gate_quant(const RadParam*, int, uint64_t, int, RadFuseStep*); diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip index f620efe9..c83a48a3 100644 --- a/libr4d/r4d_qkv_norm_rope.hip +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -18,7 +18,16 @@ // `x0*s + x1*c`), under the library's -ffp-contract=off. // // `v_from_k` is Gemma's global class: k == v, so v is the value norm of the raw k, taken before the -// k norm overwrites it, in the order the unfused block issues them. +// k norm overwrites it, in the order the unfused block issues them. `v_norm` 0 leaves v as it is +// (a Qwen3-shaped layer, the DFlash2 drafter's: q and k normed, v not), so the launch is the two +// norms and two rotaries, and with the store v's heads only store. +// +// `qkv_norm_rope_kv_store` is the same launch followed by `kv_store`: the block of a k head (and of +// a v head) ends holding its token's finished head, so it also writes it into the paged cache at +// the token's slot, converted as kv_store converts it (E4M3: times the inverse descale, clamped to +// +-448, v_cvt_pk_fp8_f32 four columns a lane; bf16: the values as they are). The head is staged in +// LDS for that, since the fp8 store packs four neighbouring columns a lane. Byte-identical to the +// pair at either cache width; the k, v and q rows are still written, as the pair leaves them. // // Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" @@ -52,10 +61,12 @@ __device__ __forceinline__ float head_ss(const uint16_t* __restrict__ x, uint32_ return s; } -// The rotary over a normed head staged in `nb`, written to `out`: rope_kernel's body for pair i. +// The rotary over a normed head staged in `nb`, written to `out` (and to `st` when the head is also +// stored): rope_kernel's body for pair i. template __device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t* __restrict__ out, - float p0, uint32_t rot, uint32_t nfreq, int den, float theta) { + float p0, uint32_t rot, uint32_t nfreq, int den, float theta, + uint16_t* __restrict__ st) { const uint32_t half = rot / 2, t = threadIdx.x; if (t < half) { float inv = 1.0f / powf(theta, (float)(2 * t) / (float)den); @@ -64,35 +75,99 @@ __device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t float c, s; sincosf(ang, &s, &c); const float x0 = bf2f(nb[t]), x1 = bf2f(nb[t + half]); - out[t] = f32_to_bf16(x0 * c - x1 * s); - out[t + half] = f32_to_bf16(x0 * s + x1 * c); + const uint16_t y0 = f32_to_bf16(x0 * c - x1 * s), y1 = f32_to_bf16(x0 * s + x1 * c); + out[t] = y0; + out[t + half] = y1; + if (st) { st[t] = y0; st[t + half] = y1; } + } + for (uint32_t i = rot + t; i < HD; i += HD) { // the unrotated tail + out[i] = nb[i]; + if (st) st[i] = nb[i]; + } +} + +// One head into the paged cache at element offset `off` (r4d_model_bf16.hip's kv_store kernels): +// KV 1 an E4M3 cache, four columns a lane as kv_store_fp8_kernel converts them; KV 2 a bf16 cache, +// the values as they are. `src` is the head in LDS, complete before the call. +template +__device__ __forceinline__ void kv_put(void* __restrict__ kv, size_t off, + const uint16_t* __restrict__ src, float inv) { + const uint32_t t = threadIdx.x; + if (KV == 1) { + if (t < HD / 4) { + const uint32_t d = t * 4u; + float f[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) f[e] = bf2f(src[d + (uint32_t)e]) * inv; + // clamped because v_cvt_pk_fp8_f32 returns NaN out of range instead of saturating + int pk = 0; + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[0], -448.0f), 448.0f), + fminf(fmaxf(f[1], -448.0f), 448.0f), pk, false); + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[2], -448.0f), 448.0f), + fminf(fmaxf(f[3], -448.0f), 448.0f), pk, true); + *(uint32_t*)((uint8_t*)kv + off + d) = (uint32_t)pk; + } + } else if (KV == 2) { + for (uint32_t i = t; i < HD; i += HD) ((uint16_t*)kv)[off + i] = src[i]; } - for (uint32_t i = rot + t; i < HD; i += HD) out[i] = nb[i]; // the unrotated tail } // blockIdx.y: [0, nq) a query head, [nq, nq+nkv) a key head (and with VK its value, from the raw // key), [nq+nkv, nq+2nkv) a value head normalised in place (without VK). -template +// +// KV 1 or 2 also stores each k and v head into the paged cache [n_blocks, nkv, block_size, 2*HD] +// at slot[m] (k at column 0, v at HD), for rows m < n_slot whose slot is in range; KV 0 stores +// nothing and ignores the cache arguments. +template __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v, const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos, - uint32_t m_rows) { + uint32_t m_rows, const int32_t* __restrict__ slot, void* __restrict__ kvc, uint32_t n_slot, + uint32_t block_size, uint32_t n_blocks, float k_inv, float v_inv, uint32_t vnorm) { __shared__ float l1[HD / kWave], l2[HD / kWave]; __shared__ uint16_t nb[HD]; + __shared__ uint16_t sb[KV ? HD : 1]; // the head this block stores + __shared__ uint16_t vb[(KV && VK) ? HD : 1]; // and, under VK, the value from the raw k const uint32_t m = blockIdx.x, hh = blockIdx.y, t = threadIdx.x; if (m >= m_rows) return; // a row the launch added past the full-card cliff (r4d_cliff_rows) const float div = rscale != 0.0f ? rscale : 1.0f; // rope rotates only the rows its positions cover; a row past them is normed and not rotated const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f; + // The row's cache slot, as kv_store reads it: a negative or out-of-range slot stores nothing. + // Uniform over the block, so the barriers below are too. + size_t base = 0; + bool put = false; + if (KV && m < n_slot) { + const int32_t sl = slot[m]; + if (sl >= 0 && (uint32_t)sl / block_size < n_blocks) { + put = true; + base = ((size_t)((uint32_t)sl / block_size) * nkv * block_size + + (size_t)((uint32_t)sl % block_size)) * 2 * HD; + } + } + const size_t head_step = (size_t)block_size * 2 * HD; - if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p - uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)(hh - nq - nkv) * HD; - const float s = rsqrtf(head_ss(x, pv, l1) / (float)HD + eps); - __syncthreads(); // every thread has read x before any writes it - for (uint32_t i = t; i < HD; i += HD) x[i] = f32_to_bf16(bf2f(x[i]) * s); + if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p (or, without v_norm, only stored) + const uint32_t h = hh - nq - nkv; + uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)h * HD; + if (vnorm) { + const float s = rsqrtf(head_ss(x, pv, l1) / (float)HD + eps); + __syncthreads(); // every thread has read x before any writes it + for (uint32_t i = t; i < HD; i += HD) { + const uint16_t y = f32_to_bf16(bf2f(x[i]) * s); + x[i] = y; + if (KV) sb[i] = y; + } + } else if (KV) { + for (uint32_t i = t; i < HD; i += HD) sb[i] = x[i]; + } + if (KV && put) { + __syncthreads(); + kv_put(kvc, base + (size_t)h * head_step + HD, sb, v_inv); + } return; } const bool isq = hh < nq; @@ -104,7 +179,11 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( if (VK && !isq) { // v = rmsnorm_p(raw k), before the k norm rewrites k uint16_t* __restrict__ vo = v + (size_t)m * v_ld + (size_t)h * HD; const float sv = rsqrtf(head_ss(x, pv, l2) / (float)HD + eps); - for (uint32_t i = t; i < HD; i += HD) vo[i] = f32_to_bf16(bf2f(x[i]) * sv); + for (uint32_t i = t; i < HD; i += HD) { + const uint16_t y = f32_to_bf16(bf2f(x[i]) * sv); + vo[i] = y; + if (KV && VK) vb[i] = y; + } } const float s = rsqrtf(head_ss(x, isq ? pq : pk, l1) / (float)HD + eps); for (uint32_t i = t; i < HD; i += HD) { @@ -112,16 +191,24 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( nb[i] = f32_to_bf16(bf2f(x[i]) * s * (g + wadd)); } __syncthreads(); // the normed head is complete before any pair reads across it - if (m < n_pos) rotate(nb, x, p0, rot, nfreq, den, theta); - else for (uint32_t i = t; i < HD; i += HD) x[i] = nb[i]; + uint16_t* const st = (KV && !isq) ? sb : nullptr; + if (m < n_pos) rotate(nb, x, p0, rot, nfreq, den, theta, st); + else for (uint32_t i = t; i < HD; i += HD) { x[i] = nb[i]; if (st) st[i] = nb[i]; } + if (KV && !isq && put) { + __syncthreads(); // the stored head (and VK's value) complete in LDS + kv_put(kvc, base + (size_t)h * head_step, sb, k_inv); + if (VK) kv_put(kvc, base + (size_t)h * head_step + HD, vb, v_inv); + } } } // namespace -// ============================================================== the plugin ABI entry point -enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW }; +// ============================================================== the plugin ABI entry points +enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW, QN_SLOT, QN_CACHE }; -extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { +// Both ops' launch: `store` reads qkv_norm_rope_kv_store's slot mapping and cache (operands 6, 7) +// and its kv_store parameters. +static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store) { int emit_rc = RAD_OK; const RadTensor* q = r4d_opt(a, QN_Q); const RadTensor* k = r4d_opt(a, QN_K); @@ -138,11 +225,12 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { const long long nkv = r4d_geti_or(a, "n_head_kv", 0); const long long rot = r4d_geti_or(a, "rotary_dim", hd); const long long vk = r4d_geti_or(a, "v_from_k", 0); - // v_norm 0: no value norm at all (Gemma 3); the v heads are left out of the grid. + // v_norm 0: no value norm (Gemma 3; a Qwen3-shaped layer such as the DFlash2 drafter's): the v + // heads are left out of the grid, or with the store only store. const long long vn = r4d_geti_or(a, "v_norm", 1); if (hd != 128 && hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE); - if (vk && !vn) return R4D_NO(RAD_E_INVAL); - if (nq <= 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + if (vk && !vn) return R4D_NO(RAD_E_INVAL); // v from k is v's norm + if (nq < 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(qw) != hd || r4d_numel(kw) != hd) return R4D_NO(RAD_E_SHAPE); const char* mode = r4d_gets(a, "mode"); if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); @@ -158,39 +246,87 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { const long long rot_l = (den == hd && rot < hd) ? hd : rot; long long M = 0, Mk = 0, Mv = 0; - const long long q_ld = r4d_rows_pitch(q, nq * hd, &M); + /* n_head 0: the k (and v) heads alone, q neither read nor written (a context pass's keys) */ + const long long q_ld = nq ? r4d_rows_pitch(q, nq * hd, &M) : 0; const long long k_ld = r4d_rows_pitch(k, nkv * hd, &Mk); const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv); if (q_ld < 0 || k_ld < 0 || v_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (!nq) M = Mk; const long long Mp = r4d_numel(ps); if (Mp <= 0 || M < Mp || Mk != M || Mv != M) return R4D_NO(RAD_E_SHAPE); // The standalone kernels' widths, from the same function: rmsnorm (one row per head) at // r4d_act_threads(rows, head_dim), rmsnorm_p at 256. - const uint32_t pq = (uint32_t)std::min(r4d_act_threads((int)(M * nq), (int)hd), hd); + const uint32_t pq = nq ? (uint32_t)std::min(r4d_act_threads((int)(M * nq), (int)hd), hd) + : (uint32_t)hd; const uint32_t pk = (uint32_t)std::min(r4d_act_threads((int)(M * nkv), (int)hd), hd); const uint32_t pv = (uint32_t)std::min(256, hd); const float eps = (float)r4d_getf(a, "eps", 1e-6); const float wadd = (float)r4d_getf(a, "wadd", 0.0); const float theta = (float)r4d_getf(a, "theta", 10000.0); const float rsc = (float)r4d_getf(a, "scale", 1.0); - const uint32_t heads = (uint32_t)(nq + nkv + ((vk || !vn) ? 0 : nkv)); + /* v's own heads: normed (and stored), stored only, or with neither nothing to do */ + const uint32_t heads = (uint32_t)(nq + nkv + ((vk || (!vn && !store)) ? 0 : nkv)); // A tp-4 verify of the 31B is 16 rows x 16 heads of 8 wavefronts: exactly a full card, the // cliff r4d_cliff_rows steps past with one idle row. const dim3 grid(r4d_cliff_rows((uint32_t)M, heads, (uint32_t)(hd / kWave)), heads); -#define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ + // The store's geometry, checked as kv_store_geom checks it (r4d_model_bf16.hip). + int kvw = 0; // 0 none, 1 E4M3, 2 bf16 + const RadTensor* sm = nullptr; + const RadTensor* kv = nullptr; + long long bs = 0, nblk = 0, nslot = 0; + float kinv = 1.0f, vinv = 1.0f; + if (store) { + sm = r4d_opt(a, QN_SLOT); + kv = r4d_opt(a, QN_CACHE); + if (!sm || !kv) return R4D_NO(RAD_E_INVAL); + if (sm->dtype != RAD_I32 || !r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE); + bs = r4d_geti_or(a, "block_size", 0); + if (bs <= 0 || kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || + kv->shape[3] != 2 * hd) + return R4D_NO(RAD_E_SHAPE); + nblk = kv->shape[0]; + nslot = r4d_numel(sm); + if (nslot <= 0 || nslot > M) return R4D_NO(RAD_E_SHAPE); + if (kv->dtype == RAD_F8E4M3) { + const double ks = r4d_getf(a, "k_scale", 1.0), vs = r4d_getf(a, "v_scale", 1.0); + if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL); + kinv = 1.0f / (float)ks; + vinv = 1.0f / (float)vs; + kvw = 1; + } else if (kv->dtype == RAD_BF16) { + kvw = 2; + } else { + return R4D_NO(RAD_E_DTYPE); + } + } + +#define R4D_QNR_T(HD, WF, VK, KV) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ (uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \ r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \ (uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp, \ - (uint32_t)M) + (uint32_t)M, (const int32_t*)(sm ? r4d_p(sm) : nullptr), (void*)(kv ? r4d_wp(kv) : nullptr), \ + (uint32_t)nslot, (uint32_t)bs, (uint32_t)nblk, kinv, vinv, (uint32_t)(vn ? 1 : 0)) +#define R4D_QNR_KV(HD, WF, VK) \ + do { if (kvw == 1) R4D_QNR_T(HD, WF, VK, 1); else if (kvw == 2) R4D_QNR_T(HD, WF, VK, 2); \ + else R4D_QNR_T(HD, WF, VK, 0); } while (0) #define R4D_QNR(HD) \ - do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_T(HD, true, true); else R4D_QNR_T(HD, true, false); } \ - else { if (vk) R4D_QNR_T(HD, false, true); else R4D_QNR_T(HD, false, false); } } while (0) + do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_KV(HD, true, true); else R4D_QNR_KV(HD, true, false); } \ + else { if (vk) R4D_QNR_KV(HD, false, true); else R4D_QNR_KV(HD, false, false); } } while (0) if (hd == 128) R4D_QNR(128); else if (hd == 256) R4D_QNR(256); else R4D_QNR(512); #undef R4D_QNR +#undef R4D_QNR_KV #undef R4D_QNR_T return emit_rc; } + +extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { + return qkv_norm_rope_launch(a, stream, false); +} + +extern "C" int r4d_rad_qkv_norm_rope_kv_store(const RadArgs* a, RadStream stream) { + return qkv_norm_rope_launch(a, stream, true); +} diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 9cccf694..4567168a 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -728,6 +728,21 @@ static const RadOperandSpec oGemmNt[] = { * (w5a16, w4a16_asym, w4a8i8_asym, w5a8i8): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each * meet their own copy of the activation, side by side in a row of `a` ([M, parts * K]). 0 leaves a * bound out. Absent on other grids, where a fused projection has one activation. */ +/* `add_rmsnorm` is `add` (x += a) followed by `rmsnorm` of the x it wrote (docs/OPS.md). */ +static const RadParamSpec pAddRmsNorm[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + P_F64("eps"), + { "dtype", RAD_P_STR, RAD_REQUIRED }, + P_F64O("wadd"), + P_F64O("mult"), +}; +static const RadOperandSpec oAddRmsNorm[] = { + { "x", RAD_OPD_INOUT, 0 }, + { "a", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pGemmNtQ[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "N", RAD_P_INT, RAD_REQUIRED }, @@ -1404,6 +1419,7 @@ static const RadParamSpec pQkvNormRope[] = { { "ladder", RAD_P_STR, RAD_OPTIONAL }, P_F64O("wadd"), { "v_from_k", RAD_P_INT, RAD_OPTIONAL }, + /* 0 leaves v unnormed (Gemma 3; a Qwen3-shaped layer); absent, 1 */ { "v_norm", RAD_P_INT, RAD_OPTIONAL }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; @@ -1415,6 +1431,39 @@ static const RadOperandSpec oQkvNormRope[] = { { "q_w", RAD_OPD_WEIGHT, 0 }, { "k_w", RAD_OPD_WEIGHT, 0 }, }; +/* `qkv_norm_rope_kv_store` is qkv_norm_rope followed by kv_store in one launch: the prologue's + * operands, then kv_store's slot mapping and paged cache; every parameter is one of the two ops'. + * Byte-identical to the pair (docs/OPS.md). */ +static const RadParamSpec pQkvNormRopeKv[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "head_dim", RAD_P_INT, RAD_REQUIRED }, + { "n_head", RAD_P_INT, RAD_REQUIRED }, + { "n_head_kv", RAD_P_INT, RAD_REQUIRED }, + P_F64("theta"), + P_F64("eps"), + P_F64O("scale"), + { "mode", RAD_P_STR, RAD_OPTIONAL }, + { "rotary_dim", RAD_P_INT, RAD_OPTIONAL }, + { "ladder", RAD_P_STR, RAD_OPTIONAL }, + P_F64O("wadd"), + { "v_from_k", RAD_P_INT, RAD_OPTIONAL }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, + { "v_norm", RAD_P_INT, RAD_OPTIONAL }, + { "block_size", RAD_P_INT, RAD_REQUIRED }, + { "kv_dtype", RAD_P_STR, RAD_REQUIRED }, + P_F64O("k_scale"), + P_F64O("v_scale"), +}; +static const RadOperandSpec oQkvNormRopeKv[] = { + { "q", RAD_OPD_INOUT, 0 }, + { "k", RAD_OPD_INOUT, 0 }, + { "v", RAD_OPD_INOUT, 0 }, + { "positions", RAD_OPD_IN, 0 }, + { "q_w", RAD_OPD_WEIGHT, 0 }, + { "k_w", RAD_OPD_WEIGHT, 0 }, + { "slot_mapping", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_INOUT, 0 }, +}; /* `gelu_mul_quant_i8` is `gelu_mul` with quant_act_i8's quantiser on its pass: the down projection * input of a GELU-gated feed-forward on the w4a8 grid, byte-identical to the pair. */ @@ -3097,9 +3146,17 @@ static const RadOpSchema kSchemas[] = { SCHEMA("rmsnorm_quant_i8", pRmsNormQuantI8, oRmsNormQuantI8, "RMS norm and the per-row int8 quantiser the w4a8 skinny GEMM reads, in one pass; with " "a residual the norm is of residual + x (+ a post-norm of x, x a scalar), stored back."), + SCHEMA("add_rmsnorm", pAddRmsNorm, oAddRmsNorm, + "x = x + a, then y = rmsnorm(x) * (w + wadd) * mult over the x written: a residual add " + "and the next norm in one pass, byte-identical to add then rmsnorm. The norm is taken " + "over the bf16 sum it stores; rmsnorm_add normalises the unrounded one."), SCHEMA("qkv_norm_rope", pQkvNormRope, oQkvNormRope, "per-head q and k RMS norms, the weightless v norm and the rotary of q and k over separate " - "q, k and v projections, in one dispatch; v from the raw k under v_from_k."), + "q, k and v projections, in one dispatch; v from the raw k under v_from_k. n_head 0 " + "leaves q unread (the k and v heads alone)."), + SCHEMA("qkv_norm_rope_kv_store", pQkvNormRopeKv, oQkvNormRopeKv, + "qkv_norm_rope, then kv_store of the finished k and v heads into the paged cache, in one " + "launch."), SCHEMA("gelu_mul_quant_i8", pGeluMulQuantI8, oGeluMulQuantI8, "gelu(gate) * up (tanh form) and the per-row int8 quantiser the w4a8 skinny GEMM reads, in " "one pass."), @@ -3548,6 +3605,19 @@ static const RadConstraint cAttnDecodeH256Gqa2Bf16[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; +/* Head_dim 128 at 8 queries per kv head under attn_paged_qrow: the gqa-4 kernel above with each kv + * head mapped onto two query groups (R4DArgs::kv_rep), so q_len * 4 <= 64 bounds it where gqa 8's + * own decode (q_len <= 8, no window) stops at 8. The 31B's DFlash drafter: 64 heads over 8 kv heads, + * sliding layers over 2048 and a full non-causal one, at a block of 16. Under attn_paged_qrow, which + * no host library declares, so a drafter asking for it learns whether a card serves it. */ +static const RadConstraint cAttnQrowH128G8Fp8[] = { + C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnQrowH128G8Bf16[] = { + C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; /* Gemma 4 dense sliding-window prefill (r4d_attn_paged_h256_gqa2.hip): the decode leg's geometry * without a q_len bound, serving q_len > 32. The kernel's WIN bit masks the window and skips tiles * below it. Without this row the prefill band would have no device kernel, which is fatal (spec @@ -4480,6 +4550,9 @@ static const RadConstraint cRmsNormQuantI8[] = { C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), }; /* head_dim 256 or 512: a workgroup is one head, a thread one channel. */ +static const RadConstraint cAddRmsNorm[] = { + C_GE("n", 1), C_IN("dtype", "bf16"), +}; static const RadConstraint cQkvNormRope[] = { C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), }; @@ -4487,6 +4560,14 @@ static const RadConstraint cQkvNormRope[] = { static const RadConstraint cQkvNormRopeH128[] = { C_EQ("head_dim", 128), C_IN("dtype", "bf16"), }; +static const RadConstraint cQkvNormRopeKv[] = { + C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), + C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cQkvNormRopeKvBf16[] = { + C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), + C_GE("block_size", 1), C_IN("kv_dtype", "bf16"), +}; static const RadConstraint cGeluMulQuantI8[] = { C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), }; @@ -5902,6 +5983,52 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_attn_decode_h128_gqa2w_bf16, r4d_rad_attn_decode_h128_gqa2w_scratch, nullptr, nullptr, r4d_shape_attn_paged }, +/* The same decode under attn_paged_qrow, reading q at its own row pitch: Gemma 4 31B's sliding + * layers read q in the fused q|k|v row. It outranks the windowed qrow rows (R4D_PRIO_ONLY) in its + * band, as attn_paged's does, since it takes 0.26-0.71 of their time there; above q_len 32 the + * windowed kernel serves the op alone. No opd_shape, as for every qrow row: libref has none. */ +{ "attn_qrow_decode_h256_gqa2_fp8kv", "attn_paged_qrow", "attn", + "paged attention reading q at its own row pitch, sliding window, split-KV (decode / verify)", + "head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, " + "window taken from the launch argument (0 = full attention)", + "bf16 query (any row pitch, a multiple of 4), fp8-e4m3 kv cache with per-(seq,head) descales, " + "bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256Gqa2Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_decode_h256_gqa2_fp8, + r4d_rad_attn_qrow_decode_h256_gqa2_scratch, + nullptr, nullptr, nullptr }, + +{ "attn_qrow_decode_h256_gqa2_bf16kv", "attn_paged_qrow", "attn", + "paged attention reading q at its own row pitch, sliding window, split-KV (decode / verify)", + "head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, " + "window taken from the launch argument (0 = full attention)", + "bf16 query (any row pitch, a multiple of 4), bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256Gqa2Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_decode_h256_gqa2_bf16, + r4d_rad_attn_qrow_decode_h256_gqa2_scratch, + nullptr, nullptr, nullptr }, + +/* Head_dim 128 at gqa 8 under attn_paged_qrow (cAttnQrowH128G8Fp8 says why). */ +{ "attn_qrow_h128_gqa8_fp8kv", "attn_paged_qrow", "attn", + "paged attention, any window, causal or not, split-KV (draft block); q at any row pitch", + "head_dim 128, 8 queries per kv head as two groups of 4 a kv head, paged block 16, q_len <= 16", + "bf16 query (any row pitch, a multiple of 4), fp8-e4m3 kv cache with per-(seq,head) descales, " + "bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnQrowH128G8Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_h128_gqa8_fp8, r4d_rad_attn_qrow_h128_gqa8_scratch, + nullptr, nullptr, nullptr }, + +{ "attn_qrow_h128_gqa8_bf16kv", "attn_paged_qrow", "attn", + "paged attention, any window, causal or not, split-KV (draft block); q at any row pitch", + "head_dim 128, 8 queries per kv head as two groups of 4 a kv head, paged block 16, q_len <= 16", + "bf16 query (any row pitch, a multiple of 4), bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnQrowH128G8Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_h128_gqa8_bf16, r4d_rad_attn_qrow_h128_gqa8_scratch, + nullptr, nullptr, nullptr }, { "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", @@ -7662,7 +7789,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "rope x2, each norm taken by its standalone kernel's partition", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkvNormRope), NOTUNE, - nullptr, nullptr, r4d_rad_qkv_norm_rope }, + nullptr, nullptr, r4d_rad_qkv_norm_rope, nullptr, nullptr, nullptr, r4d_shape_qkv_norm_rope }, { "qkv_norm_rope_h128_bf16", "qkv_norm_rope", "attn", "per-head RMS norms of separate q and k projections, the weightless norm of v unless v_norm is 0, " @@ -7675,6 +7802,41 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cQkvNormRopeH128), NOTUNE, nullptr, nullptr, r4d_rad_qkv_norm_rope }, +/* The prologue and the cache store in one launch: a k (or v) head's block ends holding its token's + * finished head, so it writes it into the cache too, converted as kv_store converts it. Saves the + * store's launch a layer, which at decode is most of its cost. */ +{ "qkv_norm_rope_kv_store_fp8", "qkv_norm_rope_kv_store", "attn", + "qkv_norm_rope, and kv_store into an E4M3 paged cache from the same launch", + "qkv_norm_rope's shapes; cache exactly [n_blocks, n_head_kv, block_size, 2*head_dim], one slot " + "a row; a negative or out-of-range slot stores nothing", + "bf16 q/k/v and gains (or f32 gains), i32 positions and slots, fp8-e4m3 cache, scalar " + "k_scale / v_scale descales; byte-identical to qkv_norm_rope + kv_store_fp8", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkvNormRopeKv), NOTUNE, + nullptr, nullptr, r4d_rad_qkv_norm_rope_kv_store, nullptr, nullptr, nullptr, + r4d_shape_qkv_norm_rope_kv_store, nullptr, r4d_fuse_qkv_norm_rope_kv_store }, + +/* The same into a bf16 cache: the store is the values kv_store_bf16 copies. */ +{ "qkv_norm_rope_kv_store_bf16", "qkv_norm_rope_kv_store", "attn", + "qkv_norm_rope, and kv_store into a bf16 paged cache from the same launch", + "qkv_norm_rope's shapes; cache exactly [n_blocks, n_head_kv, block_size, 2*head_dim], one slot " + "a row; a negative or out-of-range slot stores nothing", + "bf16 q/k/v, gains, cache; i32 positions and slots; byte-identical to qkv_norm_rope + " + "kv_store_bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkvNormRopeKvBf16), NOTUNE, + nullptr, nullptr, r4d_rad_qkv_norm_rope_kv_store, nullptr, nullptr, nullptr, + r4d_shape_qkv_norm_rope_kv_store, nullptr, r4d_fuse_qkv_norm_rope_kv_store }, + +{ "add_rmsnorm_bf16", "add_rmsnorm", "norm", + "x += a, then the root-mean-square norm of the x written, one workgroup a row as rmsnorm_bf16", + "any n; rmsnorm_bf16's width and column partition, so the sum of squares folds as it does", + "bf16 x / a / y, f32 or bf16 gain, fp32 reduction; byte-identical to add_bf16 + rmsnorm_bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAddRmsNorm), NOTUNE, + nullptr, nullptr, r4d_rad_add_rmsnorm, nullptr, nullptr, nullptr, + r4d_shape_add_rmsnorm, nullptr, r4d_fuse_add_rmsnorm }, + { "gelu_mul_quant_i8", "gelu_mul_quant_i8", "quant", "gelu(gate) * up, the tanh form, and quant_act_i8's quantiser in one pass over the row", "n a multiple of 16 and n*2 bytes within LDS; one workgroup per row", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 2f204341..47fe35a0 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -943,9 +943,11 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8 /* Numeric attention check: fill q and the paged k/v with avalanche-random data, run the row, and * compare the bf16 output against the oracle above. A negative control corrupts part of the * reference and requires the comparison to fail. */ +/* `q_extra` > 0: q is a column slice of rows q_extra elements wider than its heads (an + * attn_paged_qrow row reads it at that pitch, as from a fused q|k|v projection). */ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa, int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64, - int64_t bs = 16) { + int64_t bs = 16, int64_t q_extra = 0) { if (!sel(name)) return; const RadKernelInfo* r = find(pl, name); if (!r) { ok(name, false, "row absent"); return; } @@ -992,8 +994,16 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d } const std::vector bt = iota_i32(max_blocks); - void* d_q = dalloc((size_t)total_q * q_heads * head_dim * 2); - st_memcpy(d_q, qh.data(), qh.size() * 2, hipMemcpyHostToDevice); + const int64_t q_ld = q_heads * head_dim + q_extra; + void* d_q = dalloc((size_t)total_q * q_ld * 2); + { + /* the slice's rows at the pitch, the rest of each row a value no head holds */ + std::vector qp((size_t)total_q * q_ld, h_to_bf16(9.0f)); + for (int64_t t = 0; t < total_q; ++t) + std::memcpy(&qp[(size_t)(t * q_ld)], &qh[(size_t)(t * q_heads * head_dim)], + (size_t)(q_heads * head_dim) * 2); + st_memcpy(d_q, qp.data(), qp.size() * 2, hipMemcpyHostToDevice); + } void* d_kv = dalloc(kv.size()); st_memcpy(d_kv, kv.data(), kv.size(), hipMemcpyHostToDevice); void* d_out = dalloc((size_t)total_q * q_heads * head_dim * 2); @@ -1008,6 +1018,7 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d T(nullptr, RAD_I32, { seqs + 1 }), T(d_out, RAD_BF16, { total_q, q_heads, head_dim }), }; + ts[0].stride[0] = q_ld; if (kvdt == RAD_BF16) { absent(ts[4]); absent(ts[5]); } absent(ts[6]); std::vector ps = { @@ -10977,10 +10988,16 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { const RadKernelInfo* rp = find(pl, "rope_bf16"); const RadKernelInfo* fz = find(pl, "qkv_norm_rope_bf16"); if (!np || !nrm || !rp || !fz) { ok("qkv_norm_rope vs its five", false, "rows absent"); return; } + /* vn false: no value norm (Gemma 3's prologue, and a Qwen3-shaped layer such as the DFlash2 + * drafter's), q and k normed and v not, so the chain is four ops and v must come out as it went + * in; nq 0 as well: that layer's keys alone (the drafter's context pass), the chain a k norm and + * a k rope, q passed as k's buffer */ struct Cls { int64_t hd, nq, nkv, rot; const char* ladder; double theta; bool vk, vn; }; for (const Cls& cl : { Cls{ 256, 16, 8, 256, "rotary", 10000.0, false, true }, Cls{ 512, 16, 2, 128, "head", 1000000.0, true, true }, - Cls{ 128, 16, 8, 128, "rotary", 10000.0, false, false } }) { + Cls{ 128, 16, 8, 128, "rotary", 10000.0, false, false }, + Cls{ 256, 8, 4, 256, "rotary", 10000.0, false, false }, + Cls{ 256, 0, 4, 256, "rotary", 10000.0, false, false } }) { /* 8 rows of the head-256 class are 8 x 32 workgroups of 8 wavefronts, a full card: the * launch adds an idle row past the cliff (r4d_cliff_rows), which must not change a byte. */ for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)8, (int64_t)40 }) { @@ -10996,9 +11013,11 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { hkw[(size_t)c] = h_to_bf16(0.5f + 0.005f * (float)((c * 11) % 47)); } for (int64_t m = 0; m < M; ++m) hp[(size_t)m] = (int32_t)(1000 + 7 * m); - void* dq[2] = { dalloc(hq.size() * 2), dalloc(hq.size() * 2) }; + void* dq[2] = { nullptr, nullptr }; void* dk[2] = { dalloc(hk.size() * 2), dalloc(hk.size() * 2) }; void* dv[2] = { dalloc(hv.size() * 2), dalloc(hv.size() * 2) }; + for (int j = 0; j < 2; ++j) dq[j] = cl.nq ? dalloc(hq.size() * 2) : dk[j]; + const int64_t QW = cl.nq ? QD : KD; /* q's width as passed (k's buffer at nq 0) */ void* dqw = dalloc(hqw.size() * 2); void* dkw = dalloc(hkw.size() * 2); void* dp = dalloc(hp.size() * 4); @@ -11016,26 +11035,28 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { int rc = !cl.vn ? RAD_OK : launch_row(np, { T(cl.vk ? dk[0] : dv[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dv[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, { PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16") }); - if (rc == RAD_OK) + if (rc == RAD_OK && cl.nq) rc = launch_row(nrm, { T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }), T(dqw, RAD_BF16, { cl.hd }), T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }) }, { PI("M", M * cl.nq), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); if (rc == RAD_OK) rc = launch_row(nrm, { T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dkw, RAD_BF16, { cl.hd }), T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, { PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); - for (int j = 0; j < 2 && rc == RAD_OK; ++j) + for (int j = cl.nq ? 0 : 1; j < 2 && rc == RAD_OK; ++j) rc = launch_row(rp, { T(j ? dk[0] : dq[0], RAD_BF16, { M, (j ? cl.nkv : cl.nq) * cl.hd }), T(dp, RAD_I32, { M }) }, { PI("M", M), PI("head_dim", cl.hd), PI("n_head", j ? cl.nkv : cl.nq), PI("n_head_kv", 0), PF("theta", cl.theta), PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot), PS("ladder", cl.ladder) }); /* --- the one --- */ if (rc == RAD_OK) - rc = launch_row(fz, { T(dq[1], RAD_BF16, { M, QD }), T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }), + rc = launch_row(fz, { T(dq[1], RAD_BF16, { M, QW }), T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }), T(dp, RAD_I32, { M }), T(dqw, RAD_BF16, { cl.hd }), T(dkw, RAD_BF16, { cl.hd }) }, { PI("M", M), PI("head_dim", cl.hd), PI("n_head", cl.nq), PI("n_head_kv", cl.nkv), PF("theta", cl.theta), PF("eps", eps), PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot), PS("ladder", cl.ladder), PF("wadd", wadd), PI("v_from_k", cl.vk ? 1 : 0), PI("v_norm", cl.vn ? 1 : 0), PS("dtype", "bf16") }); - const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) + " M=" + std::to_string(M); + const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) + + (cl.nq ? "" : " n_head=0") + (cl.vn ? "" : " v_norm=0") + + " M=" + std::to_string(M); if (rc != RAD_OK) { ok((what + " vs its five").c_str(), false, "rc=" + std::to_string(rc)); continue; } int nd = 0, moved = 0; for (int t = 0; t < 3; ++t) { @@ -11047,12 +11068,149 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { const std::vector& h0 = t == 0 ? hq : (t == 1 ? hk : hv); for (size_t i = 0; i < n; ++i) { nd += a[i] != b[i]; moved += b[i] != h0[i]; } } - ok((what + " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2").c_str(), nd == 0 && moved > 0, + ok((what + (cl.nq ? " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2" + : " is byte-identical to rmsnorm + rope over k")).c_str(), + nd == 0 && moved > 0, "differs " + std::to_string(nd) + ", changed from the input " + std::to_string(moved)); + + /* --- and with kv_store folded in (qkv_norm_rope_kv_store): the pair (the prologue's + * output above, then kv_store) against the one launch from the same inputs, at both + * cache widths. Slots are unique with one row's negative (padding, which stores + * nothing), and the caches start marked, so a stray or a missing store shows. --- */ + for (const bool f8 : { true, false }) { + const RadKernelInfo* ks = find(pl, f8 ? "kv_store_fp8" : "kv_store_bf16"); + const RadKernelInfo* fk = find(pl, f8 ? "qkv_norm_rope_kv_store_fp8" + : "qkv_norm_rope_kv_store_bf16"); + const std::string w2 = what + (f8 ? " + kv_store_fp8" : " + kv_store_bf16"); + if (!ks || !fk) { ok(w2.c_str(), false, "rows absent"); continue; } + const int64_t bs = 16, nb = (M + bs - 1) / bs + 2, esz = f8 ? 1 : 2; + const size_t cb = (size_t)(nb * cl.nkv * bs * 2 * cl.hd * esz); + std::vector hs((size_t)M); + for (int64_t m = 0; m < M; ++m) hs[(size_t)m] = (int32_t)((m * 37 + 3) % (nb * bs)); + if (M > 1) hs[1] = -1; + void* dsl = dalloc(hs.size() * 4); + void* dc[2] = { dalloc(cb), dalloc(cb) }; + void* d3[3] = { nullptr, dalloc(hk.size() * 2), dalloc(hv.size() * 2) }; + d3[0] = cl.nq ? dalloc(hq.size() * 2) : d3[1]; + if (!dsl || !dc[0] || !dc[1] || !d3[0] || !d3[1] || !d3[2]) { + ok(w2.c_str(), false, "hipMalloc failed"); + continue; + } + st_memcpy(dsl, hs.data(), hs.size() * 4, hipMemcpyHostToDevice); + st_memset(dc[0], 0x5A, cb); + st_memset(dc[1], 0x5A, cb); + st_memcpy(d3[0], hq.data(), hq.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d3[1], hk.data(), hk.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d3[2], hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + const uint32_t kvdt = f8 ? RAD_F8E4M3 : RAD_BF16; + const char* kvn = f8 ? "fp8_e4m3" : "bf16"; + int r2 = launch_row(ks, { T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }), + T(dsl, RAD_I32, { M }), + T(dc[0], kvdt, { nb, cl.nkv, bs, 2 * cl.hd }) }, + { PI("M", M), PI("head_dim", cl.hd), PI("n_head_kv", cl.nkv), + PI("block_size", bs), PS("kv_dtype", kvn) }); + if (r2 == RAD_OK) + r2 = launch_row(fk, { T(d3[0], RAD_BF16, { M, QW }), T(d3[1], RAD_BF16, { M, KD }), + T(d3[2], RAD_BF16, { M, KD }), T(dp, RAD_I32, { M }), + T(dqw, RAD_BF16, { cl.hd }), T(dkw, RAD_BF16, { cl.hd }), + T(dsl, RAD_I32, { M }), + T(dc[1], kvdt, { nb, cl.nkv, bs, 2 * cl.hd }) }, + { PI("M", M), PI("head_dim", cl.hd), PI("n_head", cl.nq), + PI("n_head_kv", cl.nkv), PF("theta", cl.theta), PF("eps", eps), + PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot), + PS("ladder", cl.ladder), PF("wadd", wadd), + PI("v_from_k", cl.vk ? 1 : 0), PS("dtype", "bf16"), + PI("v_norm", cl.vn ? 1 : 0), + PI("block_size", bs), PS("kv_dtype", kvn) }); + if (r2 != RAD_OK) { ok(w2.c_str(), false, "rc=" + std::to_string(r2)); continue; } + std::vector c0(cb), c1(cb); + st_memcpy(c0.data(), dc[0], cb, hipMemcpyDeviceToHost); + st_memcpy(c1.data(), dc[1], cb, hipMemcpyDeviceToHost); + size_t ncd = 0, written = 0; + for (size_t i = 0; i < cb; ++i) { ncd += c0[i] != c1[i]; written += c1[i] != 0x5A; } + size_t nrow = 0; + for (int t = 0; t < 3; ++t) { + void* const pr = t == 0 ? dq[1] : (t == 1 ? dk[1] : dv[1]); + const size_t n = t == 0 ? hq.size() : hk.size(); + std::vector a(n), b(n); + st_memcpy(a.data(), pr, n * 2, hipMemcpyDeviceToHost); + st_memcpy(b.data(), d3[t], n * 2, hipMemcpyDeviceToHost); + for (size_t i = 0; i < n; ++i) nrow += a[i] != b[i]; + } + ok((w2 + " folded into one launch is byte-identical to the pair").c_str(), + ncd == 0 && nrow == 0 && written > 0, + "cache bytes differ " + std::to_string(ncd) + ", q/k/v differ " + + std::to_string(nrow) + ", cache bytes written " + std::to_string(written)); + } } } } +/* ---- add_rmsnorm, against add then rmsnorm -------------------------------------------------- + * + * x = x + a, then rmsnorm of the x written: a DFlash2 drafter's residual add and its next norm. + * Byte-identical on x and on y at every r4d_act_threads width (a query pass's rows, a prefill + * chunk's), with an f32 gain (as plugins declare) and a bf16 one, with and without Gemma's `1 +`. */ +static void add_rmsnorm_numeric(const Plugin& pl) { + const RadKernelInfo* ad = find(pl, "add_bf16"); + const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); + const RadKernelInfo* fz = find(pl, "add_rmsnorm_bf16"); + if (!ad || !nrm || !fz) { ok("add_rmsnorm vs add + rmsnorm", false, "rows absent"); return; } + const int64_t K = 5376; + for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)16, (int64_t)40, (int64_t)300 }) + for (int form = 0; form < 3; ++form) { + const bool f32 = form != 1; + const double wadd = form == 2 ? 1.0 : 0.0; + std::vector hx((size_t)M * K), ha((size_t)M * K), hwb((size_t)K); + std::vector hwf((size_t)K); + for (int64_t r = 0; r < M; ++r) + for (int64_t c = 0; c < K; ++c) { + hx[(size_t)r * K + c] = h_to_bf16(0.029f * (float)((r * 31 + c * 17) % 73) - 1.1f); + ha[(size_t)r * K + c] = h_to_bf16(0.013f * (float)((r * 11 + c * 23) % 61) - 0.4f); + } + for (int64_t c = 0; c < K; ++c) { + hwf[(size_t)c] = 0.7f + 0.0031f * (float)((c * 19) % 53); + hwb[(size_t)c] = h_to_bf16(hwf[(size_t)c]); + } + const size_t nb = (size_t)M * K * 2; + void* dx[2] = { dalloc(nb), dalloc(nb) }; + void* dy[2] = { dalloc(nb), dalloc(nb) }; + void* da = dalloc(nb); + void* dw = dalloc((size_t)K * 4); + if (!dx[1] || !dy[1] || !da || !dw) { ok("add_rmsnorm alloc", false, "hipMalloc failed"); return; } + for (int j = 0; j < 2; ++j) st_memcpy(dx[j], hx.data(), nb, hipMemcpyHostToDevice); + st_memcpy(da, ha.data(), nb, hipMemcpyHostToDevice); + if (f32) st_memcpy(dw, hwf.data(), (size_t)K * 4, hipMemcpyHostToDevice); + else st_memcpy(dw, hwb.data(), (size_t)K * 2, hipMemcpyHostToDevice); + const uint32_t wdt = f32 ? RAD_F32 : RAD_BF16; + const double eps = 1e-6; + int rc = launch_row(ad, { T(dx[0], RAD_BF16, { M, K }), T(da, RAD_BF16, { M, K }), T(dx[0], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(nrm, { T(dx[0], RAD_BF16, { M, K }), T(dw, wdt, { K }), T(dy[0], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); + if (rc == RAD_OK) + rc = launch_row(fz, { T(dx[1], RAD_BF16, { M, K }), T(da, RAD_BF16, { M, K }), T(dw, wdt, { K }), + T(dy[1], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); + const std::string what = std::string("add_rmsnorm M=") + std::to_string(M) + + (f32 ? " f32 gain" : " bf16 gain") + (wadd != 0.0 ? " wadd=1" : ""); + if (rc != RAD_OK) { ok(what.c_str(), false, "rc=" + std::to_string(rc)); continue; } + size_t ndx = 0, ndy = 0, moved = 0; + for (int t = 0; t < 2; ++t) { + std::vector u((size_t)M * K), v((size_t)M * K); + st_memcpy(u.data(), t ? dy[0] : dx[0], nb, hipMemcpyDeviceToHost); + st_memcpy(v.data(), t ? dy[1] : dx[1], nb, hipMemcpyDeviceToHost); + for (size_t i = 0; i < u.size(); ++i) { + (t ? ndy : ndx) += u[i] != v[i]; + if (!t) moved += v[i] != hx[i]; + } + } + ok((what + " is byte-identical to add + rmsnorm").c_str(), ndx == 0 && ndy == 0 && moved > 0, + "x differs " + std::to_string(ndx) + ", y differs " + std::to_string(ndy)); + } +} + /* ---- rmsnorm_quant_i8, against the chain it replaces ------------------------------------------ * * Byte-identical, as the fp8 fusions above, in the three forms a sandwich-norm model issues: the @@ -23810,6 +23968,20 @@ static void device_phase(const Plugin& pl) { attn_case(pl, "attn_decode_h256_gqa6_bf16kv", 256, 6, 1, "bf16", 0); attn_case(pl, "attn_decode_h128_gqa4_fp8kv", 128, 4, 1, "fp8_e4m3", 0); attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0); + /* attn_paged_qrow on the split-KV decode kernel: head_dim 128 at gqa 8 (two query groups a kv + * head, R4DArgs::kv_rep) at the drafter's block of 16, windowed and not, and the h256/gqa2 + * decode with q as a slice of a wider row, at one row and at a verify's sixteen. */ + for (const char* kvd : { "fp8_e4m3", "bf16" }) { + const bool f8 = !std::strcmp(kvd, "bf16") ? false : true; + const char* r128 = f8 ? "attn_qrow_h128_gqa8_fp8kv" : "attn_qrow_h128_gqa8_bf16kv"; + const char* r256 = f8 ? "attn_qrow_decode_h256_gqa2_fp8kv" : "attn_qrow_decode_h256_gqa2_bf16kv"; + attn_numeric_case(pl, r128, 128, 8, 16, kvd, 0, 256); + attn_numeric_case(pl, r128, 128, 8, 16, kvd, 48, 256); + attn_numeric_case(pl, r128, 128, 8, 1, kvd, 0, 256, 16, 2048); + attn_numeric_case(pl, r256, 256, 2, 1, kvd, 0, 256, 16, 2048); + attn_numeric_case(pl, r256, 256, 2, 16, kvd, 0, 256, 16, 2048); + attn_numeric_case(pl, r256, 256, 2, 16, kvd, 64, 256); + } attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 32, "bf16", 1); attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 1, "bf16", 1); /* Gemma 4 dense sliding window, decode, with the model's window of 1024: exercises the @@ -26131,14 +26303,20 @@ static void device_phase(const Plugin& pl) { if (!g_case) std::printf("\ngelu_mul_quant_i8, against the pair it replaces\n"); gelu_mul_quant_i8_numeric(pl); } - if (sel("qkv_norm_rope_bf16")) { - if (!g_case) std::printf("\nqkv_norm_rope, against the five ops it replaces\n"); + if (sel("qkv_norm_rope_bf16") || sel("qkv_norm_rope_kv_store_fp8") || + sel("qkv_norm_rope_kv_store_bf16")) { + if (!g_case) std::printf("\nqkv_norm_rope, and with kv_store folded in, against the ops it " + "replaces\n"); qkv_norm_rope_numeric(pl); } if (sel("rmsnorm_quant_i8")) { if (!g_case) std::printf("\nrmsnorm_quant_i8, against the chain it replaces\n"); rmsnorm_quant_i8_numeric(pl); } + if (sel("add_rmsnorm_bf16")) { + if (!g_case) std::printf("\nadd_rmsnorm, against add then rmsnorm\n"); + add_rmsnorm_numeric(pl); + } /* The MTP head's fc is K=10240; the DFlash2 drafter's is 25600, the largest K any shape asks * these kernels for. Both rows run: an fc declared over M 1..64 resolves to _m16 for small diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 5f8edd16..075a34e3 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -340,6 +340,20 @@ extern "C" int r4d_shape_rmsnorm(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* add_rmsnorm -- rmsnorm's operands with the addend after x. */ +extern "C" int r4d_shape_add_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t n = pi(p, n_p, "n"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { + opd(D, M, n), + opd(D, M, n), + opd((uint32_t)RAD_F32, n), + opd(D, M, n), + }; + R4D_PICK(l); +} + /* ---- the vision tower's (r4d_vit_bf16.hip). Every optional operand is passed: the norm's bias and * the GEMM's residual are the same code with a branch taken, so this covers both forms. */ extern "C" int r4d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1076,6 +1090,48 @@ extern "C" int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, R4D_PICK(l); } +/* qkv_norm_rope -- separate q [M, n_head * head_dim], k and v [M, n_head_kv * head_dim] (dense + * here; the shim also takes each as a slice of a wider row), the positions, and the q and k gains, + * f32 as every architecture plugin declares them (shim in r4d_qkv_norm_rope.hip). As for `rope`, + * a position is not a lookup: the kernel takes sincos of position x frequency, so it is drawn over + * a context's range, where the angles a decode step sees are, not over the band's rows. */ +extern "C" int r4d_shape_qkv_norm_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t hd = pi(p, n_p, "head_dim"); + const int64_t nq = pi(p, n_p, "n_head"); + const int64_t nkv = pi(p, n_p, "n_head_kv"); + const RadOpdDesc l[] = { + /* at n_head 0 the kernel reads no q; it is passed as k's buffer, so drawn like k */ + opd((uint32_t)RAD_BF16, M, (nq ? nq : nkv) * hd), + opd((uint32_t)RAD_BF16, M, nkv * hd), + opd((uint32_t)RAD_BF16, M, nkv * hd), + opd_idx(M, 0, 32768), + opd((uint32_t)RAD_F32, hd), + opd((uint32_t)RAD_F32, hd), + }; + R4D_PICK(l); +} + +/* qkv_norm_rope_kv_store -- qkv_norm_rope's six, then kv_store's slot mapping (unique slots, as + * the engine hands them) and its paged cache, sized as kv_store's description sizes it. */ +extern "C" int r4d_shape_qkv_norm_rope_kv_store(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + if (operand < 6) return r4d_shape_qkv_norm_rope(p, n_p, operand, out); + const int64_t M = pi(p, n_p, "M"); + const int64_t hd = pi(p, n_p, "head_dim"); + const int64_t kvh = pi(p, n_p, "n_head_kv"); + const int64_t bs = pi(p, n_p, "block_size"); + const uint32_t KV = dt_act(p, n_p, "kv_dtype"); + if (M <= 0 || bs <= 0) return RAD_E_UNSUPPORTED; + const int64_t nb = (M + bs - 1) / bs + 2; + const RadOpdDesc l[] = { + opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), + opd_idx(M, 0, nb * bs, -1, RAD_OPD_F_IDX_UNIQUE), + opd(KV, nb, kvh, bs, 2 * hd), + }; + R4D_PICK(l); +} + /* rope_table -- the cos/sin plane the fused prologue reads (shim in r4d_qk_norm_rope_gate.hip). */ extern "C" int r4d_shape_rope_table(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 0f93a880..56b3d8bb 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3235,7 +3235,9 @@ TEST(declare_is_a_gemma4_trunk) { /* 12 layers: 10 sliding + 2 global (layers 5 and 11). */ CHECK_EQ(count_op(b, "attn_paged"), 12); - CHECK_EQ(count_op(b, "kv_store"), 12); + /* the cache store rides the fused prologue where it resolves (qkv_norm_rope_kv_store) */ + CHECK_EQ(count_op(b, "qkv_norm_rope_kv_store"), 12); + CHECK_EQ(count_op(b, "kv_store"), 0); CHECK_EQ(count_op(b, "rmsnorm_p"), 12); /* weightless value norm, one per layer */ CHECK_EQ(count_op(b, "rope"), 24); /* q + k */ CHECK_EQ(count_op(b, "gelu_mul"), 12); /* Gemma's FFN activation, not SwiGLU */ @@ -3446,6 +3448,7 @@ TEST(gemma4_every_weight_has_a_name_map) { TEST(a_gemma4_decode_step_runs_both_classes_in_order) { RadBuilder b; b.refuse.insert("qkv_norm_rope"); /* force the unfused prologue; fused is checked below */ + b.refuse.insert("qkv_norm_rope_kv_store"); RadModelMeta meta = gemma4_meta(); RadBuildCtx ctx = build_ctx(); CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); @@ -3518,7 +3521,7 @@ TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) { for (int l = 0; l < 12; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q"); - for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) want.push_back(s); if (l < 11) want.push_back("ar_rmsnorm_quant_i8"); @@ -3532,7 +3535,7 @@ TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) { for (int l = 0; l < 12; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) plain.push_back("gemm_nt_q"); - for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q", "all_reduce" }) plain.push_back(s); @@ -3549,7 +3552,7 @@ TEST(a_gemma4_w4a8_step_fuses_its_residual_junctions) { for (int l = 0; l < 12; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q"); - for (const char* s : { "qkv_norm_rope", "kv_store", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) want.push_back(s); @@ -3576,7 +3579,8 @@ TEST(a_gemma4_w4a8_step_without_the_fused_ops_keeps_the_chain_and_one_qkv_quanti } for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) want.push_back(s); - CHECK_EQ(join(gemma4_w4_step({ "rmsnorm_quant_i8", "qkv_norm_rope", "gelu_mul_quant_i8" })), join(want)); + CHECK_EQ(join(gemma4_w4_step({ "rmsnorm_quant_i8", "qkv_norm_rope", "qkv_norm_rope_kv_store", + "gelu_mul_quant_i8" })), join(want)); } /* =============================== gemma4: the assistant (MTP) head =============================== */ @@ -3644,7 +3648,7 @@ TEST(gemma4_assistant_is_a_serial_head_with_no_cache_of_its_own) { /* Four head attention layers beside the trunk's twelve, none storing. */ CHECK_EQ(count_op(b, "attn_paged"), 16); - CHECK_EQ(count_op(b, "kv_store"), 12); + CHECK_EQ(count_op(b, "kv_store") + count_op(b, "qkv_norm_rope_kv_store"), 12); CHECK_EQ(count_op(b, "logit_softcap"), 1); /* trunk only; head logits are not capped */ CHECK_EQ(count_op(b, "logits_gemm"), 2); @@ -4609,10 +4613,10 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ for (int l = 0; l < L; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) { folded.push_back("gemm_nt_q"); apart.push_back("gemm_nt_q"); } - for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) folded.push_back(s); - for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q", "all_reduce" }) apart.push_back(s); @@ -4763,8 +4767,10 @@ rad_kvgroup kv_named(const RadBuilder& b, const char* name) { TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) { G431Df f; const RadModelMeta meta = f.meta(); + for (const bool served : { true, false }) { RadBuilder b; g431df_encs(b, false, false); + if (!served) b.refuse.insert("attn_paged_qrow"); RadBuildCtx ctx = build_ctx(); ctx.max_spec = 15; CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); @@ -4782,23 +4788,29 @@ TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) { REQUIRE(kvd != 0); CHECK_EQ((int)b.kv_groups[kvd - 1].d.kind, (int)RAD_KV_FULL); CHECK_EQ(b.kv_groups[kvd - 1].d.head_dim, 128); - /* 64 heads over 8 kv heads is gqa 8, and libr4d's head-128 attention takes 4 queries per kv - * head at a block of 16: the cache holds each kv head twice, the projections stay 8 heads - * wide, and every attention and cache write of the drafter sees 16 kv heads at gqa 4. */ - CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, 16); + /* 64 heads over 8 kv heads is gqa 8. Where a card serves it under attn_paged_qrow (libr4d's + * head-128 kernel with two query groups a kv head), the cache holds each kv head once and + * attention runs at gqa 8. Where not, libr4d's head-128 attention takes 4 queries per kv head + * at a block of 16: the cache holds each kv head twice, the projections stay 8 heads wide, and + * every attention and cache write of the drafter sees 16 kv heads at gqa 4. */ + const int64_t heads = served ? 8 : 16; + CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, heads); CHECK_EQ(b.bufs[buf_named(b, "df_k") - 1].d.shape[1], 8 * 128); - CHECK_EQ(b.bufs[buf_named(b, "df_k4") - 1].d.shape[1], 16 * 128); + if (served) CHECK_EQ(buf_named(b, "df_k4"), 0); + else CHECK_EQ(b.bufs[buf_named(b, "df_k4") - 1].d.shape[1], 16 * 128); { int n_attn = 0, n_store = 0; for (const auto& o : b.ops) { - if (o.op == "attn_paged" && pint(&o, "head_dim") == 128) { + /* the asking ops (qrow_serves) name no buffer */ + if (o.op == (served ? "attn_paged_qrow" : "attn_paged") && pint(&o, "head_dim") == 128 && + !o.reads.empty()) { ++n_attn; - CHECK_EQ(pint(&o, "gqa"), 4); + CHECK_EQ(pint(&o, "gqa"), served ? 8 : 4); CHECK_EQ(pint(&o, "n_head"), 64); } if (o.op == "kv_store" && pint(&o, "head_dim") == 128) { ++n_store; - CHECK_EQ(pint(&o, "n_head_kv"), 16); + CHECK_EQ(pint(&o, "n_head_kv"), heads); } } CHECK_EQ(n_attn, 2); /* the sliding layers' and the full layer's */ @@ -4844,6 +4856,7 @@ TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) { RadBuildCtx c4 = build_ctx(); c4.max_spec = 4; CHECK_EQ(gemma4_bf16::declare(&b4, &meta, &c4), RAD_E_UNSUPPORTED); + } } /* The taps on the w4a8 trunk are declared in the layer they copy, so `dflash_src` is live from its @@ -4917,10 +4930,10 @@ TEST(gemma4_31b_dflash_passes_run_the_drafter_and_nothing_else) { CHECK_EQ(ops.front(), std::string("quant_act_fp8")); const RecOp* o = b.op_of(c.issues.front().op); CHECK(std::find(o->reads.begin(), o->reads.end(), (rad_buf)src) != o->reads.end()); - CHECK_EQ(count_issued(ops, "attn_paged"), 0); + CHECK_EQ(count_issued(ops, "attn_paged") + count_issued(ops, "attn_paged_qrow"), 0); } else { CHECK_EQ(ops.front(), std::string("embed_lookup")); - CHECK_EQ(count_issued(ops, "attn_paged"), 5); + CHECK_EQ(count_issued(ops, "attn_paged") + count_issued(ops, "attn_paged_qrow"), 5); CHECK_EQ(count_writes_to(b, c, tok), 1); } } @@ -5052,21 +5065,26 @@ TEST(gemma4_31b_dflash_head_reads_the_int8_copy_where_the_container_holds_one) { TEST(gemma4_31b_dflash_at_four_ranks) { G431Df f; const RadModelMeta meta = f.meta(); - for (int i8 = 0; i8 < 2; ++i8) { + for (int i8 = 0; i8 < 2; ++i8) + for (const bool served : { true, false }) { RadBuilder b; g431df_encs(b, i8 == 1, true); + if (!served) b.refuse.insert("attn_paged_qrow"); RadBuildCtx ctx = build_ctx(1, 4); ctx.max_spec = 15; CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); const rad_kvgroup kvd = kv_named(b, "kv_draft"); REQUIRE(kvd != 0); - /* two kv heads a rank, each held twice: gqa 4 over the cache (the declares test says why) */ - CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, 4); + /* two kv heads a rank: once at gqa 8 where attn_paged_qrow serves it, else each held twice + * at gqa 4 (the declares test says why) */ + CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, served ? 2 : 4); CHECK_EQ(b.bufs[buf_named(b, "df_q") - 1].d.shape[1], 16 * 128); CHECK_EQ(b.bufs[buf_named(b, "df_k") - 1].d.shape[1], 2 * 128); CHECK(buf_named(b, "df_dgath") > 0); for (const auto& o : b.ops) - if (o.op == "attn_paged" && pint(&o, "head_dim") == 128) CHECK_EQ(pint(&o, "gqa"), 4); + if ((o.op == "attn_paged" || o.op == "attn_paged_qrow") && pint(&o, "head_dim") == 128 && + !o.reads.empty()) + CHECK_EQ(pint(&o, "gqa"), served ? 8 : 4); RadCtx c; c.b = &b; c.rank = 1; c.world = 4; RadBatch batch = decode_batch(); @@ -5079,8 +5097,8 @@ TEST(gemma4_31b_dflash_at_four_ranks) { CHECK_EQ(count_issued(ops, "all_gather"), 1); /* the embedding's reduction and two a layer */ CHECK_EQ(count_issued(ops, "all_reduce"), 1 + 2 * 5); - /* k and v into the cache's layout: two heads, two copies each, a layer */ - CHECK_EQ(count_issued(ops, "cast"), 5 * 2 * (2 * 2)); + /* k and v into the cache's layout: two heads, two copies each, a layer -- or none */ + CHECK_EQ(count_issued(ops, "cast"), served ? 0 : 5 * 2 * (2 * 2)); } } @@ -5231,7 +5249,7 @@ TEST(gemma4_31b_without_libr4d_declares_the_chains_and_asks_for_no_undeclared_op RadBuilder b; g431df_encs(b, i8 == 1, true); for (const char* op : { "rmsnorm_quant_i8", "gelu_mul_quant_i8", "qkv_norm_rope", - "ar_rmsnorm_quant_i8" }) + "qkv_norm_rope_kv_store", "ar_rmsnorm_quant_i8" }) b.undeclared.insert(op); RadBuildCtx ctx = build_ctx(0, world); ctx.max_spec = 15; @@ -5429,6 +5447,75 @@ TEST(gemma4_31b_declares_redhats_dflash2_from_the_speculators_layout) { } } +/* DFlash2's two passes each run their attention prologue as one launch a layer where + * qkv_norm_rope_kv_store resolves: the query pass with its q heads (8 a rank at four ranks; v_norm + * 0), the context pass with none (n_head 0: the keys alone, q passed as k's buffer, which it does + * not read). With the fold refused, both chains return: the norms, the rotaries and kv_store. */ +TEST(gemma4_31b_dflash2_folds_both_passes_prologues) { + G431Df2 f; + const RadModelMeta meta = f.meta(); + const int L = 5; + for (int off = 0; off < 2; ++off) { + RadBuilder b; + g431df2_encs(b, true); + if (off) b.refuse.insert("qkv_norm_rope_kv_store"); + RadBuildCtx ctx = build_ctx(0, 4); + ctx.max_tok = 2048; + ctx.max_spec = 7; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + const auto ver = kit(b, { 8 }, {}); + const auto ctxp = context_pass(b, *ver); + const auto qry = query_pass(b, 1, 8, 7); + const auto v = run_passes(b, gemma4_bf16::step, { ctxp.get(), qry.get() }, 0, 4); + REQUIRE(steps_ok(v)); + for (int p = 0; p < 2; ++p) { + const RadCtx& c = *v[(size_t)p]; + int fused = 0; + for (const RecIssue& is : c.issues) { + const RecOp* o = b.op_of(is.op); + if (!o || o->op != "qkv_norm_rope_kv_store") continue; + ++fused; + CHECK_EQ(pint(o, "n_head"), p == 0 ? 0 : 8); + CHECK_EQ(pint(o, "v_norm"), 0); + if (p == 0) { + REQUIRE(is.opd.size() >= 2); + CHECK_EQ(is.opd[0].handle, is.opd[1].handle); + } + } + const std::vector ops = issued_ops(b, c); + CHECK_EQ(fused, off ? 0 : L); + CHECK_EQ(count_issued(ops, "kv_store"), off ? L : 0); + CHECK_EQ(count_issued(ops, "rope"), off ? (p == 0 ? L : 2 * L) : 0); + } + } +} + +/* DFlash2's query pass issues each residual add with the norm after it, as one add_rmsnorm where it + * resolves: after every attention (the feed-forward norm) and every feed-forward (the next layer's + * attention norm, after the last the final norm), ten on the 31B's five layers, no add left and + * one plain norm (layer 0's, after the embedding). With add_rmsnorm refused, the pairs. */ +TEST(gemma4_31b_dflash2_folds_each_residual_add_into_the_next_norm) { + G431Df2 f; + const RadModelMeta meta = f.meta(); + const int L = 5; + for (int off = 0; off < 2; ++off) { + RadBuilder b; + g431df2_encs(b, true); + if (off) b.refuse.insert("add_rmsnorm"); + RadBuildCtx ctx = build_ctx(0, 4); + ctx.max_tok = 2048; + ctx.max_spec = 7; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + const auto qry = query_pass(b, 1, 8, 7); + const auto v = run_passes(b, gemma4_bf16::step, { qry.get() }, 0, 4); + REQUIRE(steps_ok(v)); + const std::vector ops = issued_ops(b, *v[0]); + CHECK_EQ(count_issued(ops, "add_rmsnorm"), off ? 0 : 2 * L); + CHECK_EQ(count_issued(ops, "add"), off ? 2 * L : 0); + CHECK_EQ(count_issued(ops, "rmsnorm"), off ? 2 * L + 1 : 1); + } +} + /* Every engine step with RedHatAI's DFlash2 behind the trunk lints clean at one, two and four ranks: * decode, a mixed step, a prefill chunk, and a verify step with the drafter's context and query * passes behind it (block 8). */ @@ -5574,20 +5661,39 @@ TEST(gemma4_31b_takes_q_k_and_v_as_one_linear_where_the_container_holds_them_so) CHECK_EQ((int)qkv->d.n_row_parts, global ? 2 : 3); } - for (const int q : { 1, 16 }) { + for (const int q : { 1, 16, 40 }) { const auto k = kit(b, { q }, {}); const auto v = run_passes(b, gemma4_bf16::step, { k.get() }, 0, world); CHECK_PASSES(b, v); const std::vector ops = issued_ops(b, *v[0]); CHECK_EQ(count_issued(ops, "gemm_nt_q"), (int)(4 * L)); - CHECK_EQ(count_issued(ops, "attn_paged_qrow"), 2); - CHECK_EQ(count_issued(ops, "attn_paged"), 10); + /* the sliding layers read the row up to 32 rows a sequence (gqa 2), copy q out above */ + const bool dec = q <= 32; + CHECK_EQ(count_issued(ops, "attn_paged_qrow"), dec ? 12 : 2); + CHECK_EQ(count_issued(ops, "attn_paged"), dec ? 0 : 10); CHECK_EQ(count_issued(ops, "quant_act_i8"), (int)L); /* o_proj's input only */ - CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qs")), q == 1 ? 0 : 10); + CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qs")), dec ? 0 : 10); /* the GEMM, then qkv_norm_rope in place */ CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qkvs")), 2 * 10); CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qkvg")), 2 * 2); } + + /* Where attn_paged_qrow is not served: attn_paged everywhere, q in the row at one row and + * copied out above it. */ + RadBuilder r; + g431df_encs(r, false, true, true); + r.refuse.insert("attn_paged_qrow"); + REQUIRE_EQ(gemma4_bf16::declare(&r, &meta, &ctx), RAD_OK); + for (const int q : { 1, 16 }) { + const auto k = kit(r, { q }, {}); + const auto v = run_passes(r, gemma4_bf16::step, { k.get() }, 0, world); + CHECK_PASSES(r, v); + const std::vector ops = issued_ops(r, *v[0]); + CHECK_EQ(count_issued(ops, "attn_paged_qrow"), 0); + CHECK_EQ(count_issued(ops, "attn_paged"), 12); + CHECK_EQ(count_writes_to(r, *v[0], buf_named(r, "attn_qs")), q == 1 ? 0 : 10); + CHECK_EQ(count_writes_to(r, *v[0], buf_named(r, "attn_qg")), q == 1 ? 0 : 2); + } } } @@ -6010,6 +6116,23 @@ TEST(qwen35_fp8_steps_lint_clean_with_a_dflash2_drafter) { lint_qwen35_fp8_family(qwen35_fp8::declare, qwen35_fp8::step, mk.meta(), 7, true, 8); } +/* Qwen3.8's DFlash2 drafter has head_dim 128, outside every qkv_norm_rope_kv_store a library serves + * (libr4d's: 256 to 512), and an op declared for a shape that resolves to no device kernel refuses + * startup whether or not it is issued. So the block declares no prologue fold for it, and each pass + * keeps its norm, rope and kv_store chain; the residual adds, which add_rmsnorm serves at n_embd, + * still fold, two a layer. */ +TEST(qwen35_fp8_dflash2_head_128_drafter_declares_no_prologue_fold) { + MetaKV mk = with_dflash2(q35fp8_meta()); + RadBuilder b; + RadBuildCtx ctx = spec_ctx(0, 1, 7); + REQUIRE_EQ(qwen35_fp8::declare(&b, mk.meta(), &ctx), RAD_OK); + int folds_128 = 0; + for (const auto& o : b.ops) + if (o.op == "qkv_norm_rope_kv_store" && pint(&o, "head_dim") == 128) ++folds_128; + CHECK_EQ(folds_128, 0); + CHECK_EQ(count_op(b, "add_rmsnorm"), 2 * 2); +} + /* =============================== gemma3: TranslateGemma 27B's trunk =========================== */ namespace { @@ -7783,13 +7906,13 @@ struct ArchCases { nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x1c28909125c12f52ull); add("qwen35_fp8 + DFlash2", [this, sc](RadBuilder* b) { auto c = sc(1, 7); return qwen35_fp8::declare(b, q35df.meta(), &c); }, - qwen35_fp8::step, 7, {}, 0xb5691456a0ce7e9dull); + qwen35_fp8::step, 7, {}, 0x76bc2f92b452df49ull); add("qwen35_w8a8 + DFlash2", [this, sc](RadBuilder* b) { auto c = sc(1, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, - qwen35_w8a8::step, 7, {}, 0xed8219da9fcc0ceaull); + qwen35_w8a8::step, 7, {}, 0x5570932de623edcaull); add("qwen35_w8a8 + DFlash2, two ranks", [this, sc](RadBuilder* b) { auto c = sc(2, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, - nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0x2c00f131709dedcfull); + nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0xec1ca3ad670311bbull); add("qwen35moe_fp8 + MTP", [this, sc](RadBuilder* b) { auto c = sc(1, 3); return qwen35moe_fp8::declare(b, q35moe.meta(), &c); }, qwen35moe_fp8::step, 3, {}, 0x1bd3b53543cd06eeull); @@ -7814,19 +7937,19 @@ struct ArchCases { * are the earlier pins, 0xafc23087c634a537, 0x719fa07788f8b98a and 0x93b174ab52cc0d31. */ add("gemma4_bf16", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0x174e157911e121a9ull); + gemma4_bf16::step, 0, {}, 0x2ba2f4943031468full); add("gemma4_bf16, w4a8", [this, sc, g4w4](RadBuilder* b) { g4w4(b); auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0x4bf536b78c6b11eeull); + gemma4_bf16::step, 0, {}, 0x2e4c6e3235dd3802ull); add("gemma4_bf16, w4a8, two ranks", [this, sc, g4w4](RadBuilder* b) { g4w4(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); }, - nullptr, 0, {}, 0xed7ccbb0c6aecfebull); + nullptr, 0, {}, 0xade9c0ccfad1fd47ull); add("gemma4_bf16, w4a8, fused qkv", [this, sc, g4qkv](RadBuilder* b) { g4qkv(b); auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0x0ae60e16d6b6424cull); + gemma4_bf16::step, 0, {}, 0x3913aca59733d0e2ull); add("gemma4_bf16, w4a8, fused qkv, two ranks", [this, sc, g4qkv](RadBuilder* b) { g4qkv(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); }, - nullptr, 0, {}, 0xcc58bb53457bca11ull); + nullptr, 0, {}, 0x8a9935e773f546efull); add("gemma4", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4::declare(b, &g4m, &c); }, gemma4::step, 0, {}, 0x0f227f5853b6488cull); @@ -8218,8 +8341,8 @@ TEST(gemma4_assistant_head_engine_step_lints_clean) { * fingerprints above). */ TEST(gemma4_bf16_without_the_fused_ops_declares_the_chains_and_asks_for_no_undeclared_op) { const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128); - const std::set fused = { "qkv_norm_rope", "rmsnorm_quant_i8", "gelu_mul_quant_i8", - "ar_rmsnorm_quant_i8" }; + const std::set fused = { "qkv_norm_rope", "qkv_norm_rope_kv_store", "rmsnorm_quant_i8", + "gelu_mul_quant_i8", "ar_rmsnorm_quant_i8" }; for (int world : { 1, 2 }) { std::vector seq[2]; for (int undeclared = 0; undeclared < 2; ++undeclared) {