merge 1.12.0: gemma4 E2B/E4B and Nemotron Bolt E4B arrive; the ref2va audio, rows and ABI work carried across

conv1d keeps both stride forms: upstream's causal codec downsample with cu_div (Fish Audio) and the port's explicit-pad non-causal one (the H3 audio encoder's), in libref, libavx and libr4d alike; the ABI takes upstream's 27 on top of the port's RadVideoGenBatch growth.
This commit is contained in:
gearwave00001 committed 2026-10-24 19:03:26 -05:00
commit 7c3b5ab7d5
285 files changed
+30500 -2898

No files matched your search

+37 -24
View File
@@ -596,25 +596,30 @@ inline rad_op rw(RadBuilder* b, rad_op h,
* (core/runtime/ctx.h): it is no collective, keeps no counter and touches no arena byte.
*
* Only at decode and verify heights, up to kPrefetchRows rows: a DFlash2 verify's 8 a sequence, a
* z-lab DFlash verify's 16, a plain decode's one. With the ceiling at 64, a prompt's prefill steps
* (40 rows on the 31B's test prompt) took the reads too, and a freshly started 31B server's first
* greedy reply then differed on 4 of 6 starts (4x R9700, the cards' memory scribbled before each
* start); at 16, and with no reads at all, 0 of 6. Per-op output hashes later located that
* divergence at the prefill all-reduce's first reuse of a double-buffered slot: a race in the
* all-reduce, which its full fence on prefill-sized messages (libr4d) cures, not in anything the
* reads touch. The reads stay off prompt steps all the same. */
* z-lab DFlash verify's 16, a plain decode's one. Prompt steps never take the reads: beside the
* prefill all-reduces they made a fresh server's first greedy reply differ, the slot-reuse race
* that libr4d's full fence on prefill-sized four-rank messages (kArFenceFromElems) also cures. */
constexpr int64_t kPrefetchRows = 16;
/* The read goes on lane 0 itself, right after the GEMM, where its chained form (libr4d
* r4dchain_prefetch) waits for that GEMM and then reads beside the collective after it without
* holding the collective: no join between the lanes, so no record on the GEMM and no barrier bit
* on it, and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1. On
* 4x R9700 (31B DFlash2, three rounds, every reply identical): code 385-386 tok/s against 363-365,
* prose 284-286 against 269-270, decode after a 6.4k prompt 580-583 against 538-541. Only where
* launches chain (rad_chain_on, the core's decision), since a plain launch would read in series
* there; elsewhere the read goes on lane 1, behind a join from lane 0. */
/* Where launches chain (rad_chain_on, the core's decision) the read goes on lane 0 itself, right
* after the GEMM: its chained form (libr4d r4dchain_prefetch) waits for that GEMM and then reads
* beside the collective after it without holding the collective, so there is no join between the
* lanes and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1 (on
* 4x R9700, the 31B with DFlash2 decoded 6-8% faster than with the read on lane 1). A plain launch
* would read in series on lane 0, so elsewhere the read goes on lane 1, behind a join from lane
* 0. */
inline bool prefetch_lane0() { return rad_chain_on() != 0; }
/* RADIANCE_PREFETCH_BESIDE=0 issues none of these reads. Beside another server on the same card
* the lane-1 form costs more than it gains: the card has fewer hardware queue slots than the two
* servers have queues, and the join puts a queue switch into every decode step. */
inline bool prefetch_beside_on() {
static const bool on = [] {
const char* e = std::getenv("RADIANCE_PREFETCH_BESIDE");
return !(e && e[0] == '0' && e[1] == 0);
}();
return on;
}
inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
if (!op || T > kPrefetchRows) return;
if (!op || T > kPrefetchRows || !prefetch_beside_on()) return;
if (prefetch_lane0()) {
RAD_ISSUE(c, op, RAD_W(w));
return;
@@ -622,15 +627,9 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w));
rad_lane(c, 0);
}
/* RADIANCE_PREFETCH=0 declares no reads at all (docs/GUIDE.md); read at declare. */
inline bool prefetch_enabled() {
const char* e = std::getenv("RADIANCE_PREFETCH");
return !(e && !std::strcmp(e, "0"));
}
/* The `prefetch` of `w`'s first `bytes`, where a library serves it and the reads are on; 0
* otherwise. */
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. */
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
if (!w || bytes <= 0 || !prefetch_enabled() || !rad_op_declared(b, "prefetch")) return 0;
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
}
@@ -687,6 +686,9 @@ struct Geom {
/* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as
* `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */
int64_t wire_min_bytes = 0;
/* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it).
* decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */
int attn_prefill_fp8 = 0;
float eps = 1e-6f;
/* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and
* store `w` near 0.1, so reading it as a plain gain shrinks every normed activation 5-10x. An
@@ -957,6 +959,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
g.world = c->world_size ? c->world_size : 1;
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
g.wire_min_bytes = c->tp_wire_min_bytes;
g.attn_prefill_fp8 = c->attn_prefill_fp8;
g.eps = m->rms_eps;
g.theta = m->rope_theta;
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
@@ -1163,6 +1166,16 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
}
/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the
* parameters are passed unchanged, so op identities and tune keys do not change. */
inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name,
const RadParam* params, int n, const rad_weight* weights, int nw) {
if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw);
std::vector<RadParam> p(params, params + n);
p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8));
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
}
/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
* after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
* free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
+1 -1
View File
@@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
* kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
op_attn = rw(b, RAD_OP(b, "attn_paged",
op_attn = rw(b, decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
+1 -1
View File
@@ -124,7 +124,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
* explains declare vs issue order). */
op_attn = rw(b, RAD_OP(b, "attn_paged",
op_attn = rw(b, decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
+1 -1
View File
@@ -195,7 +195,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
*
* The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
* a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
op_attn = rw(b, RAD_OP(b, "attn_paged",
op_attn = rw(b, decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0),
+61 -1
View File
@@ -157,6 +157,21 @@ struct AttnGatedFP8 {
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
int ar_overlap = 0;
rad_op op_ar_ov = 0;
/* Whether step() with `own_ar` false runs the dense path a piece at a time over a caller's
* normed pieces (ArPieces::in_ready): one prefill sequence in two pieces, each the chunk a
* span of 1 makes, on the unfused prologue with one rotary component per token (every token's
* components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and
* the gate quantised by gate_quant_fp8. */
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
const int64_t T = batch->n_tok;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
return pieces && pieces->in_ready && pieces->cu && pieces->cuts(T) &&
T <= 2 * pieces->rows && !op_add && !op_fill && op_gq && !op_sig && !qsa_sel &&
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL &&
!(T <= fused_rows) && batch->positions && !rope_mixed(batch) &&
kvb && kvb->slot_mapping && kvb->block_table && kvb->seqused;
}
};
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -293,7 +308,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
/* Declared before kv_store, which reads back the resolved `block_size`
* (rad_block_attn_gated.h). */
op_attn = RAD_OP(b, "attn_paged",
op_attn = decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0),
@@ -477,6 +492,51 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
const int64_t T = batch->n_tok;
/* One prefill sequence in two pieces over the caller's normed input (takes_pieces): the
* projections, prologue, cache store, attention, gate and out projection of the first piece,
* then the second's, so the first piece's reduction runs beside all of the second piece's
* work. Each piece is the chunk a span of 1 makes: its rows, its positions, its slots, and an
* attention over its own query bounds (ArPieces::cu) that sees the cache up to its own end --
* the first piece's position after its last row, the step's seqused for the second, which
* reads the first piece's keys from the cache as a later chunk would. */
if (!own_ar && takes_pieces(batch, pieces)) {
const int64_t R = pieces->rows, hd = g.head_dim, qw = g.q_dim();
const int64_t qgw = g.n_head * 2 * hd, kvw = g.n_head_kv * hd;
const int64_t tpitch = kvb->block_table_pitch;
for (int64_t p = 0; p < 2; ++p) {
const int64_t r0 = p == 0 ? 0 : R;
const int64_t n = p == 0 ? R : T - R;
const int32_t* pos = (batch->rope_pos ? batch->rope_pos : batch->positions) + r0;
qg.step(c, w.h, w.qg, T, r0, n);
kp.step(c, w.h, w.k, T, r0, n);
vp.step(c, w.h, w.v, T, r0, n);
RAD_ISSUE_N(c, op_q_norm, n * g.n_head,
bcol_at(w.qg, r0, qgw, 0, hd, n), RAD_W(w_q_norm),
brow_slice(w.q, r0, n, qw));
RAD_ISSUE_N(c, op_k_norm, n * g.n_head_kv,
brow_slice(w.k, r0, n, kvw), RAD_W(w_k_norm),
brow_slice(w.k, r0, n, kvw));
RAD_ISSUE_N(c, op_rope_q, n, brow_slice(w.q, r0, n, qw), praw(pos, RAD_I32, n));
RAD_ISSUE_N(c, op_rope_k, n, brow_slice(w.k, r0, n, kvw), praw(pos, RAD_I32, n));
RAD_ISSUE_N(c, op_kv_store, n,
brow_slice(w.k, r0, n, kvw), brow_slice(w.v, r0, n, kvw),
praw(slot + r0, RAD_I32, n), kv_cache(kv, layer));
RAD_ISSUE_N(c, op_attn, n,
brows(w.q, T), kv_cache(kv, layer), praw2(table, RAD_I32, 1, tpitch),
praw(p == 0 ? batch->positions + R : used, RAD_I32, 1),
RAD_NONE, RAD_NONE, praw(pieces->cu + p, RAD_I32, 2),
brows(w.attn.x, T));
RAD_ISSUE_N(c, op_gq, n * g.n_head,
bcol_at(w.qg, r0, qgw, hd, hd, n), brow_slice(w.attn.x, r0, n, qw),
brow_slice(w.attn.cq(), r0, n, qw),
brow_slice(w.attn.cs(), r0, n, fp8_blocks(qw)),
brow_slice(w.attn.x, r0, n, qw));
o.step(c, w.attn, w.h.x, T, r0, n);
if (p == 0) pieces->hand(r0, n);
}
return;
}
if (!ext_in) nq_h.step(c, T);
if (op_fill) {
/* Attention-zero rank: zero output, then the reduce and the residual. */
+55 -5
View File
@@ -130,6 +130,11 @@ struct Dflash2 {
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
* 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. */
int short_block = 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 (prepare's set, then finish's);
@@ -260,6 +265,10 @@ struct Dflash2 {
rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */
rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {};
/* The short block's (block_lo rows a sequence): the convolutions mask at the block's first row
* 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;
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
@@ -287,6 +296,9 @@ struct Dflash2 {
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;
/* The short block: kShortBlock rows (depth 3, the window that pays at many sequences), when
* the drafter's own block is longer (rad_drafter_short_block). */
static constexpr int64_t kShortBlock = 4;
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,
@@ -695,7 +707,26 @@ 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;
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",
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
RAD_INT("NG", NG), RAD_INT("block_size", block_lo),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_acb[i])),
{w.h, w.coef}, {w.h2});
op_fconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
RAD_INT("NG", NG), RAD_INT("block_size", block_lo),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fcb[i])),
{w.h, w.coef}, {w.h2});
}
if (rad_op_reads(b, op_fconv[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
if (block_lo && rad_op_reads(b, op_fconv_lo[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",
@@ -909,6 +940,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
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)
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),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", block_lo), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pred, w_succ)),
{w.cand, w.unary, w.hp}, {w.tokens});
/* The reads beside the all-reduces, after every weight they read is declared. */
if (op_ar && cfg.prefetch > 0)
@@ -983,6 +1022,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
const int64_t NG = cfg.ng(g.n_embd);
const int64_t half = cfg.taps * NG; /* prepare's coefficients, then finish's */
/* The block this pass was staged at: every drafting sequence carries the same number of rows,
* the drafter's own block or its short one (rad_drafter_short_block). */
const int64_t blk = batch->n_seq > 0 && T % batch->n_seq == 0 ? T / batch->n_seq : 0;
const bool lo = block_lo > 0 && blk == block_lo;
if (!lo && blk != cfg.block) {
rad_step_fail(c, "dflash2: a query pass staged at a block this drafter has no ops for");
return;
}
const rad_op* aconv = lo ? op_aconv_lo : op_aconv;
const rad_op* fconv = lo ? op_fconv_lo : op_fconv;
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
@@ -1005,7 +1055,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
/* ---- attention, wrapped in the two halves of one convolution */
norm(op_anorm[i], op_aan[i], w_anorm[i]);
RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T));
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
RAD_ISSUE_N(c, aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
@@ -1044,14 +1094,14 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
* 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),
RAD_ISSUE_N(c, 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));
add_pending = true;
/* ---- the feed-forward, wrapped in the other convolution */
norm(op_fnorm[i], op_afn[i], w_fnorm[i]);
RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T));
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
if (op_gug[i] && T <= gated_rows) {
@@ -1068,7 +1118,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pff[i][j], pff_w[i][j], T);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
add_pending = true;
}
@@ -1107,7 +1157,7 @@ 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, op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, 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));
+12 -5
View File
@@ -139,6 +139,13 @@ struct GdnFP8 {
* trailing add, which would read the delta before the reduction. */
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
ArPieces* pieces = nullptr) const;
/* Whether step() with `own_ar` false runs the whole block a piece at a time over `pieces`
* (its piece path), asked by a caller that must know before it commits to a schedule. */
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
return pieces && pieces->cu && pieces->cuts(batch->n_tok) &&
batch->n_tok <= 2 * pieces->rows && (ext_in || pieces->in_ready) && !op_add &&
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL;
}
/* Whether a step of T rows issues the all-reduce itself, asked by a caller before taking it
* over; and that all-reduce over rows [r0, r0 + rows) of the output. */
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
@@ -389,10 +396,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* piece the chunk a span of 1 makes (the projection over its rows; the convolution, solve and
* scan over its bounds, with the state handed on through the cache; the gated norm, quantiser
* and out projection), so the first piece's reduction runs beside all of the second piece's
* work. The second piece reads the history the first left in the convolution slot: a spanned
* step is past the prompt's first interval, so its context length is never zero. */
if (!own_ar && pieces && pieces->cu && pieces->cuts(T) && T <= 2 * pieces->rows && ext_in &&
!op_add && S == 1 && batch->phase == RAD_PHASE_PREFILL) {
* work. The second piece reads the history the first left in the convolution slot, so each
* piece passes its own context length, its first row's position: the step's would tell the
* second piece of a prompt's first chunk that it has none. */
if (!own_ar && takes_pieces(batch, pieces)) {
const int64_t in_w = conv_dim + v_dim;
for (int64_t p = 0; p < 2; ++p) {
const int64_t r0 = p * pieces->rows;
@@ -405,7 +412,7 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log),
RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2),
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
praw(cv_idx, RAD_I32, 1), praw(batch->ctx_lens, RAD_I32, 1),
praw(cv_idx, RAD_I32, 1), praw(batch->positions + r0, RAD_I32, 1),
brows(w.q, T), brows(w.k, T), brows(w.v, T),
brows(w.gdec, T), brows(w.beta, T));
RAD_ISSUE_N(c, op_kkt, n,
+74 -9
View File
@@ -19,6 +19,15 @@
* replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the
* image rows are not scaled).
*
* Clipped linears (vision_config.use_clipped_linears, Gemma 4 E2B/E4B): every projection clamps its
* input and its output to bounds the checkpoint stores (`<proj>.input_min/max`, `output_min/max`;
* transformers' Gemma4ClippableLinear). The tower keeps its fused q|k|v and gate|up GEMMs, so it
* takes the input bounds of q_proj (and of gate_proj) for the fused input, q_proj's output bounds for
* q's columns, k_proj's for k's and v's, and gate_proj's output bounds for gate|up. That is exact
* where the fused parts share their bounds, as NVIDIA's E4B does in all 16 layers (k and v share the
* input bounds of q and their output bounds, up shares gate's). The bound weights are one bf16
* element each, read by `clamp`.
*
* One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
* image, or one frame of a video). Every rank runs the whole tower (engine_mm.cpp), so its weights
* are replicated (RAD_SHARD_NONE) and each rank writes the rows into its own copy of the embedding
@@ -41,8 +50,12 @@ struct Gemma4Vision {
rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
/* clipped linears: the bounds (lo, hi) of the nine clamps, and the clamps */
enum { C_QKV_IN, C_Q_OUT, C_KV_OUT, C_O_IN, C_O_OUT, C_GU_IN, C_GU_OUT, C_DN_IN, C_DN_OUT, C_N };
rad_weight lo[C_N] = {}, hi[C_N] = {};
rad_op op_c[C_N] = {};
};
bool on = false, standardize = false;
bool on = false, standardize = false, clip = false;
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
int64_t npos = 0, n_embd = 0;
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
@@ -88,15 +101,14 @@ struct Gemma4Vision {
(long long)pool, (long long)depth);
return RAD_E_INVAL;
}
/* Clipped linears (their bounds are buffers the vision checkpoint states as infinite) and
* any rotary or activation other than the 2-D one and gelu-tanh are refused by name. */
if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
(std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
/* Any rotary or activation other than the 2-D one and gelu-tanh is refused by name. */
if ((std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
std::strcmp(act, "gelu_pytorch_tanh")) {
fprintf(stderr, "radiance: %s: this vision tower uses clipped linears, a '%s' rotary or "
"a '%s' activation, which it does not serve\n", who, rt, act);
fprintf(stderr, "radiance: %s: this vision tower uses a '%s' rotary or a '%s' "
"activation, which it does not serve\n", who, rt, act);
return RAD_E_UNSUPPORTED;
}
clip = rad_meta_geti(m, "vision_config.use_clipped_linears", 0) != 0;
n_embd = model_embd;
patch_dim = 3 * patch * patch;
const int64_t kk = pool * pool;
@@ -154,6 +166,27 @@ struct Gemma4Vision {
l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g);
l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g);
l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g);
if (clip) {
/* clamp k -> the checkpoint projection whose bound it takes, and which bound */
static const char* const proj[Layer::C_N] = {
"self_attn.q_proj", "self_attn.q_proj", "self_attn.k_proj", "self_attn.o_proj",
"self_attn.o_proj", "mlp.gate_proj", "mlp.gate_proj", "mlp.down_proj",
"mlp.down_proj" };
static const bool in_side[Layer::C_N] = { true, false, false, true, false, true,
false, true, false };
for (int k = 0; k < Layer::C_N; ++k) {
const char* side = in_side[k] ? "input" : "output";
const char* lo_n = nm.f("v.blk.%lld.clip%d.lo", li, k);
const char* hi_n = nm.f("v.blk.%lld.clip%d.hi", li, k);
RAD_ARCH_TRY(map_copy(b, lo_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_min", V, li,
proj[k], side)));
RAD_ARCH_TRY(map_copy(b, hi_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_max", V, li,
proj[k], side)));
l.lo[k] = decl_w(b, lo_n, RAD_BF16, {1}, A, N, g);
l.hi[k] = decl_w(b, hi_n, RAD_BF16, {1}, A, N, g);
if (!l.lo[k] || !l.hi[k]) return RAD_E_INVAL;
}
}
}
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
@@ -198,6 +231,11 @@ struct Gemma4Vision {
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
RAD_WEIGHTS(w));
};
auto clamp = [&](int64_t n, rad_weight lo, rad_weight hi) {
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(lo, hi));
};
auto gain = [&](rad_weight w) {
return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)),
@@ -212,6 +250,19 @@ struct Gemma4Vision {
char sec[48];
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
for (Layer& l : L) {
/* the clamps, each in place on the one buffer its linear reads or writes (each of those
* is read by that linear alone, or by what follows it) */
if (clip) {
using C = Layer;
const struct { int k; int64_t n; rad_buf buf; } cl[C::C_N] = {
{ C::C_QKV_IN, width, b_h }, { C::C_Q_OUT, width, b_qkv },
{ C::C_KV_OUT, 2 * width, b_qkv }, { C::C_O_IN, width, b_att },
{ C::C_O_OUT, width, b_o }, { C::C_GU_IN, width, b_h },
{ C::C_GU_OUT, 2 * ff, b_gu }, { C::C_DN_IN, ff, b_ff },
{ C::C_DN_OUT, width, b_o } };
for (const auto& e : cl)
l.op_c[e.k] = rw(b, clamp(e.n, l.lo[e.k], l.hi[e.k]), {e.buf}, {e.buf});
}
l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
@@ -272,10 +323,11 @@ struct Gemma4Vision {
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"pooled %lldx%lld%s; %lld patches a pass -> %lld rows of %lld",
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
(long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
(long long)patch, (long long)pool, (long long)pool,
standardize ? ", standardised" : "", (long long)P, (long long)R,
standardize ? ", standardised" : "", clip ? ", clipped linears" : "",
(long long)P, (long long)R,
(long long)n_embd);
on = true;
return RAD_OK;
@@ -299,20 +351,33 @@ struct Gemma4Vision {
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
/* a clamp of operand `x` in place, when the tower clips */
auto cl = [&](const Layer& l, int k, RadOperand x) {
if (clip) RAD_ISSUE_N(c, l.op_c[k], Pn, x, RAD_W(l.lo[k]), RAD_W(l.hi[k]), x);
};
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
cl(l, Layer::C_QKV_IN, brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
cl(l, Layer::C_Q_OUT, bcol(b_qkv, 0, width, Pn));
cl(l, Layer::C_KV_OUT, bcol(b_qkv, width, 2 * width, Pn));
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
cl(l, Layer::C_O_IN, brows(b_att, Pn));
RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
cl(l, Layer::C_O_OUT, brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
cl(l, Layer::C_GU_IN, brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
cl(l, Layer::C_GU_OUT, brows(b_gu, Pn));
RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
brows(b_ff, Pn));
cl(l, Layer::C_DN_IN, brows(b_ff, Pn));
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
cl(l, Layer::C_DN_OUT, brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
}
+2 -4
View File
@@ -151,7 +151,8 @@ struct GlmKda {
!w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out ||
w.forget_low == w.gate_low)
return RAD_E_INVAL;
// All seven projections are plain BF16 in the pinned checkpoint.
// All seven projections are plain bf16 in the pinned checkpoint; under w_bf16,
// LinearFP8::declare refuses a quantised one by name.
Geom bg = g;
bg.w_bf16 = true;
const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world);
@@ -193,9 +194,6 @@ struct GlmKda {
RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width,
RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) },
act(w.core.out), w.out));
if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 ||
!gate_b.bf16 || !output.bf16)
return RAD_E_UNSUPPORTED;
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
+119 -5
View File
@@ -3,14 +3,23 @@
* complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent
* for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual.
*
* Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and
* kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are
* replicated. */
* Under tensor parallelism the head form splits the 64 heads over the ranks (GlmTp::heads): the
* rows of q_b and kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent
* cache are replicated. From GlmTp::kSplitRows a prefill-sized step takes the row form instead
* (Wire::rows, Form::rows): each rank runs its run of the step's rows (GlmTp::run_of) through q_b,
* absorption, attention, expansion and the output projection with all 64 heads, then an
* all_gather lays the runs out as the whole step. The latent cache and the selection are whole on
* every rank already, so the split needs no other exchange. The gather moves half the bytes of
* the head form's all-reduce, and the attention loads each key once for all 64 heads of a row.
* The price is the three projections at full width on every rank (126 MB a layer); RowsWire::q
* unset declares neither them nor the form. */
#ifndef RAD_BLOCK_GLM_MLA_H
#define RAD_BLOCK_GLM_MLA_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
#include <algorithm>
#include <cmath>
#include <vector>
namespace rad {
namespace arch {
@@ -88,11 +97,28 @@ struct MlaLatent {
};
struct GlmMla {
/* How a prefill-sized step under tensor parallelism runs: `heads` keeps the head form at every
* step size and spares the full-width weights' VRAM; `rows` is the row form. The plugin
* chooses (RadBuildCtx::tp_attn_rows); the block takes the choice through whether it is given
* RowsWire buffers. */
enum class Form { heads, rows };
/* The row form's buffers, `rows_for(max_tok)` rows each. `out` (Wire::out) must hold
* world * rows_for(T) rows, since every rank's run is gathered at full length. */
struct RowsWire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0;
ActFP8 attn{};
};
struct Wire {
ActFP8 input{}, q_low{}, attn{};
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
MlaLatent::Wire core{};
RowsWire rows{};
};
/* The gathered row of the row form: 4096 bf16, so a run is ceil(T / world) rows. */
static constexpr int64_t kOutRowBytes = 4096 * 2;
static int64_t rows_for(int64_t T, int world) {
return GlmTp::run_rows(T, world, kOutRowBytes);
}
Geom g{};
Wire w{};
int layer = 0;
@@ -103,6 +129,10 @@ struct GlmMla {
MlaLatent core{};
rad_weight q_gain = 0, kv_gain = 0;
rad_op op_kv_norm = 0, op_store = 0, op_ar = 0;
LinearFP8 rows_q_b{}, rows_output{};
QuantFP8 rows_quant{};
rad_weight rows_kv_b = 0;
rad_op op_rows_absorb = 0, op_rows_attn = 0, op_rows_expand = 0, op_rows_gather = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, rad_kvgroup group, bool reduce = true,
bool defer_finish = false) {
@@ -160,7 +190,69 @@ struct GlmMla {
GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer),
{ nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out));
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL;
if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL;
return reduce ? declare_rows(b, nm, prefix) : RAD_OK;
}
/* Declared whatever the step size, as every TP split here is: arena levels declare again at a
* smaller max_tok and must get the same graph. The gather's message bound is the all-reduce's,
* so both share one exchange instance and its scratch. */
int declare_rows(RadBuilder* b, Names& nm, const char* prefix) {
const auto& r = w.rows;
if (!r.q || g.world < 2) return RAD_OK;
if (!r.q_latent || !r.attn_latent || !r.out || !r.attn.x || r.attn.x == r.q) return RAD_E_INVAL;
const int64_t R = rows_for(g.max_tok, g.world);
const auto wg = grp_layer(layer);
/* Whole views of the head form's container entries: one stored weight each, whose
* encoding (block fp8 at f32 scales, the decoded bf16 kv_b) the views inherit. */
rows_q_b.stored = nm.f("blk.%d.attn_q_b.weight", layer);
RAD_ARCH_TRY(rows_q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b_rows", layer), 16384, 1536,
RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
w.q_low, r.q, R));
rows_kv_b = decl_view(b, nm.f("blk.%d.attn_kv_b_rows.weight", layer),
nm.f("blk.%d.attn_kv_b.weight", layer), nullptr, RAD_BF16,
{ 64 * 2 * 256, 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
if (!rows_kv_b) return RAD_E_INVAL;
auto project = [&](const char* mode, rad_buf in, rad_buf out) {
return rw(b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("heads", 64),
RAD_INT("head_dim", 256), RAD_INT("latent_dim", 512),
RAD_STR("mode", mode), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(rows_kv_b)),
{ in }, { out });
};
op_rows_absorb = project("absorb", r.q, r.q_latent);
op_rows_attn =
rw(b,
RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512),
RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks),
RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
op_rows_expand = project("expand", r.attn_latent, r.attn.x);
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
RAD_ARCH_TRY(rows_output.declare(b, nm, g, nm.f("blk.%d.attn_output_rows", layer), 4096,
16384, RAD_SHARD_NONE, wg,
{ nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, r.out,
R));
op_rows_gather = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4096, g.max_tok * 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ r.out }, { w.out });
return op_rows_absorb && op_rows_attn && op_rows_expand && op_rows_gather ? RAD_OK
: RAD_E_INVAL;
}
/* From the TP split threshold, and while the last rank's run is not empty (always at that
* threshold for up to 8 ranks); the same answer on every rank, as the gather needs. */
bool rows_take(int64_t T) const {
return op_rows_gather && GlmTp::splits(T, g.world) &&
(g.world - 1) * rows_for(T, g.world) < T;
}
void prepare(RadCtx* ctx, const RadBatch* batch) const {
const auto* kb = kv_batch(batch, kv);
@@ -173,17 +265,39 @@ struct GlmMla {
kv_a.step(ctx, w.input, w.kv_raw, T);
q_norm.step(ctx, T);
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T));
q_b.step(ctx, w.q_low, w.core.q, T);
if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T);
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
}
void finish(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (rows_take(T)) {
finish_rows(ctx, T);
return;
}
core.step(ctx, T);
attn_quant.step(ctx, T);
output.step(ctx, w.attn, w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
/* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the
* gather sends its unwritten tail rows, which land past T. */
void finish_rows(RadCtx* ctx, int64_t T) const {
const auto& r = w.rows;
const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kOutRowBytes);
const int64_t first = run.first, n = run.rows;
rows_q_b.step(ctx, w.q_low, r.q, T, first, n, 0);
RAD_ISSUE_N(ctx, op_rows_absorb, n, brows(r.q, n), RAD_W(rows_kv_b), brows(r.q_latent, n));
RAD_ISSUE_N(ctx, op_rows_attn, n, brows(r.q_latent, n), kv_cache(kv, layer),
brow_slice(w.core.selected, first, n, core.c.blocks),
brow_slice(w.core.length, first, n, 1), brows(r.attn_latent, n));
RAD_ISSUE_N(ctx, op_rows_expand, n, brows(r.attn_latent, n), RAD_W(rows_kv_b),
brows(r.attn.x, n));
rows_quant.step(ctx, n);
rows_output.step(ctx, r.attn, r.out, n);
RAD_ISSUE_N(ctx, op_rows_gather, run.run * 4096, brows(r.out, run.run),
brows(w.out, g.world * run.run));
}
};
}
} // namespace rad::arch
+1 -1
View File
@@ -1,7 +1,7 @@
/* rad_block_glm_vision.h -- GLM-5.3's vision tower (transformers' Glm5NextVisionModel), served by
* glm5next.
*
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
* What it computes, per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the Conv3d patch embedding as a linear layer; a
* patch row is (channel, frame, y, x), no position
+20 -27
View File
@@ -365,36 +365,25 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
}
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
* every block leaves its delta in the activation its norm produced, and the input is dead by
* then. */
/* ================================================================== the control-vector projection
*
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). Turned on
* for a request, a steered layer's wide stream is projected off that layer's direction right after
* the feed-forward's write:
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). For a
* request that takes it, a steered layer's wide stream loses its component along that layer's
* direction right after the feed-forward's write:
*
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
*
* which is llama.cpp's `--cvec-mode project` and the operation the Qwen3.8-Flash-Next package
* documents. The dot is per stream, not on the stream mean: the patch applies it to the
* [n_embd, hc, tokens] view where `mul_mat(v, cur)` reduces over dim 0 alone.
* This is llama.cpp's `--cvec-mode project`. The dot is per stream, not on the stream mean, as
* llama.cpp's `mul_mat(v, cur)` over the [n_embd, hc, tokens] view reduces dim 0 alone.
*
* Two properties the architecture plugin does not have to think about, both here:
* The switch is per request: `on` is a derived buffer of one int32 per row
* (core/sched/derive.cpp, `projection_on_rows`), so a step that mixes a projected conversation
* with a stock one projects only the rows that asked. The kernel neither reads nor writes a zero
* row, and a pass with no row on issues nothing (RadBatch::control_vector). `scale` is the norm
* the file stored for the layer times the package's own scale.
*
* - **the switch is per request.** `on` is a derived buffer of one int32 per token row
* (core/sched/derive.cpp's `projection_on_rows`), so a step that mixes a projected
* conversation with a stock one projects exactly the rows that asked for it. All zeros is the
* stock model: the kernel skips a zero row without reading or writing it, so an unprojected
* request's stream is the one the stock model computes. (The *deployment* is not bit-identical
* to one with no vector: the direction table's VRAM can move an expert or a KV block, which is
* the tie-level variance radiance documents elsewhere. Measured, docs/GUIDE.md 4.10.)
* - **the parameters travel with the file.** `scale` is the norm the file stored for that layer
* (times the package's own `scale`, read from its JSON), and the direction row is sliced from
* the table at issue, so nothing is configured per deployment or scanned per layer.
*
* One instance per layer: `declare` emits an op only when the vector steers that layer, so a
* deployment without a vector declares no op, no buffer and no branch in the step. */
* One instance per layer; `declare` emits an op only where the vector steers, so a deployment
* without a vector declares no op and no buffer. */
struct HcProject {
rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */
const float* dir = nullptr; /* this layer's row of the device direction table */
@@ -456,9 +445,10 @@ struct HcProject {
}
/* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one
* call per piece, in the same place in the graph. */
void step(RadCtx* c_, int64_t r0, int64_t rows) const {
if (!op) return;
* call per piece, in the same place in the graph. Nothing is issued on a pass where no row
* takes the vector (RadBatch::control_vector): every row would be skipped. */
void step(RadCtx* c_, const RadBatch* batch, int64_t r0, int64_t rows) const {
if (!op || !batch || !batch->control_vector) return;
RAD_ISSUE_N(c_, op, rows,
brow_slice(h, r0, rows, hc * n),
praw(dir, RAD_F32, n),
@@ -466,6 +456,9 @@ struct HcProject {
}
};
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
* every block leaves its delta in the activation its norm produced, and the input is dead by
* then. */
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
if (!op_write) return;
if (takes_gather(T)) {
+33
View File
@@ -75,6 +75,20 @@ struct MlpFP8 {
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
/* The slice in its parts, for a caller that runs the norm and the tail elsewhere (qwen35_fp8's
* pipelined prefill puts both on the second lane): the projections from the normed input to
* the delta in `w.h.x`, then the all-reduce and add this block issues itself. */
void body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
void tail(RadCtx* c, int64_t r0, int64_t rows) const;
/* The block's all-reduce over rows [r0, r0 + rows) of the output, at `overlap` where declared
* (a caller that runs it beside other work). */
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
}
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
int ar_overlap = 0;
rad_op op_ar_ov = 0;
};
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
@@ -129,6 +143,17 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{w.h.x}, {w.h.x});
/* The same collective for a caller that runs it beside other work (issue_ar): at `overlap` 1
* it gets the rows that hold fewer CUs while waiting on the link. */
if (g.world > 1 && ar_overlap > 0)
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes),
RAD_INT("overlap", ar_overlap)),
RAD_NOWEIGHTS),
{w.h.x}, {w.h.x});
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
if (add_out)
@@ -149,6 +174,11 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
if (rows <= 0) rows = T - r0;
nq_h.step(c, T, r0, rows);
body(c, T, r0, rows);
tail(c, r0, rows);
}
inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
if (op_gated && rows <= gated_rows) {
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
@@ -160,6 +190,9 @@ inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const
gq_ffn.step(c, w.gate_up, T, r0, rows);
}
down.step(c, w.ffn, w.h.x, T, r0, rows);
}
inline void MlpFP8::tail(RadCtx* c, int64_t r0, int64_t rows) const {
if (op_ar && !(ar_out && ar_fused_ok(g, rows)))
RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
if (op_add)
+40
View File
@@ -73,6 +73,7 @@
#include "rad_block_hc.h"
#include "rad_block_moe_fp8.h"
#include "rad_block_mtp_fp8.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire */
#include "rad_qsa.h"
#include "rad_block_vit.h"
@@ -108,6 +109,9 @@ struct MtpHcBlock {
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
rad_buf dpair = 0, dgath = 0;
/* --draft-coupling: [max_seqs] draws and [depth, max_seqs] states, both PERSIST across
* the serial passes (round 1 resets the logical stream, not the plane). */
rad_buf couple_draws = 0, couple_state = 0;
AttnGatedFP8::Wire attn{};
MoeFP8::Wire mlp{};
QsaIndexer::Wire qsa{};
@@ -158,6 +162,9 @@ struct MtpHcBlock {
rad_op op_dsel = 0, op_dback = 0;
rad_op op_logits = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0;
rad_op op_dgather = 0, op_dmerge = 0;
/* --draft-coupling: one op a round. The ABI freezes `round` as a parameter, so a round
* cannot be an operand and each gets its own declared op. */
rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
/* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
* planes. */
@@ -422,6 +429,25 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
if (!op_dgather || !op_dmerge) return RAD_E_INVAL;
}
if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
/* The coupled proposal: one op a round, after the final rerank/merge, over the shortlist
* whose column 0 is the proposal. Linear chains only: x is a token, while a tree reads
* column 0 as a parent index. The engine refuses other drafters; this check keeps a
* mismatched declaration from writing tokens into a tree plane. */
if (w.couple_draws || w.couple_state) {
if (!w.couple_draws || !w.couple_state || depth < 1 ||
depth > RAD_MTP_COUPLE_MAX_ROUNDS || !op_drerank || (g.world > 1 && !op_dmerge))
return RAD_E_UNSUPPORTED;
for (int round = 1; round <= depth; ++round) {
op_couple[round - 1] = rw(b, RAD_OP(b, "mtp_couple_propose",
/* The whole vocabulary: `row_topk` reports global ids and the merge keeps
* them, while `g.n_vocab` is this rank's shard. */
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("round", round), RAD_INT("max_rounds", depth)),
RAD_NOWEIGHTS),
{ w.didx, w.dval, w.couple_draws }, { w.didx, w.couple_state });
if (!op_couple[round - 1]) return RAD_E_INVAL;
}
}
}
/* Keep the carry `hin` live through the head's last op: it is written before the mixer and
* lm_head run, and the planner could otherwise give its bytes to them (silently lowering
@@ -429,6 +455,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
{
rad_op last = op_logits;
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
if (op_couple[0]) last = op_couple[depth - 1];
if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL;
}
return RAD_OK;
@@ -524,6 +551,19 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
brows(w.didx, L), brows(w.dval, L), RAD_NONE);
}
/* After the final reranked shortlist: column 0 is what ADV_TAKE reads, and a sampled row
* replaces it with its x. Round 1 runs in the history pass (r < 0), later rounds in their
* own passes. */
if (op_couple[0]) {
const int round = r < 0 ? 1 : r;
if (round < 1 || round > depth) {
rad_step_fail(c, "MTP coupled round exceeds the declared draft depth");
return;
}
RAD_ISSUE_N(c, op_couple[round - 1], L, brows(w.didx, L), brows(w.dval, L),
praw(batch->seq_ids, RAD_I32, batch->n_seq),
brows(w.couple_draws, L), RAD_B(w.couple_state));
}
} else {
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
}
File diff suppressed because it is too large. Load diff
+67 -16
View File
@@ -296,6 +296,10 @@ struct ArPieces {
* chunk a span of 1 makes, the state carried through the cache) and hand off the first
* piece's reduction before the second piece's projection. Null for any other step. */
const int32_t* cu = nullptr;
/* The caller normed each piece's input itself (qwen35_fp8's pipelined prefill, on the second
* lane behind the previous block's piece), so a block with its own norm takes the piece path
* as one with an external input does and skips that norm. */
bool in_ready = false;
bool cuts(int64_t T) const { return done && rows > 0 && T > rows; }
void hand(int64_t r0, int64_t n) { done(u, r0, n); ++handed; }
};
@@ -395,6 +399,9 @@ struct NormQuantFP8 {
}
/* Asked by the preceding block before issuing its own collective. */
bool takes_ar(int64_t T) const { return pick(T) != op; }
/* The plain op whatever the wire, for a caller that issued the preceding all-reduce itself
* (qwen35_fp8's pipelined prefill, which runs it narrow beside compute). */
void step_plain(RadCtx* c, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
};
inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, rad_buf x,
@@ -472,6 +479,16 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
return RAD_OK;
}
/* step() below with the plain op, whatever the wire. */
inline void NormQuantFP8::step_plain(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
if (rows <= 0) rows = T - r0;
RAD_ISSUE_N(c, op, rows, brow_slice(src, r0, rows, n),
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
brow_slice(a.q, r0, rows, n),
brow_slice(a.s, r0, rows, n / RAD_FP8_BLOCK),
brow_slice(a.x, r0, rows, n));
}
/* `r0`/`rows` select a row slice, defaulting to the whole step (`brow_slice` at offset 0 equals
* `brows`). Slicing lets a block run in passes (the routed feed-forward). Each slice must land in
* the same bucket-table band as the whole (core/runtime/ctx.h), or a different kernel with a
@@ -755,6 +772,10 @@ struct LinearFP8 {
* this is set; otherwise the linear reads unwritten arena bytes. */
bool reads_x = false;
bool mapped = false; /* probe() made the name map; declare() does not make it again */
/* The stored weight this linear's views take when it is not `<base>.weight`: a second linear
* over one container entry, e.g. a whole projection beside its tensor-parallel slice. Set
* before declare(); no name map is made, and only block fp8 is served this way. */
const char* stored = nullptr;
/* The weight's access class (rad_builder.h): read every pass by default; a linear run once a
* request (an encoder's) says so, which lets placement keep it off the card. Set before
* declare(). */
@@ -808,8 +829,10 @@ struct LinearFP8 {
rad_weight decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc,
int64_t K,
RadWeightGroup grp);
/* Rows [r0, r0 + rows) of the input into the same rows of `y`, or from row `y0` of `y` when
* that is set: a rank's run of a step's rows written to a buffer sized for the run. */
void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0,
int64_t rows = 0) const;
int64_t rows = 0, int64_t y0 = -1) const;
/* A span per stacked row part (rad_weight_shard_span_parts), in weight rows; the scale plane
* gets the same spans in its rows. Call after declare(). With a 1/128 plane every span and
* total must be whole scale blocks. */
@@ -1047,9 +1070,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
/* Name map first: the weight's encoding, looked up through it, picks the branch below. */
const char* wn = nm.f("%s.weight", base);
if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src));
if (!mapped && !stored) RAD_ARCH_TRY(map_linear(b, wn, src));
const char* sw = stored ? stored : wn;
RadEncoding enc{};
const bool known = weight_enc(b, wn, &enc);
const bool known = weight_enc(b, sw, &enc);
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16;
@@ -1059,11 +1083,17 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
* constraints. */
bf16 = g.w_bf16 || plain;
if (bf16) {
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
"may\n", wn, stored);
return RAD_E_INVAL;
}
if (known && !plain) {
char en[256];
rad_enc_format(&enc, en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s and this model's linears are plain bf16; a "
"bf16 container is served bf16 throughout\n", wn, en);
fprintf(stderr, "radiance: '%s' is %s, but this linear runs as a plain bf16 GEMM "
"(a bf16 model, or a block that keeps its linears bf16); the "
"container must store it bf16\n", wn, en);
return RAD_E_DTYPE;
}
/* A bf16 weight needs the input's bf16 plane, which a quantised model's producer may not
@@ -1097,6 +1127,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const bool rot8 = known && linear_is_w8h(enc);
i8 = known && (linear_is_w8(enc) || rot8);
if (i8) {
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
"may\n", wn, stored);
return RAD_E_INVAL;
}
/* Upstream's rot guard: fed codes must match the weight's rotation form. */
if (a.q8_fed && rot8 != a.q8_rot) {
fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its "
@@ -1161,6 +1196,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
* codes, and (scale, zero) as `b_scale`. */
paro5 = known && linear_is_paro_w5(enc);
if (paro5) {
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
"may\n", wn, stored);
return RAD_E_INVAL;
}
const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5;
if (!a.x) {
fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight, rotated from its input's "
@@ -1227,6 +1267,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
* whole 128s, the scale group. */
w4 = known && linear_is_w4(enc);
if (w4) {
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
"may\n", wn, stored);
return RAD_E_INVAL;
}
if (!a.x) {
fprintf(stderr, "radiance: '%s' is a 4-bit weight, read from its input's bf16 plane, "
"and its input has none\n", wn);
@@ -1297,6 +1342,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
paro = known && linear_is_paro_mxfp4(enc);
mx = known && (linear_is_mxfp4(enc) || paro);
if (mx) {
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
"may\n", wn, stored);
return RAD_E_INVAL;
}
if (paro) {
/* The rotation is applied to the activation, so this linear needs the input's bf16
* plane (probe() set reads_x) and quantises it itself. */
@@ -1408,10 +1458,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32;
/* One stored weight, two operands: the codes and scale plane of `<base>.weight`, block fp8 in
* the checkpoint or made so by rad-convert's recipe. */
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K },
w = decl_view(b, wn, stored, "codes", RAD_F8E4M3, { N, K },
access, shard, grp, rp.w, rp.n);
ws_row_div = RAD_FP8_BLOCK;
ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16,
ws = decl_view(b, sn, sw, "scale", f32_scale ? RAD_F32 : RAD_BF16,
{ fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n);
if (!w || !ws) return RAD_E_INVAL;
/* An uneven slice; the scale plane takes the same slice in blocks. */
@@ -1443,10 +1493,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
* asymmetric integer and mxfp4 grids) are passed as RAD_NONE when unused, since the runtime checks
* the operand count against the schema (core/runtime/issue.cpp). */
inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0,
int64_t rows) const {
int64_t rows, int64_t y0) const {
if (rows <= 0) rows = T - r0;
const int64_t yr = y0 < 0 ? r0 : y0;
if (bf16) {
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, r0, rows, N));
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, yr, rows, N));
return;
}
if (i8) {
@@ -1455,7 +1506,7 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK));
RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K),
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK),
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
return;
}
/* The 4-bit weight's copies of the input start at their buffers' first row: they live only
@@ -1465,13 +1516,13 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK));
RAD_ISSUE_N(c, op2, rows, brow_slice(a8q, 0, rows, K),
brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK), RAD_W(w), RAD_W(ws),
brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (w4) {
RAD_ISSUE_N(c, op_a16, rows, brow_slice(a.x, r0, rows, K), brow_slice(a16, 0, rows, K));
RAD_ISSUE_N(c, op, rows, brow_slice(a16, 0, rows, K), RAD_NONE, RAD_W(w), RAD_W(ws),
brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (paro5 && rot_split && rows > rot_split) {
@@ -1480,14 +1531,14 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)));
RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K),
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)),
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (paro5) {
RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs),
RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q, r0, rows, rot_parts * K));
RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), RAD_NONE,
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (mx) {
@@ -1501,12 +1552,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK));
RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak),
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK),
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref));
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_W(wref));
return;
}
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
}
/* ================================================== an fp8 weight with no op of its own
+34 -20
View File
@@ -40,7 +40,8 @@
* The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
* four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
* layers and `False` on the full one, so this block declares two attention ops and issues the one
* each layer's type names.
* each layer's type names. A config that states `dflash_config.causal` (NVIDIA's E4B drafter:
* false, all five layers sliding) sets the sliding layers' causality.
*
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
* cap * tanh(x / cap) is strictly increasing.
@@ -115,18 +116,15 @@ inline double embed_scale(int64_t hidden) {
/* prefetch where a library serves it: the 31B trunk reading the next GEMM's leading weight bytes
* into the on-die cache beside the all-reduce in front of that GEMM, at decode heights (on lane 0
* as a chained read, or on the second lane: rad_arch.h prefetch_lane0), and the DFlash2 drafter's
* reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB. With
* the reads on lane 0 (two rounds on 4x R9700): 20 MB 391 / 391 code tok/s, 289 / 288 prose;
* 16 MB 386 / 384, 285 / 283; 24 MB 388 / 387; 12 MB 368 / 369. */
* reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB: on 4x
* R9700 with the reads on lane 0, 16 and 24 MB decoded 1-2% slower and 12 MB about 6%. */
constexpr int64_t kPrefetchBytes = (int64_t)20 << 20;
/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention. It
* took the place of o_proj's read there: the 31B at tp 4 on 4x R9700, two rounds, every reply
* identical, 380 / 281 / 203 tok/s against 367 / 271 / 196 with o_proj's 16 MB; 10, 11, 12, 14
* and 20 MB of down_proj 379, 377, 373, 373 and 362; down_proj beside o_proj's read, or beside the
* feed-forward reduction, slower than either alone. The reads beside a reduction are one queue,
* and a longer one beside the attention pushes gate_up's read past the reduction it should hide
* in. */
/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention, in
* place of a read of o_proj there (about 3.5% faster on the 31B at tp 4 on 4x R9700; 10-20 MB of
* down_proj were slower, as were two reads beside one reduction). The reads beside a reduction
* are one queue, and a longer one beside the attention pushes gate_up's read past the reduction
* it should hide in. */
constexpr int64_t kPrefetchDownBytes = (int64_t)9 << 20;
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
@@ -166,8 +164,8 @@ inline long long dflash_block(const RadModelMeta* meta) {
/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less
* the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). True when the
* container carries one and `out` now names its depth. Chained launches measured a gain with it
* (the 26B-A4B's speculative step, +1% on 4x R9700), so the probe asks for them
* container carries one and `out` names its depth. Chained launches pay with it (the 26B-A4B's
* speculative step is 1% faster on 4x R9700), so the probe asks for them
* (RadArchProbe::chain_pays). */
inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
if (dflash_kind(meta) != 1) return false;
@@ -181,8 +179,8 @@ inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
/* The same for a DFlash2 drafter, for a plugin that serves rad_block_dflash2.h (the 31B's): its
* anchor predicts nothing either, so the depth is the trained block less one, 7 for RedHatAI's
* gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches measured a gain with it (the
* 31B's speculative step, +13% on 4x R9700), so the probe asks for them. */
* gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches pay with it (the 31B's
* speculative step is 13% faster on 4x R9700), so the probe asks for them. */
inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
if (dflash_kind(meta) != 2) return false;
const long long bs = dflash_block(meta);
@@ -238,6 +236,7 @@ struct Dflash1 {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */
int64_t window = 0; /* the sliding layers' window; 0 for none */
int causal = 1; /* the sliding layers: causal (z-lab) or not (dflash_config.causal) */
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
int64_t kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */
@@ -519,7 +518,12 @@ inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int
int64_t p[RAD_MAX_ROW_PARTS] = {0};
int np = 0;
for (int64_t q : row_parts) {
if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL;
if (np >= RAD_MAX_ROW_PARTS || q % 16) {
fprintf(stderr, "radiance: '%s' has a %lld-row part per rank; an int8 weight takes at "
"most %d parts, each a multiple of 16 rows.\n", base, (long long)q,
(int)RAD_MAX_ROW_PARTS);
return RAD_E_INVAL;
}
p[np++] = q;
}
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp, p, np);
@@ -582,7 +586,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
return RAD_E_UNSUPPORTED;
}
dc.block = trained;
if (dg.n_layer > MAX_LAYERS) return RAD_E_UNSUPPORTED;
if (dg.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: gemma4: the DFlash drafter has %lld layers; this block carries "
"at most %d\n", (long long)dg.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
{
std::vector<int> full;
const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr);
@@ -610,6 +618,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
"window\n");
return RAD_E_INVAL;
}
/* z-lab's configs state no causality and train the sliding layers causal; NVIDIA's
* (Nemotron-3.5-Bolt-E4B's DFlash) states `dflash_config.causal: false`, every layer
* sliding and non-causal over its window. */
dc.causal = rad_meta_geti(meta, "draft.dflash_config.causal",
rad_meta_geti(meta, "draft.is_causal", 1)) != 0 ? 1 : 0;
}
}
if (!head_sharded(dg) && dg.world > 1) {
@@ -664,11 +677,12 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
int nfull = 0;
for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l];
rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld "
"sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the "
"sliding over %lld, %s), %lld heads / %lld kv x %lld, ffn %lld, reading the "
"trunk at %lld tap(s); linears %s. One forward over %lld rows proposes %lld "
"tokens; the head is %s, argmax %s",
(long long)dg.n_layer, t.base_layer, t.base_layer + (int)dg.n_layer - 1, nfull,
(long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head,
(long long)(dg.n_layer - nfull), (long long)dc.window,
dc.causal ? "causal" : "non-causal", (long long)dg.n_head,
(long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff,
(long long)t.n_taps,
df->i8 ? "int8 (w8a8, an int8 activation per row)" : "on the E4M3 grid (fp8a8 / mxfp4a8)",
@@ -849,7 +863,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
};
bool any_full = false, any_swa = false;
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
if (any_swa) op_attn_swa = attn(1, cfg.window);
if (any_swa) op_attn_swa = attn(cfg.causal, cfg.window);
if (any_full) op_attn_full = attn(0, 0);
/* The copies into the cache's layout (rep_kv), a head-wide strided row copy each. Each pass's
+4 -3
View File
@@ -13,9 +13,10 @@
* row-interleaved all_gather, bit for bit the replicated projection
*
* The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered
* row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside
* its page tables, so its runs are multiples of four rows. The last rank's run may be short, or
* lie wholly past a small step (`run_of`). */
* row, because an all_gather moves whole words. The MLA gathers 4096-wide bf16 rows, so its runs
* are ceil(T / world); the indexer gathers one i32 length a row beside its page tables, so its
* runs are multiples of four rows. The last rank's run may be short, or lie wholly past a small
* step (`run_of`). */
#ifndef RAD_GLM_TP_H
#define RAD_GLM_TP_H
#include "rad_arch.h"
+167
View File
@@ -0,0 +1,167 @@
/* rad_resample.h -- fp32 bicubic resampling reproducing torch's
* F.interpolate(x, size=(n, m), mode="bicubic", antialias=True) on the CPU float32 kernel,
* operation for operation, for the Unlimited-OCR DeepEncoder's position tables.
*
* The reference resamples two fixed tables (deepencoder.py):
* get_abs_pos_sam() permutes SAM's pos_embed [1,64,64,768] to (0,3,1,2), casts fp32 and
* interpolates to 40x40; get_abs_pos() takes CLIP position_embedding rows 1: as a 16x16 grid,
* interpolates to 10x10, and cats row 0 (cls) in front. Here the table is row-major [h, w, C]
* with C innermost and each of the C channels is interpolated over the (h, w) grid
* independently; the cls split/catenation is the caller's job.
*
* The float32 antialias path (upsample_bicubic2d_aa_kernel_impl ->
* upsample_separable_Nd_kernel_impl -> _compute_index_ranges_weights with antialias=true,
* aten/src/ATen/native/cpu/UpSampleKernel.cpp, torch v2.14.0) is mirrored operation for
* operation, scalar_t = float:
* per axis scale = (float)(in / out); support = scale >= 1 ? (interp_size/2) * scale =
* 2 * scale : 2; invscale = scale >= 1 ? 1 / scale : 1;
* the output-pixel centre center = scale * (i + 0.5f);
* the taps run over xmin = max((int64)(center - support + 0.5), 0) ..
* min((int64)(center + support + 0.5), in) - 1 -- truncating casts, so a negative
* start truncates toward zero before the clamp to 0; border taps are simply absent,
* the row normalization below absorbs the lost mass;
* each tap weight is aa_filter((j + xmin - center + 0.5) * invscale), the Keys cubic
* with a = -0.5 (torch's antialias filter is the Pillow-compatible -0.5 kernel; the
* -0.75 OpenCV-compatible one belongs to the non-antialias path);
* the axis weights are normalized by their float running sum total_w, exactly as
* _compute_indices_min_size_weights_aa divides wt_ptr[j] /= total_w;
* the resize is separable: the width pass over every input row first, then the height
* pass (the order upsample_separable_Nd_kernel_impl walks the dims), each tap
* accumulating acc = (float)(acc + w * v) in float.
* Golden-checked by tests/resample_golden.py (geometries 64->40, 24->20, 8->5, 16->10,
* 16x20->10x13, and both checkpoint tables).
*/
#pragma once
#ifndef RAD_RESAMPLE_H
#define RAD_RESAMPLE_H
#include <cmath>
#include <cstdint>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
namespace resample_detail {
/* aa_filter, the Keys cubic with a = -0.5 that torch's antialias path uses (the -0.75
* OpenCV-compatible kernel belongs to the non-antialias path), in float. */
inline float cubic_aa(float x) {
const float ax = std::fabs(x);
if (ax < 1.0f) return ((1.5f * ax - 2.5f) * ax) * ax + 1.0f;
if (ax < 2.0f) return (((-0.5f * ax + 2.5f) * ax - 4.0f) * ax) + 2.0f;
return 0.0f;
}
struct Axis {
int n = 0; /* tap slots per output pixel (max_interp_size) */
std::vector<int32_t> size; /* [out] taps this output pixel reads */
std::vector<int32_t> idx; /* [out*n] input index per tap (xmin + j) */
std::vector<float> w; /* [out*n] weights, normalized by the tap sum */
};
/* One axis of _compute_indices_min_size_weights_aa, float32 expression for expression. */
inline Axis make_axis(int in, int out) {
Axis a;
const float scale = (float)((double)in / (double)out);
const float support = scale >= 1.0f ? (float)(2.0 * (double)scale) : 2.0f;
const float invscale = scale >= 1.0f ? (float)(1.0 / (double)scale) : 1.0f;
a.n = (int)std::ceil((double)support) * 2 + 1; /* max_interp_size */
a.size.resize((size_t)out, 0);
a.idx.assign((size_t)out * (size_t)a.n, 0);
a.w.assign((size_t)out * (size_t)a.n, 0.0f);
for (int i = 0; i < out; ++i) {
const float c = ((float)i + 0.5f) * scale;
int xmin = (int)(c - support + 0.5f);
if (xmin < 0) xmin = 0;
int xsize = (int)(c + support + 0.5f);
if (xsize > in) xsize = in;
xsize -= xmin;
if (xsize < 0) xsize = 0;
/* ATen's own `xsize = min(xsize, n)`, kept for parity. It cannot bind here: with
* xmin > 0 the window spans 2*support + 1 taps, at most a.n = 2*ceil(support) + 1
* (the bound ATen sized the slots from), and with xmin == 0 it spans fewer. So the
* clamp is a no-op safety net, never a silent tap truncation. */
if (xsize > a.n) xsize = a.n;
int* idx = &a.idx[(size_t)i * (size_t)a.n];
float* w = &a.w[(size_t)i * (size_t)a.n];
float total = 0.0f;
for (int j = 0; j < xsize; ++j) {
w[j] = cubic_aa(((float)(xmin + j) - c + 0.5f) * invscale);
idx[j] = xmin + j;
total = (float)(total + w[j]);
}
a.size[i] = xsize;
if (total != 0.0f)
for (int j = 0; j < xsize; ++j) w[j] = (float)(w[j] / total);
}
return a;
}
/* One 1D resize pass. `rows` scans travel `src_row_stride` floats apart, taps step
* `tap_stride` floats along the resized axis, and outputs land at
* dst + r * dst_row_stride + i * out_stride + channel; tap order and float accumulation
* follow ATen's separable 1D resize. */
inline void resize_axis(const float* src, int64_t src_row_stride, int64_t tap_stride,
float* dst, int64_t dst_row_stride, int64_t out_stride, int rows,
const Axis& ax, int out_n, int channels) {
for (int r = 0; r < rows; ++r) {
const float* srow = src + (size_t)r * (size_t)src_row_stride;
float* drow = dst + (size_t)r * (size_t)dst_row_stride;
for (int i = 0; i < out_n; ++i) {
const int n = ax.size[i];
const int32_t* idx = &ax.idx[(size_t)i * (size_t)ax.n];
const float* w = &ax.w[(size_t)i * (size_t)ax.n];
for (int c = 0; c < channels; ++c) {
if (n == 0) { drow[(size_t)i * (size_t)out_stride + (size_t)c] = 0.0f; continue; }
float acc = (float)(srow[(size_t)idx[0] * (size_t)tap_stride + (size_t)c] * w[0]);
for (int j = 1; j < n; ++j)
acc = (float)(acc +
srow[(size_t)idx[j] * (size_t)tap_stride + (size_t)c] * w[j]);
drow[(size_t)i * (size_t)out_stride + (size_t)c] = acc;
}
}
}
}
} // namespace resample_detail
/* Resample an [in_h, in_w, channels] fp32 table (channels innermost) to
* [out_h, out_w, channels] with torch's bicubic + antialias interpolation: the width pass
* over every input row, then the height pass. Runs once at load. */
inline void resample_bicubic_aa(const float* src, int in_h, int in_w, int out_h, int out_w,
int channels, float* dst) {
if (!src || !dst || in_h <= 0 || in_w <= 0 || out_h <= 0 || out_w <= 0 || channels <= 0)
return;
if (in_h == out_h && in_w == out_w) {
std::memcpy(dst, src, (size_t)in_h * (size_t)in_w * (size_t)channels * sizeof(float));
return;
}
const resample_detail::Axis ay = resample_detail::make_axis(in_h, out_h);
const resample_detail::Axis ax = resample_detail::make_axis(in_w, out_w);
const float* work = src;
int work_w = in_w;
std::vector<float> wide;
if (in_w != out_w) { /* width pass first, the order upsample_separable_Nd walks the dims */
wide.assign((size_t)in_h * (size_t)out_w * (size_t)channels, 0.0f);
resample_detail::resize_axis(src, (int64_t)in_w * channels, channels, wide.data(),
(int64_t)out_w * channels, channels, in_h, ax, out_w,
channels);
work = wide.data();
work_w = out_w;
}
if (in_h == out_h) {
if (work != dst)
std::memcpy(dst, work, (size_t)out_h * (size_t)out_w * (size_t)channels * sizeof(float));
return;
}
/* height pass over the widened rows: one scan per output-width column */
resample_detail::resize_axis(work, channels, (int64_t)work_w * channels, dst, channels,
(int64_t)out_w * channels, work_w, ay, out_h, channels);
}
} // namespace arch
} // namespace rad
#endif // RAD_RESAMPLE_H