Merge main into laya-arch-plugin

This commit is contained in:
Brandon Bertelsen committed 2026-10-29 13:45:18 -04:00
commit ec243c2a7d
189 files changed
+11212 -7060

No files matched your search

+5 -3
View File
@@ -1410,16 +1410,18 @@ inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int6
}
/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them,
* `mode` otherwise. */
* `mode` otherwise. `op` names the row: "rope" (every caller), or "rope_rows" for a model that
* wants the per-(token, pair) angles form at prefill row counts. */
inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim,
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) {
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode,
const char* op = "rope") {
const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", g.rope_mc ? g.rope_mode : mode),
RAD_INT("rotary_dim", rot), RAD_STR("sections", g.rope_sections) };
const int n = (int)(sizeof ps / sizeof ps[0]) - (g.rope_mc ? 0 : 1);
return decl_rotary(b, g, "rope", ps, n, nullptr, 0);
return decl_rotary(b, g, op, ps, n, nullptr, 0);
}
/* How many of this step's sequences are decode rows, and where their tokens end.
+89 -11
View File
@@ -123,6 +123,16 @@ struct Dflash2 {
int64_t group = 16;
int64_t sel_rank = 256; /* the codebooks' width */
int64_t sel_topk = 16; /* candidates kept per position */
/* Propose a tree of `steps()` nodes instead of the selector's one path (`dflash_tree`,
* rad_drafter_tree): best-first over the candidate lattice by path probability, each
* edge's probability the softmax of its scores over the K candidates divided by
* `tree_temp`. False: the greedy walk. */
bool tree = false;
double tree_temp = 1.0;
/* A tree's draft nodes a step, 0 for `steps()`. More than the block drafts is a wider tree
* over the same lattice (its depth is still at most `steps()`); the proposal buffers, the
* drafter's declared depth and the verify are this wide. */
int64_t tree_nodes = 0;
int64_t window = 0; /* sliding attention width, 0 for none */
int causal = 0;
/* The target's embedding scale, applied to the query block as the drafter was trained
@@ -132,15 +142,18 @@ struct Dflash2 {
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
int64_t prefetch = 0;
/* Also declare the short block's query pass (kShortBlock rows) for --draft-short-from; an
* architecture that does not call rad_drafter_short_block leaves it off and its graph as
* it was. */
/* Also declare the short block's query pass (kShortBlock rows, or `short_rows`) for
* --draft-short-from; an architecture that does not call rad_drafter_short_block leaves
* it off and its graph as it was. A tree's selector at that block grows a tree of its own
* over the shorter pass, `short_rows - 1` nodes or fewer. */
int short_block = 0;
/* --draft-coupling: the temperature of the draft law Q the coupled walk samples from
* (dflash_couple_propose's `q_temp`). Any value keeps the output exact; it only moves
* acceptance, sum min(P, Q). */
double q_temp = 1.0;
int64_t short_rows = 0;
int64_t steps() const { return block - 1; }
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
/* 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. */
@@ -198,6 +211,8 @@ struct Dflash2 {
/* --draft-coupling: [max_seqs, DRAW_WORDS] draws the engine stages, and [steps, max_seqs,
* STATE_WORDS] states it reads back (abi/rad_spechub.h). Both or neither. */
rad_buf couple_draws = 0, couple_state = 0;
/* [max_seqs, steps] i32 a tree's parents (Config::tree, rad_drafter_tree); 0 otherwise */
rad_buf parents = 0;
};
/* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
@@ -277,6 +292,7 @@ struct Dflash2 {
* and the selector strides by it, so each has an op of its own; every other op is per row. */
rad_op op_aconv_lo[MAX_LAYERS] = {}, op_fconv_lo[MAX_LAYERS] = {}, op_sel_lo = 0;
int64_t block_lo = 0;
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
@@ -718,7 +734,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* 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. */
block_lo = cfg.short_block && cfg.block > kShortBlock ? kShortBlock : 0;
{
const int64_t rows = cfg.short_rows > 0 ? cfg.short_rows : kShortBlock;
block_lo = cfg.short_block && rows >= 2 && cfg.block > rows ? rows : 0;
}
for (int64_t l = 0; block_lo && l < g.n_layer; ++l) {
const int i = (int)l;
op_aconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
@@ -943,15 +962,65 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_selp)),
{w.sel_h}, {w.hp});
/* `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",
* the anchor first.
*
* A tree (Config::tree): `dflash_tree` grows `steps` nodes best-first over the same lattice
* and the same edge scores, writing each node's parent beside its token. Where no library
* serves it the block falls back to the chain and says so; the caller reads `cfg.tree` after
* declare to decide whether to tell the core (rad_drafter_tree). --draft-coupling samples one
* path per sequence, so a coupled drafter proposes the chain. */
if (cfg.tree && (w.couple_draws || w.couple_state)) {
rad_note(b, "DFlash2: --draft-coupling samples a chain; the drafter proposes no tree");
cfg.tree = false;
}
if (cfg.tree) {
op_sel = RAD_OP(b, "dflash_tree",
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),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block),
RAD_INT("nodes", cfg.nodes()), RAD_F64("temp", cfg.tree_temp),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pred, w_succ));
if (op_sel && rad_op_resolved(b, op_sel)) {
rw(b, op_sel, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
} else {
rad_note(b, "DFlash2: no library serves dflash_tree here; the drafter proposes its "
"selector's chain");
cfg.tree = false;
op_sel = 0;
}
}
if (!cfg.tree) 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),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pred, w_succ)),
{w.cand, w.unary, w.hp}, {w.tokens});
if (block_lo)
if (block_lo && cfg.tree) {
/* A tree over the short block's own lattice (the pass attends across its block, so it is
* not the full pass's prefix): as many nodes as the block drafts, or the tree's own count
* where that is fewer. */
sel_lo_nodes = std::min<int64_t>(cfg.nodes(), block_lo - 1);
op_sel_lo = RAD_OP(b, "dflash_tree",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", block_lo),
RAD_INT("nodes", sel_lo_nodes), RAD_F64("temp", cfg.tree_temp),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pred, w_succ));
if (op_sel_lo && rad_op_resolved(b, op_sel_lo)) {
rw(b, op_sel_lo, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
} else {
rad_note(b, "DFlash2: no library serves dflash_tree at the short block; the tree keeps "
"its own block under load");
op_sel_lo = 0;
block_lo = 0;
sel_lo_nodes = 0;
}
} else if (block_lo)
op_sel_lo = rw(b, RAD_OP(b, "dflash_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
@@ -1197,10 +1266,19 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
}
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
brows(w.tokens, batch->n_seq));
/* A tree's outputs as views exactly its nodes wide, at the buffers' row pitch: at the short
* block it grows fewer nodes than a row holds, and the proposals are read at the full pitch. */
const int64_t nn = lo ? sel_lo_nodes : cfg.nodes();
if (cfg.tree)
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
bcol(w.tokens, 0, nn, batch->n_seq), bcol(w.parents, 0, nn, batch->n_seq));
else
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
brows(w.tokens, batch->n_seq));
if (op_couple)
RAD_ISSUE_N(c, lo ? op_couple_lo : op_couple, batch->n_seq,
bcol(w.cand, 0, cfg.sel_topk, S), bcol(w.unary, 0, cfg.sel_topk, S),
+13
View File
@@ -127,6 +127,11 @@ struct GdnFP8 {
* the widest decode window the fold serves. */
rad_op op_cr = 0;
int64_t cr_rows = 0;
/* Set by the architecture after declare: a `prefetch` of the out-projection's leading bytes
* (decl_prefetch, rad_arch.h), issued on the second lane beside the decode recurrent update on
* steps of up to pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
rad_op op_pf_out = 0;
int64_t pf_out_rows = 0, pf_out_seqs = 0;
rad_op op_ar = 0, op_add = 0;
/* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */
bool ar_out = false;
@@ -481,6 +486,14 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
const int64_t PT = T - DT;
const int64_t in_w = conv_dim + v_dim; /* w.in.x's declared row width */
/* The recurrent update at decode heights runs one workgroup per (sequence, head) and leaves the
* card's memory mostly idle, so the out-projection's weight is read into the on-die cache
* beside it, on the second lane behind a join from lane 0 (as prefetch_beside). */
if (op_pf_out && D > 0 && D <= pf_out_seqs && P == 0 && T <= pf_out_rows) {
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
rad_lane(c, 0);
}
if (D > 0 && op_cr && qd <= cr_rows) {
RAD_ISSUE_N(c, op_cr, qd,
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
+13 -9
View File
@@ -52,9 +52,9 @@ struct MlpFP8 {
rad_op op_ar = 0, op_add = 0;
/* gate_up with the gate and quantiser in its epilogue, so the [M, 2*n_ff] bf16 product is
* never written (unfused, the extra launch and second pass are a sizeable decode cost).
* Declared beside the pair, not instead of it: the fold is the narrow tile's epilogue and
* serves M <= 64, so prefill chunks take the pair. Byte-identical, as r4d_selftest and
* ref_test check. */
* Declared beside the pair, not instead of it: the narrow fold serves M <= 64, so prefill
* chunks take the pair -- unless the model asked for `wide_fold`, whose row serves every M.
* Byte-identical, as r4d_selftest and ref_test check. */
rad_op op_gated = 0;
int64_t gated_rows = 0;
/* The next block absorbs this block's closing all-reduce, so this one must not issue it.
@@ -67,9 +67,13 @@ struct MlpFP8 {
/* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add
* (false for the first block of a chain). `add_out`: issue the trailing add here. See
* rad_fp8.h. */
/* `wide_fold`: declare the gated fold over the whole prompt (gemm_nt_q_gated_wide, whose row
* serves every M) rather than the narrow row's 64-row band. Set by a model that runs whole
* prompts through the fold; every other caller keeps the band and the pair past it. */
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0);
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0,
bool wide_fold = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
@@ -93,7 +97,7 @@ struct MlpFP8 {
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold, bool add_out,
int ar_in, bool ar_out_, double swiglu_limit) {
int ar_in, bool ar_out_, double swiglu_limit, bool wide_fold) {
g = geom; w = wire; layer = l;
ar_out = ar_out_;
@@ -120,9 +124,9 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
swiglu_limit));
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
* MXFP4 at one to eight rows. Other gate_up encodings (M2XFP4 included), and a clamped
* (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would take it, which
* would pin the layer's weights to the host. */
* MXFP4 at one to 16 rows (eight where K is short). Other gate_up encodings (M2XFP4 included),
* and a clamped (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would
* take it, which would pin the layer's weights to the host. */
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
!gate_up.i8)
@@ -131,7 +135,7 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
gq_ffn.want_x
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
&gated_rows);
&gated_rows, wide_fold);
else if (fold_ok && gate_up.mx && !gate_up.paro)
op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
gate_up.wref, { w.h.q, w.h.s },
+3 -3
View File
@@ -1419,9 +1419,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
if (separate_fp32_combine) {
/* BF16 add widens both inputs to FP32, adds, then rounds once to BF16: exactly the
* former cast + cast + F32 add + cast chain. Keep the routed gather's BF16 rounding
* and the separate TP reductions; a local gather cannot fold those reductions. */
/* BF16 add widens both inputs to FP32, adds, then rounds once to BF16: the same bytes as
* cast + cast + F32 add + cast. The routed gather's BF16 rounding and the separate TP
* reductions stay; a local gather cannot fold those reductions. */
op_combine = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", "bf16")),
+2 -1
View File
@@ -178,7 +178,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
/* E4M3 with one scale for all 320 million rows (Qwen3.8-Flash-Next-FP8's choice; E4M3 has its
* own exponent, a row's dynamic range is 2.3x, and the scale sits on a three-octave plateau).
* One stored weight, `fp8_e4m3*bf16[*x*]`: codes plus a one-element scale plane, made by the
* recipe (data/recipes/qwen4exp-w4.recipe); the gather takes them as two operands. The name map
* recipe (data/recipes/qwen4exp-w4.recipe) or read as that release ships it (its shards under
* one `weight_scale`); the gather takes them as two operands. The name map
* joins the shards along rows and is declared first, since the encoding is looked up through
* it. RAD_ACCESS_VOCAB: it is a vocabulary table, just not the token one. */
const char* tn = nm.f("blk.%d.ple_ngram.weight", layer);
+38 -18
View File
@@ -768,6 +768,11 @@ struct LinearFP8 {
/* probe() found an int8 weight; lets a model learn its trunk's format from one linear before
* declaring activation buffers (ActFP8::declare_qs's `i8`). */
bool probed_i8 = false;
/* Whether this linear's block-fp8 GEMM takes the short-prompt split rule
* (`gemm_nt_q_short`, narrow_ksplit's `short_unsplit`): at N <= 512, K <= 5120 and 41..64 rows
* the split's per-slice floors dominate, so the row runs unsplit. Opt-in, so every other
* caller keeps the split and its bits. Set before declare(). */
bool short_split = false;
/* Whether this linear reads the input's bf16 plane, known from probe() before the producer is
* declared. A producer writes the bf16 plane only when asked, so the block must ask for it when
* this is set; otherwise the linear reads unwritten arena bytes. */
@@ -1509,7 +1514,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
* caller with a tighter bound (the lm_head, over sampled rows only) passes `max_rows`, so the
* narrow kernel's split-K scratch is not sized for max_tok. */
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
op = rw(b, RAD_OP(b, "gemm_nt_q",
op = rw(b, RAD_OP(b, short_split && !f32_scale ? "gemm_nt_q_short" : "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", f32_scale?"fp8a8f32":"fp8a8")),
RAD_WEIGHTS(w, ws)),
@@ -1724,14 +1729,16 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
/* gate_up, silu_mul and the E4M3 quantiser in one GEMM epilogue (`gemm_nt_q_gated`, an fp8a8
* tile over a block-fp8 [2n, K] weight), declared for M up to min(rows, 64): the kernel refuses M
* past that band. Optional: when it does not resolve the caller's unfused ops run, and the issue
* past that band, unless the caller asks for the wide row (`wide`), whose gated prefill tile
* serves every M. Optional: when it does not resolve the caller's unfused ops run, and the issue
* site checks `*gated_rows`, set to the band only when the op exists. */
inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
rad_weight ws, std::initializer_list<rad_buf> reads,
std::initializer_list<rad_buf> writes, int64_t* gated_rows) {
const int64_t hi = rows < 64 ? rows : 64;
std::initializer_list<rad_buf> writes, int64_t* gated_rows,
bool wide = false) {
const int64_t hi = wide ? rows : (rows < 64 ? rows : 64);
if (hi <= 0) return 0;
const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated",
const rad_op op = rw(b, RAD_OP(b, wide ? "gemm_nt_q_gated_wide" : "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8"),
RAD_STR("act", "silu")),
@@ -1742,24 +1749,37 @@ inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K,
}
/* The same fold over an OCP-MXFP4 [2n, K] gate_up weight (`gemm_nt_q_gated_mx`: codes, the E8M0
* plane and that plane again as the per-row reference), up to min(rows, 8) rows, the band of
* libr4d's one-to-eight-row GEMM. Declared only when a loaded library declares the op (libref
* does not), so a CPU-only engine takes the pair. */
* plane and that plane again as the per-row reference), declared for M up to min(rows, 16):
* libr4d's gated_gemv serves 1..8 rows and gated_gemv_wide 9..64, each byte-identical to its band's
* GEMM row (gemv, gemv_wide) followed by gated_quant_fp8. 16, not the wide row's 64: Qwen3.8-27B
* at TP2 on 2x R9700 (spec 7, ms a decode step, three interleaved rounds against the 1..8 band)
* gains at 16 rows (two sequences: 1k 20.96 -> 20.78, 16k 21.96 -> 21.70) but loses at 32 (four
* sequences at 1k 23.97 -> 24.10, eight in the short block 24.99 -> 25.14), and 64 lost more
* (16k x16 +2.1 %). The wide row refuses a short K (decode_shortk's corner), so where 1..16 does
* not resolve the band drops to 1..8 rather than lose the fold. Optional like decl_gated_fold, and
* asked for only when a loaded library declares the op: libref does not, so a CPU-only engine takes
* the pair without ever naming it. */
inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
rad_weight ws, rad_weight wref,
std::initializer_list<rad_buf> reads,
std::initializer_list<rad_buf> writes, int64_t* gated_rows) {
const int64_t hi = rows < 8 ? rows : 8;
if (hi <= 0 || N % 256 || K % RAD_FP8_BLOCK) return 0;
if (rows <= 0 || N % 256 || K % RAD_FP8_BLOCK) return 0;
if (!rad_op_declared(b, "gemm_nt_q_gated_mx")) return 0;
const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"),
RAD_STR("act", "silu")),
RAD_WEIGHTS(w, ws, wref)),
reads, writes);
if (op) *gated_rows = hi;
return op;
for (const int64_t band : { (int64_t)16, (int64_t)8 }) {
const int64_t hi = rows < band ? rows : band;
const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_MX_GROUP),
RAD_STR("dtype", "mxfp4a8"), RAD_STR("act", "silu")),
RAD_WEIGHTS(w, ws, wref)),
reads, writes);
if (op) {
*gated_rows = hi;
return op;
}
if (hi <= 8) break;
}
return 0;
}
/* ================================================== a calibration tap */
+4
View File
@@ -188,6 +188,10 @@ inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
out->draft_depth = (int)(bs - 1);
out->draft_depth_fixed = 1;
out->chain_pays = 1;
/* Its proposals verified as a tree of the same node count (dflash_tree, rad_drafter_tree): on
* 4x R9700 +7% single-stream decode and +6-9% aggregate at 1-16 users over the selector's
* chain (BetterBench, thinking off; on two cards +4% and +6-12%). */
out->tree_pays = 1;
return true;
}
+10 -12
View File
@@ -831,12 +831,10 @@ struct G3Junction {
/* The tallest step that takes the fp8 junction's lossy twin (G3JunctionFP8::op_ar6); a taller one
* keeps the standalone lossy all-reduce, unfused. The fused kernel gives each block one row, so past
* a few sequences the standalone all-reduce, spread over more blocks, wins despite its extra
* launches. TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700, --tp-wire wht6, production's
* flags (--draft-short-from 8), greedy, aggregate tok/s, two rounds, limit never / 16 / 24 / any:
* 2 streams (16 rows) 350.7 346.2 / 371.8 367.7 / 370.4 367.0 / 357.7 356.0; 3 (24 rows) 455.8
* 451.2 / 455.1 454.2 / 462.8 460.6 / 437.3 436.8; 4 (32 rows) 553.7 553.6 / 557.9 554.2 / 553.9
* 560.2 / 521.0 523.0; 8 (32 rows, the short block) 717.4 718.0 / 717.2 720.5 / 716.7 720.8 /
* 662.4 661.9. One stream's 8 rows go out exact under the default --tp-wire-min-kb (op_ar). */
* launches. TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700 (--tp-wire wht6,
* --draft-short-from 8, greedy): fusing raises aggregate throughput by 1-6% up to 24 rows and
* lowers it by 6-8% at 32. One stream's 8 rows go out exact under the default --tp-wire-min-kb
* (op_ar). */
constexpr int64_t kAr6MaxRows = 24;
/* ---- the MXFP4 trunk's junction (libr4d `rmsnorm_quant_fp8`): the add of the branch `x` into
@@ -848,10 +846,10 @@ struct G3JunctionFP8 {
rad_op op = 0;
/* At two ranks: the branch's all-reduce and post-norm folded in front
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. `op_ar` sends
* the exact wire, taken by the steps whose message goes out exact (ar_wire_is_exact: a decode
* step of a few rows, under --tp-wire-min-kb); `op_ar6` the rotated 6-bit one, declared under a
* lossy --tp-wire and taken by the steps above that up to kAr6MaxRows, byte-identical to the
* standalone lossy all-reduce, rmsnorm and rmsnorm_quant_fp8 it replaces. */
* the exact wire, for the steps whose message goes out exact (ar_wire_is_exact: a decode step
* of a few rows, under --tp-wire-min-kb). `op_ar6` sends the rotated 6-bit one: declared under
* a lossy --tp-wire, it takes the steps above that up to kAr6MaxRows and is byte-identical to
* the standalone lossy all-reduce, rmsnorm and rmsnorm_quant_fp8 it replaces. */
rad_op op_ar = 0, op_ar6 = 0;
Geom gm{};
rad_buf x = 0, res = 0, q = 0, s = 0;
@@ -883,8 +881,8 @@ struct G3JunctionFP8 {
const rad_buf wa[4] = { x, q, s, res };
rad_op_reads (b, op_ar, rd, 2);
rad_op_writes(b, op_ar, wa, 4);
/* The lossy twin where that wire is reachable and the row is whole 64-element
* groups (the kernel pads a partial last 512-element chunk). */
/* The lossy twin, under a lossy wire and for a row of whole 64-element groups
* (the kernel pads a partial last 512-element chunk). */
if (!g.wire_exact && n % 64 == 0) {
const RadParam p6[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
+127 -21
View File
@@ -423,6 +423,12 @@ struct Gemma4Attn {
* the copies of k and v too, ahead of the unfused prologue, which reads them dense. */
rad_op op_attn_row = 0, op_attn_dec = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0;
int64_t dec_hi = 0;
/* Tree verification (rad_drafter_tree): attention that honours RadBatch::spec_parent over a
* step's decode rows, reading q in the row (attn_paged_qrow_tree) or dense (attn_paged_tree,
* after op_tree_lift copies it out). Declared only when `tree` is set before declare; 0 where
* no library serves it, which the model reads as "no trees". */
bool tree = false;
rad_op op_attn_tree = 0, op_tree_lift = 0;
/* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see
* "Prefetch beside the reductions") */
rad_op op_pf = 0;
@@ -697,6 +703,20 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
}
}
/* The tree form over the decode rows: a verify block of 1 + n_spec rows a sequence, so the
* split-KV band (q_len * gqa <= 64) covers it at every class here. In the row where the
* prologue leaves q there, else dense after a copy. */
if (tree) {
const int64_t thi = std::min<int64_t>(
g.max_tok, std::max<int64_t>({ (int64_t)1, 64 / cls.gqa(), (int64_t)g.max_spec + 1 }));
if (fused && op_qnr && rad_op_declared(b, "attn_paged_qrow_tree"))
op_attn_tree = attn("attn_paged_qrow_tree", {w.qkv}, thi);
if (!op_attn_tree && rad_op_declared(b, "attn_paged_tree")) {
op_attn_tree = attn("attn_paged_tree", {w.q}, thi);
if (op_attn_tree && fused && op_qnr) op_tree_lift = lift(qd, w.q);
}
}
/* With the cache store folded into the prologue where a library serves it
* (qkv_norm_rope_kv_store: the same prologue, then kv_store of the finished k and v from the
* same launch, byte for byte), one launch a layer fewer. Declared after the attention ops,
@@ -947,26 +967,51 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
if (op_kv) RAD_ISSUE(c, op_kv, K, V, praw(slot, RAD_I32, T), kv_cache(kv, layer));
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
rad_op a_op = op_attn;
RadOperand a_q = brows(w.q, T);
if (op_attn_row) {
a_op = op_attn_row;
a_q = Q;
} else if (op_attn_dec && batch->max_q_len <= dec_hi) {
a_op = op_attn_dec;
a_q = Q;
} else if (row) {
if (T == 1) a_q = Q;
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
/* A tree step (rad_drafter_tree): every decode row's verify block sees, inside the block,
* only that row's ancestors (RadBatch::spec_parent), so the decode rows go through the tree
* form. On a step of decode rows alone that is the step's attention; beside a prefill chunk the
* ordinary form runs over every row first and the tree form then rewrites the decode rows,
* which come first (spec §8). */
const bool tree_step = op_attn_tree && batch->spec_parent && batch->draft_pass == 0 &&
batch->n_seq_decode > 0;
if (!tree_step || batch->n_seq_decode < batch->n_seq) {
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
rad_op a_op = op_attn;
RadOperand a_q = brows(w.q, T);
if (op_attn_row) {
a_op = op_attn_row;
a_q = Q;
} else if (op_attn_dec && batch->max_q_len <= dec_hi) {
a_op = op_attn_dec;
a_q = Q;
} else if (row) {
if (T == 1) a_q = Q;
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
}
RAD_ISSUE_N(c, a_op, batch->max_q_len,
a_q, kv_cache(kv, layer),
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));
}
if (tree_step) {
const int64_t Td = batch->n_tok_decode, Sd = batch->n_seq_decode;
RadOperand tq = row ? bcol(w.qkv, 0, qd, Td) : brows(w.q, Td);
if (op_tree_lift) {
RAD_ISSUE_N(c, op_tree_lift, Td, bcol(w.qkv, 0, qd, Td), brows(w.q, Td));
tq = brows(w.q, Td);
}
RAD_ISSUE_N(c, op_attn_tree, batch->max_q_len_decode,
tq, kv_cache(kv, layer),
praw2(table, RAD_I32, Sd, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, Sd),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, Sd + 1),
brows(w.attn, Td),
praw(batch->spec_parent, RAD_I32, Td));
}
RAD_ISSUE_N(c, a_op, batch->max_q_len,
a_q, kv_cache(kv, layer),
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));
}
/* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's
@@ -1811,6 +1856,9 @@ struct Model {
Dflash2 df2{};
Dflash2::Wire df2w{};
bool have_df2 = false;
/* Tree verification (RadBuildCtx::draft_tree): every layer's attention has its tree form, and
* the drafter proposes trees once it has declared dflash_tree too. */
bool tree = false;
/* The prefill overlap runs attention per slice: a trim a KV group (sliding, global). */
SliceTrim trim[2]{};
int n_trim = 0;
@@ -1877,6 +1925,13 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
Dflash2::Config dc{};
dc.n_taps = m.n_taps;
dc.block = ctx->max_spec + 1;
/* A tree (m.tree, asked before the trunk) is `max_spec` nodes grown over the lattice of the
* block the drafter was trained at, whatever its width: the block is the trained one and
* --num-speculative-tokens counts nodes. */
if (m.tree && gemma4::dflash_block(meta) > 1) {
dc.block = gemma4::dflash_block(meta);
dc.tree_nodes = ctx->max_spec;
}
dc.taps = df2_geti(meta, "conv_kernel_size", 2);
dc.group = df2_geti(meta, "conv_group_size", 16);
dc.sel_rank = df2_geti(meta, "selector_rank", 0);
@@ -1985,13 +2040,39 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
}
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
const int64_t nodes = dc.tree_nodes > 0 ? dc.tree_nodes : dc.steps();
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, nodes});
/* Trees (RadBuildCtx::draft_tree; the trunk's attention already has its tree form): the
* selector's lattice grown best-first into `steps` nodes, each edge weighed by the softmax of
* its scores over a temperature. 1.25 measured best at 7 nodes on the speculator benchmarks
* (greedy, and sampled at 0.7 and 1.0); its path probabilities are calibrated there. */
if (m.tree) {
dc.tree = true;
dc.tree_temp = 1.25;
dw.parents = decl_b(b, nm.f("dflash_parents"), RAD_I32, {dg.max_seqs, nodes});
/* A block of 16 (the DBloom drafter): its 15-node tree's verify rows pay at one sequence
* and not at many, so the query pass is declared at half the block too, over which the
* drafter grows a 7-node tree of its own: the drafter's short block
* (rad_drafter_short_block), which the core runs from two decoding sequences on
* (--draft-short-from auto). A shorter block's tree verifies as few rows as that already. */
if (dc.block >= 16 && (dc.block & (dc.block - 1)) == 0) {
dc.short_block = 1;
dc.short_rows = dc.block / 2;
}
}
/* The head copy comes from the tied table, under the block's own name; the recipe makes it
* 8-bit. */
RAD_ARCH_TRY(m.df2.declare(b, nm, dg, dc, (int)m.n_main, m.kv_draft, m.w_tok, "draft",
nm.ckpt("model.language_model.embed_tokens.weight"), dw));
m.have_df2 = true;
m.tree = m.df2.cfg.tree; /* false where dflash_tree did not resolve */
if (!m.tree && nodes != dc.steps()) {
fprintf(stderr, "radiance: gemma4: a DFlash2 tree of %lld nodes needs dflash_tree, which no "
"library serves here; the block's chain is %lld\n", (long long)nodes,
(long long)dc.steps());
return RAD_E_UNSUPPORTED;
}
RadDrafterDecl drf{};
drf.name = "dflash2";
@@ -1999,7 +2080,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
drf.depth = ctx->max_spec;
drf.block = dc.block;
drf.proposal = dw.tokens;
drf.proposal_pitch = dc.steps();
drf.proposal_pitch = nodes;
drf.window = dc.window;
drf.mask_token = (int32_t)df2_geti(meta, "mask_token_id", -1);
if (drf.mask_token < 0) {
@@ -2008,6 +2089,17 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
if (m.tree) {
RAD_ARCH_TRY(rad_drafter_tree(b, dw.parents));
if (m.df2.block_lo > 0) {
RAD_ARCH_TRY(rad_drafter_short_block(b, m.df2.block_lo));
rad_note(b, "DFlash2 drafter: a short block of %lld rows, a tree of %lld nodes over it",
(long long)m.df2.block_lo, (long long)m.df2.sel_lo_nodes);
}
rad_note(b, "DFlash2 drafter: a tree of %lld nodes a step (softmax temperature %.3g) over "
"the lattice of its %lld-row block, verified in %lld rows", (long long)nodes,
dc.tree_temp, (long long)dc.block, (long long)nodes + 1);
}
rad_note(b, "DFlash2 drafter: %lld layers at absolute %lld.., %lld heads / %lld kv x %lld, ffn "
"%lld, %s attention with a %lld-token window, %d trunk taps; one forward proposes "
@@ -2351,6 +2443,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
Gemma4Attn::Wire gw{}; gw.x = m.b_x; gw.h = m.b_h; gw.q = m.b_qg; gw.k = m.b_kg; gw.v = m.b_vg; gw.attn = m.b_atting;
Gemma4Mlp::Wire mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn;
/* Tree verification for a DFlash2 drafter (RadBuildCtx::draft_tree, which the engine sets
* from this plugin's probe; rad_drafter_tree): asked of every layer's attention here, before
* the drafter, and used only if every layer has it. Not where a layer reads another layer's
* cache (KV sharing, Gemma 4 E2B/E4B): untested there. */
const bool tree_want = ctx->max_spec > 0 && m.n_taps > 0 && gemma4::dflash_kind(meta) == 2 &&
kv_shared == 0 && ctx->draft_tree != 0;
bool tree_all = tree_want;
m.layers.resize((size_t)m.n_main);
for (int64_t l = 0; l < m.n_main; ++l) {
Layer& lay = m.layers[(size_t)l];
@@ -2360,8 +2460,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
const Gemma4Attn::Wire& aw = lay.global ? gw : sw;
/* A KV-shared layer is not bound: the group's pages hold only the layers that write. */
if (kv_src[(size_t)l] < 0) RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
lay.attn.tree = tree_want;
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre,
lay.global ? &m.b_qkvg : &m.b_qkvs, kv_src[(size_t)l]));
if (tree_want && !lay.attn.op_attn_tree) tree_all = false;
/* The double-wide layers write their own pair of buffers (see b_gu_w). */
Gemma4Mlp::Wire lw = mw;
const bool wide = wide_mlp && l >= first_shared;
@@ -2626,6 +2728,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* 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 (tree_want && !tree_all)
rad_note(b, "DFlash2 tree: no library serves tree attention for every layer here "
"(attn_paged_qrow_tree / attn_paged_tree); the drafter proposes a chain");
m.tree = tree_all;
if (m.n_taps > 0 && gemma4::dflash_kind(meta) == 2) {
RAD_ARCH_TRY(declare_dflash2(b, meta, ctx, m));
} else if (m.n_taps > 0) {
+260 -75
View File
@@ -21,14 +21,35 @@
* under `model`. Which one this is comes from the config (a VL checkpoint has a `text_config`),
* not the model's name.
*
* ============================== 8-BIT LINEARS ==============================
*
* Every linear is a LinearFP8 (rad_fp8.h), so the container's encoding of each weight decides the
* GEMM: plain bf16 is `gemm_nt` over the bf16 activation, exactly as a bf16 model runs; a recipe's
* block E4M3 (`codes=fp8_e4m3 block=128x128 scale=bf16`) is `gemm_nt_q` at fp8a8 over the
* activation quantised per 128 columns (one quant_act_fp8 per activation, shared by the linears
* that read it); int8 (`codes=i8 group=128 scale=bf16`) is `gemm_nt_q` at i8a8, each linear
* quantising its input. The trunk's format is read off layer 0's down projection and every linear
* must match it. The convolution, the norms and attention stay bf16; the lm_head is read at its
* stored codes (bf16, or E4M3 / int8 where a recipe made it so; logits_gemm_fp8 / _i8). At d1-3B
* the linears are 5.8 of the 6.3 GB a token reads, so 8-bit codes nearly halve decode and short
* prefill, both bound by that read.
*
* A block-fp8 trunk also takes the fused producers (rad_fp8.h), which matter once the GEMMs are
* this cheap: each norm quantises in its own pass and does the preceding block's residual add
* (rmsnorm_quant_fp8 with a fold), and the feed-forward is MlpFP8, whose gate|up GEMM applies
* SiLU(gate) * up and quantises in its epilogue at decode and short-prompt rows. Six launches a
* layer become two; the last layer's feed-forward keeps its add for the final norm. The fused
* kernels are byte-identical to the chains they replace.
*
* ============================== WHAT IT DOES NOT SERVE ==============================
*
* Tensor parallelism (a 3B model needs one card). A drafter, MoE (LFM2-8B-A1B), conv bias, or a
* checkpoint without the rotary: each is refused by name.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_mlp.h>
#include <arch/rad_block_vit.h>
#include <arch/rad_block_mlp_fp8.h>
#include <arch/rad_fp8.h>
#include "siglip2.h"
@@ -42,17 +63,32 @@ using namespace rad::arch;
struct Layer {
bool attention = false;
MlpBF16 mlp;
rad_weight w_norm = 0, w_in = 0, w_out = 0;
rad_weight w_norm = 0;
/* in is q (attention) or the convolution's in_proj; out is the mixer's out-projection */
LinearFP8 in, out;
/* conv */
rad_weight w_conv = 0;
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
/* attention: w_in is q, these are k, v and the two head norms */
rad_weight w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0;
rad_op op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
/* `gate_quant_fp8` at act none: C * conv(B * x) and its E4M3 codes in one pass. Absent
* (bf16, int8, or no library serving it), op_gate_out and q_mix run the pair. */
rad_op op_gate_q = 0;
/* attention: k, v and the two head norms */
LinearFP8 k, v;
rad_weight w_q_norm = 0, w_k_norm = 0;
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
rad_op op_store = 0, op_attn = 0;
/* both */
rad_op op_norm = 0, op_in = 0, op_out = 0, op_add = 0;
rad_op op_norm = 0, op_add = 0;
/* the feed-forward: norm, gate|up (w1 | w3), SiLU(gate) * up, down (w2), residual add */
rad_weight w_ffn_norm = 0;
LinearFP8 gate_up, down;
rad_op op_ffn_norm = 0, op_act = 0, op_ffn_add = 0;
/* fp8a8 only: the activation quantisers, one per activation the linears read */
QuantFP8 q_h, q_mix, q_ffn_h, q_ffn;
/* fp8a8 fused: the mixer's norm (quantising, and adding the previous feed-forward's delta
* from layer 1 on) and the whole feed-forward */
NormQuantFP8 nq_mix;
MlpFP8 mlp8;
};
struct Model {
@@ -64,6 +100,12 @@ struct Model {
rad_buf b_x = 0, b_h = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate_up = 0, b_ffn = 0;
rad_buf b_hout = 0, b_logits = 0;
/* The linears' inputs: the bf16 plane plus, for an 8-bit trunk, its codes. a_mix is the
* mixer's output (attention or convolution), the out-projection's input. */
ActFP8 a_h{}, a_attn{}, a_conv{}, a_ffn{};
/* The trunk's format, read off layer 0's first linear. `fused`: the fp8 trunk's fused
* producers (see the head of the file). */
bool q_fp8 = false, q_i8 = false, fused = false;
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
@@ -215,8 +257,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.w_lm_head = decl_w(b, nm.f("output.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
/* The head at its codes' dtype: bf16, or E4M3 / int8 where a recipe quantised it. */
m.w_lm_head = decl_w(b, nm.f("output.weight"),
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
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),
@@ -227,66 +271,125 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
MlpBF16::Wire mw{};
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
auto gemm = [&](int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w)),
{in}, {out});
/* ---- the trunk's format, from layer 0's first linear: q, or the convolution's in_proj
* (probe() makes its name map and reads its encoding). Plain bf16, or no encoding yet, is a
* bf16 trunk; an int8 weight makes the activations carry int8 codes, any other 8-bit weight
* E4M3 ones. */
const char* ffn_fmt = "%s.layers.%d.feed_forward.%s";
{
Layer& L0 = m.layers[0];
const char* base0 = nm.f(L0.attention ? "blk.%d.attn_q" : "blk.%d.conv_in", 0);
RAD_ARCH_TRY(L0.in.probe(b, nm, g, base0,
{ nm.ckpt(L0.attention ? "%s.layers.%d.self_attn.%s"
: "%s.layers.%d.conv.%s",
pre, 0, L0.attention ? "q_proj.weight"
: "in_proj.weight") }));
RadEncoding enc{};
const bool known = weight_enc(b, nm.f("%s.weight", base0), &enc);
const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16);
g.w_bf16 = plain;
m.q_i8 = !plain && L0.in.probed_i8;
m.q_fp8 = !plain && !m.q_i8;
m.fused = m.q_fp8;
}
m.a_h.x = m.b_h; m.a_attn.x = m.b_attn; m.a_conv.x = m.b_conv_out; m.a_ffn.x = m.b_ffn;
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8));
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8));
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8));
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8));
/* An E4M3 activation is quantised once by the model and read by every linear on it; an int8
* linear quantises its own input (LinearFP8::op_q), and a bf16 one reads the bf16 plane. */
auto quant = [&](QuantFP8& q, const ActFP8& a, int64_t n) {
return m.q_fp8 ? q.declare(b, g, a, n) : RAD_OK;
};
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, RAD_OP(b, "rmsnorm",
/* `op`: "rmsnorm", or "rmsnorm_rows" for the head norms, whose short-row form a prefill's
* thousands of head_dim-wide rows take. */
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out,
const char* op = "rmsnorm") {
return rw(b, RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w)),
{in}, {out});
};
auto add = [&](rad_buf x, rad_buf h) {
return rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{x, h}, {x});
};
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
uint32_t dtype) {
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
};
/* One linear: `base` is the declared name without `.weight`. Every linear must have the
* trunk's format; LinearFP8 refuses a bf16 weight in an 8-bit trunk with no bf16 plane, and
* this refuses the other mixes. */
auto linear = [&](LinearFP8& lin, int l, const char* base_fmt, int64_t N, int64_t K,
std::initializer_list<const char*> src, const ActFP8& a, rad_buf y,
std::initializer_list<int64_t> parts) -> int {
const char* base = nm.f(base_fmt, l);
RAD_ARCH_TRY(lin.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(l), src, a, y, 0,
parts));
const bool ok = g.w_bf16 ? lin.bf16 : m.q_i8 ? lin.i8 : (!lin.bf16 && !lin.i8);
if (!ok) {
fprintf(stderr, "radiance: lfm2: '%s.weight' is not in the trunk's format (%s); quantise "
"every linear of the trunk alike\n",
base, g.w_bf16 ? "bf16" : m.q_i8 ? "int8" : "block fp8");
return RAD_E_DTYPE;
}
return RAD_OK;
};
for (int l = 0; l < (int)m.layers.size(); ++l) {
Layer& L = m.layers[(size_t)l];
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
nm.ckpt("%s.layers.%d.operator_norm.weight", pre, l)));
L.w_norm = layer_w("blk.%d.attn_norm.weight", l, {g.n_embd}, RAD_F32);
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
if (m.fused) {
/* From layer 1 on the previous feed-forward's delta is still in h: the norm adds it
* into the stream, then normalises and quantises. */
const bool fold = l > 0;
RAD_ARCH_TRY(L.nq_mix.declare(b, g, L.w_norm, fold ? m.b_h : m.b_x, m.a_h, g.n_embd,
fold ? m.b_x : 0));
} else {
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
RAD_ARCH_TRY(quant(L.q_h, m.a_h, g.n_embd));
}
if (L.attention) {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn));
const char* a = "%s.layers.%d.self_attn.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), nm.ckpt(a, pre, l, "q_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), nm.ckpt(a, pre, l, "k_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), nm.ckpt(a, pre, l, "v_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l),
nm.ckpt(a, pre, l, "q_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l),
nm.ckpt(a, pre, l, "k_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
nm.ckpt(a, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.attn_q.weight", l, {g.q_dim(), g.n_embd}, RAD_BF16);
L.w_k = layer_w("blk.%d.attn_k.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
L.w_v = layer_w("blk.%d.attn_v.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
RAD_ARCH_TRY(linear(L.in, l, "blk.%d.attn_q", g.q_dim(), g.n_embd,
{ nm.ckpt(a, pre, l, "q_proj.weight") }, m.a_h, m.b_q, {}));
/* k and v are the trunk's narrowest linears: past 40 rows the narrow fp8 row's split
* leaves each slice too few waves, so they ask for the short-prompt split rule. */
L.k.short_split = L.v.short_split = true;
RAD_ARCH_TRY(linear(L.k, l, "blk.%d.attn_k", g.kv_dim(), g.n_embd,
{ nm.ckpt(a, pre, l, "k_proj.weight") }, m.a_h, m.b_k, {}));
RAD_ARCH_TRY(linear(L.v, l, "blk.%d.attn_v", g.kv_dim(), g.n_embd,
{ nm.ckpt(a, pre, l, "v_proj.weight") }, m.a_h, m.b_v, {}));
L.w_q_norm = layer_w("blk.%d.attn_q_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_k_norm = layer_w("blk.%d.attn_k_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_out = layer_w("blk.%d.attn_output.weight", l, {g.n_embd, g.q_dim()}, RAD_BF16);
L.op_in = gemm(g.q_dim(), g.n_embd, L.w_in, m.b_h, m.b_q);
L.op_k = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k);
L.op_v = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v);
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
* T * heads rows. */
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q);
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k);
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q,
"rmsnorm_rows");
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k,
"rmsnorm_rows");
L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim,
"neox"), {m.b_q}, {m.b_q});
"neox", "rope_rows"), {m.b_q}, {m.b_q});
L.op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
"neox"), {m.b_k}, {m.b_k});
"neox", "rope_rows"), {m.b_k}, {m.b_k});
/* attn_paged before kv_store: the cache's block size is read from the resolved
* attention kernel. */
L.op_attn = rw(b, RAD_OP(b, "attn_paged",
@@ -309,21 +412,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_k, m.b_v}, {});
L.op_out = gemm(g.n_embd, g.q_dim(), L.w_out, m.b_attn, m.b_h);
RAD_ARCH_TRY(quant(L.q_mix, m.a_attn, g.q_dim()));
RAD_ARCH_TRY(linear(L.out, l, "blk.%d.attn_output", g.n_embd, g.q_dim(),
{ nm.ckpt(a, pre, l, "out_proj.weight") }, m.a_attn, m.b_h, {}));
} else {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
const char* c = "%s.layers.%d.conv.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_in.weight", l), nm.ckpt(c, pre, l, "in_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_out.weight", l), nm.ckpt(c, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.conv_in.weight", l, {3 * g.n_embd, g.n_embd}, RAD_BF16);
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
RAD_ARCH_TRY(linear(L.in, l, "blk.%d.conv_in", 3 * g.n_embd, g.n_embd,
{ nm.ckpt(c, pre, l, "in_proj.weight") }, m.a_h, m.b_bcx, {}));
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
* convert, as the gated delta net's conv1d is. */
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
L.w_out = layer_w("blk.%d.conv_out.weight", l, {g.n_embd, g.n_embd}, RAD_BF16);
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
L.op_in = gemm(3 * g.n_embd, g.n_embd, L.w_in, m.b_h, m.b_bcx);
L.op_gate_in = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
@@ -334,25 +436,78 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(L.w_conv)),
{m.b_conv_in}, {m.b_conv_out});
L.op_gate_out = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
L.op_out = gemm(g.n_embd, g.n_embd, L.w_out, m.b_conv_out, m.b_h);
/* C * conv(B * x), then the codes the out projection reads, in one pass. The kernel
* rounds the product to bf16 before taking the codes, so it is byte-identical to the
* mul + quant_act_fp8 pair; the bf16 product has no reader in a block-fp8 trunk. */
if (m.q_fp8 && rad_op_declared(b, "gate_quant_fp8"))
L.op_gate_q = rw(b, RAD_OP(b, "gate_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype),
RAD_STR("act", "none")),
RAD_NOWEIGHTS),
{m.b_bcx, m.b_conv_out}, {m.a_conv.cq(), m.a_conv.cs()});
if (!L.op_gate_q) {
L.op_gate_out = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
RAD_ARCH_TRY(quant(L.q_mix, m.a_conv, g.n_embd));
}
RAD_ARCH_TRY(linear(L.out, l, "blk.%d.conv_out", g.n_embd, g.n_embd,
{ nm.ckpt(c, pre, l, "out_proj.weight") }, m.a_conv, m.b_h, {}));
}
L.op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
if (m.fused) {
/* The feed-forward's norm adds the mixer's delta; its own add is left to the next
* layer's norm, except after the last layer, whose output the final norm reads. */
MlpFP8::Wire mw{};
mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
MlpFP8::Src ms{};
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
ms.gate = nm.ckpt(ffn_fmt, pre, l, "w1.weight");
ms.up = nm.ckpt(ffn_fmt, pre, l, "w3.weight");
ms.down = nm.ckpt(ffn_fmt, pre, l, "w2.weight");
const bool last = l + 1 == (int)m.layers.size();
/* The whole prompt in the fold: gemm_nt_q_gated_wide serves every M, so a prefill
* chunk does not fall back to the pair past 64 rows. */
RAD_ARCH_TRY(L.mlp8.declare(b, nm, g, l, mw, ms, /*fold=*/true, /*add_out=*/last,
0, false, 0, /*wide_fold=*/true));
if (L.mlp8.gate_up.bf16 || L.mlp8.gate_up.i8 || L.mlp8.down.bf16 || L.mlp8.down.i8) {
fprintf(stderr, "radiance: lfm2: layer %d's feed-forward is not block fp8 like the "
"rest of the trunk; quantise every linear alike\n", l);
return RAD_E_DTYPE;
}
continue;
}
L.op_add = add(m.b_x, m.b_h);
/* ---- the feed-forward */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l),
nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l)));
L.w_ffn_norm = layer_w("blk.%d.ffn_norm.weight", l, {g.n_embd}, RAD_F32);
L.op_ffn_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(L.w_ffn_norm)),
{m.b_x}, {m.b_h});
RAD_ARCH_TRY(quant(L.q_ffn_h, m.a_h, g.n_embd));
RAD_ARCH_TRY(linear(L.gate_up, l, "blk.%d.ffn_gate_up", 2 * g.n_ff, g.n_embd,
{ nm.ckpt(ffn_fmt, pre, l, "w1.weight"),
nm.ckpt(ffn_fmt, pre, l, "w3.weight") },
m.a_h, m.b_gate_up, { g.n_ff, g.n_ff }));
L.op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_x, m.b_h}, {m.b_x});
MlpBF16::Src ms{};
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
ms.gate = nm.ckpt("%s.layers.%d.feed_forward.w1.weight", pre, l);
ms.up = nm.ckpt("%s.layers.%d.feed_forward.w3.weight", pre, l);
ms.down = nm.ckpt("%s.layers.%d.feed_forward.w2.weight", pre, l);
RAD_ARCH_TRY(L.mlp.declare(b, nm, g, l, mw, ms));
{m.b_gate_up}, {m.b_ffn});
RAD_ARCH_TRY(quant(L.q_ffn, m.a_ffn, g.n_ff));
RAD_ARCH_TRY(linear(L.down, l, "blk.%d.ffn_down", g.n_embd, g.n_ff,
{ nm.ckpt(ffn_fmt, pre, l, "w2.weight") }, m.a_ffn, m.b_h, {}));
L.op_ffn_add = add(m.b_x, m.b_h);
}
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
@@ -363,6 +518,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS),
{m.b_x}, {m.b_hout});
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, m.b_hout);
/* A tied head is the bf16 embedding table, whatever codes the head itself is read at: a
* scored step (/v1/systemone) leaves the final-normed rows in h_out and the core takes the
* candidates' logits from the table on the host (rad_declare_scores), with no head read. */
if (text_bool(meta, "tie_word_embeddings", false))
RAD_ARCH_TRY(rad_declare_scores(b, m.b_hout, m.w_tok));
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
@@ -431,12 +591,17 @@ static void step(RadCtx* c, const RadBatch* batch) {
for (int l = 0; l < (int)m.layers.size(); ++l) {
const Layer& L = m.layers[(size_t)l];
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
if (m.fused) {
L.nq_mix.step(c, T);
} else {
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
L.q_h.step(c, T);
}
if (L.attention) {
const RadKVGroupBatch* kv = kv_batch(batch, m.kv_attn);
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_q, T));
RAD_ISSUE(c, L.op_k, brows(m.b_h, T), RAD_W(L.w_k), brows(m.b_k, T));
RAD_ISSUE(c, L.op_v, brows(m.b_h, T), RAD_W(L.w_v), brows(m.b_v, T));
L.in.step(c, m.a_h, m.b_q, T);
L.k.step(c, m.a_h, m.b_k, T);
L.v.step(c, m.a_h, m.b_v, T);
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
brows(m.b_q, T));
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
@@ -453,18 +618,36 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(m.b_attn, T));
RAD_ISSUE(c, L.op_out, brows(m.b_attn, T), RAD_W(L.w_out), brows(m.b_h, T));
L.q_mix.step(c, T);
L.out.step(c, m.a_attn, m.b_h, T);
} else {
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_bcx, T));
L.in.step(c, m.a_h, m.b_bcx, T);
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
brows(m.b_conv_in, T));
conv_step(m, L, c, batch, l);
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
brows(m.b_conv_out, T));
RAD_ISSUE(c, L.op_out, brows(m.b_conv_out, T), RAD_W(L.w_out), brows(m.b_h, T));
if (L.op_gate_q) {
RAD_ISSUE(c, L.op_gate_q, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
brows(m.a_conv.cq(), T), brows(m.a_conv.cs(), T), RAD_NONE);
} else {
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
brows(m.b_conv_out, T));
L.q_mix.step(c, T);
}
L.out.step(c, m.a_conv, m.b_h, T);
}
if (m.fused) {
L.mlp8.step(c, batch);
continue;
}
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
L.mlp.step(c, batch);
RAD_ISSUE(c, L.op_ffn_norm, brows(m.b_x, T), RAD_W(L.w_ffn_norm), brows(m.b_h, T));
L.q_ffn_h.step(c, T);
L.gate_up.step(c, m.a_h, m.b_gate_up, T);
RAD_ISSUE(c, L.op_act, brows(m.b_gate_up, T), brows(m.b_ffn, T));
L.q_ffn.step(c, T);
L.down.step(c, m.a_ffn, m.b_h, T);
RAD_ISSUE(c, L.op_ffn_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
}
/* The lm_head runs only on the rows the sampler asked for; a prefill chunk that finishes no
@@ -474,15 +657,17 @@ static void step(RadCtx* c, const RadBatch* batch) {
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_out_norm), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
if (!batch->score_only)
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
}
}
} /* namespace lfm2_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.1.0",
"LiquidAI LFM2 / LFM2-VL, bf16: short gated convolutions and GQA attention in the "
"checkpoint's own schedule, one rank; LFM2-VL's SigLIP2 tower for images")
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.2.0",
"LiquidAI LFM2 / LFM2-VL, bf16, or with block-fp8 or int8 linears from a recipe: "
"short gated convolutions and GQA attention in the checkpoint's own schedule, one "
"rank; LFM2-VL's SigLIP2 tower for images")
#endif
+38 -79
View File
@@ -6,7 +6,7 @@
* returns each sequence's pooled row. Attention is bidirectional on every layer, so nothing is
* paged: a token attends to later tokens, and there is nothing to carry between steps.
*
* ============================== THE SHAPE ==============================
* Shape:
*
* 12 layers, hidden 768, 12 heads of 64, ffn 3072, vocab 250048, type vocab 1
* post-norm block, the config's `prenorm: false`:
@@ -20,14 +20,12 @@
* output: the mean of every real token, then cast to the f32 pooled buffer
*
* The expert tables are one concatenated tensor each: w1 [8 * 3072, 768] as [out, in], w2
* [8 * 3072, 768] as [in, out] per expert, so w2 is sliced then transposed at convert
* (RAD_MAP_TRANSPOSE with src_index and src_rows). Every expert's two tensors take distinct group
* slots.
* [8 * 3072, 768] as [in, out] per expert, so w2 is sliced, then transposed (RAD_MAP_TRANSPOSE
* with src_index and src_rows). Every expert's two tensors take distinct group slots.
*
* The block order and the unused shared experts.bias were settled against the production
* llama.cpp embedder by scripts/nomic_ref.py; the winning variant and the vectors it produced are
* in tests/data/nomic/golden.json (norm=post, bias=none). The checkpoint's `experts.bias` tensors
* are therefore not declared and stay unconverted.
* The block order and the omitted shared bias match llama.cpp's embedder for this model
* (post-norm, no expert bias). The checkpoint's `experts.bias` tensors are not declared and stay
* unconverted.
*/
#include <arch/rad_arch.h>
@@ -40,10 +38,8 @@ namespace nomicbert {
using namespace rad::arch;
/* Post-norm, the reading scripts/nomic_ref.py and tests/data/nomic/golden.json settle: the
* attention is on the raw stream, then LN1, then the feed-forward on LN1's output, then LN2 over
* that output plus the feed-forward's. The shared experts.bias is not applied (bias=none there). */
constexpr bool kPostNorm = true;
/* Post-norm: attention on the raw stream, then LN1, then the feed-forward on LN1's output, then
* LN2 over that output plus the feed-forward's. */
struct Layer {
bool moe = false;
@@ -77,10 +73,9 @@ struct Model {
static Model g_model[MAX_RANKS];
/* The layer schedule, read rather than derived: a wrong interval would turn a dense layer into a
* MoE layer whose tensors the checkpoint does not hold, which convert refuses but only after the
* graph was built. Layer l is routed when (l + 1) % moe_every_n_layers == 0, as nomic's
* modeling_hf_nomic_bert builds it. */
/* The layer schedule, read from moe_every_n_layers rather than derived: a wrong interval would
* declare a MoE layer whose tensors the checkpoint does not hold. Layer l is routed when
* (l + 1) % moe_every_n_layers == 0, as nomic's modeling_hf_nomic_bert builds it. */
static bool is_moe_layer(int64_t l, int64_t every) {
return every > 0 && (l + 1) % every == 0;
}
@@ -99,7 +94,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
/* One 475M-parameter encoder on one card; tensor parallelism would only add an all-reduce per
/* A 475M-parameter encoder fits one card; tensor parallelism would only add an all-reduce per
* layer. */
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: nomicbert runs on one card (--tp 1); the model is 475M "
@@ -325,8 +320,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
src("mlp.router.layer.weight")));
y.w_router = decl_w(b, nm.f("blk.%lld.ffn_router.weight", ll), RAD_BF16,
{m.n_expert, E}, A, N, gl);
/* mlp.experts.bias is deliberately not mapped: the verified variant applies no
* expert bias, so the tensor is left in the checkpoint. */
/* mlp.experts.bias is not mapped (no expert bias, see the header). */
/* Each projection is a consecutive run of expert handles: all w1 in expert order,
* then all w2. A grouped GEMM takes the run's first handle and its length. The name
* maps come first: declare reads a weight's planned encoding when the weight is
@@ -356,9 +350,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
}
const rad_buf att_in = kPostNorm ? m.b_x : m.b_h;
y.op_qkv = rw(b, gemm_bias_op(3 * E, E, y.w_qkv, y.b_qkv, nullptr),
{att_in}, {m.b_qkv});
{m.b_x}, {m.b_qkv});
y.op_rope = rw(b, RAD_OP(b, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head),
@@ -381,12 +374,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
if (!y.moe) {
y.op_fc1 = rw(b, gemm_bias_op(g.n_ff, E, y.w_fc1, y.b_fc1, "gelu"),
{m.b_h}, {m.b_ff});
if constexpr (kPostNorm)
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
{m.b_ff, m.b_h}, {m.b_o});
else
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
{m.b_ff, m.b_x}, {m.b_x});
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
{m.b_ff, m.b_h}, {m.b_o});
} else {
y.op_router = rw(b, gemm_op(m.n_expert, E, y.w_router), {m.b_h}, {m.b_logits});
y.op_topk = rw(b, RAD_OP(b, "router_topk",
@@ -416,16 +405,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_STR("act", "none")),
RAD_NOWEIGHTS),
{m.b_edn, m.b_ew, m.b_sorted}, {m.b_emoe});
if constexpr (kPostNorm)
y.op_add = add_op(m.b_h, m.b_emoe, m.b_o);
else
y.op_add = add_op(m.b_x, m.b_emoe, m.b_x);
y.op_add = add_op(m.b_h, m.b_emoe, m.b_o);
}
if constexpr (kPostNorm)
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_o}, {m.b_x});
else
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_x}, {m.b_h});
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_o}, {m.b_x});
if (!y.op_qkv || !y.op_rope || !y.op_attn || !y.op_out || !y.op_norm1 || !y.op_norm2)
return RAD_E_INVAL;
@@ -446,13 +429,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS),
{m.b_mean}, {m.b_pooled});
rad_note(b, "embedding model: %lld layers (%lld routed every %lld), hidden %lld, ffn %lld, "
"%lld heads of %lld, %lld experts top %lld; post-norm %d, no expert bias; "
int64_t n_routed = 0;
for (const Layer& y : m.layers) n_routed += y.moe ? 1 : 0;
rad_note(b, "embedding model: %lld layers (%lld routed, every %lld), hidden %lld, ffn %lld, "
"%lld heads of %lld, %lld experts top %lld; post-norm, no expert bias; "
"mean-pooled to %lld",
(long long)g.n_layer, (long long)m.n_expert, (long long)every, (long long)E,
(long long)g.n_layer, (long long)n_routed, (long long)every, (long long)E,
(long long)g.n_ff, (long long)g.n_head, (long long)g.head_dim,
(long long)m.n_expert, (long long)m.n_expert_used, kPostNorm ? 1 : 0,
(long long)E);
(long long)m.n_expert, (long long)m.n_expert_used, (long long)E);
return RAD_OK;
}
@@ -474,43 +458,22 @@ static void step(RadCtx* c, const RadBatch* batch) {
for (int64_t l = 0; l < g.n_layer; ++l) {
const Layer& y = m.layers[(size_t)l];
auto attention = [&] {
const rad_buf att_in = kPostNorm ? m.b_x : m.b_h;
RAD_ISSUE_N(c, y.op_qkv, T, brows(att_in, T), RAD_W(y.w_qkv), RAD_W(y.b_qkv),
RAD_NONE, brows(m.b_qkv, T));
RAD_ISSUE(c, y.op_rope, brows(m.b_qkv, T), pos);
RAD_ISSUE(c, y.op_attn, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), RAD_W(y.b_out),
brows(m.b_x, T), brows(m.b_x, T));
};
if constexpr (kPostNorm) {
attention();
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
brows(m.b_h, T));
} else {
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
brows(m.b_h, T));
attention();
}
RAD_ISSUE_N(c, y.op_qkv, T, brows(m.b_x, T), RAD_W(y.w_qkv), RAD_W(y.b_qkv),
RAD_NONE, brows(m.b_qkv, T));
RAD_ISSUE(c, y.op_rope, brows(m.b_qkv, T), pos);
RAD_ISSUE(c, y.op_attn, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), RAD_W(y.b_out),
brows(m.b_x, T), brows(m.b_x, T));
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
brows(m.b_h, T));
if (!y.moe) {
RAD_ISSUE_N(c, y.op_fc1, T, brows(m.b_h, T), RAD_W(y.w_fc1), RAD_W(y.b_fc1),
RAD_NONE, brows(m.b_ff, T));
if constexpr (kPostNorm)
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
RAD_W(y.b_fc2), brows(m.b_h, T), brows(m.b_o, T));
else
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
RAD_W(y.b_fc2), brows(m.b_x, T), brows(m.b_x, T));
if constexpr (kPostNorm)
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
brows(m.b_x, T));
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
RAD_W(y.b_fc2), brows(m.b_h, T), brows(m.b_o, T));
} else {
if constexpr (!kPostNorm)
RAD_ISSUE(c, y.op_norm2, brows(m.b_x, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
brows(m.b_h, T));
RAD_ISSUE(c, y.op_router, brows(m.b_h, T), RAD_W(y.w_router), brows(m.b_logits, T));
RAD_ISSUE(c, y.op_topk, brows(m.b_logits, T), brows(m.b_ids, T), brows(m.b_ew, T));
RAD_ISSUE(c, y.op_scatter, brows(m.b_ids, T), brows(m.b_sorted, T * K),
@@ -524,14 +487,10 @@ static void step(RadCtx* c, const RadBatch* batch) {
brows(m.b_edn, T * K));
RAD_ISSUE_N(c, y.op_gather, T, brows(m.b_edn, T * K), brows(m.b_ew, T),
brows(m.b_sorted, T * K), RAD_NONE, RAD_NONE, brows(m.b_emoe, T));
if constexpr (kPostNorm)
RAD_ISSUE(c, y.op_add, brows(m.b_h, T), brows(m.b_emoe, T), brows(m.b_o, T));
else
RAD_ISSUE(c, y.op_add, brows(m.b_x, T), brows(m.b_emoe, T), brows(m.b_x, T));
if constexpr (kPostNorm)
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
brows(m.b_x, T));
RAD_ISSUE(c, y.op_add, brows(m.b_h, T), brows(m.b_emoe, T), brows(m.b_o, T));
}
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
brows(m.b_x, T));
}
RAD_ISSUE(c, m.op_mean, brows(m.b_x, T), cu, brows(m.b_mean, S));
+20 -14
View File
@@ -114,6 +114,16 @@ using MtpHead = MtpFP8;
* wash. The drafter's reads (Dflash2::Config::prefetch) take the same size. */
constexpr int64_t kPrefetchBytes = (int64_t)12 << 20;
constexpr int64_t kPrefetchStepRows = 32;
/* The delta net's out-projection read into the on-die cache beside its decode recurrent update
* (GdnFP8::op_pf_out): the update runs one workgroup per (sequence, head) and leaves the memory mostly
* idle, so the whole projection (7.9 MB a rank in MXFP4; the read stops at the weight's end) is read
* there. Qwen3.8-27B MXFP4 + DFlash2 at tp 2, production flags, 1k context, hwgrid ms/step, median of
* five interleaved rounds, none -> whole: x1 19.40 -> 19.10, x2 20.93 -> 20.78, x4 24.26 -> 24.17
* (every round faster), x8 25.22 -> 25.48 (four rounds of five slower: eight sequences' state traffic
* fills the memory and the read competes with it), so up to four sequences. 4 MB read as the whole
* (x1 19.24 / 19.10 against 19.20 / 19.06); 90k x4 and x16 (64 rows, no read) unchanged. */
constexpr int64_t kGdnOutPrefetchBytes = (int64_t)8 << 20;
constexpr int64_t kGdnOutPrefetchSeqs = 4;
struct Layer {
int full = 0;
@@ -430,11 +440,11 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
/* --draft-coupling (RadBuildCtx::draft_coupling): the walk samples each draft from Q, its
* scores' softmax over the best eight candidates, and the sampler couples the target's own draw
* to it (abi/rad_spechub.h). The planes are named as the MTP head's, which is how the engine
* finds them. RADIANCE_DFLASH_Q_TEMP sets Q's temperature; any value keeps the output exact
* and moves only acceptance. The default, 0.6, is where held-out acceptance peaked on
* Qwen3.8-27B MXFP4 + its DFlash2 drafter at request temperature 1 (tokens a step at x4, 32
* rows: ordinary rule 3.52; Q at 1.0 3.71, 0.7 3.88, 0.5 3.85, 0.35 3.77): the walk's scores
* are flatter than the target's law, and a sharper Q puts its mass where the target's is. */
* finds them. Q's temperature keeps the output exact at any value and moves only acceptance;
* 0.6 is where held-out acceptance peaked on Qwen3.8-27B MXFP4 + its DFlash2 drafter at request
* temperature 1 (tokens a step at x4, 32 rows: ordinary rule 3.52; Q at 1.0 3.71, 0.7 3.88,
* 0.5 3.85, 0.35 3.77): the walk's scores are flatter than the target's law, and a sharper Q
* puts its mass where the target's is. */
if (ctx->draft_coupling) {
if (dc.steps() > RAD_MTP_COUPLE_MAX_ROUNDS || dc.sel_topk > RAD_DFLASH_COUPLE_MAX_K ||
dc.sel_rank % RAD_DFLASH_EDGE_PARTS || dc.sel_rank > RAD_DFLASH_COUPLE_MAX_R) {
@@ -445,15 +455,6 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
return RAD_E_UNSUPPORTED;
}
dc.q_temp = 0.6;
if (const char* e = std::getenv("RADIANCE_DFLASH_Q_TEMP")) {
const double t = std::strtod(e, nullptr);
if (!(t > 0.0) || t > 100.0) {
fprintf(stderr, "radiance: RADIANCE_DFLASH_Q_TEMP=%s is not a temperature in "
"(0, 100]\n", e);
return RAD_E_INVAL;
}
dc.q_temp = t;
}
dw.couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
{dg.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, RAD_BUF_PERSIST);
dw.couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
@@ -1097,6 +1098,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
Layer& lay = m.layers[(size_t)l];
lay.pf_gu_w = lay.mlp.gate_up.w;
lay.op_pf_gu = decl_prefetch(b, lay.pf_gu_w, kPrefetchBytes);
if (!lay.full) {
lay.gdn.op_pf_out = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes);
lay.gdn.pf_out_rows = kPrefetchStepRows;
lay.gdn.pf_out_seqs = kGdnOutPrefetchSeqs;
}
if (l + 1 < m.n_main) {
const Layer& nx = m.layers[(size_t)l + 1];
lay.pf_next_w = nx.full ? nx.attn.qg.w : nx.gdn.in.w;