radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+177 -311
View File
@@ -1,39 +1,32 @@
/* rad_block_dflash2.h -- the DFlash2 block-diffusion drafter, bf16.
*
* ============================== WHAT IT IS ==============================
* A small transformer that proposes a whole block of tokens in one forward pass. Compared with
* the MTP head (rad_block_mtp_fp8.h):
*
* A SECOND, SMALLER TRANSFORMER that proposes a whole block of tokens in ONE forward pass. It is
* the other drafter this engine serves, and it is a different shape of thing from the MTP head
* beside it (rad_block_mtp_fp8.h):
* MTP depth d costs d chained forwards; round i+1 embeds round i's token.
* DFlash2 depth d costs one forward over d+1 positions: the anchor token plus d mask
* tokens are denoised together.
*
* MTP depth d costs d CHAINED forwards. Round i+1 cannot start until round i has
* produced a token, because the token is what it embeds.
* DFlash2 depth d costs ONE forward over d+1 positions. The block is denoised together --
* the anchor token plus d mask tokens go in, d+1 hidden states come out.
* So depth is nearly free here, and there is no `draft_pass`. Published acceptance is 4.10-5.46
* versus MTP's 3.74-5.02 at 7 drafts.
*
* That is why depth is nearly free here and expensive there, and it is why this file has no
* `draft_pass`: there are no rounds. Published acceptance for this drafter is 4.10-5.46 against
* MTP's 3.74-5.02 at 7 drafts.
*
* The price of proposing the positions together is that position l+1 was computed WITHOUT KNOWING
* what position l would choose. The candidate selector is what puts that dependence back: each
* position keeps the draft head's top K, a low-rank bilinear form scores the edge between
* consecutive positions, and a greedy walk picks one path. `dflash_select` is that kernel.
* Since positions are proposed together, position l+1 does not know what position l chose. The
* candidate selector (`dflash_select`) restores that dependence: each position keeps the draft
* head's top K, a low-rank bilinear form scores edges between consecutive positions, and a greedy
* walk picks one path.
*
* ============================== THE TWO PASSES ==============================
*
* THE CONTEXT PASS, one row a committed token. The drafter never runs its layers over the context
* -- it reads the TARGET's hidden states instead, at five intermediate layers, and turns them
* straight into its own K and V:
* Context pass, one row per committed token. The drafter does not run its layers over the
* context; it turns the target's hidden states at five intermediate layers into its own K and V:
*
* c = fc(concat of the trunk's residual stream at layers 5, 19, 33, 47, 61) [n_taps*n_embd]
* c = hidden_norm(c)
* for each draft layer: k|v = kv_proj(c); k = k_norm(k) then rope; kv_store(k, v)
*
* The trunk's side of that -- the taps, and the `dflash_src` buffer they land in -- is in
* qwen35_fp8.cpp. This file reads the buffer and never asks where the rows came from.
* The taps and the `dflash_src` buffer they land in are the trunk's (qwen35_fp8.cpp).
*
* THE QUERY PASS, one row a draft position, `block` = 1 + n_spec of them a sequence:
* Query pass, one row per draft position, `block` = 1 + n_spec rows per sequence:
*
* x = embed(anchor, mask, mask, ...)
* for each layer:
@@ -47,9 +40,8 @@
* h = dflash_conv(h, coef[taps*NG:], ffn_conv_base[1]); x += h
* x = norm(x)
*
* and then, over the MASK rows of each sequence's block -- offsets 1..block-1, NOT 0..steps-1.
* The anchor at offset 0 is a token the target has already chosen, so its row predicts nothing and
* is there to condition the rest; each mask row predicts the token AT ITS OWN POSITION:
* then, over the mask rows of each block (offsets 1..block-1; the anchor at offset 0 is already
* chosen and only conditions the rest), each predicting the token at its own position:
*
* cand, unary = top_k(draft_head(x)) the candidates and their logits
* hp = hidden_projection(x) the selector's query, rank 256
@@ -57,61 +49,38 @@
*
* ============================== WHAT IS SHARED WITH THE TARGET ==============================
*
* The embedding table and the lm_head, both. The checkpoint ships neither -- 81 tensors, no
* `embed_tokens` and no `lm_head` -- so a drafter without a target is not a model. `mask_token_id`
* is an ordinary id in the target's vocabulary (248070 here), which is why there is no separate
* mask embedding to load.
* The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and
* `mask_token_id` is an ordinary id in the target's vocabulary (248070 here), so there is no
* separate mask embedding.
*
* The head reads the 2-BIT copy of the lm_head, exactly as the MTP head does and for exactly the
* reason rad_block_mtp_fp8.h gives at op_dlogits: a draft is a proposal, the target verifies every
* one of them with its own untouched head, and speculative decoding is distribution-preserving --
* so a coarser draft costs acceptance and cannot change a token the model emits. Its candidates
* are then rescored against the target's own head where that head is fp8 or int8 (op_drerank), so
* the coarseness costs only which candidates are proposed, not how they are ranked. The 2-bit head
* also buys something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
* global without an all-gather and the selector's codebooks can be indexed directly.
* The head reads the 2-bit copy of the lm_head, as the MTP head does (rad_block_mtp_fp8.h,
* op_dlogits): the target verifies every draft with its own head, so a coarser draft costs only
* acceptance, never an emitted token. Candidates are rescored against the target's head when it
* is fp8 or int8 (op_drerank), so coarseness affects only which candidates are proposed.
*
* ============================== THE NORMS ARE PLAIN ==============================
* ============================== PLAIN NORMS ==============================
*
* `w`, not `1 + w`, unlike every norm in the trunk this drafter is bolted to. vLLM says so by
* using the ordinary RMSNorm rather than the family's GemmaRMSNorm, and the checkpoint agrees:
* hidden_norm sits at 0.11..1.24 (mean 0.82), input_layernorm at 0.05..1.70, k_norm at 0.32..2.53
* and the final norm at 2.45..5.25. All positive, all centred near one -- which is a plain gain
* and is not what a `1 + w` tensor looks like. So `Geom::wadd` and `wadd_qk` are ZERO here while
* the trunk's are one, and the two geometries are separate structs for this reason among others.
* The norms use `w`, not the trunk's `1 + w`: vLLM uses plain RMSNorm here, and the gains are all
* positive and centred near one (hidden_norm 0.11..1.24, input_layernorm 0.05..1.70, k_norm
* 0.32..2.53, final norm 2.45..5.25). So this geometry's `wadd` and `wadd_qk` are zero.
*
* ============================== SHARDING ==============================
*
* The layers shard the way any transformer's do: q/kv and gate_up by row, o and down by column
* with an all-reduce. Ten collectives a draft pass, each 5120 * block * 2 bytes -- 80 KiB at the
* shipped block of 8 -- which is below the lossy wire's floor and is served exactly.
* q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per
* draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor.
*
* THREE THINGS ARE REPLICATED AND EACH IS A DECISION:
* Replicated:
*
* fc [n_embd, n_taps*n_embd], 262 MiB. It could be COLUMN-sharded, since its input
* is the replicated residual stream and its output would then be a partial sum:
* 131 MiB a rank and half the read bytes on the context pass's widest GEMM. Not
* done, because it puts an all-reduce on the PREFILL path to save a small
* fraction of it, and the real fix for the context pass's cost is not to run it
* over the whole prompt at all (see below).
* conv weights the projection and the base kernel, 26 MiB a layer. The convolution is over
* the whole replicated hidden row and every rank needs every coefficient; a row
* shard would give each rank a fraction of the groups.
* the codebooks [n_vocab, 256] each, 127 MiB each. They are gathered by GLOBAL token id and
* the ids come out of a whole-vocabulary draft head, so a vocabulary shard would
* let a rank score only the candidates that happened to land in its own slice.
* The gather is 128 rows a pass, so the bytes READ are nothing; it is the
* residency that costs.
* fc [n_embd, n_taps*n_embd], 262 MiB. Column-sharding would halve it but add an
* all-reduce to the prefill path.
* conv weights projection and base kernel, 26 MiB a layer. The convolution spans the whole
* replicated hidden row, so every rank needs every coefficient.
* codebooks [n_vocab, 256], 127 MiB each, gathered by global token id. Only 128 rows are
* read per pass; the cost is residency.
*
* ============================== THE CONTEXT PASS IS THE EXPENSIVE HALF ==============================
*
* In bytes: `fc` is 262 MiB and the five KV projections read 3.4 GB over a 2048-token prefill
* chunk, which is a real fraction of what the chunk costs.
*
* THE FIX IS NOT A FASTER GEMM. The drafter's attention has a 2048-token window, so a context
* position more than 2048 before the query is never read: for a prompt of any real length, all but
* the last 2048 rows of the context pass are computed and thrown away. The scheduler can simply
* not run it over them. That is scheduler work and it is noted here rather than done here.
* Cost: the context pass is the expensive half (`fc` plus five KV projections read 3.4 GB over a
* 2048-token prefill chunk). The attention window is 2048 tokens, so context rows further back
* are never read and the scheduler need not compute them.
*/
#ifndef RAD_BLOCK_DFLASH2_H
#define RAD_BLOCK_DFLASH2_H
@@ -122,9 +91,8 @@
namespace rad {
namespace arch {
/* A row slice of a WEIGHT, the same thing brow_slice() is for a buffer. The conv's base kernel is
* [2, taps, n_embd] and the two sides are the prepare tap set and the finish tap set; there is one
* checkpoint tensor and the op takes one side at a time. */
/* brow_slice() for a weight. The conv base kernel is one [2, taps, n_embd] tensor holding the
* prepare and finish tap sets; the op takes one side at a time. */
inline RadOperand wrow_slice(rad_weight h, int64_t first, int64_t n, int64_t pitch) {
RadOperand o = RAD_W(h);
o.offset = first * pitch;
@@ -135,9 +103,7 @@ inline RadOperand wrow_slice(rad_weight h, int64_t first, int64_t n, int64_t pit
struct Dflash2 {
enum { MAX_LAYERS = 8 };
/* Everything the drafter's own config.json says that its geometry does not. Read by the
* plugin from `draft.*` metadata keys and handed in whole, so this file reads no environment
* and no container. */
/* The drafter config beyond its geometry, read by the plugin from `draft.*` metadata keys. */
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* query rows a sequence: the anchor plus n_spec mask tokens */
@@ -149,8 +115,8 @@ struct Dflash2 {
int causal = 0;
int64_t steps() const { return block - 1; }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
/* The kernel projection emits [2, taps, NG] per token -- one coefficient set for `prepare`
* and one for `finish` -- and `dflash_conv` reads a slice of it at the FULL row pitch. */
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
* `dflash_conv` reads a slice of it at the full row pitch. */
int64_t coef_dim(int64_t n_embd) const { return 2 * taps * ng(n_embd); }
};
@@ -158,43 +124,33 @@ struct Dflash2 {
/* the context pass */
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
rad_buf c = 0; /* [max_tok, n_embd] fc's output, then normed in place */
/* K AND V ARE TWO BUFFERS, not one [max_tok, 2*kv_dim] with K in its left half. Both
* halves are written by one projection and read by one kv_store, so fusing them is the
* obvious thing -- and it is wrong, because of the PER-HEAD NORM in between. `rmsnorm`
* takes one row pitch. K inside a fused row is `head_dim` apart within a token and
* `2*kv_dim` apart between tokens, and no single pitch is both; answering with the
* between-tokens stride normalises every eighth head against the wrong numbers. libr4d
* refuses that operand (libr4d/r4d_model.cpp, rows_pitch), and the drafter gives it rows
* that are what they claim to be. The trunk's attention block splits
* k and v for the same reason -- see rad_block_attn_gated.h. */
/* K and V are separate buffers because of the per-head k norm: `rmsnorm` takes one row
* pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but
* 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp,
* rows_pitch). Same reason as in rad_block_attn_gated.h. */
rad_buf ck = 0; /* [max_tok, kv_dim] ONE layer's K, reused across layers */
rad_buf cv = 0; /* [max_tok, kv_dim] ONE layer's V, reused across layers */
/* the query pass */
rad_buf x = 0; /* [qrows, n_embd] the drafter's residual stream */
rad_buf h = 0; /* [qrows, n_embd] normed input, o/down output, and the final norm */
rad_buf h2 = 0; /* [qrows, n_embd] the convolution's output -- it may not alias x */
rad_buf h2 = 0; /* [qrows, n_embd] the convolution's output; must not alias x */
rad_buf coef = 0; /* [qrows, coef_dim] */
rad_buf q = 0; /* [qrows, q_dim] */
rad_buf k = 0; /* [qrows, kv_dim] -- two buffers, and `ck` above says why */
rad_buf k = 0; /* [qrows, kv_dim] separate from v, see `ck` */
rad_buf v = 0; /* [qrows, kv_dim] */
rad_buf attn = 0; /* [qrows, q_dim] */
rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
rad_buf ffn = 0; /* [qrows, n_ff] */
/* THE FP8 TWINS OF THE FOUR ACTIVATIONS A LINEAR READS. `quant_act_fp8` writes them and
* the six `gemm_nt_q` linears read them; nothing else touches them, and the bf16 buffer
* beside each stays the thing the rest of the graph reads and writes.
*
* ONE PAIR PER ACTIVATION, NOT PER LINEAR. q and k|v both read h2, so quantising it once
* is the difference between two launches a layer and three -- the same argument rad_fp8.h
* makes for keeping QuantFP8 a separate struct from LinearFP8. h2 is quantised twice a
* layer all the same, because the convolution rewrites it between the attention half and
* the feed-forward half. */
/* FP8 codes and scales of the activations the linears read, written by `quant_act_fp8`
* and read only by the `gemm_nt_q` linears. One pair per activation, not per linear: q, k
* and v all read h2. h2 is still quantised twice a layer, because the convolution
* rewrites it between the attention and feed-forward halves. */
rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] e4m3 | [.., /128] f32 */
rad_buf cq = 0, cs = 0; /* [max_tok, n_embd] */
rad_buf h2q = 0, h2s = 0; /* [qrows, n_embd] */
rad_buf atq = 0, ats = 0; /* [qrows, q_dim] */
rad_buf ffq = 0, ffs = 0; /* [qrows, n_ff] */
/* the head and the selector, at one row per DRAFT POSITION (block - 1 a sequence) */
/* the head and the selector, one row per draft position (block - 1 per sequence) */
rad_buf sel_h = 0; /* [srows, n_embd] the gathered final hidden states */
rad_buf hp = 0; /* [srows, sel_rank] hidden_projection of them */
rad_buf dq = 0; /* [srows, n_embd] i8 the 2-bit head's quantised activation */
@@ -203,57 +159,45 @@ struct Dflash2 {
rad_buf dlog = 0; /* [srows, head_rows(g)] bf16 the coarse logits */
rad_buf cand = 0; /* [srows, sel_topk] i32 candidate token ids, global */
rad_buf unary = 0; /* [srows, sel_topk] f32 and their logits */
/* The vocab-parallel pair, declared only when head_sharded(g). Both are f32 (int32 id,
* float value) pairs: this rank's top-R, and the all-gathered world_size * R of them. */
/* Vocab-parallel pairs, declared only when head_sharded(g): (int32 id, f32 value) pairs
* stored as f32, this rank's top-R and the all-gathered world_size * R. */
rad_buf dpair = 0; /* [srows, sel_topk, 2] f32 */
rad_buf dgath = 0; /* [srows, world * sel_topk, 2] f32 */
rad_buf tokens = 0; /* [max_seqs, steps] i32 THE DRAFT -- the engine reads this by name */
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
};
/* WHETHER THE 2-BIT DRAFT HEAD IS VOCAB-SHARDED. The test itself is rad_arch.h's
* `vocab_head_sharded` -- shared, because the second block-diffusion drafter in this library
* asks it too and both the op and the buffer under it have to agree. These two names stay so
* that whoever declares Dflash2's buffers can ask the BLOCK rather than re-derive the rule.
*
* Sharding halves the widest read on the draft path -- 341 MiB of codes and scales at 248320
* rows when it is replicated -- at the price of one all_gather of R pairs a row. At 248320
* over two ranks the shard is 124160, which is 7760 whole 16-row blocks. */
/* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
* declares the buffers can ask the block. Sharding halves the draft path's widest read (341 MiB
* of codes and scales at 248320 rows) for one all_gather of R pairs a row. */
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
/* Rows of the draft head, and therefore the width of `dlog`, on THIS rank. */
/* Rows of the draft head on this rank, and so the width of `dlog`. */
static int64_t head_rows(const Geom& g) { return vocab_head_rows(g); }
Geom g{}; /* the DRAFTER's geometry, not the trunk's */
Geom g{}; /* the drafter's geometry, not the trunk's */
Config cfg{};
Wire w{};
int first_layer = 0; /* absolute, so the KV group's layer_slot lookup finds these five */
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
int64_t qrows = 0, crows = 0, srows = 0;
int64_t gated_rows = 0; /* the band op_gug was declared over; 0 when there is no fold */
rad_kvgroup kv = 0;
/* model-scope weights.
*
* THE SIX LINEARS ARE FP8 OR MXFP4 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares
* each as block fp8 or OCP-MXFP4, whichever the recipe made it -- and the reason is bytes: the
* drafter is read WHOLE on every decode step, which makes it one of the largest single items in
* the decode budget after the trunk's own GEMMs. On Qwen3.8-27B at depth 7, MXFP4 rounded to
* nearest accepts ~1% fewer tokens a step than fp8 and takes ~1.5 ms off a ~34 ms step.
* Nothing it computes can change an emitted token, because every draft is verified against the
* trunk exactly; the only thing quantising it can move is acceptance. */
* The linears are block fp8 or OCP-MXFP4 (rad_fp8.h: DenseFP8, per the recipe) although the
* checkpoint is bf16: the drafter is read whole every decode step. On Qwen3.8-27B at depth 7,
* MXFP4 accepts ~1% fewer tokens per step than fp8 and saves ~1.5 ms of a ~34 ms step.
* Quantisation can only change acceptance, since every draft is verified. */
DenseFP8 w_fc{};
rad_weight w_hnorm = 0, w_norm = 0;
rad_weight w_selp = 0, w_pred = 0, w_succ = 0;
rad_weight w_tok = 0; /* the TARGET's embedding table */
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the TARGET's lm_head */
rad_weight w_tok = 0; /* the target's embedding table */
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the target's lm_head */
/* per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
/* K AND V ARE TWO WEIGHTS, and the fp8 layout hook is why. One fused [2*kv_dim, n_embd]
* tensor issued a half at a time through wrow_slice would cost a launch and no bytes -- and a
* block-scaled weight cannot be used that way. The layout of an operand is a function of the
* OP's N, and this op's N is kv_dim because it computes one half; the hook would be handed a
* [2*kv_dim/128][K/128] plane for a [kv_dim, K] op and refuse it. Two weights make the op's N
* and the planes' rows the same number again, shard independently at kv_dim, and issue the
* same two launches. */
/* K and V are separate weights: a block-scaled operand's layout follows the op's N, so a fused
* [2*kv_dim, n_embd] weight issued one half at a time would hand the layout hook a
* [2*kv_dim/128][K/128] plane for a [kv_dim, K] op, which it refuses. */
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]{};
@@ -264,14 +208,14 @@ struct Dflash2 {
rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
/* THE ACTIVATION QUANTISERS, one per activation that feeds a linear. Weightless and shape-only,
* so one declaration each serves every layer -- the per-layer ops above are per-layer only
* because a weight's prefetch interval comes from the op that declares it. */
rad_op op_qsrc = 0, op_qc = 0; /* the context pass's two */
rad_op op_qh2 = 0, op_qat = 0, op_qff = 0; /* the query pass's three */
/* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration
* serves every layer; ops with weights are per layer because a weight's prefetch interval
* comes from the op that declares it. */
rad_op op_qsrc = 0, op_qc = 0; /* context pass */
rad_op op_qh2 = 0, op_qat = 0, op_qff = 0; /* query pass */
/* query-pass ops. The weightless ones are declared once and issued per layer: an op's declared
* read and write sets are what the buffer planner reads, and they are the same every layer. */
/* query-pass ops. Weightless ones are declared once and issued per layer; their read and write
* sets are the same every layer. */
rad_op op_embed = 0, op_embed_ar = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
rad_op op_acoef[MAX_LAYERS] = {}, op_fcoef[MAX_LAYERS] = {};
@@ -288,11 +232,11 @@ struct Dflash2 {
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
rad_op op_drerank = 0; /* the candidates rescored against the target's head */
/* THE TARGET'S lm_head, set by the plugin before declare when its plane is one logit_rerank
* reads (fp8 or int8 rows); 0 leaves the coarse head's own scores as the candidates'. */
/* The target's lm_head, set by the plugin before declare when logit_rerank can read it (fp8 or
* int8 rows); 0 keeps the coarse head's scores. */
rad_weight w_lm = 0;
/* How many candidates the coarse head proposes for the rerank: logit_rerank's and row_topk's
* ceiling. Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
/* Candidates the coarse head proposes for the rerank (logit_rerank's and row_topk's ceiling).
* Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
static constexpr int64_t kRerankR = 32;
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
rad_op op_hp = 0, op_sel = 0;
@@ -300,10 +244,10 @@ struct Dflash2 {
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_prefix,
const char* ck_lm, const Wire& wire);
/* The context pass, one row a committed token. `batch` carries those rows and the draft KV
* group's slot mapping; nothing about the query block is read. */
/* The context pass, one row per committed token; `batch` carries those rows and the draft KV
* group's slot mapping. */
void context(RadCtx* c, const RadBatch* batch) const;
/* The query pass and the selector, one call, `block` rows a sequence. */
/* The query pass and the selector, `block` rows per sequence. */
void step(RadCtx* c, const RadBatch* batch) const;
private:
@@ -360,26 +304,15 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
/* THE 2-BIT DRAFT HEAD. The same declaration the MTP head makes, for the same reasons, argued
* at length in rad_block_mtp_fp8.h: `dflash.draft_head.weight` is the target's lm_head under a
* name of its own, which the recipe quantises to the 2-bit grid (u2 codes, an f16 scale and a
* u8 zero a group of 128) -- one checkpoint tensor, two logical weights. The GEMM takes the
* codes as one operand and the scale and zero planes, interleaved by its relayout, as the
* other.
/* The 2-bit draft head, declared as the MTP head's is (rad_block_mtp_fp8.h):
* `dflash.draft_head.weight` is the target's lm_head under its own name, quantised by the
* recipe to u2 codes with an f16 scale and u8 zero per group of 128. One checkpoint tensor,
* two views: codes, and the scale|zero planes the GEMM's relayout interleaves.
*
* IT IS SHARDED, AND THE MERGE IS WHAT MAKES THAT SAFE. The draft path never goes through the
* sampler, so its argmax is a `row_topk` over one rank's plane -- and a sharded plane on its
* own would let each rank propose only from its own half, while the selector's codebooks are
* gathered by GLOBAL token id and would then see only the candidates that landed locally. The
* merge runs BEFORE the selector: each rank's top-R comes back as global ids, an all_gather
* moves R pairs a row, and `row_topk_merge` reduces them to the same global top-R an unsharded
* head would have found -- exactly, ties included (docs/OPS.md). Both ranks then hold the same
* candidate set and the codebooks are replicated, so everything downstream is unchanged.
*
* What it buys is the widest read on the draft path halved -- 341 MiB of codes and scales at
* the whole vocabulary -- and that much device memory given back per rank. What it costs is
* one all_gather of `world * R` pairs a row, which at R = 16 is 2 KiB: the link's latency and
* essentially no bytes. */
* When sharded, each rank's `row_topk` reports global ids, an all_gather moves R pairs a row,
* and `row_topk_merge` reduces them to exactly the unsharded global top-R, ties included
* (docs/OPS.md). This runs before the selector, so every rank holds the same candidates for
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16). */
enum { DF_W2_GROUP = 128 };
const bool dh_shard = head_sharded(g);
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
@@ -418,12 +351,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
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, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
/* K, V AND Q ARE THREE WEIGHTS, which is not the fusion every other attention block in
* this library makes. Q is separate because of the context pass: it needs k and v over the
* trunk's projected hidden state and has no use for q at all, so a fused qkv would make it
* compute and discard a q_dim-wide GEMM per layer per context token. K and V are separate
* because a block-scaled weight's layout follows its op's N, and both passes take one of
* them at a time -- see the note beside the declarations. */
/* q, k and v are separate weights. The context pass needs only k and v, so a fused qkv
* would compute and discard q for every context token. k and v: see w_q's declaration. */
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, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
@@ -461,16 +390,12 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
}
/* NON-CAUSAL, WINDOWED. The block is denoised as a whole, so every query row sees every other
* row of its own block as well as the context -- `causal` 0 is the drafter's own config
* (`is_causal: false`) and not a default. The window is the checkpoint's `sliding_window`, and
* it is the reason the context pass has a bounded amount of real work in it.
/* Non-causal and windowed: the block is denoised as a whole, so each query row sees its whole
* block plus the context (`causal` comes from the config's `is_causal: false`). The window is
* the checkpoint's `sliding_window`.
*
* DECLARED FIRST, before either kv_store, even though it runs long after both. `block_size` is
* RAD_DERIVED -- the KV block is a property of the resolved attention kernel and not a number
* anyone gets to choose -- so it is omitted here and READ BACK with rad_kv_block_size() for the
* two stores, which need it as a parameter. Ask before the attention op is declared and the
* answer is zero. */
* Declared before both kv_stores, which read the resolved `block_size` back with
* rad_kv_block_size(); before this declaration it returns zero. */
op_attn = 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", cfg.causal),
@@ -482,37 +407,28 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.q}, {w.attn});
/* ---------------------------------------------------------------- the context pass */
/* EVERY LINEAR HERE IS `fp8a8` -- or `mxfp4a8` where the recipe made the drafter 4-bit; DenseFP8
* reads which off the container and declares the GEMM (`gemm()`), and either one reads the
* same E4M3 pair -- and every activation that feeds one gets a `quant_act_fp8` in
* front of it. The fp8 weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
* why), and there is no `fp8a16` band anywhere in this block: that kernel is M <= 1, and
* neither pass here ever runs at one row -- a context pass is a committed chunk and a query
* pass is `block` rows by construction.
/* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
* container and declares the GEMM), reading an E4M3 activation pair from a `quant_act_fp8`.
* There is no `fp8a16` band: that kernel is M <= 1, and neither pass runs at one row.
*
* AND NOTHING HERE IS ROW-SLICED. The fp8a8 pair covers every M (narrow to 16, tiled above),
* so a context pass over a 2048-token prefill chunk is one launch a layer rather than one per
* 64 rows.
*
* The convolutions' coefficient projections and the selector's hidden projection are still
* bf16, and they are not sliced either: libr4d's bf16 GEMM row is C_LE("M", 65536), and all
* three of these carry K = n_embd, a multiple of 16, so the wide row serves them whole. */
* Nothing is row-sliced: the fp8a8 pair covers every M, and libr4d's bf16 GEMM row (used by
* the conv coefficient projections and the selector's hidden projection, K = n_embd) is
* C_LE("M", 65536). */
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});
/* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
* which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
* written. */
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", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
/* ONE QUANTISE FOR ALL FIVE LAYERS. `c` is the normed projection of the trunk's taps and every
* layer's k|v reads that same buffer, so this is one launch a context pass and not five. */
/* One quantise for all layers: every layer's k and v read the same `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)),
@@ -520,9 +436,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* TWO OPS OF THE SAME SHAPE, one per weight. An op's declared weight list is what gives a
* weight its prefetch interval and its residency class, so two weights want two ops even
* where one would issue both. */
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
* and residency class. */
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",
@@ -532,17 +447,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ck});
}
/* K-ONLY ROPE. `rope` rotates the first n_head + n_head_kv heads of its operand and leaves the
* V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
* n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
* serves every layer. */
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});
/* A whole-head NeoX rope over a q-only or k-only tensor of `heads` heads: `rope` rotates the
* first n_head + n_head_kv heads, so n_head_kv is 0. Weightless, so one op serves every layer. */
auto rope = [&](int64_t rows, int64_t heads, rad_buf x) {
return rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{x}, {x});
};
op_crope = rope(crows, g.n_head_kv, 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),
@@ -558,9 +474,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
/* The trunk's embedding is vocab-sharded, so this gather is partial and takes the same exact
* reduction. It is on the DRAFT path, which runs once a step ahead of the trunk: a second
* small collective. */
/* The trunk's embedding is vocab-sharded, so the lookup is partial and needs an exact
* all-reduce. */
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -568,10 +483,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{w.x}, {w.x});
/* The query pass's three quantisers, declared once and issued per layer -- weightless ops with
* the same shape every layer, exactly like the ropes and the residual add below. h2 is
* quantised TWICE a layer because the convolution rewrites it between the two halves; attn and
* ffn once each. */
/* The query pass's quantisers, issued per layer: h2 twice (the convolution rewrites it between
* the halves), attn and ffn once each. */
op_qh2 = 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)),
@@ -629,40 +542,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_fcp[i])),
{w.h}, {w.coef});
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
/* THE SAME FOLD THE TRUNK'S MLP HAS, over the same weights and into the same activation;
* rad_block_mlp_fp8.h declares it beside the pair for the same reason. Unfused, a layer
* runs gate_up -> silu_mul -> quant, which is two extra launches and two extra passes over
* the [T, n_ff] product. The gated kernel is also the faster of the two on the SAME shape,
* because the fold saves the bf16 round trip.
*
* NOT RAD_ARCH_TRY: a kernel set without the row is the ordinary case and the pair below
* still runs. `gated_rows` is the band it was declared over and the issue site checks it,
* because M > 64 is a refusal in the kernel and not a slower path. */
{
const int64_t hi = qrows < 64 ? qrows : 64;
if (hi > 0 && !w_gu[i].mx) { /* the fold is an fp8a8 tile; an MXFP4 gate_up takes the pair */
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.h2q, w.h2s}, {w.ffq, w.ffs});
if (op_gug[i]) gated_rows = hi;
}
}
/* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
* fp8a8 tile, so an MXFP4 gate_up takes the pair. */
if (!w_gu[i].mx)
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
{w.h2q, w.h2s}, {w.ffq, w.ffs}, &gated_rows);
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
}
/* The convolutions. `block_size` is the QUERY BLOCK -- the mask that kills the shifted tap at
* the first row of each block is what keeps one sequence's block from convolving with the
* previous sequence's, so it is the batch's per-sequence row count and not a tuning number.
/* The convolutions. `block_size` is the query block: the shifted tap is masked at each block's
* first row so one sequence's block does not convolve with the previous one's.
*
* ONE OP PER (LAYER, CONVOLUTION) even though every one of them is the same shape, because the
* base kernel is a WEIGHT and an op's declared weight list is what gives a weight its prefetch
* interval and its residency class. A single shared declaration would leave ten weights that
* no op admits to using. Each is issued twice -- `prepare` and `finish` -- against the two
* halves of one [2, taps, n_embd] tensor. */
* One op per (layer, convolution) because the base kernel is a weight (see op_ck). Each op is
* issued twice, prepare and finish, against the two halves of its [2, taps, n_embd] tensor. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_aconv[i] = rw(b, RAD_OP(b, "dflash_conv",
@@ -680,20 +572,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_fcb[i])),
{w.h, w.coef}, {w.h2});
}
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});
/* The attention output is written and read inside every layer, between the two halves of the
* attention convolution, but its two ops (op_attn, op_qat) are declared once ahead of the
* layers. Planned from those alone, its range would end before the coefficients' begins and
* the plan could lay one over the other. Read by the last convolution as well, it is live
* wherever the coefficients are. */
if (rad_op_reads(b, op_fconv[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
op_qrope = rope(qrows, g.n_head, w.q);
op_krope = rope(qrows, g.n_head_kv, 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),
@@ -728,15 +614,12 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
/* ---------------------------------------------------------------- the head and the selector
*
* THE MASK ROWS, offsets 1..block-1 of each sequence's block. Offset 0 is the ANCHOR -- the
* token the target has already chosen -- and its row predicts nothing: it is there so the mask
* rows have something to attend to. Each mask row predicts the token at ITS OWN position, so
* the head runs over `steps` rows a sequence and not `block`. Getting this off by one is the
* kind of mistake that costs nothing visible: the drafts are simply wrong, acceptance
* collapses, and the model's own output stays exactly correct.
* The head runs over the mask rows, offsets 1..block-1 of each block: `steps` rows per
* sequence, each predicting the token at its own position. The anchor row predicts nothing.
* An off-by-one here only shows as collapsed acceptance; the output stays correct.
*
* The gather is what makes those rows contiguous, and it is also what fixes the head's row
* numbering at s * steps + l -- which is the numbering `dflash_select` reads. */
* The gather makes those rows contiguous, numbered s * steps + l as `dflash_select` reads
* them. */
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)),
@@ -753,10 +636,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
/* Sharded, the top-R runs over THIS RANK'S plane and reports global ids, and it also writes
* the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
* replicated, so that graph is the one it always was -- an optional parameter present with
* the value 0 is not the same declaration as an absent one. */
/* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
* with value 0 is a different declaration from an absent one. */
const bool rerank = w_lm && (dh_shard || g.world <= 1); /* see op_drerank below */
if (!rerank) top_w = cfg.sel_topk;
op_dtopk = dh_shard
@@ -771,17 +653,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("R", top_w), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary});
/* THE CANDIDATES ARE RESCORED EXACTLY when the target's head can be read row by row. The
* coarse head proposes its top kRerankR, `logit_rerank` scores those against the target's own
* fp8 head and re-sorts them, and the selector reads the best sel_topk of that order -- the
* candidate set and the unary logits the drafter was trained against, at kRerankR rows of the
* weight a draft row instead of a second, finer copy of the head. On Qwen3.8-27B the 2-bit
* head's own top-1 matches the exact head's on 76% of draft rows and the rescored one on all of
* them; served at depth 7 that is the 4-bit head's speed at half its bytes (330 MiB).
/* Exact rescoring when the target's head can be read row by row: the coarse head proposes its
* top kRerankR, `logit_rerank` scores them against the target's head and re-sorts, and the
* selector reads the best sel_topk, giving the candidates and unary logits the drafter was
* trained against. On Qwen3.8-27B the 2-bit head's top-1 matches the exact head on 76% of
* draft rows, the rescored one on all; this matches the 4-bit head's speed at half its bytes.
*
* Sharded, each rank rescores only ids it owns (row_topk reports this rank's slice), and the
* gather and merge below then rank exact values. A replicated draft head above one rank
* proposes ids another rank owns, so it keeps its own scores. */
* Sharded, each rank rescores only ids it owns and the merge below ranks exact values. A
* replicated head above one rank proposes ids other ranks own, so it keeps its own scores. */
if (rerank) {
op_drerank = RAD_OP(b, "logit_rerank",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
@@ -795,9 +674,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
}
if (dh_shard) {
/* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
* `row_topk_merge` reads one row at one row stride, the same reason the sampler's own
* candidate gather carries `row`. */
/* Row-interleaved, so one draft position's pairs from every rank are adjacent, as
* `row_topk_merge` reads them. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * top_w * 2),
@@ -817,8 +695,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_selp)),
{w.sel_h}, {w.hp});
/* `anchor_stride` is `block`, because the operand is the step's own token_ids: a draft pass
* carries `block` ids a sequence and the anchor is the first of them. */
/* `anchor_stride` is `block`: the operand is the step's token_ids, `block` per sequence with
* the anchor first. */
op_sel = rw(b, RAD_OP(b, "dflash_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
@@ -838,10 +716,7 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
/* NOT SLICED. A context pass is one row a committed token, so it is as wide as the prefill
* chunk; the fp8a8 pair covers every M, so each op here is one launch and not one per 64
* rows. */
/* As wide as the prefill chunk, one launch per op (the fp8a8 pair covers every M). */
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());
@@ -872,7 +747,6 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
const int64_t NG = cfg.ng(g.n_embd);
const int64_t half = cfg.taps * NG; /* prepare's coefficients, then finish's */
@@ -913,10 +787,9 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
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());
/* BEFORE the closing convolution, not after. The convolution is linear in its input and
* its coefficients come from the replicated pre-attention norm, so either order is the
* same arithmetic -- and reducing first keeps the residual stream's contract ("what the
* ranks add to x has already been agreed") in one place. */
/* Reduce before the closing convolution. It is linear with coefficients from the
* replicated norm, so either order gives the same result; reducing first keeps x's
* update agreed across ranks. */
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
@@ -948,27 +821,20 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
/* The rows that predict something: `steps` of every sequence's `block`. The scheduler names
* them through out_ids, the same field the trunk's own logits gather reads. */
/* The predicting rows, `steps` per sequence, named by the scheduler through out_ids. */
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));
/* `dsum` is quant_act_i8's GROUP-major plane, [n_embd/group][ceil(M/16)*16], so it is passed
* whole: there is no row slice of it that means anything. */
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
* whole. */
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
/* The trailing operand is mxfp4's optional reference and is absent here; an absent optional
* operand is a null tensor in a full-length list, not a shorter list. */
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
* so an absent optional one is RAD_NONE, not a shorter list. */
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE);
/* RAD_NONE is the `pairs` slot: operands are POSITIONAL, so an optional one that the graph
* does not use is still passed, absent. Omitting it is a miscount and the engine refuses the
* op rather than guessing which of the four was left out.
*
* SHARDED, the top-R over this rank's plane is not the answer -- it is this rank's CANDIDATES,
* and `cand`/`unary` are overwritten by the merge two ops below. Writing them here anyway
* costs nothing (they are the same R entries the pairs plane holds) and keeps one issue site
* for both paths. */
/* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
* the merge overwrites `cand`/`unary`. */
if (op_dmerge) {
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
brows(w.dpair, S));