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 <noreply@anthropic.com>
This commit is contained in:
AshlynandClaude Opus 5.5 authored and StillDeadcode committed 2026-10-21 09:48:20 +02:00
1 parent 04e5480387
commit 015cba8837
20 files changed
+1332 -164

No files matched your search

+127 -12
View File
@@ -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;
+43 -6
View File
@@ -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),
+81 -33
View File
@@ -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<rad_buf> rd) {
auto attn = [&](const char* op, std::initializer_list<rad_buf> 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<int64_t>(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");