diff --git a/README.md b/README.md index 5447de41..9689564e 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | | Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` | +| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (20 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-w4a8-df.yaml` | +| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | | Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` | @@ -256,6 +258,14 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-w4a8.ra --recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \ --set quantization_config.quant_method=compressed-tensors \ --draft-model /srv/models/hf/google/gemma-4-31B-it-assistant +build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-w4a8-df.rad \ + --recipe data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe \ + --set quantization_config.quant_method=compressed-tensors \ + --draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash +build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-q8-df.rad \ + --recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \ + --set quantization_config.quant_method=compressed-tensors \ + --draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \ --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \ --draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2 diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 8a262e4d..c756bdf3 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -1515,10 +1515,12 @@ struct DenseFP8 { /* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */ bool mapped = false; + /* `mapped`: the caller made the name map already, to ask the encoding before choosing this + * struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */ int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, int access, int shard, RadWeightGroup grp, std::initializer_list src, - std::initializer_list row_parts = {}); + std::initializer_list row_parts = {}, bool mapped = false); /* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */ rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K, std::initializer_list reads, std::initializer_list writes) const { @@ -1541,7 +1543,7 @@ struct DenseFP8 { inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, int access, int shard, RadWeightGroup grp, std::initializer_list src, - std::initializer_list row_parts) { + std::initializer_list row_parts, bool mapped) { if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL; /* ---- OCP-MXFP4, from the weight's encoding. The exponent grid is one row tall, so parts need diff --git a/arch/common/rad_gemma4_dflash.h b/arch/common/rad_gemma4_dflash.h new file mode 100644 index 00000000..0340e1a2 --- /dev/null +++ b/arch/common/rad_gemma4_dflash.h @@ -0,0 +1,1162 @@ +/* rad_gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4, + * and what both Gemma 4 plugins need to carry it: arch/gemma4 (the 26B-A4B and the dense sizes, + * from bf16) and arch/gemma4_bf16 (the dense 31B at w4a8 or w8a8). + * + * ============================== WHAT IT IS ============================== + * + * rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around + * attention and the feed-forward, and the candidate selector). The original DFlash is a small + * Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one + * forward and takes every position's argmax from the target's lm_head. + * + * context pass, one row a committed token: + * c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids))) + * for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v) + * + * query pass, `block` rows a sequence: + * x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below + * for each layer: + * h = input_layernorm(x) + * q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store + * x += o_proj(attention(q, cache)) sliding layers causal over a 2048 window, + * the full layer non-causal over everything + * x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x) + * x = norm(x) + * over the mask rows: logits = lm_head(x) [the target's]; draft = argmax + * + * z-lab publishes one for gemma-4-26B-A4B-it (2816 wide, 32 heads, taps 1 6 11 17 22 27 of 30) and + * one for gemma-4-31B-it (5376 wide, 64 heads / 8 kv x 128, ffn 10752, taps 1 12 23 35 46 57 of + * 60), both five layers, four sliding and one full, at block 16. Nothing below is per size. + * + * ============================== THE THREE GEMMA-SPECIFIC FACTS ============================== + * + * From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is + * verified against the trunk. + * + * The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as + * bf16 (53.0 at 2816, 73.5 at 5376), and the drafter was trained through the target's embedding + * module, which applies it. `embed_lookup`'s `mult` carries it; embed_scale() below is the value. + * + * The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names + * four sliding layers and one full one, and the PR's test pins `causal True` on the sliding + * layers and `False` on the full one, so this block declares two attention ops and issues the one + * each layer's type names. + * + * The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and + * cap * tanh(x / cap) is strictly increasing. + * + * ============================== THE HEAD ============================== + * + * The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma + * ties it to the embedding, so it is the weight the trunk's `embed_lookup` reads and costs no extra + * bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's slice and the ranks' + * candidates merge exactly (`row_topk` at R = 2 -> `all_gather` -> `pair_argmax`; R = 2 because the + * gather moves 16-byte rows, see kTopR). + * + * The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a + * 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds an 8-bit copy of the table + * under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical weights, as in + * rad_block_dflash2.h), made by one of the recipe lines + * + * dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 (block fp8) + * dflash.draft_head.weight rtn codes=i8 group=128 scale=f16 clamp=sym (int8, w8a8) + * + * the head is `gemm_nt_q` over that copy, half the bytes, with the argmax over its coarser logits. + * Drafts are still verified, so the copy can change proposals but never accepted text. Without the + * copy, or in another encoding, the bf16 table is read. The copy costs half the table's bytes again + * (176 MiB per rank at tp 4 on the 26B, 352 MiB on the 31B). There is no rerank against the bf16 + * table: DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not. + * + * ============================== THE LINEARS ARE 8-BIT ============================== + * + * As in DFlash2, since the drafter is read whole on every decode step: the container must be + * converted with a recipe that makes the seven linears (fc, and six a layer) 8-bit, on one of two + * activation grids, which the container's choice for `fc` decides: + * + * E4M3 block fp8 (`codes=fp8_e4m3 block=128x128 scale=bf16`) or OCP-MXFP4, read at fp8a8 / + * mxfp4a8 against an E4M3 activation with an f32 scale per (row, 128): quant_act_fp8, or + * rmsnorm_quant_fp8 where the input is a norm. + * int8 int8 codes with an f16 scale per (row, 128 columns) (`codes=i8 group=128 scale=f16 + * clamp=sym`), the Q8 grid gemma4_bf16's trunk takes at w8a8, read by gemm_nt_q at w8a8 + * against quant_act_i8's activation: int8 in the GEMM's fragment order and one f32 scale + * per row, or rmsnorm_quant_i8 where the input is a norm. + * + * The two cannot mix within the drafter: one quantised activation feeds several linears (q, k and v + * read one pair), so every linear must read the grid its producer writes. declare() refuses a bf16 + * linear, and a linear on the other grid, by name rather than letting the loader fail on a view. + */ +#ifndef RAD_GEMMA4_DFLASH_H +#define RAD_GEMMA4_DFLASH_H + +#include "rad_arch.h" +#include "rad_fp8.h" + +#include +#include +#include +#include +#include +#include + +namespace gemma4 { + +using namespace rad::arch; + +/* ============================================================== what both plugins share */ + +/* The embedding scale as the reference applies it: Gemma4TextScaledWordEmbedding multiplies the + * looked-up rows by `embed_scale.to(weight.dtype)`, sqrt(hidden) rounded to bf16 (53.0 at 2816, not + * 53.066; 73.5 at 5376, not 73.32). The trunk, the assistant head and the drafter all read the + * embedding through that module, so all three take this value. */ +inline double embed_scale(int64_t hidden) { + return rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)hidden))); +} + +/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no + * transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */ +inline bool block_fp8_128(const RadEncoding& e) { + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] && + e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 && + sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK; +} + +/* Int8 on the w8a8 grid: i8 codes and an f16 scale per [1 x 128], no transform (a recipe's `rtn + * codes=i8 group=128 scale=f16 clamp=sym`), what gemm_nt_q reads at w8a8. Not rad_fp8.h's + * linear_is_w8, which is the i8a8 grid's bf16 scale over a per-(row, 128) activation. */ +inline bool linear_w8a8(const RadEncoding& e) { + if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || e.transform[0]) return false; + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_F16 && + sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK; +} + +/* Which drafter the container carries under `draft.`: 1 for DFlash (v1), 2 for DFlash2 (which is + * rad_block_dflash2.h's, not this block), 0 for none or a draft that is not a DFlash. */ +inline int dflash_kind(const RadModelMeta* meta) { + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (!da || !std::strstr(da, "DFlash")) return 0; + return std::strstr(da, "DFlash2") ? 2 : 1; +} + +/* The block a DFlash checkpoint was trained at, 0 where it states none. v1 states it at the top + * level; a SpecForge config nests it under dflash_config. */ +inline long long dflash_block(const RadModelMeta* meta) { + long long bs = rad_meta_geti(meta, "draft.block_size", 0); + if (bs <= 0) bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); + return bs > 0 ? bs : 0; +} + +/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less + * the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). True when the + * container carries one and `out` now names its depth. */ +inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) { + if (dflash_kind(meta) != 1) return false; + const long long bs = dflash_block(meta); + if (bs <= 1) return false; + out->draft_depth = (int)(bs - 1); + out->draft_depth_fixed = 1; + return true; +} + +/* ============================================================== the block */ + +struct Dflash1 { + enum { MAX_LAYERS = 8, MAX_TAPS = 8 }; + + struct Config { + int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */ + int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */ + int64_t window = 0; /* the sliding layers' window; 0 for none */ + int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */ + double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */ + int64_t kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */ + 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. */ + 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; + } + + /* What the trunk hands the drafter (declare_drafter). */ + struct Trunk { + int64_t n_taps = 0; + double escale = 1.0; /* embed_scale(hidden) */ + rad_buf src = 0; /* [max_tok, n_taps * n_embd] bf16: the taps, in tap order */ + rad_weight w_tok = 0; /* the trunk's tied table, row-sharded with the vocabulary */ + const char* tok_src = nullptr; /* its checkpoint name, which the head's 8-bit copy maps */ + int base_layer = 0; /* the drafter's first absolute layer, past the trunk's */ + }; + + struct Wire { + /* the context pass */ + rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | codes | f32 */ + rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */ + rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */ + rad_buf ck4 = 0, cv4 = 0; /* [max_tok, kv_dim * kv_rep]: the cache's copies */ + /* the query pass */ + rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */ + rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */ + rad_buf k4 = 0, v4 = 0; /* [qrows, kv_dim * kv_rep] */ + rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */ + rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */ + rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */ + /* the head, one row per draft position */ + rad_buf sel_h = 0; /* [srows, n_embd] */ + rad_buf selq = 0, sels = 0; /* [srows, n_embd] codes | f32, the 8-bit head's */ + rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */ + rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */ + rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */ + rad_buf tokens = 0; /* [srows, 1] i32: the draft, pitch `steps` */ + }; + + /* One of the drafter's linears, in the grid the container holds it (see the file header): block + * fp8 or MXFP4 through DenseFP8, or int8 at w8a8 -- codes and an f16 scale per [1 x 128] as two + * views of one stored weight, the w4a8 grid's layout at twice the radix. `w` and `s` are the + * GEMM's two weight operands either way, and `bref()` its trailing one. */ + struct Lin { + rad_weight w = 0, s = 0; + bool i8 = false; + DenseFP8 f{}; + + int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, int access, + int shard, RadWeightGroup grp, std::initializer_list src, + std::initializer_list row_parts = {}); + rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K, + std::initializer_list reads, + std::initializer_list writes) const { + if (!i8) return f.gemm(b, hi, N, K, reads, writes); + return rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w8a8")), + RAD_WEIGHTS(w, s)), + reads, writes); + } + RadOperand bref() const { return i8 ? RAD_NONE : f.bref(); } + }; + + Geom g{}; /* the drafter's geometry */ + Config cfg{}; + Wire w{}; + int first_layer = 0; + int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0; + rad_kvgroup kv = 0; + bool sharded = false; + /* The activation grid: false is E4M3 with a scale per (row, 128), true int8 with a scale per + * row. Read off `fc`'s encoding; every other linear has to agree (see the file header). */ + bool i8 = false; + + Lin w_fc{}; + rad_weight w_hnorm = 0, w_norm = 0; + rad_weight w_tok = 0; /* the target's table: embedding and head */ + Lin w_dh{}; /* its 8-bit copy, the head where it is stored */ + bool q_head = false; /* the head reads w_dh */ + rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; + Lin w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{}; + rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}; + Lin w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{}; + + rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0; + /* the kv heads' copies into the cache's layout (kv_rep > 1): k and v, context and query pass */ + rad_op op_rep_ck = 0, op_rep_cv = 0, op_rep_k = 0, op_rep_v = 0; + rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; + + rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0; + rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}; + /* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` (on the int8 + * grid `rmsnorm_quant_i8`) is served: op_anq[i] for the attention input (layer 0's without the + * add) and op_fnq[i] for the feed-forward input. Zero where not served; the `add` / `rmsnorm` / + * quantiser chain is issued instead. */ + rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {}; + rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; + rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}; + rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; + rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0; + rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; + rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0; + + /* Candidates each rank contributes under a sharded head. The draft needs one, but the gather + * moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is + * refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax` + * reduces the world * 2 of them to the global top-1. */ + static constexpr int64_t kTopR = 2; + + static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); } + + /* The taps the container's drafter reads, when it carries a DFlash (v1) drafter and the serve + * speculates: the trunk layers into `out` and their count (0 when there is nothing to tap), or a + * refusal -- a DFlash2 drafter, which this block is not, or one naming no layer of an + * `n_layer`-layer trunk, which belongs to another target. */ + static int taps(const RadModelMeta* meta, const RadBuildCtx* ctx, int64_t n_layer, int* out, + int max); + + /* The whole drafter, declared after the trunk (declaration order is the buffer planner's + * liveness): its config read off `draft.`, its KV group bound from `t.base_layer`, the block, + * and the RadDrafterDecl the engine drives it by. `trunk` is the trunk's geometry, which the + * drafter's copies for what they share: the ranks, the vocabulary shard, the step bounds. */ + static int declare_drafter(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Names& nm, const Geom& trunk, const Trunk& t, Dflash1* df, + rad_kvgroup* kv_out); + + int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, + rad_kvgroup group, rad_weight tok_embd, const char* ck, rad_buf src, + const char* tok_src); + void context(RadCtx* c, const RadBatch* batch) const; + void step(RadCtx* c, const RadBatch* batch) const; + +private: + int64_t q_dim() const { return g.n_head * g.head_dim; } + int64_t kv_dim() const { return g.n_head_kv * g.head_dim; } + + /* The pair a quantiser writes for an n-wide activation of `rows`: the codes, and the f32 scale + * plane -- one per (row, 128) on the E4M3 grid, one per row on the int8 one. */ + void decl_pair(RadBuilder* b, Names& nm, const char* q, const char* s, int64_t rows, int64_t n, + rad_buf* qb, rad_buf* sb) const { + *qb = decl_b(b, nm.f("%s", q), i8 ? RAD_I8 : RAD_F8E4M3, {rows, n}); + *sb = decl_b(b, nm.f("%s", s), RAD_F32, {rows, i8 ? 1 : fp8_blocks(n)}); + } + /* The standalone quantiser of an n-wide activation, in the grid: `quant_act_fp8` with a scale + * per 128 columns, or `quant_act_i8` with one per row, whose `group` only sizes the optional + * code sums this symmetric grid does not take (gemma4_bf16.cpp's G4Linear). */ + rad_op decl_quant(RadBuilder* b, int64_t rows, int64_t n, rad_buf x, rad_buf q, + rad_buf s) const { + return rw(b, RAD_OP(b, i8 ? "quant_act_i8" : "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {x}, {q, s}); + } + /* ...and its issue. quant_act_i8 has a third output, the row sums an asymmetric grid reads, + * absent on this symmetric one and passed as a null operand, since operands are positional. */ + void quant(RadCtx* c, rad_op op, int64_t T, rad_buf x, rad_buf q, rad_buf s) const { + if (i8) RAD_ISSUE_N(c, op, T, brows(x, T), brows(q, T), brows(s, T), RAD_NONE); + else RAD_ISSUE_N(c, op, T, brows(x, T), brows(q, T), brows(s, T)); + } + /* A fused norm and quantiser's issue: x (the delta where it adds), the residual or none, the + * gain, the pair, no bf16 copy, and on the int8 grid rmsnorm_quant_i8's two junction gains + * (post-norm and scalar), which a drafter layer has neither of. */ + void norm_quant(RadCtx* c, rad_op op, int64_t T, RadOperand x, RadOperand res, + rad_weight gain) const { + if (i8) + RAD_ISSUE_N(c, op, T, x, res, RAD_W(gain), brows(w.hq, T), brows(w.hs, T), RAD_NONE, + RAD_NONE, RAD_NONE); + else + RAD_ISSUE_N(c, op, T, x, res, RAD_W(gain), brows(w.hq, T), brows(w.hs, T), RAD_NONE); + } + /* The kv heads into the cache's layout: head h to copies h * kv_rep .. h * kv_rep + kv_rep - 1, + * so the copies of one head sit side by side and query head q of a gqa-4 attention, which reads + * cache head q / 4, reads head q / (4 * kv_rep), the projection's own. One head-wide strided row + * copy (`cast`, bf16 to bf16) a copy. */ + void rep_kv(RadCtx* c, rad_op op, int64_t T, rad_buf src, rad_buf dst) const { + const int64_t hd = g.head_dim, r = cfg.kv_rep; + for (int64_t h = 0; h < g.n_head_kv; ++h) + for (int64_t i = 0; i < r; ++i) + RAD_ISSUE(c, op, bcol(src, h * hd, hd, T), bcol(dst, (h * r + i) * hd, hd, T)); + } + /* A linear's GEMM over its input's pair. */ + void gemm(RadCtx* c, rad_op op, int64_t T, rad_buf q, rad_buf s, const Lin& l, + rad_buf y) const { + RAD_ISSUE_N(c, op, T, brows(q, T), brows(s, T), RAD_W(l.w), RAD_W(l.s), brows(y, T), + RAD_NONE, l.bref()); + } + /* The linears must be quantised by the recipe, in the grid `fc` set. A bf16 one would be read + * through a view of a dtype it is not stored in, and the loader's error would name the view, + * not the missing recipe; one on the other grid would read a pair its producer does not write. */ + int need_quantised(RadBuilder* b, const char* wn, const Lin& l) const { + RadEncoding e{}; + if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */ + const uint32_t dt = e.plane[0].dtype; + if (dt != RAD_F8E4M3 && dt != RAD_FP4E2M1 && dt != RAD_I8) { + fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its linears " + "are served 8-bit: convert with a recipe that names them, e.g. " + "`dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 " + "scale=bf16` (or `codes=i8 group=128 scale=f16 clamp=sym`) and the " + "same for fc, attn_k/v/output, ffn_gate_up and ffn_down.\n", + wn, rad_dtype_name(dt)); + return RAD_E_DTYPE; + } + if (l.i8 != i8) { + fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is %s and its fc is %s; " + "one quantised activation feeds several linears, so the drafter's " + "linears take one grid and the recipe's rules for them must agree\n", + wn, l.i8 ? "int8 (w8a8)" : "on the E4M3 grid (fp8 or MXFP4)", + i8 ? "int8 (w8a8)" : "on the E4M3 grid (fp8 or MXFP4)"); + return RAD_E_DTYPE; + } + return RAD_OK; + } +}; + +/* ------------------------------------------------------------------------------ one linear */ + +inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, + int access, int shard, RadWeightGroup grp, + std::initializer_list src, + std::initializer_list row_parts) { + /* The name map once, before the question it answers: a COPY map declared twice is refused and + * a CONCAT one extended (rad_builder.cpp), so DenseFP8 is told the map is made. */ + const char* wn = nm.f("%s.weight", base); + RAD_ARCH_TRY(map_linear(b, wn, src)); + RadEncoding enc{}; + i8 = weight_enc(b, wn, &enc) && linear_w8a8(enc); + if (!i8) { + RAD_ARCH_TRY(f.declare(b, nm, base, N, K, access, shard, grp, src, row_parts, true)); + w = f.w; + s = f.s; + return RAD_OK; + } + /* w8a8: rows in 16s (the fragment's tile) and K in whole 128-column scale groups. The scale + * plane has the weight's rows, so it takes the weight's row parts as they are. */ + if (N % 16 || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an int8 weight takes rows in 16s " + "and K in whole %d-column scale groups.\n", + base, (long long)N, (long long)K, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + int64_t p[RAD_MAX_ROW_PARTS] = {0}; + int np = 0; + for (int64_t q : row_parts) { + if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL; + p[np++] = q; + } + w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp, p, np); + s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_F16, { N, K / RAD_FP8_BLOCK }, + access, shard, grp, p, np); + return w && s ? RAD_OK : RAD_E_INVAL; +} + +/* ------------------------------------------------------------------------------ the taps */ + +inline int Dflash1::taps(const RadModelMeta* meta, const RadBuildCtx* ctx, int64_t n_layer, + int* out, int max) { + if (ctx->max_spec <= 0) return 0; + const int kind = dflash_kind(meta); + if (kind == 0) return 0; + if (kind == 2) { + fprintf(stderr, "radiance: gemma4: the container carries a DFlash2 drafter; this plugin " + "serves the DFlash (v1) block z-lab publishes for Gemma 4\n"); + return RAD_E_UNSUPPORTED; + } + const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr); + if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr); + const int n = parse_layer_ids(ids, n_layer, out, max); + if (n <= 0) { + fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model has; it is " + "paired with a different target\n"); + return RAD_E_UNSUPPORTED; + } + return n; +} + +/* ------------------------------------------------------------------------------ the drafter */ + +inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta, + const RadBuildCtx* ctx, Names& nm, const Geom& trunk, + const Trunk& t, Dflash1* df, rad_kvgroup* kv_out) { + Geom dg{}; + RAD_ARCH_TRY(drafter_geom(dg, trunk, meta, "gemma4 DFlash")); + if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) { + fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads " + "the target's embedding and head, so it is not this target's drafter\n", + (long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd); + return RAD_E_UNSUPPORTED; + } + + Config dc{}; + dc.n_taps = t.n_taps; + dc.escale = t.escale; + const long long trained = dflash_block(meta); + if (trained < 2) { + fprintf(stderr, "radiance: gemma4: the DFlash checkpoint states no block_size\n"); + return RAD_E_FORMAT; + } + if ((long long)ctx->max_spec + 1 != trained) { + fprintf(stderr, "radiance: gemma4: the DFlash drafter was trained at block_size %lld, " + "which is %lld draft tokens, and this serve asks for %d. A block-diffusion " + "drafter denoises a fixed number of mask positions; run it at " + "--num-speculative-tokens %lld (or `auto`).\n", + trained, trained - 1, ctx->max_spec, trained - 1); + return RAD_E_UNSUPPORTED; + } + dc.block = trained; + if (dg.n_layer > MAX_LAYERS) return RAD_E_UNSUPPORTED; + { + std::vector full; + const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr); + if (lt) { + RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention", + &full)); + if ((int64_t)full.size() != dg.n_layer) { + fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and " + "it has %lld\n", full.size(), (long long)dg.n_layer); + return RAD_E_INVAL; + } + } else { + full.assign((size_t)dg.n_layer, 1); + } + bool any_swa = false; + for (int64_t l = 0; l < dg.n_layer; ++l) { + dc.full[l] = full[(size_t)l]; + any_swa = any_swa || !full[(size_t)l]; + } + if (any_swa) { + dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size", + rad_meta_geti(meta, "draft.sliding_window", 0)); + if (!rad_meta_geti(meta, "draft.use_sliding_window", 1) || dc.window <= 0) { + fprintf(stderr, "radiance: gemma4: the drafter names sliding layers and no " + "window\n"); + return RAD_E_INVAL; + } + } + } + if (!head_sharded(dg) && dg.world > 1) { + fprintf(stderr, "radiance: gemma4: the vocabulary (%lld) does not split evenly into whole " + "16-row blocks over %d ranks, which the drafter's sharded head needs\n", + (long long)dg.n_vocab_all, dg.world); + return RAD_E_UNSUPPORTED; + } + + /* One unbounded cache for all the drafter's layers, because its full layer reads every + * position. The sliding layers bound themselves with their attention op's `window`, so the + * declared drafter window is 0 and the core stages the whole context. A 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). */ + dc.kv_rep = kv_rep_for(dg); + { + Geom cg = dg; + cg.n_head_kv *= dc.kv_rep; + cg.n_head_kv_all *= dc.kv_rep; + RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, cg, 0, t.base_layer, kv_out)); + dg.kv_dtype = cg.kv_dtype; + } + + RAD_ARCH_TRY(df->declare(b, nm, dg, dc, t.base_layer, *kv_out, t.w_tok, "draft", t.src, + t.tok_src)); + + RadDrafterDecl drf{}; + drf.name = "dflash"; + drf.kind = RAD_DRAFT_BLOCK; + drf.depth = ctx->max_spec; + drf.block = dc.block; /* the anchor predicts nothing: block = depth + 1 */ + drf.proposal = df->w.tokens; + drf.proposal_pitch = dc.steps(); + drf.window = 0; /* the full layer reads everything; see the group */ + drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", + rad_meta_geti(meta, "draft.mask_token_id", -1)); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: gemma4: the DFlash checkpoint declares no mask_token_id\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + + int nfull = 0; + for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l]; + rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld " + "sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the " + "trunk at %lld tap(s); linears %s. One forward over %lld rows proposes %lld " + "tokens; the head is %s, argmax %s", + (long long)dg.n_layer, t.base_layer, t.base_layer + (int)dg.n_layer - 1, nfull, + (long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head, + (long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, + (long long)t.n_taps, + df->i8 ? "int8 (w8a8, an int8 activation per row)" : "on the E4M3 grid (fp8a8 / mxfp4a8)", + (long long)dc.block, (long long)dc.steps(), + !df->q_head ? "the target's tied bf16 table" + : df->w_dh.i8 ? "the container's int8 copy of the target's table (dflash.draft_head)" + : "the container's block-fp8 copy of the target's table (dflash.draft_head)", + head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary"); + if (dc.kv_rep > 1) + rad_note(b, "the DFlash drafter's cache holds each of its %lld kv head(s) a rank %lld times, " + "so its attention runs at %lld queries per kv head, the width libr4d's head-%lld " + "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()); + return RAD_OK; +} + +/* ------------------------------------------------------------------------------ declare */ + +inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, + int base_layer, rad_kvgroup group, rad_weight tok_embd, + const char* ck, rad_buf src, const char* tok_src) { + g = geom; cfg = c; first_layer = base_layer; kv = group; w_tok = tok_embd; + w = Wire{}; + w.src = src; + if (!ck || !w_tok || !tok_src || !src) return RAD_E_INVAL; + if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) { + fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most " + "%d\n", (long long)g.n_layer, MAX_LAYERS); + return RAD_E_UNSUPPORTED; + } + if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL; + if (cfg.kv_rep < 1 || g.gqa() % cfg.kv_rep) return RAD_E_INVAL; + + const int64_t qd = q_dim(), kvd = kv_dim(), rep = cfg.kv_rep; + crows = g.max_tok; + qrows = g.max_seqs * cfg.block; + if (qrows > g.max_tok) qrows = g.max_tok; + srows = g.max_seqs * cfg.steps(); + if (qrows <= 0 || srows <= 0) return RAD_E_INVAL; + sharded = head_sharded(g); + const int64_t tw = cfg.n_taps * g.n_embd; + + /* ---------------------------------------------------------------- model-scope weights + * `fc` first: its encoding is the drafter's activation grid, which the buffers below take. */ + RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, tw, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model(), { nm.ckpt("%s.fc.weight", ck) })); + i8 = w_fc.i8; + RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight"), w_fc)); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck))); + w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + + /* ---------------------------------------------------------------- the buffers */ + decl_pair(b, nm, "df_srcq", "df_srcs", g.max_tok, tw, &w.srcq, &w.srcs); + w.c = decl_b(b, nm.f("df_c"), g.act_dtype, {g.max_tok, g.n_embd}); + decl_pair(b, nm, "df_cq", "df_cs", g.max_tok, g.n_embd, &w.cq, &w.cs); + w.ck = decl_b(b, nm.f("df_ck"), g.act_dtype, {g.max_tok, kvd}); + w.cv = decl_b(b, nm.f("df_cv"), g.act_dtype, {g.max_tok, kvd}); + if (rep > 1) { + w.ck4 = decl_b(b, nm.f("df_ck4"), g.act_dtype, {g.max_tok, kvd * rep}); + w.cv4 = decl_b(b, nm.f("df_cv4"), g.act_dtype, {g.max_tok, kvd * rep}); + } + w.x = decl_b(b, nm.f("df_x"), g.act_dtype, {qrows, g.n_embd}); + w.h = decl_b(b, nm.f("df_h"), g.act_dtype, {qrows, g.n_embd}); + decl_pair(b, nm, "df_hq", "df_hs", qrows, g.n_embd, &w.hq, &w.hs); + w.q = decl_b(b, nm.f("df_q"), g.act_dtype, {qrows, qd}); + w.k = decl_b(b, nm.f("df_k"), g.act_dtype, {qrows, kvd}); + w.v = decl_b(b, nm.f("df_v"), g.act_dtype, {qrows, kvd}); + if (rep > 1) { + w.k4 = decl_b(b, nm.f("df_k4"), g.act_dtype, {qrows, kvd * rep}); + w.v4 = decl_b(b, nm.f("df_v4"), g.act_dtype, {qrows, kvd * rep}); + } + w.attn = decl_b(b, nm.f("df_attn"), g.act_dtype, {qrows, qd}); + decl_pair(b, nm, "df_atq", "df_ats", qrows, qd, &w.atq, &w.ats); + w.gate_up = decl_b(b, nm.f("df_gate_up"), g.act_dtype, {qrows, 2 * g.n_ff}); + w.ffn = decl_b(b, nm.f("df_ffn"), g.act_dtype, {qrows, g.n_ff}); + decl_pair(b, nm, "df_ffq", "df_ffs", qrows, g.n_ff, &w.ffq, &w.ffs); + w.sel_h = decl_b(b, nm.f("df_selh"), g.act_dtype, {srows, g.n_embd}); + w.dlog = decl_b(b, nm.f("df_dlog"), g.act_dtype, {srows, g.n_vocab}); + if (sharded) { + w.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {srows, kTopR}); + w.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {srows, kTopR}); + w.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {srows, kTopR, 2}); + w.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {srows, (int64_t)g.world * kTopR, 2}); + } else { + w.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {srows, 1}); + } + /* The draft, one row per draft position: [n_seq * steps, 1], which is [n_seq, steps] with a + * pitch of `steps`, read by the engine through the drafter's declaration. */ + w.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {srows, 1}); + + /* ---------------------------------------------------------------- per-layer weights */ + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + const RadWeightGroup gl = grp_layer(first_layer + i); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i), + nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), + nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), + nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), + nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i))); + w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + /* The declared names match rad_block_dflash2.h's, so one recipe quantises both + * drafters. */ + RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, + { nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff, + g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i), + nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) }, + { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, + { nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) })); + const Lin* lins[6] = { &w_q[i], &w_k[i], &w_v[i], &w_o[i], &w_gu[i], &w_dn[i] }; + const char* names[6] = { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", + "ffn_down" }; + for (int k = 0; k < 6; ++k) + RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, names[k]), *lins[k])); + } + /* The int8 grid's prefill band: above 64 rows libr4d's w8a8 GEMM is the tiled one, which takes + * N in 256s. The context pass runs at prefill heights (fc, k and v over every committed row) and + * the query pass at qrows, so a linear whose rows on this rank are not whole 256s has no kernel + * past 64, and is refused here by name rather than as an op that does not resolve. */ + if (i8) { + const int64_t ns[4] = { g.n_embd, kvd, qd, 2 * g.n_ff }; + const int64_t hi[4] = { crows, crows, qrows, qrows }; + for (int k = 0; k < 4; ++k) + if (hi[k] > 64 && ns[k] % 256) { + fprintf(stderr, "radiance: gemma4: one of the DFlash drafter's int8 linears is " + "%lld rows per rank, and above 64 rows the w8a8 GEMM takes them in " + "256s; serve this drafter at fewer ranks or on the E4M3 grid\n", + (long long)ns[k]); + return RAD_E_UNSUPPORTED; + } + } + + /* ---------------------------------------------------------------- attention: two kinds + * 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", + 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), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.attn}); + }; + bool any_full = false, any_swa = false; + for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true; + if (any_swa) op_attn_swa = attn(1, cfg.window); + if (any_full) op_attn_full = attn(0, 0); + + /* The copies into the cache's layout (rep_kv), a head-wide strided row copy each. Each pass's + * pair is declared in its first layer, where it is first issued: declaration order is the + * buffer planner's liveness, and declared after the layers the copies' buffers would look born + * after the last layer's input and free to share its bytes. */ + auto rep_op = [&](int64_t rows, rad_buf src, rad_buf dst) { + return rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.head_dim), + RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)), + RAD_NOWEIGHTS), + {src}, {dst}); + }; + + /* ---------------------------------------------------------------- the context pass */ + op_qsrc = decl_quant(b, crows, tw, w.src, w.srcq, w.srcs); + op_cfc = w_fc.gemm(b, crows, g.n_embd, tw, {w.srcq, w.srcs}, {w.c}); + op_cnorm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_hnorm)), + {w.c}, {w.c}); + op_qc = decl_quant(b, crows, g.n_embd, w.c, w.cq, w.cs); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck}); + op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv}); + if (rep > 1 && i == 0) { + op_rep_ck = rep_op(crows, w.ck, w.ck4); + op_rep_cv = rep_op(crows, w.cv, w.cv4); + } + op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn[i])), + {w.ck}, {w.ck}); + } + op_crope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.ck}, {w.ck}); + op_cstore = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv * rep), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {rep > 1 ? w.ck4 : w.ck, rep > 1 ? w.cv4 : w.cv}, {}); + + /* ---------------------------------------------------------------- the query pass */ + op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)), + RAD_WEIGHTS(w_tok)), + {}, {w.x}); + if (g.world > 1) + op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {w.x}, {w.x}); + op_qh = decl_quant(b, qrows, g.n_embd, w.h, w.hq, w.hs); + op_qat = decl_quant(b, qrows, qd, w.attn, w.atq, w.ats); + op_qff = decl_quant(b, qrows, g.n_ff, w.ffn, w.ffq, w.ffs); + + /* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the + * fused_add_rms_norm form (x += h first). On the E4M3 grid it computes exactly the chain's + * result, the norm of the bf16-rounded sum and the codes of the bf16-rounded norm + * (libr4d/r4d_rows.cpp); the int8 one keeps the sum in f32 (docs/OPS.md). It is asked about + * first, since declaring an op no loaded library declares is an error. */ + const bool has_nq = rad_op_declared(b, i8 ? "rmsnorm_quant_i8" : "rmsnorm_quant_fp8") != 0; + auto norm_quant_op = [&](rad_weight gain, bool add) -> rad_op { + if (!has_nq) return (rad_op)0; + const rad_op h = i8 + ? RAD_OP(b, "rmsnorm_quant_i8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype), + RAD_F64("wadd", 0.0)), + RAD_WEIGHTS(gain)) + : RAD_OP(b, "rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)), + RAD_WEIGHTS(gain)); + return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs}); + }; + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_anorm[i])), + {w.x}, {w.h}); + op_anq[i] = norm_quant_op(w_anorm[i], l > 0); + op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q}); + op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k}); + op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v}); + if (rep > 1 && i == 0) { + op_rep_k = rep_op(qrows, w.k, w.k4); + op_rep_v = rep_op(qrows, w.v, w.v4); + } + op_qn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qn[i])), + {w.q}, {w.q}); + op_kn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn[i])), + {w.k}, {w.k}); + op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h}); + op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_fnorm[i])), + {w.x}, {w.h}); + op_fnq[i] = norm_quant_op(w_fnorm[i], true); + op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up}); + /* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's + * rule, band included). E4M3 grid only: libr4d's fold is fp8a8. */ + { + const int64_t hi = qrows < 64 ? qrows : 64; + if (hi > 0 && !i8 && !w_gu[i].f.mx) { + op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff), + RAD_INT("K", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")), + RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)), + {w.hq, w.hs}, {w.ffq, w.ffs}); + if (op_gug[i]) gated_rows = hi; + } + } + op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h}); + } + op_qrope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.q}, {w.q}); + op_krope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.k}, {w.k}); + op_store = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv * rep), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {rep > 1 ? w.k4 : w.k, rep > 1 ? w.v4 : w.v}, {}); + op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.gate_up}, {w.ffn}); + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + op_final = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + + /* ---------------------------------------------------------------- the head + * The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous, + * projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded, + * each rank reports its best kTopR as global ids with logits; these are all-gathered and + * reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the + * global winner is its own shard's first. */ + op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.h}, {w.sel_h}); + /* The 8-bit copy, where the container holds one (see the file header). The name map comes + * first since it is how the encoding is looked up; rad-convert writes only declared weights. + * The copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and + * `vocab_off` holds. Its grid is its own, not the linears': it reads its own quantised copy of + * the gathered rows. */ + const char* dhn = nm.f("dflash.draft_head.weight"); + RAD_ARCH_TRY(map_copy(b, dhn, tok_src)); + RadEncoding he{}; + const bool known = weight_enc(b, dhn, &he); + const bool head_fp8 = known && block_fp8_128(he); + const bool head_i8 = known && linear_w8a8(he); + q_head = head_fp8 || head_i8; + if (q_head) { + if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: gemma4: the 8-bit draft head is %lldx%lld a rank, which " + "is not whole %d-row scale blocks\n", + (long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE; + w_dh.i8 = head_i8; + w_dh.w = decl_view(b, dhn, nullptr, "codes", head_i8 ? RAD_I8 : RAD_F8E4M3, + { g.n_vocab, g.n_embd }, RAD_ACCESS_PER_TOKEN, shard, grp_model()); + w_dh.s = head_i8 + ? decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16, + { g.n_vocab, g.n_embd / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, shard, + grp_model()) + : decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16, + { fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN, + shard, grp_model()); + w_dh.f.w = w_dh.w; + w_dh.f.s = w_dh.s; + if (!w_dh.w || !w_dh.s) return RAD_E_INVAL; + w.selq = decl_b(b, nm.f("df_selq"), head_i8 ? RAD_I8 : RAD_F8E4M3, {srows, g.n_embd}); + w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, + {srows, head_i8 ? 1 : fp8_blocks(g.n_embd)}); + op_qsel = rw(b, RAD_OP(b, head_i8 ? "quant_act_i8" : "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.sel_h}, {w.selq, w.sels}); + op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog}); + } else { + op_head = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_tok)), + {w.sel_h}, {w.dlog}); + } + if (sharded) { + op_topk = rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.dlog}, {w.cand, w.unary, w.dpair}); + /* Row-interleaved, so one draft position's pairs from every rank land side by side. */ + op_dgather = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"), + RAD_INT("row", kTopR * 2)), + RAD_NOWEIGHTS), + {w.dpair}, {w.dgath}); + op_pick = rw(b, RAD_OP(b, "pair_argmax", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {w.dgath}, {w.tokens}); + if (!op_pick) { + fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the " + "device, and no loaded kernel library serves it there\n"); + return RAD_E_UNSUPPORTED; + } + } else { + op_topk = rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", 1), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.dlog}, {w.tokens, w.unary}); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------------------ the context pass */ + +inline void Dflash1::context(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + + quant(c, op_qsrc, T, w.src, w.srcq, w.srcs); + gemm(c, op_cfc, T, w.srcq, w.srcs, w_fc, w.c); + RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T)); + quant(c, op_qc, T, w.c, w.cq, w.cs); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + gemm(c, op_ck[i], T, w.cq, w.cs, w_k[i], w.ck); + gemm(c, op_cv[i], T, w.cq, w.cs, w_v[i], w.cv); + 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)); + const bool rep = cfg.kv_rep > 1; + if (rep) { + rep_kv(c, op_rep_ck, T, w.ck, w.ck4); + rep_kv(c, op_rep_cv, T, w.cv, w.cv4); + } + RAD_ISSUE_N(c, op_cstore, T, brows(rep ? w.ck4 : w.ck, T), brows(rep ? w.cv4 : w.cv, T), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + } +} + +/* ------------------------------------------------------------------------------ the query pass */ + +inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + + RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T)); + if (op_embed_ar) + RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE); + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa; + + /* The attention input, with the last layer's residual add where one launch takes both. */ + if (op_anq[i]) { + norm_quant(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T), + l > 0 ? brows(w.x, T) : RAD_NONE, w_anorm[i]); + } else { + RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); + quant(c, op_qh, T, w.h, w.hq, w.hs); + } + gemm(c, op_qp[i], T, w.hq, w.hs, w_q[i], w.q); + gemm(c, op_kp[i], T, w.hq, w.hs, w_k[i], w.k); + gemm(c, op_vp[i], T, w.hq, w.hs, w_v[i], w.v); + 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)); + const bool rep = cfg.kv_rep > 1; + if (rep) { + rep_kv(c, op_rep_k, T, w.k, w.k4); + rep_kv(c, op_rep_v, T, w.v, w.v4); + } + RAD_ISSUE_N(c, op_store, T, brows(rep ? w.k4 : w.k, T), brows(rep ? w.v4 : w.v, T), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + RAD_ISSUE_N(c, op_attn, batch->max_q_len, + brows(w.q, T), kv_cache(kv, first_layer + i), + praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), + praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T)); + quant(c, op_qat, T, w.attn, w.atq, w.ats); + gemm(c, op_op[i], T, w.atq, w.ats, w_o[i], w.h); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + if (op_fnq[i]) { + norm_quant(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), w_fnorm[i]); + } else { + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); + quant(c, op_qh, T, w.h, w.hq, w.hs); + } + if (op_gug[i] && T <= gated_rows) { + RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T), + RAD_NONE); + } else { + gemm(c, op_gu[i], T, w.hq, w.hs, w_gu[i], w.gate_up); + RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T)); + quant(c, op_qff, T, w.ffn, w.ffq, w.ffs); + } + gemm(c, op_dn[i], T, w.ffq, w.ffs, w_dn[i], w.h); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + /* the residual add, unless the next layer's input norm takes it */ + if (l + 1 == g.n_layer || !op_anq[i + 1]) + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + } + RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + + const int64_t S = batch->n_out; + if (S <= 0) return; + RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S)); + if (q_head) { + if (w_dh.i8) + RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S), + RAD_NONE); + else + RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S)); + RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w), + RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref()); + } else { + RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S)); + } + if (sharded) { + RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S), + brows(w.dpair, S)); + RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S)); + RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE); + } else { + RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S), + RAD_NONE); + } +} + +} /* namespace gemma4 */ + +#endif /* RAD_GEMMA4_DFLASH_H */ diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index f6d56cef..1bff90fe 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -90,8 +90,7 @@ #include #include #include - -#include "gemma4_dflash.h" +#include #include #include @@ -223,16 +222,15 @@ struct Model { rad_weight w_tok = 0, w_onorm = 0; rad_op op_embed = 0, op_embed_ar = 0, op_onorm = 0, op_gather = 0, op_logits = 0, op_cap = 0; - enum { MAX_TAPS = 8 }; + enum { MAX_TAPS = Dflash1::MAX_TAPS }; int n_taps = 0; int tap_layer[MAX_TAPS] = {}; rad_buf b_dfsrc = 0; Dflash1 df{}; - Dflash1::Wire dfw{}; rad_kvgroup kv_draft = 0; bool have_df = false; - const char* tok_src = nullptr; /* the checkpoint's table, which the fp8 draft head copies */ + const char* tok_src = nullptr; /* the checkpoint's table, which the 8-bit draft head copies */ std::vector layers; }; @@ -301,159 +299,19 @@ static rad_op decl_full_rope(RadBuilder* b, const Kind& k, int64_t rows, int64_t /* ============================================================== the drafter */ +/* z-lab's DFlash drafter (arch/common/rad_gemma4_dflash.h), past the trunk's layers, reading the + * taps the trunk copies into `dflash_src` and the trunk's tied table. */ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Model& m, int base_layer) { - Names& nm = m.nm; - Geom dg{}; - RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma4 DFlash")); - if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) { - fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads " - "the target's embedding and head, so it is not this target's drafter\n", - (long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd); - return RAD_E_UNSUPPORTED; - } - - Dflash1::Config dc{}; - dc.n_taps = m.n_taps; - dc.escale = m.escale; - /* v1 states its block at the top level; a SpecForge config nests it under dflash_config. */ - long long trained = rad_meta_geti(meta, "draft.block_size", 0); - if (trained <= 0) trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); - if (trained < 2) { - fprintf(stderr, "radiance: gemma4: the DFlash checkpoint states no block_size\n"); - return RAD_E_FORMAT; - } - if ((long long)ctx->max_spec + 1 != trained) { - fprintf(stderr, "radiance: gemma4: the DFlash drafter was trained at block_size %lld, " - "which is %lld draft tokens, and this serve asks for %d. A block-diffusion " - "drafter denoises a fixed number of mask positions; run it at " - "--num-speculative-tokens %lld (or `auto`).\n", - trained, trained - 1, ctx->max_spec, trained - 1); - return RAD_E_UNSUPPORTED; - } - dc.block = trained; - if (dg.n_layer > Dflash1::MAX_LAYERS) return RAD_E_UNSUPPORTED; - { - std::vector full; - const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr); - if (lt) { - RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention", - &full)); - if ((int64_t)full.size() != dg.n_layer) { - fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and " - "it has %lld\n", full.size(), (long long)dg.n_layer); - return RAD_E_INVAL; - } - } else { - full.assign((size_t)dg.n_layer, 1); - } - bool any_swa = false; - for (int64_t l = 0; l < dg.n_layer; ++l) { - dc.full[l] = full[(size_t)l]; - any_swa = any_swa || !full[(size_t)l]; - } - if (any_swa) { - dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size", - rad_meta_geti(meta, "draft.sliding_window", 0)); - if (!rad_meta_geti(meta, "draft.use_sliding_window", 1) || dc.window <= 0) { - fprintf(stderr, "radiance: gemma4: the drafter names sliding layers and no " - "window\n"); - return RAD_E_INVAL; - } - } - } - - /* One unbounded cache for all the drafter's layers, because its full layer reads every - * position. The sliding layers bound themselves with their attention op's `window`, so the - * declared drafter window is 0 and the core stages the whole context. A separate window group - * for the sliding layers would save memory. */ - RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, 0, base_layer, &m.kv_draft)); - - const int64_t qd = dg.n_head * dg.head_dim; - const int64_t kvd = dg.n_head_kv * dg.head_dim; - int64_t qr = dg.max_seqs * dc.block; - if (qr > dg.max_tok) qr = dg.max_tok; - const int64_t sr = dg.max_seqs * dc.steps(); - const int64_t tw = dc.n_taps * dg.n_embd; - - Dflash1::Wire& dw = m.dfw; - dw.src = m.b_dfsrc; - dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, tw}); - dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(tw)}); - dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd}); - dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd}); - dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)}); - dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd}); - dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd}); - dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd}); - dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd}); - dw.hq = decl_b(b, nm.f("df_hq"), RAD_F8E4M3, {qr, dg.n_embd}); - dw.hs = decl_b(b, nm.f("df_hs"), RAD_F32, {qr, fp8_blocks(dg.n_embd)}); - dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd}); - dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd}); - dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd}); - dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd}); - dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd}); - dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)}); - dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff}); - dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff}); - dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff}); - dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)}); - dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd}); - dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, dg.n_vocab}); - if (Dflash1::head_sharded(dg)) { - const int64_t R = Dflash1::kTopR; - dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, R}); - dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, R}); - dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, R, 2}); - dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * R, 2}); - } else { - dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, 1}); - } - if (!Dflash1::head_sharded(dg) && dg.world > 1) { - fprintf(stderr, "radiance: gemma4: the vocabulary (%lld) does not split evenly into whole " - "16-row blocks over %d ranks, which the drafter's sharded head needs\n", - (long long)dg.n_vocab_all, dg.world); - return RAD_E_UNSUPPORTED; - } - /* The draft, one row per draft position: [n_seq * steps, 1], i.e. [n_seq, steps] with pitch - * `steps`, read by the engine through the drafter declaration below. */ - dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {sr, 1}); - - RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw, - m.tok_src)); + Dflash1::Trunk t{}; + t.n_taps = m.n_taps; + t.escale = m.escale; + t.src = m.b_dfsrc; + t.w_tok = m.w_tok; + t.tok_src = m.tok_src; + t.base_layer = base_layer; + RAD_ARCH_TRY(Dflash1::declare_drafter(b, meta, ctx, m.nm, m.g, t, &m.df, &m.kv_draft)); m.have_df = true; - - RadDrafterDecl drf{}; - drf.name = "dflash"; - drf.kind = RAD_DRAFT_BLOCK; - drf.depth = ctx->max_spec; - drf.block = dc.block; /* the anchor predicts nothing: block = depth + 1 */ - drf.proposal = dw.tokens; - drf.proposal_pitch = dc.steps(); - drf.window = 0; /* the full layer reads everything; see the group */ - drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", - rad_meta_geti(meta, "draft.mask_token_id", -1)); - if (drf.mask_token < 0) { - fprintf(stderr, "radiance: gemma4: the DFlash checkpoint declares no mask_token_id\n"); - return RAD_E_FORMAT; - } - RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); - - int nfull = 0; - for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l]; - rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld " - "sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the " - "trunk at %d tap(s). ONE forward over %lld rows proposes %lld tokens; the head is " - "%s, argmax %s", - (long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, nfull, - (long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head, - (long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, m.n_taps, - (long long)dc.block, (long long)dc.steps(), - m.df.fp8_head - ? "the container's block-fp8 copy of the target's table (dflash.draft_head)" - : "the target's tied bf16 table", - Dflash1::head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary"); return RAD_OK; } @@ -662,7 +520,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ---- the embedding scale and the rotary scaling the converter may have written. The scale * is rounded to bf16 because the reference holds it in a bf16 buffer: sqrt(2816) = 53.066 * multiplies as 53.0. */ - m.escale = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)E))); + m.escale = embed_scale(E); RAD_ARCH_TRY(yarn_from(g, meta, "", m.ks.hd)); if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f) { fprintf(stderr, "radiance: gemma4: --rope-scaling is not implemented for this family's " @@ -794,24 +652,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ---- the drafter's taps, declared when the container carries a DFlash drafter and this * serve speculates. DFlash2 is refused by name: its convolutions and selector are another * block. */ - if (ctx->max_spec > 0) { - const char* da = rad_meta_gets(meta, "draft.architectures", ""); - if (da && std::strstr(da, "DFlash2")) { - fprintf(stderr, "radiance: gemma4: the container carries a DFlash2 drafter; this plugin " - "serves the DFlash (v1) block z-lab publishes for Gemma 4\n"); - return RAD_E_UNSUPPORTED; - } - if (da && std::strstr(da, "DFlash")) { - const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr); - if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr); - m.n_taps = parse_layer_ids(ids, m.n_layer, m.tap_layer, Model::MAX_TAPS); - if (m.n_taps <= 0) { - fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model " - "has; it is paired with a different target\n"); - return RAD_E_UNSUPPORTED; - } - m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)m.n_taps * E}); - } + { + const int n = Dflash1::taps(meta, ctx, m.n_layer, m.tap_layer, Model::MAX_TAPS); + if (n < 0) return n; + m.n_taps = n; + if (n > 0) m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)n * E}); } m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); @@ -1869,15 +1714,7 @@ static void step(RadCtx* c, const RadBatch* batch) { static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; out->draft_depth = 0; - const char* da = rad_meta_gets(meta, "draft.architectures", ""); - if (da && std::strstr(da, "DFlash") && !std::strstr(da, "DFlash2")) { - long long bs = rad_meta_geti(meta, "draft.block_size", 0); - if (bs <= 0) bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); - if (bs > 1) { - out->draft_depth = (int)(bs - 1); - out->draft_depth_fixed = 1; - } - } + (void)dflash_probe(meta, out); return RAD_OK; } diff --git a/arch/gemma4/gemma4_dflash.h b/arch/gemma4/gemma4_dflash.h deleted file mode 100644 index 1e6e2e2f..00000000 --- a/arch/gemma4/gemma4_dflash.h +++ /dev/null @@ -1,682 +0,0 @@ -/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4. - * - * ============================== WHAT IT IS ============================== - * - * rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around - * attention and the feed-forward, and the candidate selector). The original DFlash is a small - * Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one - * forward and takes every position's argmax from the target's lm_head. - * - * context pass, one row a committed token: - * c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids))) - * for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v) - * - * query pass, `block` rows a sequence: - * x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below - * for each layer: - * h = input_layernorm(x) - * q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store - * x += o_proj(attention(q, cache)) sliding layers causal over a 2048 window, - * the full layer non-causal over everything - * x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x) - * x = norm(x) - * over the mask rows: logits = lm_head(x) [the target's]; draft = argmax - * - * ============================== THE THREE GEMMA-SPECIFIC FACTS ============================== - * - * From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is - * verified against the trunk. - * - * The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as - * bf16 (53.0 at 2816), and the drafter was trained through the target's embedding module, which - * applies it. `embed_lookup`'s `mult` carries it. - * - * The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names - * four sliding layers and one full one, and the PR's test pins `causal True` on the sliding - * layers and `False` on the full one, so this block declares two attention ops and issues the one - * each layer's type names. - * - * The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and - * cap * tanh(x / cap) is strictly increasing. - * - * ============================== THE HEAD ============================== - * - * The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma - * ties it to the embedding, so it is the weight the trunk's `embed_lookup` and `logits_gemm` read - * and costs no extra bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's - * slice and the ranks' candidates merge exactly (`row_topk` at R = 2 -> `all_gather` -> - * `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR). - * - * The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a - * 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds a block-fp8 copy of the - * table under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical - * weights, as in rad_block_dflash2.h), made by the recipe line - * - * dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 - * - * the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, with the argmax over its - * coarser logits. Drafts are still verified, so the copy can change proposals but never accepted - * text. Without the copy, or in another encoding, the bf16 table is read. The copy costs half the - * table's bytes again (176 MiB per rank at tp 4). There is no rerank against the bf16 table: - * DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not. - * - * ============================== THE LINEARS ARE FP8 ============================== - * - * As in DFlash2, since the drafter is read whole on every decode step: the container must be - * converted with a recipe that makes the six linears block fp8 (or MXFP4). declare() refuses a bf16 - * one by name rather than letting the loader fail on a view. - */ -#ifndef GEMMA4_DFLASH_H -#define GEMMA4_DFLASH_H - -#include -#include - -#include -#include - -namespace gemma4 { - -using namespace rad::arch; - -/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no - * transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */ -inline bool block_fp8_128(const RadEncoding& e) { - const RadEncPlane* sc = rad_enc_plane(&e, "scale"); - return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] && - e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 && - sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK; -} - -struct Dflash1 { - enum { MAX_LAYERS = 8 }; - - struct Config { - int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */ - int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */ - int64_t window = 0; /* the sliding layers' window; 0 for none */ - int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */ - double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */ - int64_t steps() const { return block - 1; } - }; - - struct Wire { - /* the context pass */ - rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */ - rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */ - rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */ - /* the query pass */ - rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */ - rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */ - rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */ - rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */ - rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */ - /* the head, one row per draft position */ - rad_buf sel_h = 0; /* [srows, n_embd] */ - rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */ - rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */ - rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */ - rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */ - rad_buf tokens = 0; /* [srows, 1] i32: the draft, pitch `steps` */ - }; - - Geom g{}; /* the drafter's geometry */ - Config cfg{}; - Wire w{}; - int first_layer = 0; - int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0; - rad_kvgroup kv = 0; - bool sharded = false; - - DenseFP8 w_fc{}; - rad_weight w_hnorm = 0, w_norm = 0; - rad_weight w_tok = 0; /* the target's table: embedding and head */ - DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */ - bool fp8_head = false; - rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; - DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{}; - rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}; - DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{}; - - rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0; - rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; - - rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0; - rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}; - /* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` is served - * (libr4d): op_anq[i] for the attention input (layer 0's without the add) and op_fnq[i] for - * the feed-forward input. Zero where not served; the `add` / `rmsnorm` / `quant_act_fp8` chain - * is issued instead. */ - rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {}; - rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; - rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}; - rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; - rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0; - rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; - rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0; - - /* Candidates each rank contributes under a sharded head. The draft needs one, but the gather - * moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is - * refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax` - * reduces the world * 2 of them to the global top-1. */ - static constexpr int64_t kTopR = 2; - - static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); } - - int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, - rad_kvgroup group, rad_weight tok_embd, const char* ck, const Wire& wire, - const char* tok_src); - void context(RadCtx* c, const RadBatch* batch) const; - void step(RadCtx* c, const RadBatch* batch) const; - -private: - int64_t q_dim() const { return g.n_head * g.head_dim; } - int64_t kv_dim() const { return g.n_head_kv * g.head_dim; } - /* The six linears must be quantised by the recipe. DenseFP8 declares E4M3 (or MXFP4) views - * whatever the container holds, and the loader's error for a bf16 weight read through an fp8 - * view would name the view, not the missing recipe. */ - static int need_quantised(RadBuilder* b, const char* wn) { - RadEncoding e{}; - if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */ - const uint32_t dt = e.plane[0].dtype; - if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK; - fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears " - "are served block fp8 (or MXFP4): convert with a recipe that names them, " - "e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 " - "scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and " - "ffn_down.\n", wn, rad_dtype_name(dt)); - return RAD_E_DTYPE; - } -}; - -/* ------------------------------------------------------------------------------ declare */ - -inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, - int base_layer, rad_kvgroup group, rad_weight tok_embd, - const char* ck, const Wire& wire, const char* tok_src) { - g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd; - if (!ck || !w_tok || !tok_src) return RAD_E_INVAL; - if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) { - fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most " - "%d\n", (long long)g.n_layer, MAX_LAYERS); - return RAD_E_UNSUPPORTED; - } - if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL; - - const int64_t qd = q_dim(), kvd = kv_dim(); - crows = g.max_tok; - qrows = g.max_seqs * cfg.block; - if (qrows > g.max_tok) qrows = g.max_tok; - srows = g.max_seqs * cfg.steps(); - if (qrows <= 0 || srows <= 0) return RAD_E_INVAL; - sharded = head_sharded(g); - - /* ---------------------------------------------------------------- model-scope weights */ - RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(), - { nm.ckpt("%s.fc.weight", ck) })); - RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck))); - w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); - w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); - - /* ---------------------------------------------------------------- per-layer weights */ - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - const RadWeightGroup gl = grp_layer(first_layer + i); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i), - nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), - nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), - nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), - nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i))); - w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); - w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); - w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); - w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); - /* The declared names match rad_block_dflash2.h's, so one recipe quantises both - * drafters. */ - RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, - { nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) })); - RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, - { nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) })); - RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, - { nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) })); - RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, - { nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) })); - RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff, - g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, - { nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i), - nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) }, - { g.n_ff, g.n_ff })); - RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, - { nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) })); - for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", - "ffn_down" }) - RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s))); - } - - /* ---------------------------------------------------------------- attention: two kinds - * Declared before either kv_store, 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", - RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim), - RAD_INT("gqa", g.gqa()), RAD_INT("causal", causal), - RAD_INT("window", window), RAD_INT("n_head", g.n_head), - RAD_INT("block_size", RAD_KV_BLOCK), - RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), - RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS), - {w.q}, {w.attn}); - }; - bool any_full = false, any_swa = false; - for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true; - if (any_swa) op_attn_swa = attn(1, cfg.window); - if (any_full) op_attn_full = attn(0, 0); - - /* ---------------------------------------------------------------- the context pass */ - op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.src}, {w.srcq, w.srcs}); - op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c}); - op_cnorm = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_hnorm)), - {w.c}, {w.c}); - op_qc = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.c}, {w.cq, w.cs}); - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck}); - op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv}); - op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv), - RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), - RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_kn[i])), - {w.ck}, {w.ck}); - } - op_crope = rw(b, decl_rotary(b, g, "rope", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), - RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), - RAD_STR("mode", "neox")), - RAD_NOWEIGHTS), - {w.ck}, {w.ck}); - op_cstore = rw(b, RAD_OP(b, "kv_store", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head_kv", g.n_head_kv), - RAD_INT("block_size", rad_kv_block_size(b, kv)), - RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS), - {w.ck, w.cv}, {}); - - /* ---------------------------------------------------------------- the query pass */ - op_embed = rw(b, RAD_OP(b, "embed_lookup", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd), - RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), - RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)), - RAD_WEIGHTS(w_tok)), - {}, {w.x}); - if (g.world > 1) - op_embed_ar = rw(b, RAD_OP(b, "all_reduce", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), - RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), - RAD_NOWEIGHTS), - {w.x}, {w.x}); - op_qh = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.h}, {w.hq, w.hs}); - op_qat = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.attn}, {w.atq, w.ats}); - op_qff = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.ffn}, {w.ffq, w.ffs}); - - /* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the - * fused_add_rms_norm form (x += h first). It computes exactly the chain's result: the norm of - * the bf16-rounded sum and the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp). */ - auto norm_quant = [&](rad_weight gain, bool add) -> rad_op { - const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), - RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)), - RAD_WEIGHTS(gain)); - return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs}); - }; - - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_anorm[i])), - {w.x}, {w.h}); - op_anq[i] = norm_quant(w_anorm[i], l > 0); - op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q}); - op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k}); - op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v}); - op_qn[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_qn[i])), - {w.q}, {w.q}); - op_kn[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv), - RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), - RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_kn[i])), - {w.k}, {w.k}); - op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h}); - op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_fnorm[i])), - {w.x}, {w.h}); - op_fnq[i] = norm_quant(w_fnorm[i], true); - op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up}); - /* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's - * rule, band included). */ - { - const int64_t hi = qrows < 64 ? qrows : 64; - if (hi > 0 && !w_gu[i].mx) { - op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff), - RAD_INT("K", g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), - RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")), - RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)), - {w.hq, w.hs}, {w.ffq, w.ffs}); - if (op_gug[i]) gated_rows = hi; - } - } - op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h}); - } - op_qrope = rw(b, decl_rotary(b, g, "rope", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0), - RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), - RAD_STR("mode", "neox")), - RAD_NOWEIGHTS), - {w.q}, {w.q}); - op_krope = rw(b, decl_rotary(b, g, "rope", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), - RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), - RAD_STR("mode", "neox")), - RAD_NOWEIGHTS), - {w.k}, {w.k}); - op_store = rw(b, RAD_OP(b, "kv_store", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head_kv", g.n_head_kv), - RAD_INT("block_size", rad_kv_block_size(b, kv)), - RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS), - {w.k, w.v}, {}); - op_act = rw(b, RAD_OP(b, "silu_mul", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), - RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.gate_up}, {w.ffn}); - if (g.world > 1) - op_ar = rw(b, RAD_OP(b, "all_reduce", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), - RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), - RAD_INT("min_bytes", g.wire_min_bytes)), - RAD_NOWEIGHTS), - {w.h}, {w.h}); - op_add = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.x, w.h}, {w.x}); - op_final = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_norm)), - {w.x}, {w.h}); - - /* ---------------------------------------------------------------- the head - * The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous, - * projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded, - * each rank reports its best kTopR as global ids with logits; these are all-gathered and - * reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the - * global winner is its own shard's first. */ - op_gather = rw(b, RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), - RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.h}, {w.sel_h}); - /* The fp8 copy, where the container holds one (see the file header). The name map comes first - * since it is how the encoding is looked up; rad-convert writes only declared weights. The - * copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and - * `vocab_off` holds. */ - const char* dhn = nm.f("dflash.draft_head.weight"); - RAD_ARCH_TRY(map_copy(b, dhn, tok_src)); - RadEncoding he{}; - fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he); - if (fp8_head) { - if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) { - fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which " - "is not whole %d-row scale blocks\n", - (long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK); - return RAD_E_INVAL; - } - const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE; - w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd }, - RAD_ACCESS_PER_TOKEN, shard, grp_model()); - w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16, - { fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN, - shard, grp_model()); - if (!w_dh.w || !w_dh.s) return RAD_E_INVAL; - w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd}); - w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)}); - op_qsel = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.sel_h}, {w.selq, w.sels}); - op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog}); - } else { - op_head = rw(b, RAD_OP(b, "gemm_nt", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), - RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_tok)), - {w.sel_h}, {w.dlog}); - } - if (sharded) { - op_topk = rw(b, RAD_OP(b, "row_topk", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), - RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off), - RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.dlog}, {w.cand, w.unary, w.dpair}); - /* Row-interleaved, so one draft position's pairs from every rank land side by side. */ - op_dgather = rw(b, RAD_OP(b, "all_gather", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"), - RAD_INT("row", kTopR * 2)), - RAD_NOWEIGHTS), - {w.dpair}, {w.dgath}); - op_pick = rw(b, RAD_OP(b, "pair_argmax", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR), - RAD_STR("dtype", "f32")), - RAD_NOWEIGHTS), - {w.dgath}, {w.tokens}); - if (!op_pick) { - fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the " - "device, and no loaded kernel library serves it there\n"); - return RAD_E_UNSUPPORTED; - } - } else { - op_topk = rw(b, RAD_OP(b, "row_topk", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), - RAD_INT("R", 1), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.dlog}, {w.tokens, w.unary}); - } - return RAD_OK; -} - -/* ------------------------------------------------------------------------------ the context pass */ - -inline void Dflash1::context(RadCtx* c, const RadBatch* batch) const { - const int64_t T = batch->n_tok; - if (T <= 0) return; - const RadKVGroupBatch* kvb = kv_batch(batch, kv); - const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; - - RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T)); - RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s), - brows(w.c, T), RAD_NONE, w_fc.bref()); - RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T)); - RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T)); - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T), - RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref()); - RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T), - RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref()); - RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]), - brows(w.ck, T)); - RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T)); - RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T), praw(slot, RAD_I32, T), - kv_cache(kv, first_layer + i)); - } -} - -/* ------------------------------------------------------------------------------ the query pass */ - -inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { - const int64_t T = batch->n_tok; - if (T <= 0) return; - const RadKVGroupBatch* kvb = kv_batch(batch, kv); - const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; - const int32_t* table = kvb ? kvb->block_table : nullptr; - const int32_t* used = kvb ? kvb->seqused : nullptr; - - RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T)); - if (op_embed_ar) - RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE); - - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa; - - /* The attention input, with the last layer's residual add where one launch takes both. */ - if (op_anq[i]) { - RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T), - l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T), - brows(w.hs, T), RAD_NONE); - } else { - RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); - RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); - } - RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref()); - RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref()); - RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref()); - RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T)); - RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T)); - RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T)); - RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T)); - RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), - kv_cache(kv, first_layer + i)); - RAD_ISSUE_N(c, op_attn, batch->max_q_len, - brows(w.q, T), kv_cache(kv, first_layer + i), - praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), - praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE, - praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T)); - RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T)); - RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T), - RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref()); - if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - if (op_fnq[i]) { - RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]), - brows(w.hq, T), brows(w.hs, T), RAD_NONE); - } else { - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); - RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); - RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); - } - if (op_gug[i] && T <= gated_rows) { - RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T), - RAD_NONE); - } else { - RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE, - w_gu[i].bref()); - RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T)); - RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T)); - } - RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T), - RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref()); - if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - /* the residual add, unless the next layer's input norm takes it */ - if (l + 1 == g.n_layer || !op_anq[i + 1]) - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); - } - RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); - - const int64_t S = batch->n_out; - if (S <= 0) return; - RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S)); - if (fp8_head) { - RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S)); - RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w), - RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref()); - } else { - RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S)); - } - if (sharded) { - RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S), - brows(w.dpair, S)); - RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S)); - RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE); - } else { - RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S), - RAD_NONE); - } -} - -} /* namespace gemma4 */ - -#endif /* GEMMA4_DFLASH_H */ diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 34c2ba87..ebdd95a0 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -7,10 +7,17 @@ * declare), with a second norm on each projection's output before its residual, a weightless RMS * norm on the value, and a GELU (not SwiGLU) feed-forward. The final logits are soft-capped to * cap * tanh(x / cap). + * + * Two draft models, whichever the container carries under `draft.`: Google's assistant head (a + * serial head over the trunk's own cache, the Gemma4Head below) or z-lab's DFlash drafter (a + * five-layer block drafter with its own cache, reading the trunk's residual stream at six layers, + * arch/common/rad_gemma4_dflash.h) -- the 31B's z-lab/gemma-4-31B-it-DFlash proposes 15 tokens a + * pass where the assistant proposes one a round. */ #include #include #include +#include #include #include @@ -20,12 +27,6 @@ #include #include -/* sqrt(n_embd) rounded to bf16: the reference's embedding module multiplies the looked-up rows by - * `embed_scale.to(bf16)`, 73.5 at 5376 and not 73.32. */ -static double embed_scale(int64_t n) { - return rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)n))); -} - namespace gemma4_bf16 { using namespace rad::arch; @@ -839,7 +840,7 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_embd", n_trunk), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), RAD_INT("vocab_offset", g.vocab_off), - RAD_F64("mult", embed_scale(n_trunk))), + RAD_F64("mult", gemma4::embed_scale(n_trunk))), RAD_WEIGHTS(w_tok)), {}, {b_e}); if (g.world > 1) @@ -1098,6 +1099,8 @@ struct Layer { * The last layer has no j_ma: its stream goes to the final norm, which feeds the lm_head, not * a quantiser. */ G4Junction j_am{}, j_ma{}; + /* the DFlash drafter's tap: this layer's output into its column slice of `dflash_src` */ + rad_op op_tap = 0; }; struct Model { @@ -1133,6 +1136,17 @@ struct Model { bool fuse = false; bool fuse_ar = false; /* every junction also carries the all-reduce in front of it */ int64_t ar_rows = 0; /* ...in a step of at most this many rows (G4Junction::ar_rows) */ + + /* z-lab's DFlash drafter (arch/common/rad_gemma4_dflash.h), declared only when the container + * carries one and the deployment speculates: the trunk layers it taps, the [max_tok, taps x + * n_embd] plane the taps fill, the block and its own KV group. */ + enum { MAX_TAPS = gemma4::Dflash1::MAX_TAPS }; + int n_taps = 0; + int tap_layer[MAX_TAPS] = {}; + rad_buf b_dfsrc = 0; + gemma4::Dflash1 df{}; + rad_kvgroup kv_draft = 0; + bool have_df = false; }; static Model g_model[MAX_RANKS]; @@ -1255,6 +1269,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); + /* ---- the DFlash drafter's taps, declared when the container carries z-lab's drafter and this + * serve speculates. The plane is declared here and written by an op declared inside each layer + * it taps, because the buffer planner's liveness is declaration order (the tap below). */ + { + const int n = gemma4::Dflash1::taps(meta, ctx, g.n_layer, m.tap_layer, Model::MAX_TAPS); + if (n < 0) return n; + m.n_taps = n; + if (n > 0) + m.b_dfsrc = decl_b(b, nm.f("dflash_src"), g.act_dtype, + {g.max_tok, (int64_t)n * g.n_embd}); + } + /* ---- the vocabulary edges. Gemma 4 ties the head to the embedding. */ const char* pre = "model.language_model.layers"; RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.language_model.embed_tokens.weight"))); @@ -1276,14 +1302,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* The embedding is scaled by sqrt(n_embd) at the lookup, not in the table (as in llama.cpp's * build_inp_embd and HF's ScaledWordEmbedding), so the plain table stays tied to the head. * Without it the token signal in the residual stream would be ~73x too small. The scale is - * sqrt(n_embd) rounded to bf16, as the reference multiplies by it (embed_scale: 73.5 + * sqrt(n_embd) rounded to bf16, as the reference multiplies by it (gemma4::embed_scale: 73.5 * at 5376, not 73.32). The first norm hides the difference but the residual stream does not, * and the DFlash drafter was trained on the reference's hidden states. */ m.op_embed = rw(b, RAD_OP(b, "embed_lookup", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), RAD_INT("vocab_offset", g.vocab_off), - RAD_F64("mult", embed_scale(g.n_embd))), + RAD_F64("mult", gemma4::embed_scale(g.n_embd))), RAD_WEIGHTS(m.w_tok)), {}, {m.b_x}); if (g.world > 1) @@ -1329,6 +1355,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(lay.w_scalar)), {mw.x}, {mw.x}); + + /* The tap: a row copy of the layer's output (after the scalar, HF's hidden_states[l + 1]) + * into the column slice the tap owns. It is declared here, in the layer it is issued + * after, because the buffer planner's liveness is declaration order. A tap declared once + * after the trunk made `dflash_src` look born at its end and free to share with what every + * layer writes, which on arch/gemma4 cost 98% of the drafts with the reply still fluent. */ + for (int t = 0; t < m.n_taps; ++t) + if (m.tap_layer[t] == (int)l && !lay.op_tap) + lay.op_tap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_dfsrc}); } /* ---- the junctions, declared once every layer exists (j_ma reads the next layer's gain). @@ -1414,10 +1453,31 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(rad_drafter_shared_kv(b, kHeadPosOffset)); } - /* ---- the vision tower, its weight groups past the trunk's and the head's (counted even when - * the head is not declared, so the groups do not move with max_spec). */ + /* ---- or z-lab's DFlash drafter, past the trunk's layers. It is declared last because + * declaration order is the buffer planner's liveness. It reads the taps the trunk copied into + * `dflash_src` and the trunk's tied table, as its embedding and, where the container holds no + * 8-bit copy, as its head. */ + if (m.n_taps > 0) { + gemma4::Dflash1::Trunk t{}; + t.n_taps = m.n_taps; + t.escale = gemma4::embed_scale(g.n_embd); + t.src = m.b_dfsrc; + t.w_tok = m.w_tok; + t.tok_src = nm.ckpt("model.language_model.embed_tokens.weight"); + t.base_layer = (int)m.n_main; + RAD_ARCH_TRY(gemma4::Dflash1::declare_drafter(b, meta, ctx, nm, g, t, &m.df, &m.kv_draft)); + m.have_df = true; + } + + /* ---- the vision tower, its weight groups past the trunk's and the draft model's: the + * assistant's layers and its exit, or the DFlash drafter's layers. They are counted even when + * the draft model is not declared, so the groups do not move with max_spec. */ { - const int64_t head_groups = has_assistant(meta) ? meta_text_geti(meta, "num_hidden_layers", 0, "draft.") + 1 : 0; + int64_t head_groups = 0; + if (has_assistant(meta)) + head_groups = meta_text_geti(meta, "num_hidden_layers", 0, "draft.") + 1; + else if (gemma4::dflash_kind(meta) == 1) + head_groups = rad_meta_geti(meta, "draft.num_hidden_layers", 0); RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups), "model.", "gemma4_bf16")); } @@ -1448,12 +1508,19 @@ static void step(RadCtx* c, const RadBatch* batch) { m.vis.step(c, batch); return; } - /* A draft pass runs only the head. The trunk already left its final-normed hidden state in - * `h`, which the head's history pass gathers from. */ + /* A draft pass runs only the draft model. The trunk already left its final-normed hidden state + * in `h`, which the assistant's history pass gathers from, and its taps in `dflash_src`, which + * the DFlash drafter's context pass reads. */ if (batch->draft_pass != 0) { + if (m.have_df) { + if (batch->draft_pass > 0) m.df.step(c, batch); + else m.df.context(c, batch); + return; + } if (!m.have_head) { rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " - "container carries no `draft.` assistant, or declare ran at max_spec 0"); + "container carries no `draft.` assistant or DFlash drafter, or declare " + "ran at max_spec 0"); return; } m.head.step(c, batch); @@ -1483,13 +1550,20 @@ static void step(RadCtx* c, const RadBatch* batch) { if (m.fuse && !last) { /* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */ l.j_ma.step(c, T, far); - continue; + } else { + /* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after + * the mlp add, as vLLM's `hidden_states = hidden_states * self.layer_scalar`. The + * checkpoint's values (0.03-0.99) are trained weights that rescale the residual toward + * O(1). */ + RAD_ISSUE(c, l.op_scale, brows(m.b_x, batch->n_tok), RAD_W(l.w_scalar), + brows(m.b_x, batch->n_tok)); } - /* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after the - * mlp add, as vLLM's `hidden_states = hidden_states * self.layer_scalar`. The checkpoint's - * values (0.03-0.99) are trained weights that rescale the residual toward O(1). */ - RAD_ISSUE(c, l.op_scale, brows(m.b_x, batch->n_tok), RAD_W(l.w_scalar), - brows(m.b_x, batch->n_tok)); + /* The drafter's taps, once the layer's output is whole. Either way that is after the + * scalar, since the junction applies it to the stream it writes. */ + for (int t = 0; t < m.n_taps && l.op_tap; ++t) + if (m.tap_layer[t] == (int)li) + RAD_ISSUE(c, l.op_tap, brows(m.b_x, T), + bcol(m.b_dfsrc, (int64_t)t * m.g.n_embd, m.g.n_embd, T)); } RAD_ISSUE(c, m.op_final, @@ -1513,13 +1587,16 @@ static void step(RadCtx* c, const RadBatch* batch) { const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_format(); } /* The default draft depth for `--num-speculative-tokens auto`. A serial head's depth is an - * operating point, not a trained depth: every depth runs. */ + * operating point, not a trained depth: every depth runs. A DFlash drafter's is the block it was + * trained at, fixed. */ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; if (has_assistant(meta)) { out->draft_depth = kHeadDepth; out->draft_depth_fixed = 0; } + /* A DFlash drafter names the block it was trained at, and only that (rad_gemma4_dflash.h). */ + (void)gemma4::dflash_probe(meta, out); /* The tower's pooling window, so a pass size the core picks itself is whole windows. */ if (Gemma4Vision::present(meta)) { const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0); @@ -1530,9 +1607,10 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { #ifndef RAD_ARCH_NO_EXPORTS RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0", - "Gemma 4 dense (text and images), w4a8 from its bf16 or its CT-INT4 (QAT) release: " - "sliding-window and proportional-RoPE global attention over a plain RMSNorm stream " - "with GELU feed-forward, per-layer scalar scaling and soft-capped logits") + "Gemma 4 dense (text and images), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) " + "release: sliding-window and proportional-RoPE global attention over a plain " + "RMSNorm stream with GELU feed-forward, per-layer scalar scaling and soft-capped " + "logits; Google's assistant head or z-lab's DFlash drafter") RAD_ARCH_CHAT_FORMAT(gemma4_bf16) RAD_ARCH_PROBE(gemma4_bf16) #endif diff --git a/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe b/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe new file mode 100644 index 00000000..2276fb5f --- /dev/null +++ b/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe @@ -0,0 +1,56 @@ +# gemma4-31b-dense-bf16-q8-df.recipe -- Gemma 4 31B dense (text) from Google's bf16 checkpoint at +# eight bits (Q8_0's grid as libr4d serves it), with z-lab's DFlash drafter at eight bits too. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \ +# --set quantization_config.quant_method=compressed-tensors -o gemma4-31b-dense-q8-df.rad +# +# radiance serve gemma4-31b-dense-q8-df.rad --num-speculative-tokens auto ... +# +# Q8_0 is int8 codes, symmetric, one f16 scale per block, the scale amax / 127: exactly `codes=i8 +# scale=f16 clamp=sym` and the default absmax rule. What differs is the block. GGML's is 32 values +# and libr4d's int8 GEMMs read 128 (their group is compiled in, C_EQ("group", 128)), so a block +# here is four of Q8_0's. Every rule below is that one grid: +# +# the trunk's linears gemm_nt_q at w8a8: the w4a8 grid at twice the radix, read by the same +# fused junctions (rmsnorm_quant_i8, qkv_norm_rope, gelu_mul_quant_i8), so +# the step takes the int4 container's launches with twice its weight bytes +# the drafter's linears gemm_nt_q at w8a8 too, rmsnorm_quant_i8 folding each residual add, norm +# and quantiser (arch/common/rad_gemma4_dflash.h) +# the drafter's head its own int8 copy of the tied table, gemm_nt_q at w8a8 +# +# The activations are int8 with a scale per row, not per 32-block (llama.cpp's q8_1): the w8a8 +# grid's quantiser is per row, the one the int4 container already reads. libr4d's other int8 grid, +# i8a8, takes a scale per (row, 128) and is closer still to Q8_0 x Q8_1, but nothing in libr4d +# fuses a norm into its quantiser yet, so it would cost five launches per junction at decode. +# +# The trunk's lm_head is int8 as well, as Q8_0 makes `output.weight`: logits_gemm_i8 reads it +# against the bf16 hidden state (no activation quantiser), with a bf16 scale per row and 128 +# columns. It is the trunk's verifier, so drop the line to keep it bf16, at 352 MB per rank more +# read each step. The embedding table stays bf16: it is read one row per token, and it is the +# drafter's table too. +# +# ~33 GiB: the int8 trunk's linears (~28 GiB), the bf16 table and its int8 head (2 GiB), the +# vision tower, the drafter (1.4 GiB) and its head's copy (0.7 GiB). At tp 4, ~8 GiB per rank on a +# 32 GiB R9700. +# +# This starts from bf16 for the reason gemma4-31b-dense-bf16-w4a8-df.recipe gives: the drafter +# reads the trunk's hidden states and was trained beside the bf16 trunk. + +blk.*.attn_q.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.attn_k.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.attn_v.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.attn_o.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.ffn_down.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=f16 clamp=sym + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym + +dflash.fc.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.attn_q.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.attn_k.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.attn_v.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.attn_output.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.ffn_down.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.draft_head.weight rtn codes=i8 group=128 scale=f16 clamp=sym diff --git a/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe b/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe new file mode 100644 index 00000000..ba60ebea --- /dev/null +++ b/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe @@ -0,0 +1,56 @@ +# gemma4-31b-dense-bf16-w4a8-df.recipe -- Gemma 4 31B dense (text) from Google's bf16 checkpoint +# at w4a8, as gemma4-31b-dense-bf16-w4a8.recipe makes it, with z-lab's DFlash drafter merged in +# place of the assistant head. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe \ +# --set quantization_config.quant_method=compressed-tensors -o gemma4-31b-dense-w4a8-df.rad +# +# radiance serve gemma4-31b-dense-w4a8-df.rad --num-speculative-tokens auto ... +# +# The drafter (z-lab/gemma-4-31B-it-DFlash) is five Qwen3-shaped layers of 5376 (64 heads / 8 kv +# x 128, ffn 10752) and an fc over the trunk's residual stream at layers 1 12 23 35 46 57: 1.5 B +# parameters, 3.1 GB at bf16. It denoises a block of 16 in one pass and proposes 15 tokens; z-lab +# measures 4.2-8.6 accepted per step on B300 at bf16, against the assistant head's ~2. The plugin's +# probe names that depth, so rad-convert declares at it and `--num-speculative-tokens auto` serves +# it; any other depth is refused by name. +# +# This starts from bf16, not from the QAT release. The drafter reads the trunk's hidden states at +# six layers and was trained beside the bf16 trunk, so the trunk that serves it should be as close +# to that one as four bits allow: rule=search, as in the plain bf16 recipe, which measured the +# assistant head accepting 0.71/0.62/0.63 of its k=3 drafts from this grid against 0.49/0.50/0.44 +# from the QAT one. +# +# The trunk's lm_head is int8, as keptn42's container has it: logits_gemm_i8 reads it against the +# bf16 hidden state (no activation quantiser), with a bf16 scale per row and 128 columns. At tp 4 a +# rank's slice of the 262144 x 5376 table is 704 MB in bf16, a sixth of everything a verify step +# reads at int4, and 352 MB at int8. It is the trunk's verifier; drop the line to keep it bf16. +# +# ~20 GiB: the int4 trunk's linears (~14 GiB), the bf16 table and its int8 head (2 GiB), the +# vision tower, the drafter at block fp8 (1.4 GiB) and its head's block-fp8 copy (0.7 GiB). + +blk.*.attn_q.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_k.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_v.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_o.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_down.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_gate_up.weight rtn codes=i4 group=128 scale=f16 rule=search + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym + +# The DFlash drafter's seven linears: block fp8, read at fp8a8 against an E4M3 activation (the +# drafter only proposes; the trunk verifies). All seven take one grid, because one quantised +# activation feeds several of them, and the plugin checks it. +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The drafter's head: the target's tied table again under a name of its own, block fp8, which the +# draft head reads instead of the bf16 table. That halves the widest read on the draft path (704 MB +# per rank at tp 4 in bf16), for half the table's bytes again. Drafts are verified, so this changes +# what is proposed, never what is accepted. +dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/deploy/compose/gemma4-31b-q8-df.yaml b/deploy/compose/gemma4-31b-q8-df.yaml new file mode 100644 index 00000000..3ee8ce9c --- /dev/null +++ b/deploy/compose/gemma4-31b-q8-df.yaml @@ -0,0 +1,16 @@ +# Gemma 4 31B-it at eight bits: the trunk's linears and its lm_head int8 on Q8_0's grid (symmetric, +# an f16 scale a block of 128 columns, absmax / 127), int8 activations, z-lab's DFlash drafter +# merged in at int8 too (15 tokens a pass), and the vision tower. Converted with +# data/recipes/gemma4-31b-dense-bf16-q8-df.recipe. Sampling defaults are the checkpoint's +# generation_config; thinking is switched per request (chat_template_kwargs). +# 33 GiB of weights: ~16.5 GiB per card at --tp 2, ~8 GiB at --tp 4 on four cards. +name: radiance-gemma4-31b-q8-df +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-gemma4-31b-q8-df + command: > + --model /models/gemma4-31b-dense-q8-df.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 65536 --kv-cache-dtype fp8 + --num-speculative-tokens auto --max-num-batched-tokens 2048 --temp 1.0 --top-p 0.95 --top-k 64 diff --git a/deploy/compose/gemma4-31b-w4a8-df.yaml b/deploy/compose/gemma4-31b-w4a8-df.yaml new file mode 100644 index 00000000..f9e322da --- /dev/null +++ b/deploy/compose/gemma4-31b-w4a8-df.yaml @@ -0,0 +1,17 @@ +# Gemma 4 31B-it: int4 trunk (round-to-nearest with a scale search, from the bf16 checkpoint) with +# int8 activations, z-lab's DFlash drafter merged in (block fp8, 15 tokens a pass), and the vision +# tower. Converted with data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe. Sampling defaults are the +# checkpoint's generation_config; thinking is switched per request (chat_template_kwargs). +# The drafter serves one depth, the block it was trained at (16, so 15 drafts); `auto` asks the +# container. On four cards use --tp 4. --draft-window adaptive lets each sequence verify only as +# much of the block as its own acceptance pays for, worth it at higher --max-num-seqs. +name: radiance-gemma4-31b-w4a8-df +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-gemma4-31b-w4a8-df + command: > + --model /models/gemma4-31b-dense-w4a8-df.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 65536 --kv-cache-dtype fp8 + --num-speculative-tokens auto --max-num-batched-tokens 2048 --temp 1.0 --top-p 0.95 --top-k 64 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 7cddba35..7df0b1f7 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -17,7 +17,7 @@ plugin claims. | `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Text only, bf16 KV | | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | -| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release, served w4a8. Optional draft head: Google's assistant (`rad-convert --draft-model`), with no cache of its own (`rad_drafter_shared_kv`) | +| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`) | | `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) | | `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 | | `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 | @@ -637,8 +637,10 @@ Traps: `arch/gemma4` serves a container converted from Google's bf16 checkpoint (`Gemma4ForConditionalGeneration` or `Gemma4ForCausalLM`), the recipe choosing what is fp8: gemma-4-26B-A4B-it, and the dense sizes without per-layer embeddings. The CT-INT4 31B release is -`arch/gemma4_bf16`'s. A z-lab DFlash drafter is merged at convert time (`--draft-model`); the -recipes are `data/recipes/gemma4-26b-a4b-df*.recipe`. The reference is transformers' +`arch/gemma4_bf16`'s, and so is the 31B quantised from bf16 at w4a8 or w8a8, which takes the same +DFlash drafter (see "The 31B" below). A z-lab DFlash drafter is merged at convert time +(`--draft-model`); the recipes are `data/recipes/gemma4-26b-a4b-df*.recipe` and +`data/recipes/gemma4-31b-dense-bf16-*-df.recipe`. The reference is transformers' `modeling_gemma4`. ``` @@ -705,13 +707,43 @@ and cannot show it, so time a prefill without it. A step that runs whole (every step) puts the dense arm on the second lane instead, beside the routed arm, with its reductions on lane 0. The startup notes say which form each step takes. -**The draft head in fp8.** The drafter's head is the widest read on the draft path: the target's +**The draft head in 8 bits.** The drafter's head is the widest read on the draft path: the target's bf16 table, 352 MiB per rank at tp 4, every draft pass. A container converted with the line -`dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16` (the three `-df` recipes -carry it) stores a block-fp8 copy under that name, and the head reads it at fp8a8 instead: half -the bytes, for 176 MiB per rank more. Drafts are verified, so the coarser logits can change what is -proposed, never what is accepted; `draft_n_accepted` shows whether they propose worse. Without the -copy the head reads the bf16 table, and the startup note names which head is in use. +`dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16` (the 26B `-df` recipes and +the 31B w4a8 one carry it) stores a block-fp8 copy under that name, and the head reads it at fp8a8 +instead: half the bytes, for 176 MiB per rank more. With `codes=i8 group=128 scale=f16 clamp=sym` +(the 31B Q8 recipe) the copy is int8, read at w8a8. Drafts are verified, so the coarser logits can +change what is proposed, never what is accepted; `draft_n_accepted` shows whether they propose +worse. Without the copy the head reads the bf16 table, and the startup note names which head is in +use. + +**The drafter's linears on either 8-bit grid.** The seven linears (fc and six per layer) are on the +E4M3 grid (block fp8 or MXFP4, at fp8a8 / mxfp4a8 over an E4M3 activation with a scale per (row, +128)) or on the int8 one (`codes=i8 group=128 scale=f16`, at w8a8 over `quant_act_i8`'s activation +with a scale per row, and `rmsnorm_quant_i8` folding each residual add, norm and quantiser as +`rmsnorm_quant_fp8` does on the other). `fc`'s encoding picks the grid. One quantised activation +feeds several linears, so a linear on the other grid is refused by name. The gate_up|silu|quant +fold (`gemm_nt_q_gated`) is fp8a8 only, so the int8 grid keeps `silu_mul` and the quantiser, one +launch per layer more. Above 64 rows the w8a8 GEMM is the tiled one, which takes N in 256s; the +31B drafter's k and v are 256 rows per rank at tp 4, the narrowest that still fits. + +**The 31B.** z-lab's `gemma-4-31B-it-DFlash` is the same block at 5376 (64 heads / 8 kv x 128, +ffn 10752, five layers, taps 1 12 23 35 46 57 of 60, block 16), and `arch/gemma4_bf16` serves it +beside its w4a8 or w8a8 trunk. The taps are copies of the stream each tapped layer's junction +leaves (`rmsnorm_quant_i8` adds the feed-forward and applies the layer scalar, so the copy is +`hidden_states[l + 1]`), declared in the layer they copy for the liveness reason below. The drafter +is declared after the trunk, its layers at 60..64 on a KV group of its own. Its 64 heads over 8 kv +heads are gqa 8 at every rank count, and libr4d's head-128 attention (the one the 26B's gqa-4 +drafter runs on, causal over a window or not) takes 4 queries per kv head at a block of 16. So the +cache holds each kv head twice, written by a head-wide copy of k and v after the projection, and +the attention runs at gqa 4. It is exact: query head q reads a copy of kv head q / 8. A container carries the +assistant head or the drafter under `draft.`, not both. The recipes are +`gemma4-31b-dense-bf16-w4a8-df.recipe` (int4 trunk, int8 lm_head, block-fp8 drafter, ~20 GiB) +and `gemma4-31b-dense-bf16-q8-df.recipe` (Q8_0's grid at libr4d's group of 128 for the trunk, its +lm_head and the drafter, ~33 GiB). Both start from bf16, because the drafter reads the trunk's +hidden states and was trained beside the bf16 trunk. Both plugins scale the embedding by +sqrt(hidden) rounded to bf16, as the reference's embedding module does (73.5 at 5376, not 73.32), +and the drafter reads it through the same scale. **The 31B's junctions at four ranks.** At two ranks every junction carries the all-reduce in front of it (`ar_rmsnorm_quant_i8`). At four it does too, at decode heights. libr4d's diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 9522f5f0..13d38a5a 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -4677,6 +4677,481 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ for (const auto& o : off.ops) CHECK(o.op != "ar_rmsnorm_quant_i8"); } +/* ============ gemma4 31B + DFlash: z-lab's block drafter on the w4a8 / w8a8 trunk ============ */ + +namespace { + +/* The twelve-layer 31B above with z-lab/gemma-4-31B-it-DFlash merged under `draft.` as + * `rad-convert --draft-model` writes it: its own geometry (5376 wide, 64 heads / 8 kv x 128, ffn + * 10752, five layers -- four sliding over 2048, one full -- at block 16), reading the trunk at three + * of the fixture's twelve layers where the real one reads six of sixty. */ +std::vector g431df_keys() { + std::vector k(std::begin(k_gem4_keys), std::end(k_gem4_keys)); + for (const char* s : { "draft.architectures", "draft.num_hidden_layers", "draft.head_dim", + "draft.num_attention_heads", "draft.num_key_value_heads", + "draft.intermediate_size", "draft.rms_norm_eps", "draft.rope_theta", + "draft.hidden_size", "draft.vocab_size", "draft.block_size", + "draft.dflash_config.target_layer_ids", + "draft.dflash_config.mask_token_id", "draft.layer_types", + "draft.sliding_window" }) + k.push_back(s); + return k; +} +std::vector g431df_vals() { + std::vector v(std::begin(k_gem4_vals), std::end(k_gem4_vals)); + for (const char* s : { "[\"DFlashDraftModel\"]", "5", "128", "64", "8", "10752", "1e-06", + "1000000", "5376", "262144", "16", "[1, 5, 9]", "4", + "[\"sliding_attention\", \"sliding_attention\", \"sliding_attention\", " + "\"sliding_attention\", \"full_attention\"]", + "2048" }) + v.push_back(s); + return v; +} + +struct G431Df { + std::vector keys = g431df_keys(), vals = g431df_vals(); + RadModelMeta meta() const { + RadModelMeta m = gemma4_meta(); + m.n_kv = (int)keys.size(); + m.kv_key = keys.data(); + m.kv_val = vals.data(); + return m; + } +}; + +/* The trunk at w4a8 as the -df recipe makes it, the drafter's linears on one 8-bit grid -- the + * E4M3 one (block fp8) or the int8 one (w8a8) -- and, with `head`, the table's 8-bit copy in the + * same grid. The drafter's keys come FIRST: the fake answers the first key a name contains, and + * `attn_q.` is in `dflash.blk.0.attn_q.weight` too. */ +void g431df_encs(RadBuilder& b, bool i8, bool head) { + const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128); + const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); + const RadEncoding q8 = rad_enc_affine(RAD_I8, RAD_F16, 1, 128); + const RadEncoding& d = i8 ? q8 : fp8; + b.encs = { { "dflash.fc.", d }, { "dflash.blk.", d } }; + if (head) b.encs.push_back({ "dflash.draft_head.", d }); + for (const char* s : { "attn_q.", "attn_k.", "attn_v.", "attn_o.", "ffn_gate_up.", "ffn_down." }) + b.encs.push_back({ s, w4 }); +} + +int count_writes_to(const RadBuilder& b, const RadCtx& c, int buf) { + int n = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (o && std::find(o->writes.begin(), o->writes.end(), (rad_buf)buf) != o->writes.end()) + ++n; + } + return n; +} + +rad_kvgroup kv_named(const RadBuilder& b, const char* name) { + for (size_t i = 0; i < b.kv_groups.size(); ++i) + if (b.kv_groups[i].name == name) return (rad_kvgroup)(i + 1); + return 0; +} + +} /* namespace */ + +/* The 31B declares z-lab's drafter as a block drafter past its trunk: five layers at 12..16 on a KV + * group of their own, the trunk's taps in one plane, its embedding read at the reference's scale, + * and the depth the block was trained at, the only one it serves, which probe names for rad-convert + * and `--num-speculative-tokens auto`. Without speculation none of it is declared. */ +TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) { + G431Df f; + const RadModelMeta meta = f.meta(); + RadBuilder b; + g431df_encs(b, false, false); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + CHECK_EQ(b.drafter_name, std::string("dflash")); + CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_BLOCK); + CHECK_EQ(b.drafter.depth, 15); + CHECK_EQ((int)b.drafter.block, 16); + CHECK_EQ(b.drafter.mask_token, 4); + CHECK(!b.drafter_shared); + CHECK_EQ(b.drafter.proposal, (rad_buf)buf_named(b, "dflash_tokens")); + + /* its own cache, the five layers past the trunk's twelve bound to it */ + const rad_kvgroup kvd = kv_named(b, "kv_draft"); + 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); + 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); + { + int n_attn = 0, n_store = 0; + for (const auto& o : b.ops) { + if (o.op == "attn_paged" && pint(&o, "head_dim") == 128) { + ++n_attn; + CHECK_EQ(pint(&o, "gqa"), 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(n_attn, 2); /* the sliding layers' and the full layer's */ + CHECK_EQ(n_store, 2); /* the context pass's and the query pass's */ + } + std::vector bound; + for (const auto& [layer, g] : b.binds) if (g == kvd) bound.push_back(layer); + CHECK(bound == (std::vector{ 12, 13, 14, 15, 16 })); + + /* three taps of 5376 a row */ + const int src = buf_named(b, "dflash_src"); + REQUIRE(src > 0); + CHECK_EQ(b.bufs[src - 1].d.shape[1], 3 * 5376); + + /* the drafter embeds the anchor and the masks through the TRUNK's table at 73.5 */ + const RecOp* te = find_op(b, "embed_lookup", 0); + const RecOp* de = find_op(b, "embed_lookup", 1); + REQUIRE(te != nullptr && de != nullptr); + CHECK(te->w == de->w); + CHECK_NEAR(pflt(de, "mult"), 73.5, 1e-9); + + /* one name map a declared weight: a COPY map repeated is refused by the real builder */ + std::map maps; + for (const auto& mp : b.maps) if (mp.mode == RAD_MAP_COPY) ++maps[mp.declared]; + for (const auto& [name, n] : maps) CHECK_EQ(name + " x" + std::to_string(n), name + " x1"); + + RadArchProbe p{}; + CHECK_OK(gemma4_bf16::probe(&meta, &p)); + CHECK_EQ(p.draft_depth, 15); + CHECK_EQ(p.draft_depth_fixed, 1); + + /* no speculation: no drafter, no taps */ + RadBuilder b0; + g431df_encs(b0, false, false); + RadBuildCtx c0 = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b0, &meta, &c0)); + CHECK_EQ(buf_named(b0, "dflash_src"), 0); + CHECK(b0.drafter_name.empty()); + + /* and a depth the block was not trained at is refused by name */ + RadBuilder b4; + g431df_encs(b4, false, false); + 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 + * first write on (the arch/gemma4 trap that cost 98% of the drafts). Each is issued once its + * layer's output is whole, after the junction that adds the feed-forward, applies the layer scalar + * and quantises the next layer's input, so the copy is HF's hidden_states[l + 1]. */ +TEST(gemma4_31b_dflash_taps_the_stream_the_junction_leaves) { + G431Df f; + const RadModelMeta meta = f.meta(); + RadBuilder b; + g431df_encs(b, false, false); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + const int src = buf_named(b, "dflash_src"), gu = buf_named(b, "gate_up"); + REQUIRE(src > 0 && gu > 0); + int first_src = -1, last_gu = -1; + for (size_t i = 0; i < b.ops.size(); ++i) + for (rad_buf w : b.ops[i].writes) { + if ((int)w == src && first_src < 0) first_src = (int)i; + if ((int)w == gu) last_gu = (int)i; + } + REQUIRE(first_src >= 0 && last_gu >= 0); + CHECK(first_src < last_gu); + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + CHECK_EQ(count_writes_to(b, c, src), 3); + int t = 0; + for (size_t i = 0; i < c.issues.size(); ++i) { + const RecOp* o = b.op_of(c.issues[i].op); + if (!o || std::find(o->writes.begin(), o->writes.end(), (rad_buf)src) == o->writes.end()) + continue; + REQUIRE(i > 0); + CHECK_EQ(b.op_of(c.issues[i - 1].op)->op, std::string("rmsnorm_quant_i8")); + REQUIRE(c.issues[i].opd.size() == 2); + CHECK_EQ(c.issues[i].opd[1].handle, (uint32_t)src); + CHECK_EQ(c.issues[i].opd[1].offset, (int64_t)t * 5376); /* the tap's own column slice */ + ++t; + } +} + +/* A draft pass runs only the drafter: the context pass from the taps into the drafter's cache, + * the query pass over the block to the proposal. */ +TEST(gemma4_31b_dflash_passes_run_the_drafter_and_nothing_else) { + G431Df f; + const RadModelMeta meta = f.meta(); + RadBuilder b; + g431df_encs(b, false, true); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + const int src = buf_named(b, "dflash_src"), tok = buf_named(b, "dflash_tokens"); + + for (int pass : { -1, 1 }) { + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + batch.draft_pass = pass; + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + REQUIRE(!ops.empty()); + CHECK_EQ(count_issued(ops, "gelu_mul_quant_i8"), 0); /* no trunk layer */ + CHECK_EQ(count_issued(ops, "kv_store"), 5); + if (pass < 0) { + 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); + } else { + CHECK_EQ(ops.front(), std::string("embed_lookup")); + CHECK_EQ(count_issued(ops, "attn_paged"), 5); + CHECK_EQ(count_writes_to(b, c, tok), 1); + } + } +} + +/* Q8, the drafter on the int8 grid. Every linear is gemm_nt_q at w8a8 over quant_act_i8's per-row + * activation, each residual add, norm and quantiser is one rmsnorm_quant_i8 (ten per draft pass, as + * rmsnorm_quant_fp8 is on the E4M3 grid), and nothing on the E4M3 grid is declared. The + * gate_up|silu|quant fold is fp8a8 only, so the int8 grid keeps silu_mul and the quantiser. Where + * rmsnorm_quant_i8 is refused, the chain runs. */ +TEST(gemma4_31b_dflash_on_the_int8_grid_reads_w8a8_and_folds_its_norms) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int refuse = 0; refuse < 2; ++refuse) { + RadBuilder b; + g431df_encs(b, true, true); + if (refuse) b.refuse.insert("rmsnorm_quant_i8"); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + CHECK(b.bufs[buf_named(b, "df_hq") - 1].d.dtype == RAD_I8); + CHECK_EQ(b.bufs[buf_named(b, "df_hs") - 1].d.shape[1], 1); /* a scale a row */ + const RecWeight* wq = find_w(b, "dflash.blk.0.attn_q.weight"); + const RecWeight* sq = find_w(b, "dflash.blk.0.attn_q.scale"); + REQUIRE(wq != nullptr && sq != nullptr); + CHECK(wq->d.dtype == RAD_I8 && sq->d.dtype == RAD_F16); + CHECK_EQ(sq->d.shape[1], 5376 / 128); + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + batch.draft_pass = 1; + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + CHECK_EQ(count_issued(ops, "rmsnorm_quant_i8"), refuse ? 0 : 10); + CHECK_EQ(count_issued(ops, "add"), refuse ? 10 : 1); + /* the attention output's and the gated product's a layer, x's twice a layer in the chain, + * and the head's copy of the gathered rows */ + CHECK_EQ(count_issued(ops, "quant_act_i8"), (refuse ? 20 : 10) + 1); + CHECK_EQ(count_issued(ops, "silu_mul"), 5); + for (const char* fp : { "quant_act_fp8", "rmsnorm_quant_fp8", "gemm_nt_q_gated" }) + CHECK_EQ(count_issued(ops, fp), 0); + int q = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (!o || o->op != "gemm_nt_q") continue; + CHECK_EQ(pstr(o, "dtype"), std::string("w8a8")); + ++q; + } + CHECK_EQ(q, 5 * 6 + 1); /* six linears a layer, and the head */ + if (refuse) continue; + + /* the fused form's operands: rmsnorm_quant_i8's eight, the delta and the residual past + * layer 0, and no junction gains */ + const uint32_t x = (uint32_t)buf_named(b, "df_x"), h = (uint32_t)buf_named(b, "df_h"); + int k = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (!o || o->op != "rmsnorm_quant_i8") continue; + REQUIRE(i.opd.size() == 8); + CHECK_EQ(i.opd[0].handle, k++ == 0 ? x : h); + CHECK_EQ((int)i.opd[6].kind, (int)RAD_OPK_NONE); + CHECK_EQ((int)i.opd[7].kind, (int)RAD_OPK_NONE); + } + + /* and the context pass: two quantisers, eleven w8a8 GEMMs (fc, then k and v a layer) */ + RadCtx cc; cc.b = &b; cc.rank = 0; cc.world = 1; + RadBatch cb = decode_batch(); + cb.draft_pass = -1; + cc.batch = &cb; + gemma4_bf16::step(&cc, &cb); + CHECK(cc.step_fail.empty()); + const std::vector cops = issued_ops(b, cc); + CHECK_EQ(count_issued(cops, "quant_act_i8"), 2); + CHECK_EQ(count_issued(cops, "gemm_nt_q"), 11); + } +} + +/* The drafter's linears take one grid: one quantised activation feeds several of them, so an fc on + * the E4M3 grid and layers on the int8 one would read pairs nothing writes. Refused by name. */ +TEST(gemma4_31b_dflash_refuses_linears_on_two_grids) { + G431Df f; + const RadModelMeta meta = f.meta(); + RadBuilder b; + g431df_encs(b, true, false); + b.encs[0].second = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); /* fc on E4M3 */ + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_E_DTYPE); +} + +/* The head's int8 copy: where the container holds one, the gathered rows are quantised a row at a + * time and read by gemm_nt_q at w8a8 over it; otherwise the head reads the tied bf16 table. */ +TEST(gemma4_31b_dflash_head_reads_the_int8_copy_where_the_container_holds_one) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int copy = 0; copy < 2; ++copy) { + RadBuilder b; + g431df_encs(b, true, copy == 1); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + const int dlog = buf_named(b, "df_dlog"); + const RecOp* head = nullptr; + for (const auto& o : b.ops) + if (o.resolved && + std::find(o.writes.begin(), o.writes.end(), (rad_buf)dlog) != o.writes.end()) + head = &o; + REQUIRE(head != nullptr); + CHECK_EQ(head->op, std::string(copy ? "gemm_nt_q" : "gemm_nt")); + if (!copy) continue; + CHECK_EQ(pstr(head, "dtype"), std::string("w8a8")); + const int selq = buf_named(b, "df_selq"), sels = buf_named(b, "df_sels"); + REQUIRE(selq > 0 && sels > 0); + CHECK(b.bufs[selq - 1].d.dtype == RAD_I8); + CHECK_EQ(b.bufs[sels - 1].d.shape[1], 1); + const RecWeight* hs = find_w(b, "dflash.draft_head.scale"); + REQUIRE(hs != nullptr); + CHECK(hs->d.dtype == RAD_F16); + CHECK_EQ(hs->d.shape[0], 262144); + CHECK_EQ(hs->d.shape[1], 5376 / 128); + } +} + +/* At four ranks, as the R9700 box serves it: the drafter's heads split 16 / 2 kv per rank, its head + * is vocab-sharded with the trunk's and merged by pair_argmax, and both 8-bit grids declare (the + * int8 one's prefill GEMM takes N in 256s, which a 256-row k and v still are). */ +TEST(gemma4_31b_dflash_at_four_ranks) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int i8 = 0; i8 < 2; ++i8) { + RadBuilder b; + g431df_encs(b, i8 == 1, true); + 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); + 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); + + RadCtx c; c.b = &b; c.rank = 1; c.world = 4; + RadBatch batch = decode_batch(); + batch.draft_pass = 1; + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + CHECK_EQ(count_issued(ops, "pair_argmax"), 1); + 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)); + } +} + +/* Where no loaded library declares libr4d's fused ops (a CPU-only build, where rad-convert and the + * host backend run), asking for one is an error, so the 31B with its DFlash drafter asks first and + * declares the chains: the junctions, the attention prologue, the gated quantiser, the folded + * all-reduce, and the drafter's fused norm on the int8 grid. It declares on both grids, at one rank + * and two, and never asks for an undeclared op. */ +TEST(gemma4_31b_without_libr4d_declares_the_chains_and_asks_for_no_undeclared_op) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int i8 = 0; i8 < 2; ++i8) + for (int world : { 1, 2 }) { + 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" }) + b.undeclared.insert(op); + RadBuildCtx ctx = build_ctx(0, world); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + CHECK(b.asked_undeclared.empty()); + RadCtx c; c.b = &b; c.rank = 0; c.world = world; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + CHECK_EQ(count_issued(ops, "rmsnorm_p"), 12); /* the prologue's value norm, unfused */ + CHECK_EQ(count_issued(ops, "gelu_mul"), 12); + batch.draft_pass = 1; + RadCtx d; d.b = &b; d.rank = 0; d.world = world; d.batch = &batch; + gemma4_bf16::step(&d, &batch); + CHECK(d.step_fail.empty()); + CHECK_EQ(count_issued(issued_ops(b, d), "rmsnorm_quant_i8"), 0); + } +} + +/* The 31B's engine steps lint clean with z-lab's drafter, on both of the drafter's grids, at one, + * two and four ranks (the first and last rank of each): a decode step, a mixed step, a prefill + * chunk tall enough to run as two slices, and a verify step with the drafter's context and query + * passes behind it. The lint holds the buffers each pass reads to what an earlier op of the step + * wrote and the planner kept alive, across the passes, so a tap whose plane the planner let another + * buffer share, or a drafter buffer read after its arena slot was reused, fails here. Eight + * sequences at a block of 16 is 128 query rows, past every fused band the drafter has. */ +TEST(gemma4_31b_steps_lint_clean_with_a_dflash_drafter) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int i8 = 0; i8 < 2; ++i8) + for (int world : { 1, 2, 4 }) + for (int rank : { 0, world - 1 }) { + if (world == 1 && rank > 0) continue; + RadBuilder b; + g431df_encs(b, i8 == 1, true); + RadBuildCtx ctx = build_ctx(rank, world); + ctx.max_tok = 2048; + ctx.max_spec = 15; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + REQUIRE_EQ((int)b.drafter.kind, (int)RAD_DRAFT_BLOCK); + for (const auto& k : { kit(b, { 1, 1, 1 }, {}), kit(b, { 8, 1 }, { 5 }), + kit(b, {}, { 1500 }) }) { + const auto v = run_passes(b, gemma4_bf16::step, { k.get() }, rank, world); + CHECK_PASSES(b, v); + } + for (int64_t n_seq : { 2, 8 }) { + const auto ver = kit(b, std::vector((size_t)n_seq, 16), {}); + const auto ctxp = context_pass(b, *ver); + const auto qry = query_pass(b, n_seq, 16, 15); + const auto v = run_passes(b, gemma4_bf16::step, + { ver.get(), ctxp.get(), qry.get() }, rank, world); + CHECK_PASSES(b, v); + } + } +} + /* ==================================================================== the step lint, checked */ namespace {