Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port

102 upstream commits. Nine conflicts resolved. Fork side of the merge:
- libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it
  from libavx and libref; the device libraries now each carry it).
- plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table
  regenerated, kTableAbi = 42.

Known before the PR: arch_test (MTP lint and pinned graph hashes for
qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
aneinanderandClaude Opus 5.5 committed 2026-11-18 15:06:17 +01:00
commit 4b70a96378
850 files changed
+157819 -58519

No files matched your search

+67 -22
View File
@@ -37,9 +37,12 @@ namespace rad {
namespace arch {
/* One thread per tensor-parallel rank in one process (spec §1), and declare runs once per rank,
* so declared handles are per-rank state; a single global would let rank 1 overwrite rank 0.
* libr4d all-reduces over 2/4/8 ranks, hence eight. */
enum { MAX_RANKS = 8 };
* so declared handles are per-instance state; a single global would let rank 1 overwrite rank 0.
* libr4d all-reduces over 2/4/8 ranks, hence eight ranks. Several engines may run in the process
* (docs/MULTIMODEL.md), each with its own ranks, so state is indexed by the instance's slot
* (rad_build_slot at declare, rad_slot in step), unique across all of them, never by the rank two
* engines share. */
enum { MAX_RANKS = 8, MAX_SLOTS = RAD_MAX_SLOTS };
/* ================================================================== a debug residual probe
*
@@ -220,13 +223,14 @@ inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const c
return calib_write_host(h.data(), k, rows, what, domain, rad_rank(c));
}
/* A pinned host buffer of at least `bytes`, one per rank, held for the process lifetime, so a tap
* that copies a scratch back every pass runs at link speed. Null (and logged) on failure. */
/* A pinned host buffer of at least `bytes`, one per instance (slot), held for the process
* lifetime, so a tap that copies a scratch back every pass runs at link speed. Null (and logged)
* on failure. */
inline float* calib_staging(RadCtx* c, int64_t bytes) {
static std::mutex mu;
static std::map<int, std::pair<void*, int64_t>> per_rank;
static std::map<int, std::pair<void*, int64_t>> per_slot;
std::lock_guard<std::mutex> lk(mu);
std::pair<void*, int64_t>& s = per_rank[rad_rank(c)];
std::pair<void*, int64_t>& s = per_slot[rad_slot(c)];
if (s.second >= bytes) return (float*)s.first;
if (s.first) rad_dev_free(s.first, RAD_MEM_HOST_PINNED);
s.first = rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED);
@@ -672,8 +676,13 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
}
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. A plugin declares
* none where the deployment turns the reads off (RadBuildCtx::weight_prefetch_off). */
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes, int64_t blocks = 0) {
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
/* `blocks`: the workgroups reading, where the architecture measured its own count (docs/OPS.md);
* 0 leaves the kernel's. Stated only when asked, so a declaration without it is what it was. */
if (blocks > 0)
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes), RAD_INT("blocks", blocks)),
RAD_WEIGHTS(w));
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
}
@@ -733,9 +742,6 @@ 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;
/* RadBuildCtx::plain_norm: a block norm none of whose readers takes codes may run as `add` +
* `rmsnorm` (rad_fp8.h, NormQuantFP8::x_only). */
int plain_norm = 0;
@@ -774,6 +780,12 @@ struct Geom {
* setting because producers and consumers must agree; the plugin reads it off a trunk weight's
* encoding and every linear checks its own against it. */
bool w_bf16 = false;
/* The linears are rotated int8 (rad_fp8.h's linear_is_w8h: IQ8R, or the 128-group form) with
* one activation scale per `w_i8_group` columns, for a plugin whose producers are declared away
* from its probe: each then declares an int8 code pair (ActFP8::declare_pair). Model-wide as
* w_bf16 is. */
bool w_i8h = false;
int64_t w_i8_group = 128;
int64_t q_dim() const { return n_head * head_dim; }
int64_t kv_dim() const { return n_head_kv * head_dim; }
@@ -1010,7 +1022,6 @@ 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.plain_norm = c->plain_norm != 0;
g.eps = m->rms_eps;
g.theta = m->rope_theta;
@@ -1328,16 +1339,6 @@ 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
@@ -1474,6 +1475,45 @@ inline void batch_split(const RadBatch* b, int64_t* n_seq_dec, int64_t* n_tok_de
}
}
/* What a step's attention reads of the QSA selection (AttnGatedFP8::qsa_use), which decides what
* the indexer issues for the layer (QsaIndexer::step, docs/QSA.md "Below the bound"):
*
* kQsaSelect score and select, per layer: a step past the exactness bound, a streamed group,
* and every step of a block that did not ask for the forms below;
* kQsaUnread nothing reads the selection: the step is entirely at or below the bound and its
* attention is the dense one, or the sparse row over the sequence's own block table
* (one row a sequence), which is what the selection would be. The indexer stores its
* keys and tail and issues no query, score or select;
* kQsaOnce the attention reads a selection (the sparse row a query) on a step entirely at or
* below the bound: every complete block is taken whatever it scores, so the
* selection depends on the positions and the block table alone and is the same
* bytes at every layer. The first full-attention layer of the pass issues it as
* always; no later layer issues a query, a score or a select. */
enum QsaUse : int { kQsaSelect = 0, kQsaUnread = 1, kQsaOnce = 2 };
/* Ops of a chain that is independent of a block's own, for the block to issue behind its ordered
* launches. A recorded pass lets a launch start beside the last ordered one when it touches
* nothing in flight (Ctx::haz_mark). A dependent chain issued in one piece is therefore a row of
* ordered launches, each paid in turn; issued one op behind each of the block's own ordered
* launches, every op of it is unordered behind the block's launch in front of it, and still
* behind its own predecessor, which that launch already waited for. The block calls `at(k)` for
* k = 0, 1, 2, ... behind its ordered launches in turn, and the owner issues what is left once
* the block returns. The chain must read nothing the block writes and write nothing the block
* touches, and its buffers must be excluded from sharing (rad_buf_concurrent): they are in use at
* launches the linear order puts after their last declared use. */
struct SideOps {
void (*fn)(void* u, int stage) = nullptr;
void* u = nullptr;
void at(int stage) const { if (fn) fn(u, stage); }
};
/* RADIANCE_DEBUG_QSA_EAGER: every step is kQsaSelect, the issue sequence before the forms above
* existed. An instrument for comparing the two (the text must not move); read once. */
inline bool qsa_eager() {
static const bool on = std::getenv("RADIANCE_DEBUG_QSA_EAGER") != nullptr;
return on;
}
/* The step batch's entry for one declared KV group (built once per step by the core, spec §8). */
inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
for (int i = 0; i < b->n_kv_groups; ++i)
@@ -1658,6 +1698,11 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
#define RAD_ARCH_SERVES_IMPORTS(V) \
extern "C" int rad_arch_serves_imports(void) { return V; }
/* RAD_ARCH_MULTI_INSTANCE() states that the plugin keeps all per-instance state by slot, so several
* engines in one process may run it at once (rad_builder.h, rad_arch_multi_instance). */
#define RAD_ARCH_MULTI_INSTANCE() \
extern "C" int rad_arch_multi_instance(void) { return 1; }
} /* namespace arch */
} /* namespace rad */
+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, decl_attn(b, g, "attn_paged",
op_attn = rw(b, rad_decl_op(b, "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
@@ -137,7 +137,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, decl_attn(b, g, "attn_paged",
op_attn = rw(b, rad_decl_op(b, "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, decl_attn(b, g, "attn_paged",
op_attn = rw(b, rad_decl_op(b, "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),
+124 -37
View File
@@ -9,7 +9,7 @@
* state); the gate pass quantises the out-projection's input.
* - Per-head norms, rope, kv_store and attn_paged stay bf16.
* - The KV cache dtype is `g.kv_dtype`, not `g.dtype`: it is a deployment choice that selects
* libr4d's fp8kv attention family. The attention op and kv_store both take it, so they agree.
* the attention family's cache rows. The attention op and kv_store both take it, so they agree.
* - Optional fused prologue, QSA sparse attention and an attention-zero mode (see declare).
*
* The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, scale plane
@@ -26,14 +26,6 @@
namespace rad {
namespace arch {
/* Whether the streamed store has a row for this cache layout: libr4d's are E4M3 and bf16 only. A
* packed cache (fp8_v4, k6_v4) must not declare it, since a weightless op with no row is a hole
* that refuses startup even with --kv-resident off; kvstream_configure then names the layout. */
inline bool kv_store_streamed_dtype(const char* kv_dtype) {
return kv_dtype && (std::strcmp(kv_dtype, "fp8_e4m3") == 0 ||
std::strcmp(kv_dtype, "bf16") == 0);
}
struct AttnGatedFP8 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
@@ -87,6 +79,21 @@ struct AttnGatedFP8 {
/* `sel`'s row pitch is `topk + 1`; the extra slot is the partial page
* (r4d_qsa_select_bf16.hip). */
int64_t qsa_topk = 0;
/* The architecture's word that a sequence with one row in the step has that row at its
* context's last position (`seqused - 1`: a plain decode row, a serial head's round), so at or
* below `qsa_exact_to` such a row's selection is the head of the sequence's block table and its
* `seqused` the sequence's (qsa_select: every complete block in block order, then the partial
* page, and `pos + 1`). The sparse row is then issued over the table and the indexer selects
* nothing (qsa_use). Off: such a step keeps the selection. */
bool qsa_table_rows = false;
/* The architecture's pass key carries whether this group's exact host bound
* (RadBatch::kv_used_max_h, the furthest context any row of the step can read) is within
* `qsa_exact_to`, so that bound may say whether the step needs scores (qsa_within) in place of
* the rounded `max_ctx_len + max_q_len`, which a 4-row step leaves at 1025 tokens. It never
* moves the choice between the dense and the sparse kernel, which stays the rounded bound's:
* the two agree on the keys, not on the last bit of the sum. Off: the rounded bound, which the
* core's key holds. */
bool qsa_exact_host = false;
/* Query rows per sparse attention launch, a scratch budget. The decode kernel's split-KV
* partials are sized at declare from `max_seqs` and `q_len`, so issuing more rows than
* `max_seqs` means declaring a larger value, which grows the scratch arena (the maximum over
@@ -115,6 +122,18 @@ struct AttnGatedFP8 {
/* The input was normed and quantised by the caller; this block declares no norm. */
bool ext_in = false;
LinearFP8 qg{}, kp{}, vp{}, o{};
/* Set by the architecture after declare: a `prefetch` of the out projection's leading bytes
* (decl_prefetch, rad_arch.h), issued behind the q, k and v projections on decode steps
* (prefetch_beside). 0 where none is declared. */
rad_op op_pf_o = 0;
/* The same read as a second op for steps of at least pf_o_v_rows rows, where the
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
* every step takes op_pf_o. */
rad_op op_pf_o_v = 0;
int64_t pf_o_v_rows = 0;
/* The most rows of a decode step whose k and v projections are issued in front of the q|gate
* projection (step()); 0, the default, keeps the declared order on every step. */
int64_t kv_first_rows = 0;
NormQuantFP8 nq_h{};
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
@@ -125,7 +144,7 @@ struct AttnGatedFP8 {
int64_t fused_rows = 0; /* widest T the fused ops take */
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
rad_op op_attn = 0, op_kv_store = 0, op_gq = 0;
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 or gate_had_quant_i8g */
/* kv_store_streamed: the host mirror always, the ring slot when `res` says the block is resident
* (docs/OPS.md). Zero when no row serves it; a streamed group then fails the step. */
rad_op op_kv_stream = 0;
@@ -172,8 +191,12 @@ struct AttnGatedFP8 {
/* The block's tail, declared last by every rank: the all-reduce and the trailing add. */
int declare_out(RadBuilder* b, bool add_out);
/* `own_ar` false: the caller issues the all-reduce itself (GdnFP8::step says when). */
/* `side`: an independent chain's ops, issued behind this block's ordered launches (SideOps,
* rad_arch.h): one behind the prologue and the store, one behind the attention, one behind
* the gate where the gate is a launch of its own. Null, and on the paths that return early,
* nothing is asked of it. */
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
ArPieces* pieces = nullptr) const;
ArPieces* pieces = nullptr, const SideOps* side = nullptr) const;
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
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,
@@ -189,6 +212,41 @@ struct AttnGatedFP8 {
* 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. A streamed group never takes it: the pieces path's
* plain store never writes the host mirror. */
/* The rounded host bound of the furthest context a row of the step reads; by it a step of
* several rows a sequence takes the dense or the sparse kernel (step(), `sparse`). */
int64_t qsa_reach(const RadBatch* batch) const {
return (int64_t)batch->max_ctx_len + batch->max_q_len;
}
/* Whether every row of the step is at or below the exactness bound, by the tightest host
* ceiling there is: the group's exact one where the pass key holds its side of the bound
* (qsa_exact_host), else the rounded one. Every row's position + 1 is at most either. */
bool qsa_within(const RadBatch* batch, const RadKVGroupBatch* kvb) const {
if (qsa_exact_to <= 0) return false;
int64_t reach = qsa_reach(batch);
if (qsa_exact_host && kvb && batch->kv && batch->kv_used_max_h) {
const int64_t tight = batch->kv_used_max_h[kvb - batch->kv];
if (tight > 0 && tight < reach) reach = tight;
}
return reach <= qsa_exact_to;
}
/* What this step's attention reads of the selection (QsaUse, rad_arch.h); the architecture
* hands it to the indexer, which runs first, and step() takes its path by the same call. */
int qsa_use(const RadBatch* batch) const {
if (!qsa_sel || !qsa_sequ || op_fill || qsa_eager()) return kQsaSelect;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
/* A streamed group may be ring-bound, where every pass is sparse and the resolve rewrites
* the selection; it keeps the selection at every context. */
if (!kvb || kvb->stream || !kvb->block_table || !kvb->seqused) return kQsaSelect;
if (!qsa_within(batch, kvb)) return kQsaSelect;
/* One row a sequence is the sparse row at every context: over the table where the
* architecture vouches for it, else over a selection. */
if (batch->n_tok == batch->n_seq)
return (qsa_table_rows && batch->max_q_len == 1) ? kQsaUnread : kQsaOnce;
/* Several rows a sequence: the dense attention, which reads the table, where the rounded
* bound is within the budget too, else the sparse row a query over a selection. */
return qsa_reach(batch) <= qsa_exact_to ? kQsaUnread : kQsaOnce;
}
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
const int64_t T = batch->n_tok;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
@@ -342,7 +400,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 = decl_attn(b, g, "attn_paged",
op_attn = rad_decl_op(b, "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),
@@ -382,8 +440,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
/* The streamed store: kv_store's operands and parameters plus the residency map and the layer's
* mirror row, which the batch carries (store_cache). `block_size` does not bind the group;
* `attn_paged` already has. Only for a layout with a row (kv_store_streamed_dtype). */
if (kv_store_streamed_dtype(g.kv_dtype) && rad_op_declared(b, "kv_store_streamed"))
* `attn_paged` already has. */
if (rad_op_declared(b, "kv_store_streamed"))
op_kv_stream = rw(b, RAD_OP(b, "kv_store_streamed",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("head_dim", g.head_dim),
@@ -396,7 +454,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
/* The fused prologue with the cache store folded in: a k head's block already holds its
* token's rotated k, so it also writes k and v into the cache, byte-identical to kv_store.
* Declared here because the cache block size is read back from the attention op above.
* Resolves for E4M3 and bf16 caches. */
* Resolves for either cache. */
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store"))
op_fused_kv = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
@@ -410,9 +468,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
/* The fold for a streamed group: also writes the mirror and consults the residency map, whose
* operands are added at issue. Gated on the same layouts. */
if (op_fused && kv_store_streamed_dtype(g.kv_dtype) &&
rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
* operands are added at issue. */
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
op_fused_stream = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store_streamed",
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
@@ -463,7 +520,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
if (rad_op_declared(b, gq))
op_gq = rw(b, RAD_OP(b, gq,
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
RAD_INT("n", g.head_dim), RAD_INT("group", w.attn.cg()),
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
RAD_NOWEIGHTS),
{w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
@@ -488,10 +545,12 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
* row is one (token, head) at q_len 1, and the merge already holds the head_dim values the gate
* and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the
* pair). Declared only with a selection: the dense path also uses the prefill kernel, which
* has no merge. */
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && !w.attn.q8_rot &&
rad_op_declared(b, "attn_paged_gate_quant")) {
op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
* has no merge. Rotated int8 codes (ActFP8::q8_rot) take attn_paged_gate_had_quant, the merge
* with gate_had_quant_i8g's quantiser. */
const char* attn_gq = w.attn.q8_rot ? "attn_paged_gate_had_quant" : "attn_paged_gate_quant";
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && w.attn.cg() == RAD_FP8_BLOCK &&
rad_op_declared(b, attn_gq)) {
op_attn_gq = RAD_OP(b, attn_gq,
RAD_PARAMS(RAD_INT("q_len", 1), 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),
@@ -591,7 +650,7 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
}
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
ArPieces* pieces) const {
ArPieces* pieces, const SideOps* side) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
@@ -636,7 +695,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
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.cs(), r0, n, qw / w.attn.cg()),
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);
@@ -653,9 +712,23 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
return;
}
qg.step(c, w.h, w.qg, T);
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
/* The three projections read the same input and none reads another's output, so a recorded
* pass starts them together (Ctx::haz_mark) whatever their order; the order decides which
* the card launches first. On a decode step of up to `kv_first_rows` rows the two small ones
* go first: behind the wide q|gate projection their launches wait until its blocks are all
* on the card, and the prologue then waits for them. Qwen3.8-Flash-Next at tp 2, chain 3
* with coupling (twelve trunk layers and the head's): -0.66% a step. */
if (T <= kv_first_rows && batch->phase == RAD_PHASE_DECODE) {
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
qg.step(c, w.h, w.qg, T);
} else {
qg.step(c, w.h, w.qg, T);
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
}
/* The out projection's weight, read beside the prologue and the attention (op_pf_o). */
prefetch_beside(c, op_pf_o_v && T >= pf_o_v_rows ? op_pf_o_v : op_pf_o, o.w, T);
/* Fused or unfused prologue. The fused kernel takes the whole [q|gate] projection and splits it
* itself, and rotates k in place like the unfused ops. It reads one rotary component per
@@ -700,6 +773,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
}
if (!fused_kv && !folded_stream) store_cache(c, kvb, slot, T);
if (side) side->at(0);
/* Sparse attention issues one row per query. `attn_paged` indexes its block table and length
* by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with
@@ -712,7 +786,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* Launches are chunked because the split-KV scratch is sized at declare from `max_seqs` and
* `q_len` (rows = max_seqs * q_len_max * heads); more rows are refused as RAD_E_SCRATCH at
* issue. Rows of q_len 1 up to the declared max_seqs always fit. */
const int64_t reach = (int64_t)batch->max_ctx_len + batch->max_q_len;
const int64_t reach = qsa_reach(batch);
/* A pass on a streamed group's ring (a ring smaller than the id space, and not staged) must
* take the sparse path: on the ring a block id is not a pool address, so the dense path would
* read ring slots as pages. `T == n_seq` alone misses a verify pass, whose T is
@@ -726,6 +800,19 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
const bool sparse = qsa_sel && qsa_sequ &&
(ring_bound || T == batch->n_seq || qsa_exact_to <= 0 ||
reach > qsa_exact_to);
/* At or below the bound a step of one row a sequence has no selection (qsa_use): the sparse
* row reads the sequence's own block table and length, which is what qsa_select would have
* written for it (the field says why), so the launch, its kernel and its bytes are the sparse
* row's. */
const bool by_table = sparse && T == batch->n_seq && qsa_use(batch) == kQsaUnread;
const int64_t tpitch = kvb ? kvb->block_table_pitch : 0;
auto sel_rows = [&](int64_t off, int64_t rows) {
return by_table ? praw2(table + off * tpitch, RAD_I32, rows, tpitch)
: brow_slice(qsa_sel, off, rows, qsa_topk + 1);
};
auto sequ_rows = [&](int64_t off, int64_t rows) {
return by_table ? praw(used + off, RAD_I32, rows) : brow_slice(qsa_sequ, off, rows, 1);
};
const bool gated = sparse && op_attn_gq;
/* A streamed group's selection, per launch: make the rows' blocks resident and rewrite `sel`
* as ring slots, after this layer's store (a block copied in from the mirror must carry this
@@ -733,6 +820,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* and never resolves, so a prefill cannot overflow the ring. */
const KVStreamLayer res_l = op_resolve ? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
auto resolve_sel = [&](int64_t off, int64_t rows) {
if (by_table) return; /* never a streamed group (qsa_use) */
if (kv_stage_layer(c, kv, kvb, layer)) return;
if (!res_l.host || res_l.blocks <= 0 || res_l.slots <= 0 || rows <= 0) return;
kv_resolve_issue(c, op_resolve, res_l, brow_slice(qsa_sel, off, rows, qsa_topk + 1),
@@ -754,13 +842,12 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
RAD_ISSUE_N(c, op_attn_gq, 1,
brow_slice(w.q, off, rows, qw),
kv_cache(kv, layer),
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
brow_slice(qsa_sequ, off, rows, 1),
sel_rows(off, rows), sequ_rows(off, rows),
RAD_NONE, RAD_NONE, RAD_NONE,
brow_slice(w.attn.x, off, rows, qw),
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
brow_slice(w.attn.cq(), off, rows, qw),
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
}
o.step(c, w.attn, w.h.x, T, p0, pn);
if (p0 + pn < T) pieces->hand(p0, pn);
@@ -778,13 +865,12 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
RAD_ISSUE_N(c, op_attn_gq, 1,
brow_slice(w.q, off, rows, qw),
kv_cache(kv, layer),
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
brow_slice(qsa_sequ, off, rows, 1),
sel_rows(off, rows), sequ_rows(off, rows),
RAD_NONE, RAD_NONE, RAD_NONE,
brow_slice(w.attn.x, off, rows, qw),
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
brow_slice(w.attn.cq(), off, rows, qw),
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
}
} else if (sparse) {
const int64_t chunk = qsa_rows();
@@ -795,8 +881,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
RAD_ISSUE_N(c, op_attn, 1,
brow_slice(w.q, off, rows, qw),
kv_cache(kv, layer),
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
brow_slice(qsa_sequ, off, rows, 1),
sel_rows(off, rows), sequ_rows(off, rows),
RAD_NONE, RAD_NONE, RAD_NONE,
brow_slice(w.attn.x, off, rows, qw));
}
@@ -857,6 +942,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
/* Every attention launch of this layer is issued: start the next layer's stage copy, which
* crosses the link under the out projection and the next layer's projections. */
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
if (side) side->at(1);
if (gated) {
/* the sparse attention gated and quantised in its merge */
} else if (op_sig) {
@@ -870,6 +956,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.attn.x, T),
brows(w.attn.cq(), T), brows(w.attn.cs(), T), brows(w.attn.x, T));
}
if (side && !gated) side->at(2);
o.step(c, w.attn, w.h.x, T);
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
+130 -42
View File
@@ -147,6 +147,9 @@ struct Dflash2 {
/* The target's embedding scale, applied to the query block as the drafter was trained
* (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */
double escale = 1.0;
/* Optional DFlash2 logit transform shipped by Muse Glimmer. */
double omul = 1.0;
double scap = 0.0;
/* 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;
@@ -161,6 +164,14 @@ struct Dflash2 {
* acceptance, sum min(P, Q). */
double q_temp = 1.0;
int64_t short_rows = 0;
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
* by had_quant_act_i8g. Every linear must agree. `fc_mapped`: probe_i8 made
* `dflash.fc.weight`'s name map. */
bool act_i8 = false;
int64_t act_g8 = RAD_FP8_BLOCK;
bool fc_mapped = false;
/* LiLiCorr's backbone (the LILICORR section above): sinks, and the head left to the
* plugin. sel_rank and sel_topk are then unused. */
int lili = 0;
@@ -198,7 +209,9 @@ struct Dflash2 {
rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
rad_buf ffn = 0; /* [qrows, n_ff] */
/* FP8 codes and scales of the activations the linears read, written by `quant_act_fp8`
* and read only by the `gemm_nt_q` linears. One pair per activation, not per linear: q, k
* and read only by the `gemm_nt_q` linears (int8 codes with a scale per Config::act_g8,
* written by `had_quant_act_i8g`, when the drafter's linears are rotated int8:
* Config::act_i8). One pair per activation, not per linear: q, k
* and v all read h2. h2 is still quantised twice a layer, because the convolution
* rewrites it between the attention and feed-forward halves. */
rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] e4m3 | [.., /128] f32 */
@@ -260,6 +273,9 @@ struct Dflash2 {
* 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and
* the 2-bit grid otherwise. Set by declare from the copy's encoding. */
bool head_i8 = false;
/* Muse Glimmer's 202048-token vocab is not divisible by the int8/w2a8 head kernels' 128-row
* tile; its copied draft head stays BF16 and uses gemm_nt. */
bool head_bf16 = false;
/* per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
@@ -324,7 +340,7 @@ struct Dflash2 {
rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {};
/* head and selector */
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dcap = 0, op_dtopk = 0;
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
rad_op op_drerank = 0; /* the candidates rescored against the target's head */
/* The target's lm_head, set by the plugin before declare when logit_rerank can read it (fp8 or
@@ -342,6 +358,18 @@ struct Dflash2 {
* the drafter's own block is longer (rad_drafter_short_block). */
static constexpr int64_t kShortBlock = 4;
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
* declared, since it decides their dtype and scale grid. */
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
const char* fwn = nm.f("dflash.fc.weight");
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
RadEncoding fe{};
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
return RAD_OK;
}
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
const char* ck_lm, const Wire& wire);
@@ -381,11 +409,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
srows = g.max_seqs * cfg.steps();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
w_fc.w8h_ok = cfg.act_i8;
for (int i = 0; i < MAX_LAYERS; ++i)
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
w_dn[i].w8h_ok = cfg.act_i8;
/* ---------------------------------------------------------------- model-scope weights */
{
const int64_t K = cfg.n_taps * g.n_embd;
const char* fwn = nm.f("dflash.fc.weight");
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
if (!cfg.fc_mapped) RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
/* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole
* 16-byte words (the gather's unit). */
RadEncoding fe{};
@@ -453,12 +488,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which
* gemm_nt_q reads at w8a8 against the same quant_act_i8 activation (without its asum). */
RadEncoding dhe{};
const bool head_known = weight_enc(b, dhn, &dhe);
{
RadEncoding e{};
const RadEncPlane* sc = nullptr;
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 &&
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 &&
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 &&
head_i8 = head_known && rad_enc_is(&dhe, "affine") && dhe.n_planes == 2 &&
!dhe.transform[0] && dhe.plane[0].dtype == RAD_I8 && dhe.plane[0].block[1] == 1 &&
(sc = rad_enc_plane(&dhe, "scale")) && sc->dtype == RAD_F16 &&
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
}
if (head_i8) {
@@ -467,6 +503,11 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN,
dh_split, grp_model());
} else if (head_known && rad_enc_is(&dhe, "plain") && dhe.n_planes == 1 &&
dhe.plane[0].dtype == RAD_BF16) {
head_bf16 = true;
w_dh = decl_w(b, dhn, RAD_BF16, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
} else {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
@@ -474,7 +515,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split,
grp_model());
}
if (!w_dh || !w_dhs) return RAD_E_INVAL;
if (!w_dh || (!head_bf16 && !w_dhs)) return RAD_E_INVAL;
}
/* ---------------------------------------------------------------- per-layer weights */
@@ -602,9 +643,29 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* Nothing is row-sliced: the fp8a8 pair covers every M, and libr4d's bf16 GEMM row (used by
* the conv coefficient projections and the selector's hidden projection, K = n_embd) is
* C_LE("M", 65536). */
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
/* A rotated int8 drafter (cfg.act_i8): the same five quantisers as had_quant_act_i8g at its
* scale group, and no fp8a8 fold. Its linears read one activation pair, so they are all
* i8a8h forms at one group or none is. */
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
{
auto fits = [&](const DenseFP8& d) {
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
};
bool same = fits(w_fc);
for (int64_t l = 0; l < g.n_layer; ++l)
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
fits(w_gu[l]) && fits(w_dn[l]);
if (!same) {
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
"group or all block fp8 / MXFP4; they read one activation pair, so the "
"recipe must give them one format\n");
return RAD_E_DTYPE;
}
}
op_qsrc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
if (fc_rows) {
@@ -634,9 +695,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
/* One quantise for all layers: every layer's k and v read the same `c`. */
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
op_qc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
@@ -700,19 +761,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.x}, {w.x});
/* The query pass's quantisers, issued per layer: h2 twice (the convolution rewrites it between
* the halves), attn and ffn once each. */
op_qh2 = rw(b, RAD_OP(b, "quant_act_fp8",
op_qh2 = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h2}, {w.h2q, w.h2s});
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
op_qat = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn}, {w.atq, w.ats});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
op_qff = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.ffn}, {w.ffq, w.ffs});
@@ -759,7 +820,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
/* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
* fp8a8 tile, so an MXFP4 or M2XFP4 gate_up takes the pair. */
if (!w_gu[i].mx && !w_gu[i].m2x)
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
{w.h2q, w.h2s}, {w.ffq, w.ffs}, &gated_rows);
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
@@ -832,12 +893,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
/* Only for a shape a library serves: an op declared for one that resolves to no device
* kernel is a hole that refuses startup (Program::device_holes), whether or not it is
* issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in
* steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim
* 128) keeps the chain. */
* steps of 256, bf16 rows, either cache). Qwen3.8's DFlash2 drafter (head_dim 128) keeps
* the chain. */
const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 &&
!std::strcmp(g.dtype, "bf16") &&
(!std::strcmp(g.kv_dtype, "fp8_e4m3") ||
!std::strcmp(g.kv_dtype, "bf16"));
!std::strcmp(g.dtype, "bf16");
if (fold_shape && g.yarn.factor == 0.0f &&
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
const int64_t bsz = rad_kv_block_size(b, kv);
@@ -898,12 +957,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h2}, {w.x});
op_final = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
op_final = cfg.omul != 1.0
? rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_F64("mult", cfg.omul), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h})
: rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
/* Each residual add and the norm after it as one launch where a library serves add_rmsnorm
* (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only
* where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run
@@ -927,6 +993,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
op_afinal = all ? an(w_norm) : 0;
if (!op_afinal)
for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0;
/* add_rmsnorm has no `mult`; keep Muse's output_multiplier on the final norm. */
if (cfg.omul != 1.0) op_afinal = 0;
}
/* ---------------------------------------------------------------- the head and the selector
@@ -944,12 +1012,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.h}, {w.sel_h});
/* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */
if (cfg.lili) return RAD_OK;
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.dq, w.ds, w.dsum});
op_dlogits = head_i8
if (!head_bf16)
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.dq, w.ds, w.dsum});
op_dlogits = head_bf16
? rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_dh)),
{w.sel_h}, {w.dlog})
: head_i8
? rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
@@ -962,6 +1037,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
if (cfg.scap > 0.0) {
op_dcap = rw(b, RAD_OP(b, "logit_softcap",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", head_rows(g)),
RAD_F64("cap", cfg.scap), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.dlog});
if (!op_dcap) return RAD_E_INVAL;
}
/* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
* with value 0 is a different declaration from an absent one. */
@@ -1312,12 +1395,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
* whole. */
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric and
* takes no asum. */
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
if (head_bf16) {
RAD_ISSUE_N(c, op_dlogits, S, brows(w.sel_h, S), RAD_W(w_dh), brows(w.dlog, S));
} else {
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric
* and takes no asum. */
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
}
if (op_dcap) RAD_ISSUE_N(c, op_dcap, S, brows(w.dlog, S), brows(w.dlog, S));
/* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
* the merge overwrites `cand`/`unary`. */
if (op_dmerge) {
+93 -82
View File
@@ -93,12 +93,15 @@
*
* ============================== PRECISION ==============================
*
* E4M3 + a bf16 [N/128][K/128] plane fc, q/k/v/o, gate_up, down -- every linear
* what the recipe made them fc, q/k/v/o, gate_up, down -- every linear
* bf16, no plane every norm, and both Markov codebooks
*
* The checkpoint is dense bf16; the linears are rad_fp8.h's DenseFP8 over weights the recipe
* quantises, because the drafter is read whole every decode step (324M parameters: 648 MB at
* bf16, 324 MB at fp8). This can only change acceptance.
* bf16, 324 MB at eight bits). DenseFP8 reads block fp8 or MXFP4 against E4M3 activations, or a
* rotated int8 form (IQ8R and the narrower grids under the same rotation) against int8 ones
* (Config::act_i8); one format for all of them, since they share the activation pairs. This can
* only change acceptance.
*
* The codebooks are bf16 and replicated: they are gathered by global token id from a merged
* candidate set. 66.8 MiB each; only K rows are read per position, so the cost is residency.
@@ -135,6 +138,14 @@ struct Dspark {
int64_t top_k = 0; /* candidates the Markov walk re-ranks */
int64_t window = 0; /* sliding attention width, 0 for none */
int causal = 0;
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
* by had_quant_act_i8g and the rotating norm. Every linear must agree. `fc_mapped`:
* probe_i8 made `dspark.fc.weight`'s name map. */
bool act_i8 = false;
int64_t act_g8 = RAD_FP8_BLOCK;
bool fc_mapped = false;
/* Every row predicts, so `block`, not `block - 1` (see ROW ALIGNMENT). */
int64_t steps() const { return block; }
};
@@ -149,7 +160,10 @@ struct Dspark {
* rows_pitch). */
rad_buf ck = 0; /* [max_tok, kv_dim] one layer's K, reused across layers */
rad_buf cv = 0; /* [max_tok, kv_dim] one layer's V, reused across layers */
rad_buf srcq = 0, srcs = 0; /* fp8 codes and scales: e4m3 | f32 [.., /128] */
/* The codes and scales the linears read: e4m3 | f32 [.., /128], or with Config::act_i8
* i8 | f32 [.., /act_g8]. The same holds for the three ActFP8 pairs below, whose `q` and
* `s` are then the int8 pair. */
rad_buf srcq = 0, srcs = 0;
rad_buf cq = 0, cs = 0;
/* ---- the query pass, `block` rows per sequence */
@@ -235,6 +249,18 @@ struct Dspark {
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
rad_op op_sel = 0;
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
* declared, since it decides their dtype and scale grid. */
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
const char* fwn = nm.f("dspark.fc.weight");
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
RadEncoding fe{};
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
return RAD_OK;
}
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
const char* ck_lm, const char* ck_lm_alt, const Wire& wire);
@@ -274,10 +300,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
srows = g.max_seqs * cfg.steps();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
w_fc.w8h_ok = cfg.act_i8;
for (int i = 0; i < MAX_LAYERS; ++i)
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
w_dn[i].w8h_ok = cfg.act_i8;
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
{ nm.ckpt("%s.fc.weight", ck) }, {}, cfg.fc_mapped));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
@@ -379,19 +412,34 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
/* ---------------------------------------------------------------- the context pass
*
* Every linear is `fp8a8`, fed by a `quant_act_fp8`. There is no `fp8a16` band: that kernel is
* M <= 1, and neither pass runs at one row. */
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
* Every linear is a DenseFP8 GEMM over the pair its quantiser writes: `quant_act_fp8` codes
* for block fp8 or MXFP4, had_quant_act_i8g's at the weights' scale group for a rotated int8
* drafter (cfg.act_i8). The linears read one activation pair, so they are all i8a8h forms at
* one group or none is. There is no `fp8a16` band: that kernel is M <= 1, and neither pass
* runs at one row. */
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
{
auto fits = [&](const DenseFP8& d) {
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
};
bool same = fits(w_fc);
for (int64_t l = 0; l < g.n_layer; ++l)
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
fits(w_gu[l]) && fits(w_dn[l]);
if (!same) {
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
"group or all block fp8 / MXFP4; they read one activation pair, so the "
"recipe must give them one format\n");
return RAD_E_DTYPE;
}
}
op_qsrc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
RAD_INT("K", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_fc.w, w_fc.s)),
{w.srcq, w.srcs}, {w.c});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
* written. */
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
@@ -401,27 +449,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
/* One quantise for all layers: every layer's k and v read the same `c`. */
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
op_qc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
* and residency class. */
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.cq, w.cs}, {w.ck});
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.cq, w.cs}, {w.cv});
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
@@ -468,7 +506,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
{w.x}, {w.x});
/* Norm, residual add and quantise are one op, `rmsnorm_quant_fp8` (what rad_fp8.h's
* NormQuantFP8 wraps). Layer 0 has no delta to fold, each later norm folds the previous
* NormQuantFP8 wraps), or its rotating int8 twin `rmsnorm_had_quant_i8g` for a rotated int8
* drafter, which takes the same operands. Layer 0 has no delta to fold, each later norm folds the previous
* block's delta, and op_outnorm folds the last into the final norm, so there is no `add` op.
* The final norm's fp8 output is unused (the head runs its own i8 quantiser), a few KiB of
* waste that saves a launch: libr4d has no plain `rmsnorm_add` row.
@@ -478,9 +517,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
* stream as `x` and no residual. `residual` is INOUT, so it is in both the read and write sets;
* otherwise the planner could reorder a reader in front of it. */
auto decl_norm = [&](rad_weight gain, bool fold) -> rad_op {
rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
rad_op h = RAD_OP(b, cfg.act_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_F64("eps", g.eps), RAD_INT("group", qgr),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(gain));
if (!h) return 0;
@@ -490,9 +529,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
rad_op_writes(b, h, wr, fold ? 4 : 3);
return h;
};
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
op_qat = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn.x}, {w.attn.q, w.attn.s});
if (!op_qat) return RAD_E_INVAL;
@@ -508,24 +547,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
const int i = (int)l;
op_anorm[i] = decl_norm(w_anorm[i], i != 0);
if (!op_anorm[i]) return RAD_E_INVAL;
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
{w.h.q, w.h.s}, {w.q});
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.h.q, w.h.s}, {w.k});
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.h.q, w.h.s}, {w.v});
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h.q, w.h.s}, {w.q});
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.k});
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.v});
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
@@ -538,28 +562,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.k});
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
{w.attn.q, w.attn.s}, {w.h.x});
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.attn.q, w.attn.s}, {w.h.x});
op_fnorm[i] = decl_norm(w_fnorm[i], true);
if (!op_fnorm[i]) return RAD_E_INVAL;
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
{w.h.q, w.h.s}, {w.gate_up});
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
{w.ffn.q, w.ffn.s}, {w.h.x});
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h.q, w.h.s}, {w.gate_up});
/* The fold is an fp8a8 tile, so any other gate_up takes the pair. */
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffn.q, w.ffn.s}, {w.h.x});
}
op_qrope = rw(b, decl_rotary(b, g, "rope",
@@ -588,9 +599,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn.x});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
op_qff = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.ffn.x}, {w.ffn.q, w.ffn.s});
/* One collective, issued after both the out and the down projection (same shape, same buffer).
@@ -687,16 +698,16 @@ inline void Dspark::context(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, RAD_NONE);
brows(w.c, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
@@ -735,11 +746,11 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
* quantises; at layer 0 it norms the embedding. */
issue_norm(op_anorm[i], i != 0, w_anorm[i], T);
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
@@ -757,7 +768,7 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
brows(w.attn.x, T));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn.x, T), brows(w.attn.q, T), brows(w.attn.s, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.attn.q, T), brows(w.attn.s, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, w_o[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
/* ---- the feed-forward, behind the same fused norm-add-quantise */
@@ -769,12 +780,12 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
RAD_NONE);
w_gu[i].bref());
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn.x, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn.x, T), brows(w.ffn.q, T), brows(w.ffn.s, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffn.q, T), brows(w.ffn.s, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, w_dn[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
}
+47 -20
View File
@@ -129,12 +129,19 @@ struct GdnFP8 {
/* Geom::plain_norm with an out projection that reads no codes (a 4-bit one): the recurrent
* epilogue and the prefill quantiser leave the code pair unwritten. */
bool o_plain = false;
/* Whether op_cr writes the out projection's codes; otherwise q_o follows it. */
bool cr_codes = false;
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. */
* (decl_prefetch, rad_arch.h), issued 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;
/* The same read as a second op for steps of at least pf_out_v_rows rows, where the
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
* every step takes op_pf_out. */
rad_op op_pf_out_v = 0;
int64_t pf_out_v_rows = 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;
@@ -351,17 +358,25 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
* tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
{
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
op_cr = rw(b, RAD_OP(b, w.o.q8_rot ? "gdn_conv_recurrent_update_had" : "gdn_conv_recurrent_update",
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v),
RAD_INT("conv_width", cfg.conv_width),
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
RAD_STR("state_form",
g.max_spec > 0 ? "anchor" : "per_candidate")),
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias, w_out_norm)),
/* The fold's rotated epilogue writes one scale per (row, 128), or per 256 for an IQ8R
* trunk's codes (ActFP8::g8; `group`, stated to that form alone: last, and cut off
* otherwise), where this rank's value heads pair up. */
const bool cr_wide = w.o.q8_rot && w.o.g8 == RAD_I8_GROUP_WIDE && cfg.n_head_v % 2 == 0;
cr_codes = w.o.cq() && !o_plain && (!w.o.q8_rot || w.o.g8 == RAD_FP8_BLOCK || cr_wide);
const RadParam cp[] = { RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v),
RAD_INT("conv_width", cfg.conv_width),
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate"),
RAD_INT("group", RAD_I8_GROUP_WIDE) };
const rad_weight cw[] = { w_conv, w_a_log, w_dt_bias, w_out_norm };
op_cr = rw(b, rad_decl_op(b, w.o.q8_rot && cr_codes ? "gdn_conv_recurrent_update_had"
: "gdn_conv_recurrent_update",
cp, (int)(sizeof cp / sizeof *cp) - (cr_wide && cr_codes ? 0 : 1),
cw, 4),
{w.in.x, w.ab}, {w.o.x});
if (op_cr && w.o.cq() && !o_plain) {
if (op_cr && cr_codes) {
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
RAD_ARCH_TRY(rad_op_writes(b, op_cr, oq, 2));
}
@@ -467,8 +482,12 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
/* At decode and verify sizes the a|b projection is nearly all launch cost and reads only the
* norm's output, as the in-projection does, so it runs beside it on lane 1 and is joined before
* the convolution reads `ab`. A prefill chunk keeps one lane, where the two would share
* bandwidth. */
if (ab_lane && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) {
* bandwidth. Where launches chain it stays on lane 0: its chained form starts beside the
* in-projection without the two lane joins, each of which holds a launch back until the host
* has seen the other lane finish (Qwen3.8-27B on two cards: the projection started 55 us late
* and the update behind it another 20 to 40 us). */
if (ab_lane && !rad_chain_on() && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK &&
rad_lane(c, 1) == RAD_OK) {
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
rad_lane(c, 0);
in.step(c, w.h, w.in.x, T);
@@ -502,11 +521,18 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
/* 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). */
* beside it: in front of the update on lane 0 where launches chain (the read's chained form
* holds nothing behind it), else 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);
const rad_op pf = op_pf_out_v && T >= pf_out_v_rows ? op_pf_out_v : op_pf_out;
if (prefetch_lane0()) {
RAD_ISSUE(c, pf, RAD_W(out.w));
} else {
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
RAD_ISSUE(c, pf, RAD_W(out.w));
rad_lane(c, 0);
}
}
if (D > 0 && op_cr && qd <= cr_rows) {
RAD_ISSUE_N(c, op_cr, qd,
@@ -517,8 +543,9 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1),
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
w.o.cq() && !o_plain ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() && !o_plain ? brows(w.o.cs(), DT) : RAD_NONE);
cr_codes ? brows(w.o.cq(), DT) : RAD_NONE,
cr_codes ? brows(w.o.cs(), DT) : RAD_NONE);
if (w.o.cq() && !o_plain && !cr_codes) q_o.step(c, T, 0, DT);
} else if (D > 0) {
RAD_ISSUE_N(c, op_conv_update, qd,
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
+39 -11
View File
@@ -77,12 +77,13 @@ struct HyperConn {
* skips its own on every step takes_ar() accepts. The block's partial sum is the write's
* input buffer, so this saves a launch. */
int reduce = 0;
/* Whether the read also emits Hadamard-rotated fp8 codes of the block input, for a
* consumer whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in
* the plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
/* Whether the read also emits Hadamard-rotated codes of the block input, for a consumer
* whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in the
* plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
int rotate = 0;
/* Whether the plain codes are int8 (q8/s8) rather than E4M3 (q/s), for int8 trunk linears
* (LinearFP8::i8). The rotated codes stay E4M3, the routed experts' operand. */
* (LinearFP8::i8). The rotated codes take the same dtype (had_quant_act_i8g's beside int8,
* had_quant_act_fp8's beside E4M3), so `Wire::rq` is declared to match. */
int codes_i8 = 0;
/* The most rows one read is declared for, 0 for max_tok; a wider step reads in pieces
* (read_pieces). The read's scratch is sized for its band (some 22 KiB a row at
@@ -115,6 +116,11 @@ struct HyperConn {
* `mix`), read from their encoding at declare. */
bool mix_e4m3 = false;
rad_op op_read = 0, op_write = 0;
/* The block input's own int8 pair is the rotated one (ActFP8::q8_rot, a trunk stored rotated):
* the read writes its rotated codes there and its plain ones into `pq` / `ps`, a pair of this
* connection's that nothing reads. */
bool xrot = false;
rad_buf pq = 0, ps = 0;
/* The write with the all-reduce folded in; 0 when not requested or not served.
* `op_ar_write6` is the same on the rotated 6-bit wire, declared only when a lossy payload is
* accepted and issued on the steps ar_wire_is_exact rejects (every trunk all-reduce at a
@@ -193,6 +199,17 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
return RAD_E_INVAL;
}
if (c.quant && (c.codes_i8 ? (!w.x.q8 || !w.x.s8) : (!w.x.q || !w.x.s))) return RAD_E_INVAL;
/* A trunk whose int8 linears are stored rotated reads the rotated codes alone: `x`'s int8 pair
* is then that pair (ActFP8::q8_rot), and every reader of the block input -- the trunk's
* projections and the rotated experts -- takes it. The read derives the rotated codes in its
* plain codes' finisher, so the plain ones still have somewhere to go: a pair of this
* connection's own that nothing reads. */
xrot = c.quant && c.codes_i8 && w.x.q8_rot;
if (xrot && c.rotate) {
fprintf(stderr, "radiance: %s: the block input's own codes are the rotated ones "
"(ActFP8::q8_rot), so there is no second rotated pair to ask for\n", name);
return RAD_E_INVAL;
}
if (c.rotate && (!c.quant || !w.rq || !w.rs)) {
fprintf(stderr, "radiance: %s: the rotated codes need the plain ones (quant) and the "
"rq/rs pair on the wire\n", name);
@@ -248,8 +265,16 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
int n_wr = 1;
if (c.inject) wr[n_wr++] = w.inj;
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
if (xrot) {
pq = decl_b(b, nm.f("%s.plain.q8", name), RAD_I8, { g.max_tok, g.n_embd });
ps = decl_b(b, nm.f("%s.plain.s8", name), RAD_F32, { g.max_tok, fp8_blocks(g.n_embd) });
if (!pq || !ps || w.x.g8 != RAD_FP8_BLOCK) return RAD_E_INVAL;
wr[n_wr++] = pq; wr[n_wr++] = ps;
wr[n_wr++] = w.x.q8; wr[n_wr++] = w.x.s8;
} else {
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
}
op_read = RAD_OP(b, "hc_read",
RAD_PARAMS(RAD_RANGE("M", 1, c.read_rows > 0 && c.read_rows < g.max_tok
@@ -259,7 +284,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
RAD_F64("wadd", g.wadd), RAD_INT("inject", c.inject ? 1 : 0),
RAD_INT("group", c.quant ? RAD_FP8_BLOCK : 0),
RAD_INT("rotate", c.rotate ? 1 : 0),
RAD_INT("rotate", (c.rotate || xrot) ? 1 : 0),
RAD_STR("mix", mix_e4m3 ? "e4m3" : "bf16")),
wts, n_wts);
if (!op_read) return RAD_E_INVAL;
@@ -358,11 +383,14 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
c.inject ? RAD_W(w_inj) : RAD_NONE,
brow_slice(w.x.x, r0, rows, g.n_embd),
c.inject ? brow_slice(w.inj, r0, rows, c.hc) : RAD_NONE,
c.quant ? brow_slice(c.codes_i8 ? w.x.q8 : w.x.q, r0, rows, g.n_embd) : RAD_NONE,
c.quant ? brow_slice(c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
c.quant ? brow_slice(xrot ? pq : c.codes_i8 ? w.x.q8 : w.x.q, r0, rows,
g.n_embd) : RAD_NONE,
c.quant ? brow_slice(xrot ? ps : c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
fp8_blocks(g.n_embd)) : RAD_NONE,
c.rotate ? brow_slice(w.rq, r0, rows, g.n_embd) : RAD_NONE,
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
(c.rotate || xrot) ? brow_slice(xrot ? w.x.q8 : w.rq, r0, rows, g.n_embd)
: RAD_NONE,
(c.rotate || xrot) ? brow_slice(xrot ? w.x.s8 : w.rs, r0, rows,
fp8_blocks(g.n_embd)) : RAD_NONE);
}
/* ================================================================== the control-vector projection
+332 -133
View File
@@ -259,6 +259,17 @@ struct MoeFP8 {
* layer's; the 64-group codebook forms may differ by layer and projection, and declare()
* resolves each layer's (MoeFP8::fmt). */
int expert_w5 = 0;
int expert_w6 = 0; /* six-bit codebook, E4M3 scale per 64 */
/* Int8 experts (`i8*bf16[1x128]/fwht128`): codes -127..127 with a bf16 scale per (row, 128
* of K), each 128 of K rotated as `expert_rot` describes, read against int8 activations
* (dtype `i8a8h`). The eight-bit expert of an int8 model, where block fp8 is that of an
* E4M3 one. Set with `expert_rot`. */
int expert_i8 = 0;
/* Experts as IQR weights: the rotated computed trellis (libquant's tcq_code=mad) under one
* f32 scale a row, two to six bits a code, each expert decoded where the grouped GEMM
* reads it against the rotated int8 activations (dtype `i8a8h`, libr4d's moe_gemm_iqr).
* Set with `expert_rot`. */
int expert_iqr = 0;
/* Plain bf16 experts (no quantising recipe). Both GEMMs are `moe_gemm` over one table of
* whole experts with `silu_mul` between, and the shared arm follows the trunk
* (Geom::w_bf16). Not sliced by parity: each expert is served whole on its rank, which
@@ -302,6 +313,11 @@ struct MoeFP8 {
rad_buf ew = 0; /* [max_tok, top_k] F32 for sigmoid_router, BF16 otherwise */
rad_buf eoff = 0; /* [n_expert + 1] i32 */
rad_buf ecnt = 0; /* [n_expert] i32 */
/* Above 0, `ecnt` is the model's routing table (rad_route_table), [layers, ecnt_pitch],
* and this block's counts are its row `layer`: the report then costs no copy and every
* layer keeps its own counts. 0: `ecnt` is one row, which the layers sharing the wire
* overwrite in turn. */
int64_t ecnt_pitch = 0;
/* the expert planes, one row per (token, slot), a pass tall */
rad_buf sorted = 0; /* [rows * top_k] i32, pass-relative slot indices */
/* Each slot's row in `sorted`, -1 when dropped; with it the sort writes the gather's slot
@@ -364,6 +380,18 @@ struct MoeFP8 {
NormQuantFP8 nq_h{};
GateQuantFP8 gq_exp{}, gq_sh{};
/* The shared arm's gate_up and its quantiser as one launch (decl_gated_fold_iqr), and the rows
* it serves; 0 where the pair runs. */
rad_op op_sh_gated = 0;
int64_t sh_gated_rows = 0;
/* Whether the routed gate_up is a trellis weight (moe_gemm_iqr), and the routed rows from
* which the shared arm's first stage then runs beside the router instead (pass()). */
bool gu_trellis = false;
static constexpr int64_t kSharedFirstRows = 100;
/* The steps, by their rows [lo, hi], whose shared down projection is issued in front of the
* routed down GEMM instead of behind it (pass()); hi 0, the default, keeps it behind on
* every step. */
int64_t sh_down_first_lo = 0, sh_down_first_hi = 0;
LinearFP8 sh_gate_up{}, sh_down{};
rad_op op_router = 0, op_topk = 0, op_scatter = 0;
/* `op_scatter` is moe_scatter_inv and `op_gather` moe_gather_inv: the sort writes `w.inv` and
@@ -392,6 +420,16 @@ struct MoeFP8 {
* no quantiser for it. Set before declare. */
bool hr_in = false;
rad_op op_gu = 0, op_dn = 0, op_gather = 0;
/* The routed arm's activations are int8: rotated codes with an f32 scale per (row, group),
* which the grouped GEMMs meet with the iu8 WMMA (the `a8i8` and `i8a8h` dtypes). The
* architecture asks for it by feeding `Wire::eff` int8 (ActFP8::q8_fed with q8_rot); int8
* experts take nothing else, and the rotated four-bit forms take either. Resolved by
* declare(). */
bool a8 = false;
/* The codes gate_up reads and the K one of their scales covers: `h`'s own pair where the
* trunk feeds rotated int8 (at its group, 128 or IQ8R's 256), else `hr`'s. */
rad_buf gin_q = 0, gin_s = 0;
int64_t gin_g = RAD_FP8_BLOCK;
/* Protected experts: local experts a quantised layer keeps bf16, the few whose output dwarfs
* the rest (docs/MOE-W4.md). The scatter sorts them last (`protect`, `prot_list`), the
* quantised GEMMs serve the other `n_reg`, and a bf16 grouped GEMM pair serves these over the
@@ -413,9 +451,13 @@ struct MoeFP8 {
* number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */
int ncls = 2;
/* This layer's gate_up and down formats (format_of's numbers), resolved by declare(): the
* probed layer's, except that among the codebook forms at E4M3 scales (w4nl64a8h, w4nl32a8h,
* w5nl64a8h) each projection of each layer takes its own experts'. */
* probed layer's, except that among the forms reading one input (declare()'s `family`: the
* codebook forms at E4M3 scales, or under an int8 routed arm every form with an int8 row) each
* projection of each layer takes its own experts'. */
int fmt[2] = { 0, 0 };
/* The encoding of the layer's first quantised expert, per projection: a trellis's code width
* is the views' dtype. */
RadEncoding fenc[2]{};
std::vector<rad_weight> w_pgu, w_pdn;
rad_buf b_pgu = 0;
ActFP8 pff{};
@@ -469,11 +511,18 @@ struct MoeFP8 {
static int probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg);
/* The format `e` names: 0 block fp8, 1 four-bit, 2 four-bit rotated, 3 plain bf16, 4 the
* rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales per 64 and 32 of K, 7 its
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales; RAD_E_DTYPE otherwise. */
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales, 10 rotated int8, 11 the rotated
* computed trellis under one f32 scale a row (an IQR weight an expert); RAD_E_DTYPE
* otherwise. */
static int format_of(const RadEncoding& e);
/* format_of's numbers as the grouped GEMMs' dtype strings. */
static constexpr const char* kServed[10] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8", "fp8a8f32" };
/* format_of's numbers as the grouped GEMMs' dtype strings against an E4M3 activation, and
* against an int8 one (null: the format has no such row). Int8 experts read int8 only. */
static constexpr const char* kServed[13] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8",
"fp8a8f32", nullptr, nullptr, "w6nl64a8h" };
static constexpr const char* kServed8[13] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr,
"w4nl64a8i8h", "w4nl32a8i8h", nullptr, nullptr,
nullptr, "i8a8h", "i8a8h", nullptr };
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
@@ -505,6 +554,10 @@ struct MoeFP8 {
inline int MoeFP8::format_of(const RadEncoding& e) {
if (linear_is_mxfp4(e)) return 8;
if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3;
/* The computed trellis under one f32 scale a row, rotated (IQR-V4's feed-forward form). */
if (rad_enc_is(&e, "trellis"))
return std::strcmp(e.transform, "fwht128") == 0 && linear_w8h_mad(e) &&
linear_w8h_rowf(e) ? 11 : RAD_E_DTYPE;
if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
/* The codebook at E4M3 scales per 64 or 32 of K under one fixed f32 (w4nl64a8h, w4nl32a8h),
@@ -521,6 +574,8 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
return sc->block[1] == RAD_FP8_BLOCK / 2 ? 5 : 6;
if (t->extent[1] == 32 && e.plane[0].dtype == RAD_U5 && sc->block[1] == RAD_FP8_BLOCK / 2)
return 7;
if (t->extent[1] == 64 && e.plane[0].dtype == RAD_U6 && sc->block[1] == RAD_FP8_BLOCK / 2)
return 12;
return RAD_E_DTYPE;
}
if (!sc) return RAD_E_DTYPE;
@@ -544,6 +599,9 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
if (!e.transform[0]) return 1;
if (std::strcmp(e.transform, "fwht128") == 0) return 2;
}
if (e.plane[0].dtype == RAD_I8 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
std::strcmp(e.transform, "fwht128") == 0)
return 10;
return RAD_E_DTYPE;
}
@@ -616,7 +674,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
cfg->probed_count = ge - g0 + 1;
RadEncoding e{};
f = 0;
if (weight_enc(b, guw, &e) && (f = format_of(e)) < 0) {
const bool known = weight_enc(b, guw, &e);
if (known && (f = format_of(e)) < 0) {
char en[256];
rad_enc_format(&e, en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s, and the routed experts are served as block fp8 "
@@ -624,17 +683,23 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
"/fwht128; or u4 codes into a 16-entry f32 table, /fwht128) or plain "
"bf16; or the codebook at E4M3 scales a 64 or 32 of K under a fixed "
"f32, or its 32-entry five-bit form at a 64, or OCP MXFP4 "
"(fp4_e2m1*e8m0[1x32]). "
"Convert it with a recipe that makes one of them.\n", guw, en);
"(fp4_e2m1*e8m0[1x32]), or rotated int8 (i8*bf16[1x128]/fwht128), or "
"the rotated computed trellis under one f32 scale a row. Convert it "
"with a recipe that makes one of them.\n", guw, en);
return RAD_E_DTYPE;
}
if (known && (f == 0 || f == 8 || f == 9))
return linear_refuse_retired(guw, f == 8 ? "MXFP4" : "block fp8");
if (f != 3) break;
}
cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0;
cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 12) ? 1 : 0;
cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 10 || f == 11 || f == 12) ? 1 : 0;
cfg->expert_i8 = f == 10 ? 1 : 0;
cfg->expert_iqr = f == 11 ? 1 : 0;
cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7 || f == 12) ? 1 : 0;
cfg->expert_g64 = (f == 5 || f == 7 || f == 12) ? 2 : f == 6 ? 4 : 0;
cfg->expert_w5 = f == 7 ? 1 : 0;
cfg->expert_w6 = f == 12 ? 1 : 0;
cfg->expert_bf16 = f == 3 ? 1 : 0;
cfg->expert_mx = f == 8 ? 1 : 0;
cfg->expert_f32_scale = f == 9 ? 1 : 0;
@@ -693,7 +758,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* refused, since the fused all-reduce lives inside the norm. See rad_block_attn_gated_fp8.h. */
ext_in = (src.norm == nullptr);
if (ext_in) {
if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
if (!w.h.x || (!g.w_bf16 && (!w.h.cq() || !w.h.cs())) || ar_in != kArNone)
return RAD_E_INVAL;
} else {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l), src.norm));
w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
@@ -714,9 +780,12 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_ARCH_TRY(moe_map_expert(b, nm, src, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge),
nm.f("blk.%d.ffn_down_exps.%lld.weight", l, ge), ge, !probed));
}
/* The routed arm's activations (see `a8`), known before the layer's formats are resolved:
* which forms may share a model depends on the codes they read. */
a8 = w.eff.q8_fed && !c.expert_bf16;
prot.clear();
{
const int want = c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
const int want = c.expert_iqr ? 11 : c.expert_i8 ? 10 : c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w6 ? 12 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
: c.expert_g64 ? 5 : c.expert_nl ? 4
: c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0;
auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) {
@@ -728,36 +797,54 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
if (weight_enc(b, nmv[i], &enc[i])) fe[i] = format_of(enc[i]);
}
};
/* The codebook forms at E4M3 scales differ only in the GEMM's dtype (same rotated input,
* scale views, fixed second level, accumulators), so each layer and projection may use any
* of them. The layer's first non-bf16 expert decides both; every other must match. Outside
* that family a layer uses the probed layer's form. */
auto family = [](int f) { return f == 5 || f == 6 || f == 7; };
/* The forms that read one input may differ by layer and projection: against E4M3 codes the
* codebook forms at E4M3 scales (same rotated input, scale views, fixed second level,
* accumulators; only the GEMM's dtype differs), and against the rotated int8 pair every
* form with a row for it (four-bit, the codebook at a 64 or 32 of K, int8), whose views
* efmt_of states per projection. The layer's first non-bf16 expert decides both
* projections; every other must match. Outside its family a layer uses the probed
* layer's form. */
const bool a8f = a8;
auto family = [a8f](int f) {
return a8f ? (f == 2 || f == 5 || f == 6 || f == 10 || f == 11)
: (f == 5 || f == 6 || f == 7 || f == 12);
};
fmt[0] = fmt[1] = want;
if (family(want))
for (int64_t e = 0; e < ne; ++e) {
RadEncoding enc[2]{};
int fe[2];
const char* nmv[2];
fmt_of(e, enc, fe, nmv);
if (fe[0] == 3 && fe[1] == 3) continue;
for (int i = 0; i < 2; ++i)
if (family(fe[i])) fmt[i] = fe[i];
break;
fenc[0] = fenc[1] = RadEncoding{};
for (int64_t e = 0; e < ne; ++e) {
RadEncoding enc[2]{};
int fe[2];
const char* nmv[2];
fmt_of(e, enc, fe, nmv);
if (fe[0] == 3 && fe[1] == 3) continue;
for (int i = 0; i < 2; ++i) {
/* A trellis gate_up reads rotated int8, but the down projection can use the
* W5NL E4M3 kernel: its gated intermediate is quantised independently below. */
const bool mixed_codebook_down = a8f && want == 11 && i == 1 &&
(fe[i] == 7 || fe[i] == 12);
if (family(want) && (family(fe[i]) || mixed_codebook_down)) fmt[i] = fe[i];
fenc[i] = enc[i];
}
break;
}
for (int64_t e = 0; e < ne; ++e) {
RadEncoding enc[2]{};
int fe[2];
const char* names[2];
fmt_of(e, enc, fe, names);
if (fe[0] == fmt[0] && fe[1] == fmt[1]) continue;
/* A trellis layer is one code width a projection: the views are declared at it. */
const bool same = fe[0] == fmt[0] && fe[1] == fmt[1] &&
(fmt[0] != 11 || enc[0].plane[0].dtype == fenc[0].plane[0].dtype) &&
(fmt[1] != 11 || enc[1].plane[0].dtype == fenc[1].plane[0].dtype);
if (same) continue;
if (want != 3 && fe[0] == 3 && fe[1] == 3) { prot.push_back(e); continue; }
const int i = fe[0] != fmt[0] ? 0 : 1;
char en[256];
rad_enc_format(&enc[i], en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s, and this layer's experts are served as %s -- one "
"table of experts takes one encoding, and only a whole expert kept "
"plain bf16 is served beside it.\n", names[i], en, kServed[fmt[i]]);
"plain bf16 is served beside it.\n", names[i], en,
kServed[fmt[i]] ? kServed[fmt[i]] : kServed8[fmt[i]]);
return RAD_E_DTYPE;
}
}
@@ -950,14 +1037,33 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
(long long)wq[q], (long long)g.n_embd, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
/* The codes view's dtype and planes; a codebook's table is selected with its codes so the
* relayout sees it. */
auto edt_of = [&](int f) {
return f == 8 ? (uint32_t)RAD_FP4E2M1 : f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
: c.expert_w4 ? (uint32_t)RAD_I4 : (uint32_t)RAD_F8E4M3;
/* A format's views: the codes view's dtype and planes (a codebook's table is selected with its
* codes so the relayout sees it), and the scale view's -- bf16 per
* (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group forms E4M3 per (row, 64 of
* K) selected with the fixed second level; f32 per 128x128 tile (format 9) or E8M0 per (row, 32
* of K) for MXFP4. `sgk` is the K one declared scale column covers: a view of two planes is a
* view of the logical weight, like the codes view (rad_builder.cpp), declared at the weight's
* extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
* hook. */
struct EFmt { uint32_t cdt; const char* cplanes; uint32_t sdt; int64_t sgk; const char* splanes; };
auto efmt_of = [](int f, const RadEncoding& fe) -> EFmt {
switch (f) {
/* An IQR weight: the codes at their stored width with the code's planes, and the row and
* block scales as one view at the weight's extents (LinearFP8's views of the same form). */
case 12: return { RAD_U6, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
case 11: return { fe.plane[0].dtype, "codes,trellis,trellis.mad", RAD_F32, 1,
"scale,scale.col" };
case 10: return { RAD_I8, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
case 9: return { RAD_F8E4M3, "codes", RAD_F32, RAD_FP8_BLOCK, "scale" };
case 8: return { RAD_FP4E2M1, "codes", RAD_E8M0, RAD_MX_GROUP, "scale" };
case 7: return { RAD_U5, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
case 5: case 6: return { RAD_U4, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
case 4: return { RAD_U4, "codes,table", RAD_BF16, RAD_FP8_BLOCK, "scale" };
case 1: case 2: return { RAD_I4, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
default: return { RAD_F8E4M3, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
}
};
const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) };
const char* const ecodes = c.expert_nl ? "codes,table" : "codes";
const EFmt ef[2] = { efmt_of(fmt[0], fenc[0]), efmt_of(fmt[1], fenc[1]) };
/* Under expert parallelism each owned expert is whole, so its weights are not sharded;
* RAD_SHARD_ROW would make the loader slice it again (and refuse). */
const bool ep = c.n_expert != c.n_expert_all;
@@ -972,33 +1078,57 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
*
* Rotation exists only for the 4-bit plane (the fp8 layout hook has no rotated form), and the
* codebook only with rotation; other combinations are refused. */
if ((c.expert_rot && !c.expert_w4) || (c.expert_nl && !c.expert_rot)) {
fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit expert format, "
"and a codebook (expert_nl) the rotated one; there is no rotated E4M3 "
"expert plane and no unrotated codebook\n");
if ((c.expert_rot && !c.expert_w4 && !c.expert_i8 && !c.expert_iqr) ||
(c.expert_nl && !c.expert_rot) || ((c.expert_i8 || c.expert_iqr) && !c.expert_rot)) {
fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit or the int8 "
"expert format, and a codebook (expert_nl) or int8 experts the rotated "
"one; there is no rotated E4M3 expert plane, no unrotated codebook and no "
"unrotated int8 expert\n");
return RAD_E_INVAL;
}
/* ---- The routed arm's activations (see `a8`). */
if ((c.expert_i8 || c.expert_iqr || fmt[0] == 10 || fmt[0] == 11 ||
fmt[1] == 10 || fmt[1] == 11) && !a8) {
fprintf(stderr, "radiance: layer %d's experts read int8 activations (int8, or an IQR weight); the "
"architecture declared the routed arm's codes E4M3\n", l);
return RAD_E_UNSUPPORTED;
}
const bool down_codebook_fp8 = a8 && fmt[0] == 11 && (fmt[1] == 7 || fmt[1] == 12);
if (a8) {
const bool pair = w.eff.q8 && w.eff.s8 && w.eff.q8_rot && w.eff.g8 == RAD_FP8_BLOCK;
const bool down_supported = down_codebook_fp8 ? (w.eff.q && w.eff.s && kServed[fmt[1]])
: kServed8[fmt[1]] != nullptr;
/* A clamped layer is served too: GateQuantFP8 clamps into the bf16 plane, then
* quantises it into the rotated codes. Not before a codebook (W5NL, W6NL) down
* projection, which reads rotated E4M3: no clamp writes those codes. */
const bool clamp_codebook = down_codebook_fp8 && c.swiglu_limit > 0;
if (!pair || !c.expert_rot || !kServed8[fmt[0]] || !down_supported || c.calib ||
clamp_codebook) {
fprintf(stderr, "radiance: layer %d: int8 activations meet rotated experts (int8, "
"four-bit, or the codebook at E4M3 scales a 64 or 32 of K) through "
"rotated codes at one scale a 128 of K, outside calibration; these "
"are %s / %s%s%s\n", l,
kServed[fmt[0]] ? kServed[fmt[0]] : kServed8[fmt[0]],
kServed[fmt[1]] ? kServed[fmt[1]] : kServed8[fmt[1]],
pair ? "" : ", and the gated product's int8 pair is not that",
clamp_codebook ? ", and a W5NL or W6NL down projection is served unclamped only"
: "");
return RAD_E_UNSUPPORTED;
}
}
const int sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW;
const int sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL;
const int n_parts = ep ? 0 : (int)gu;
/* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit (per 32
* for MXFP4). `sdiv` is how many weight rows or columns one scale covers along the split
* dimension. */
const int64_t sdiv = (c.expert_w4 || c.expert_mx) ? 1 : RAD_FP8_BLOCK;
const bool rowscale = c.expert_w4 || c.expert_mx || c.expert_i8 || c.expert_iqr;
const int64_t sdiv = rowscale ? 1 : RAD_FP8_BLOCK;
/* The dtype string per projection selects the grouped GEMM; its layout hook then accepts the
* experts' encoding or the kernel is not a candidate. */
const char* const edtype[2] = { kServed[fmt[0]], kServed[fmt[1]] };
/* The scale views: bf16 per (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group
* forms E4M3 per (row, 64 of K) selected with the fixed second level; f32 per 128x128 tile
* (expert_f32_scale) or E8M0 per (row, 32 of K) for MXFP4. With two planes it is a
* view of the logical weight, like the codes view (rad_builder.cpp): declared at the weight's
* extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
* hook. `sgk` is the K one declared scale column covers. */
const uint32_t sdt = c.expert_f32_scale ? (uint32_t)RAD_F32
: c.expert_mx ? (uint32_t)RAD_E8M0
: c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
const int64_t sgk = c.expert_mx ? RAD_MX_GROUP : c.expert_g64 ? 1 : RAD_FP8_BLOCK;
const char* escale = c.expert_g64 ? "scale,scale.1" : "scale";
gu_trellis = fmt[0] == 11;
const char* const edtype[2] = { a8 ? kServed8[fmt[0]] : kServed[fmt[0]],
a8 && !down_codebook_fp8 ? kServed8[fmt[1]] : kServed[fmt[1]] };
/* This class's slice of each expert: gate and up rows [lo, hi), down columns [lo, hi), scale
* planes the same in their own units. */
auto span = [&](rad_weight h, int q, int64_t unit) -> int {
@@ -1064,7 +1194,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rad_weight& h = w_gu[(size_t)s];
h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
nullptr, ecodes, edt[0], {gu * wq[q], g.n_embd},
nullptr, ef[0].cplanes, ef[0].cdt, {gu * wq[q], g.n_embd},
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
parts, n_parts);
if (!h) return RAD_E_INVAL;
@@ -1079,9 +1209,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
(long long)(c.expert_base + e)),
nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{(c.expert_w4 || c.expert_mx) ? gu * wq[q] : fp8_blocks(gu * wq[q]),
(c.expert_w4 || c.expert_mx) ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
ef[0].splanes, ef[0].sdt,
{rowscale ? gu * wq[q] : fp8_blocks(gu * wq[q]),
rowscale ? g.n_embd / ef[0].sgk : fp8_blocks(g.n_embd)},
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
parts, n_parts);
if (!h) return RAD_E_INVAL;
@@ -1093,7 +1223,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rad_weight& h = w_dn[(size_t)s];
h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
nullptr, ecodes, edt[1], {g.n_embd, wq[q]},
nullptr, ef[1].cplanes, ef[1].cdt, {g.n_embd, wq[q]},
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
if (!h) return RAD_E_INVAL;
RAD_ARCH_TRY(span(h, q, 1));
@@ -1106,11 +1236,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
(long long)(c.expert_base + e)),
nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{(c.expert_w4 || c.expert_mx) ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
ef[1].splanes, ef[1].sdt,
{rowscale ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / ef[1].sgk},
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
if (!h) return RAD_E_INVAL;
RAD_ARCH_TRY(span(h, q, sgk));
RAD_ARCH_TRY(span(h, q, ef[1].sgk));
}
/* ---- the two grouped GEMMs. `M` is a pass's token count, not the sorted row count: kernels
@@ -1125,19 +1255,32 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The routed arm's rotated copy of the input. Not in place: the shared expert also reads
* `w.h.q` with an unrotated weight (see Config::expert_rot). Declared just before its one
* consumer so graph and issue order agree. */
if (rot) {
if (!w.hr.q || !w.hr.s) {
fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire; "
"the architecture declares the buffers\n");
gin_q = w.h.q;
gin_s = w.h.s;
gin_g = RAD_FP8_BLOCK;
if (a8 && w.h.q8_fed && w.h.q8_rot) {
/* The trunk's own rotated int8 codes, at its group: no second quantiser. */
gin_q = w.h.q8;
gin_s = w.h.s8;
gin_g = w.h.g8;
} else if (rot) {
if (a8 ? !(w.hr.q8 && w.hr.s8 && w.hr.q8_fed && w.hr.q8_rot) : !(w.hr.q && w.hr.s)) {
fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire%s; "
"the architecture declares the buffers\n",
a8 ? ", int8 and fed" : "");
return RAD_E_INVAL;
}
gin_q = w.hr.cq();
gin_s = w.hr.cs();
gin_g = w.hr.cg();
if (!hr_in)
op_hq = rw(b, RAD_OP(b, "had_quant_act_fp8",
op_hq = rw(b, RAD_OP(b, a8 ? "had_quant_act_i8g" : "had_quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", gin_g), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h.x}, {w.hr.q, w.hr.s});
{w.h.x}, {gin_q, gin_s});
}
if (!gin_q || !gin_s || g.n_embd % gin_g) return RAD_E_INVAL;
/* A table op's weights in operand order: even experts' codes and scales, then odd experts'
* (`w`, `w_scale`, `w_odd`, `w_odd_scale`), or at four classes classes 0 to 3. */
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
@@ -1154,55 +1297,64 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* and the zeros past the width are never read by that class's down projection. */
{
const std::vector<rad_weight> tab = tables(w_gu, w_gus);
/* `a_group` is stated to the int8 rows alone: last, and cut off otherwise, so an E4M3
* graph is the one it was. */
const RadParam p4[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_1", gu * wq[1]), RAD_INT("K_1", g.n_embd),
RAD_INT("N_2", gu * wq[2]), RAD_INT("K_2", g.n_embd),
RAD_INT("N_3", gu * wq[3]), RAD_INT("K_3", g.n_embd),
RAD_INT("parts", gu), RAD_INT("a_group", gin_g) };
const RadParam p2[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
RAD_INT("parts", gu), RAD_INT("a_group", gin_g) };
const int cut = a8 ? 0 : 1;
rad_op h = ncls == 4
? rad_decl_op(b, "moe_gemm_q_mod4",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_1", gu * wq[1]), RAD_INT("K_1", g.n_embd),
RAD_INT("N_2", gu * wq[2]), RAD_INT("K_2", g.n_embd),
RAD_INT("N_3", gu * wq[3]), RAD_INT("K_3", g.n_embd),
RAD_INT("parts", gu)),
tab.data(), (int)tab.size())
: rad_decl_op(b, "moe_gemm_q",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
RAD_INT("parts", gu)),
tab.data(), (int)tab.size());
op_gu = rw(b, h, {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, w.sorted, w.eoff}, {w.egu});
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
tab.data(), (int)tab.size())
: rad_decl_op(b, "moe_gemm_q", p2, (int)(sizeof p2 / sizeof *p2) - cut,
tab.data(), (int)tab.size());
op_gu = rw(b, h, {gin_q, gin_s, w.sorted, w.eoff}, {w.egu});
}
/* The down projection's input can be rotated in place: `w.eff` is read only by the down GEMM,
* which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to
* the rotated op at no extra launch. */
gq_exp.fuse_clamped = c.swiglu_quant != 0;
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
false, rot, c.swiglu_limit, c.swiglu_step != 0));
/* Gate_up and down are separate GEMMs. A trellis gate uses int8 input while W5NL down
* reads rotated E4M3: select the latter pair only for the gated intermediate. */
ActFP8 down_eff = w.eff;
if (down_codebook_fp8) down_eff.q8_fed = down_eff.q8_rot = false;
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, down_eff, c.n_ff_exp, gact, c.rows * c.top_k,
false, rot && (!a8 || down_codebook_fp8), c.swiglu_limit,
c.swiglu_step != 0));
{
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
const RadParam p4[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
RAD_INT("parts", 1), RAD_INT("a_group", RAD_FP8_BLOCK) };
const RadParam p2[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]),
RAD_INT("parts", 1), RAD_INT("a_group", RAD_FP8_BLOCK) };
const int cut = a8 && !down_codebook_fp8 ? 0 : 1;
rad_op h = ncls == 4
? rad_decl_op(b, "moe_gemm_q_mod4",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
RAD_INT("parts", 1)),
tab.data(), (int)tab.size())
: rad_decl_op(b, "moe_gemm_q",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]),
RAD_INT("parts", 1)),
tab.data(), (int)tab.size());
op_dn = rw(b, h, {w.eff.q, w.eff.s, w.sorted, w.eoff}, {w.edn});
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
tab.data(), (int)tab.size())
: rad_decl_op(b, "moe_gemm_q", p2, (int)(sizeof p2 / sizeof *p2) - cut,
tab.data(), (int)tab.size());
op_dn = rw(b, h, {down_eff.cq(), down_eff.cs(), w.sorted, w.eoff}, {w.edn});
}
/* ---- The protected experts' own GEMM pair. Their weights belong to the layer group, not to
* expert slots: each container expert unit has a fixed size and these are four times larger, so
@@ -1339,7 +1491,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_NOWEIGHTS),
{rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, b_gram_gu}, {b_gram_gu});
{gin_q, gin_s, b_gram_gu}, {b_gram_gu});
/* The down tap's M is the sorted height `rows * top_k` (one row per (token, slot)).
* gate_up's is the token height: every token goes to exactly top_k experts, so the gathered
* distribution is the token distribution scaled by top_k, and H is used only up to scale. */
@@ -1412,7 +1564,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const char* shared_up = src.shared_mlp_up
? src.shared_mlp_up
: nm.ckpt("%s.up_proj.weight", src.shared);
RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, { shared_down }));
/* An architecture that sized the gate's code pair from this weight has probed it. */
if (!sh_down.mapped) RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, { shared_down }));
/* The code pair the gate writes, E4M3 or int8 (ActFP8::q8_fed); an int8 down projection
* that quantises for itself also writes the int8 pair on this lane. */
if (w.sff.cq()) {
@@ -1441,6 +1594,17 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows,
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false,
sh_limit, c.swiglu_step != 0));
/* An IQR gate_up between the rotated int8 trunk's fed pairs folds SwiGLU and the rotating
* quantiser into its epilogue, to 16 rows: one launch a layer less than the pair, which
* stays declared for longer steps, other encodings and a clamped product. */
if (sh_limit <= 0 && sh_gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.sff.q8_fed &&
w.sff.q8_rot)
op_sh_gated = decl_gated_fold_iqr(
b, c.rows, sh_gate_up.N, sh_gate_up.K, sh_gate_up.w, sh_gate_up.ws,
{ w.h.q8, w.h.s8 },
gq_sh.want_x ? std::initializer_list<rad_buf>{ w.sff.q8, w.sff.s8, w.sff.x }
: std::initializer_list<rad_buf>{ w.sff.q8, w.sff.s8 },
&sh_gated_rows);
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
{ shared_down },
@@ -1641,7 +1805,14 @@ inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
brow_slice(w.sgate, r0, rows, 1));
}
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
if (op_sh_gated && rows <= sh_gated_rows)
RAD_ISSUE_N(c_, op_sh_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(sh_gate_up.w),
RAD_W(sh_gate_up.ws), brow_slice(w.sff.cq(), r0, rows, c.n_ff_shared),
brow_slice(w.sff.cs(), r0, rows, c.n_ff_shared / RAD_FP8_BLOCK),
gq_sh.want_x ? brow_slice(w.sff.x, r0, rows, c.n_ff_shared) : RAD_NONE);
else
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
}
/* One pass of at most `c.rows` tokens. Every op is per row (norm and quantiser within a row,
@@ -1660,9 +1831,10 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
/* The shared arm is interleaved with the routed arm on the same queue. It reads the same
* input and writes nothing the routed arm touches before the gather, so each of its stages
* (gate + gate_up, quantiser, down) is issued right behind the matching routed stage. A
* recorded pass leaves each such pair unordered (Ctx::haz_mark), so they overlap without a
* second queue's fork/join cost. The arm's buffers are excluded from sharing (see declare), so
* (gate + gate_up, quantiser, down) is issued right behind the matching routed stage (its
* first stage behind the router instead where `sh_first` below says so). A recorded pass
* leaves each such pair unordered (Ctx::haz_mark), so they overlap without a second queue's
* fork/join cost. The arm's buffers are excluded from sharing (see declare), so
* issuing them ahead of their declared position is safe. */
/* The routed arm. */
@@ -1675,8 +1847,11 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
* the histogram the kernel writes there never lands, and a consumer reading the reported
* counts -- the file stager, at the layer's trigger -- sees zeros and skips every expert's
* weights. The declared buffer is stable across record and replay, and route_report hands
* the same buffer on, so the stager's stream-ordered read sees this pass's counts. */
const RadOperand ecnt = brows(w.ecnt, ne);
* the same buffer on, so the stager's stream-ordered read sees this pass's counts. With a
* routing table (Wire::ecnt_pitch) the buffer is the core's rows too, and this is the
* layer's. */
const RadOperand ecnt = w.ecnt_pitch > 0 ? brow_slice(w.ecnt, layer, 1, w.ecnt_pitch)
: brows(w.ecnt, ne);
/* The fused router when it resolved and the pass fits: router, topk + scatter and (with
* `router_fused_gate`) the shared gate in one launch. Otherwise the separate ops. */
const bool rfused = op_router_fused && rows <= router_fused_rows;
@@ -1726,13 +1901,22 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
const bool rot = c.expert_rot != 0;
if (op_hq)
RAD_ISSUE_N(c_, op_hq, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
brow_slice(w.hr.q, r0, rows, g.n_embd),
brow_slice(w.hr.s, r0, rows, g.n_embd / RAD_FP8_BLOCK));
brow_slice(gin_q, r0, rows, g.n_embd),
brow_slice(gin_s, r0, rows, g.n_embd / gin_g));
/* The grouped GEMMs. Each table is the first handle of its run and its length; runs are
* contiguous (see declare), so `w_gu[q] + i` is expert 2 * i + q, or 4 * i + q at four
* classes, where class q holds ceil((n_reg - q) / 4). */
const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 };
/* Behind a trellis gate_up from kSharedFirstRows routed rows, the shared arm's first stage is
* issued here, so it overlaps the router and the routed gate_up runs alone: that GEMM is
* compute-bound at such heights, and with the arm beside it the pair ends later than the two
* in turn. Flash-Next's 16- and 32-row verify passes on two R9700: 22.1 -> 21.9 ms and
* 31.6 -> 30.95 ms. Below, the arm fits inside the routed GEMM's time and stays beside it. */
const bool sh_first = shared && gu_trellis && rows * k >= kSharedFirstRows;
if (sh_first)
shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
/* Apply the previous layer's prefetch prediction: substitute the copied experts into the
* tables. */
(void)rad_expert_prefetch_step(c_, layer);
@@ -1742,8 +1926,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
brows(w.egu, rows * k));
else if (ncls == 4)
RAD_ISSUE_N(c_, op_gu, rows,
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
brow_slice(gin_q, r0, rows, g.n_embd),
brow_slice(gin_s, r0, rows, g.n_embd / gin_g),
RAD_WTAB(w_gu[0], n4[0]), RAD_WTAB(w_gus[0], n4[0]),
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_gu[1], n4[1]), RAD_WTAB(w_gus[1], n4[1]),
@@ -1752,22 +1936,36 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
brows(w.egu, rows * k));
else
RAD_ISSUE_N(c_, op_gu, rows,
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
brow_slice(gin_q, r0, rows, g.n_embd),
brow_slice(gin_s, r0, rows, g.n_embd / gin_g),
RAD_WTAB(w_gu[0], n_reg / 2), RAD_WTAB(w_gus[0], n_reg / 2),
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2),
brows(w.egu, rows * k));
if (shared) shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
if (shared && !sh_first)
shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
gq_exp.step(c_, w.egu, rows * k, 0, rows * k);
if (shared) gq_sh.step(c_, w.sgu, T, r0, rows);
if (shared && !(op_sh_gated && rows <= sh_gated_rows)) gq_sh.step(c_, w.sgu, T, r0, rows);
/* The shared arm's down projection in front of the routed down GEMM on a step of
* [sh_down_first_lo, sh_down_first_hi] rows. Behind it (below) the two still run together,
* but the card launches the arm only once every block of the routed GEMM is on it; at a
* verify step's forty routed rows that is a few microseconds before that GEMM ends, and the
* gather then waits for the arm. In front, the arm is the ordered launch behind the two
* quantisers and the routed GEMM starts beside it (it reads nothing the arm writes): the same
* start for the routed GEMM, and the arm is done long before it. At one row the routed GEMM
* is a quarter of the blocks, the arm behind it is launched in time, and in front it only
* delays that GEMM's launch (+0.38% a step), hence the lower bound. The arm's buffers are
* excluded from sharing (declare), so the order is free. Qwen3.8-Flash-Next at tp 2 with
* coupling, chain 1 / 2 / 3 (two / three / four rows): -0.28% / -0.21% / -0.25% a step. */
const bool sh_dn_first = shared && T >= sh_down_first_lo && T <= sh_down_first_hi;
if (sh_dn_first) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
if (c.expert_bf16)
RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k));
else if (ncls == 4)
RAD_ISSUE_N(c_, op_dn, rows,
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
brows(gq_exp.a.cq(), rows * k), brows(gq_exp.a.cs(), rows * k),
RAD_WTAB(w_dn[0], n4[0]), RAD_WTAB(w_dns[0], n4[0]),
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_dn[1], n4[1]), RAD_WTAB(w_dns[1], n4[1]),
@@ -1776,7 +1974,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
brows(w.edn, rows * k));
else
RAD_ISSUE_N(c_, op_dn, rows,
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
brows(gq_exp.a.cq(), rows * k), brows(gq_exp.a.cs(), rows * k),
RAD_WTAB(w_dn[0], n_reg / 2), RAD_WTAB(w_dns[0], n_reg / 2),
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_dn[1], n_reg / 2), RAD_WTAB(w_dns[1], n_reg / 2),
@@ -1796,7 +1994,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
RAD_ISSUE_N(c_, op_pdn, rows, brows(pff.x, rows * k), RAD_WTAB(w_pdn[0], np),
brows(w.sorted, rows * k), poff, brows(w.edn, rows * k));
}
if (shared) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
if (shared && !sh_dn_first) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
/* The calibration tap reads the GEMMs' operands and writes nothing they touch, so it does not
* change the model's output. */
if (op_gram_gu && !calib_done) {
@@ -1946,12 +2144,13 @@ inline void MoeFP8::route_report(RadCtx* c_) const {
* destination row, the copy here is skipped, and the row stays zero -- which the file stager
* read as "no expert routed" and skipped every layer's weights (NaN logits, empty text).
* Copying w.ecnt into the row (the pointers now differ) also feeds the heat engine real
* histograms instead of the zeros it saw before. */
* histograms instead of the zeros it saw before. With a routing table (Wire::ecnt_pitch) the
* router did write the core's row, as a declared operand, and the report copies nothing. */
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0);
RadRouting r{};
r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids);
r.expert_w = nullptr;
r.expert_count = (const int32_t*)rad_buf_ptr(c_, w.ecnt);
r.expert_count = (const int32_t*)rad_buf_ptr(c_, w.ecnt) + (int64_t)layer * w.ecnt_pitch;
r.sorted_tok = (const int32_t*)rad_buf_ptr(c_, w.sorted);
r.expert_offset = (const int32_t*)rad_buf_ptr(c_, w.eoff);
r.top_k = c.top_k;
+65 -4
View File
@@ -152,6 +152,13 @@ struct MtpHcBlock {
MoeFP8 mlp{};
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
/* The selected draft calibration also records the bf16 attention input shared by
* qg/k/v, independently of the expert gate's later input. */
rad_buf b_attn_gram = 0;
rad_op op_attn_gram = 0;
const char* attn_gram_stem = nullptr;
mutable int64_t attn_gram_rows = 0;
mutable bool attn_gram_done = false;
/* Media rows over the head's embedding (see MtpBlockFP8::media). Set before declare when the
* program has an encoder. */
@@ -258,6 +265,20 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
* order. */
RAD_ARCH_TRY(hc_attn.declare(b, nm, g, nm.f("mtp.attn_hc"), hc, HyperConn::Wire{w.hw, w.x, w.inj},
src.hc_attn));
if (src.mlp.cfg.calib) {
/* Only a BF16 source supplies domain-0 inputs for this calibration. The input
* is replicated, so each TP rank records the same width and GPTQ sums them. */
if (!src.mlp.cfg.expert_bf16 || !w.attn.h.x) return RAD_E_UNSUPPORTED;
attn_gram_stem = nm.f("blk.%d.attn_qg", l);
b_attn_gram = decl_b(b, nm.f("blk.%d.mtp_attn_gram", l), RAD_F32,
{g.n_embd, g.n_embd}, RAD_BUF_PERSIST);
op_attn_gram = rw(b, RAD_OP(b, "gram_accum",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.attn.h.x, b_attn_gram}, {b_attn_gram});
if (!b_attn_gram || !op_attn_gram) return RAD_E_INVAL;
}
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
attn.ar_out_take = hc_attn.ar_take();
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn,
@@ -282,7 +303,11 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
/* The connection's read also writes the rotated expert input, as on the trunk. */
HyperConn::Config mcfg = hc;
HyperConn::Wire mwire{w.hw, w.x, w.inj};
if (src.mlp.cfg.expert_rot) { mcfg.rotate = 1; mwire.rq = w.mlp.hr.q; mwire.rs = w.mlp.hr.s; }
if (src.mlp.cfg.expert_rot && !w.x.q8_rot) {
mcfg.rotate = 1;
mwire.rq = w.mlp.hr.cq();
mwire.rs = w.mlp.hr.cs();
}
RAD_ARCH_TRY(hc_mlp.declare(b, nm, g, nm.f("mtp.ffn_hc"), mcfg, mwire, src.hc_mlp));
mlp.ar_out_take = hc_mlp.ar_take();
mlp.hr_in = mcfg.rotate != 0;
@@ -467,6 +492,17 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int r = batch->draft_pass;
/* Expert calibration needs real draft-layer inputs, not the trunk's Hessian. In a
* selected calibration layer, run the history's teacher-forced rows through the full
* draft block before selecting the rows needed by the drafter. Normal inference and
* a tap that has reached its target retain the ordinary history-only fast path. */
const bool tap_history = r < 0 && mlp.c.calib && !mlp.calib_done;
/* serial_batch names one trunk hidden row per history token. Refuse an incomplete
* gather instead of silently calibrating stale hin rows if that contract changes. */
if (tap_history && (batch->n_out != T || !batch->out_ids)) {
rad_step_fail(c, "MTP calibration needs one trunk hidden row per history token");
return;
}
/* The history pass continues from the trunk's wide stream; later rounds from the head's,
* which the carry left in the same buffer. */
@@ -489,11 +525,26 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
hc_attn.read_pieces(c, T);
if (tap_history && op_attn_gram && !attn_gram_done) {
if (attn_gram_rows == 0)
rad_memset_async(rad_buf_ptr(c, b_attn_gram), 0,
g.n_embd * g.n_embd * 4, rad_stream(c));
RAD_ISSUE_N(c, op_attn_gram, T, brows(w.attn.h.x, T), RAD_NONE,
brows(b_attn_gram, g.n_embd));
attn_gram_rows += T;
if (attn_gram_rows >= calib_target()) {
if (!calib_write(c, b_attn_gram, g.n_embd, attn_gram_rows, attn_gram_stem, 0)) {
rad_step_fail(c, "MTP calibration could not write its attention input Gram");
return;
}
attn_gram_done = true;
}
}
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only stores
* the head's state: K and V, and the indexer's block keys and tail. `n_draft_out` is the same
* on every rank, so skipped collectives match. */
if (r < 0 && batch->n_draft_out <= 0) {
if (r < 0 && batch->n_draft_out <= 0 && !tap_history) {
qsa.store(c, attn.w.h, batch);
attn.store_kv(c, batch);
return;
@@ -501,7 +552,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
/* The indexer runs first because the attention reads its selection; `w.h` is already final,
* written by the connection above. */
qsa.step(c, attn.w.h, batch, qsa_win_cu);
qsa.step(c, attn.w.h, batch, qsa_win_cu, attn.qsa_use(batch));
attn.step(c, batch);
hc_attn.write(c, T, 0, T);
@@ -509,7 +560,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
/* A history pass with drafting rows continues on those rows alone (round 1): they are moved
* to the front of `hw` and the rest of the head runs over them. */
int64_t L = T; /* the rows the stream goes on with */
if (r < 0) {
if (r < 0 && !tap_history) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hin, L));
@@ -520,6 +571,16 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
mlp.step_rows(c, L);
hc_mlp.write(c, L, 0, L);
if (tap_history) {
/* History-only chunks have no proposal. For the last chunk, select the same
* round-1 rows the ordinary path would have selected before its feed-forward. */
L = batch->n_draft_out;
if (L <= 0) return;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hin, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
}
/* The carry, only if a later round reads it: a history pass is round 1, followed by round 2
* when depth > 1; the last round is followed by a trunk step. */
if (r < 0 ? depth > 1 : r < depth)
File diff suppressed because it is too large. Load diff
+584
View File
@@ -0,0 +1,584 @@
/* rad_block_museglimmer_vision.h -- Muse Glimmer's vision tower (transformers'
* MuseGlimmerVisionModel, an InternVit-shaped stack), its adapter and the perception norm, served
* by museglimmer.
*
* What it computes, per encoder pass (RadBatch::enc), in the reference's order:
*
* x = patches @ Wp^T the patch embedding as a linear layer, bias-less;
* a patch row is (temporal, channel, y, x)
* x += position table resampled to the grid `grid_embed_pad`, bilinear at half-pixel
* centres, align_corners=False, out-of-range taps
* zero-weighted (grid_sample padding zeros)
* x = LN_pre(x) LayerNorm, eps `layer_norm_eps`
* x = x[window order] `window_order`: the 32x32-patch window permutation
* (per frame, ragged edges smaller windows), its
* inverse, per-slot rotary positions and the
* per-window cumulative boundaries
* depth times:
* h = LN1(x) LayerNorm, eps 1e-5 (the blocks hard-code it)
* q|k|v = qkv(h) the reference's three biased projections, joined
* q first into one GEMM as the reference's fused
* tensors would read
* rope(q, k) `rope` axial, the whole head, sections
* head_dim/4 a side on theta^(-j/(head_dim/4)),
* positions (column + 1, row + 1) -- HF's
* position_ids.flip(-1) + 1
* x += proj(attn(q, k, v)) non-causal, scale 1/sqrt(head_dim). A
* window_attention layer attends within one window
* (cu = the per-window boundaries in permuted
* order); a full_attention layer attends within
* its frame (cu = the frame boundaries). The
* window permutation never moves a patch across
* frames, so the frame boundaries among permuted
* rows are the boundaries among natural rows:
* `enc_cu` is passed unchanged, exactly what the
* reference passes (modeling_muse_glimmer.py maps
* full_attention to the frame cu_seqlens while the
* rows stay permuted).
* x += fc2(gelu(fc1(LN2(x)))) both biased; `gelu` the exact erf form the
* config's hidden_act names, in gemm_nt_bias's
* epilogue
* x = x[inv] the window order undone (gather_rows)
* x = LN_post(x) LayerNorm, eps `layer_norm_eps`
* y = pixel_shuffle(x) the merge (`pixtral_merge`): each 2x2 block's
* four patches fold into one row of merge^2 *
* width, channels interleaved -- the reference's
* [block, merge^2, dim].permute(0, 2, 1)
* y = gelu(fc2(gelu(fc1(y)))) the adapter: both linears bias-less, TWO
* activations (projector_hidden_act)
* y = y @ Wproj^T the projection, bias-less, the model's width
* out = rms(y) `perception_emb_norm`, a weightless RMS norm at
* the TEXT model's rms_norm_eps
*
* The reference permutes AFTER ln_pre, so the tower works in window order and un-permutes before
* ln_post, exactly as above. The processor stages patches in the reference's raster order; the
* merge is a real fold (not a view: the reference interleaves the four patches' channels, which
* four consecutive rows do not spell), and its output is what the adapter reads.
*
* Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the
* weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx::
* max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's
* step; the attention's longest segment stays at the real pass so the kernel rows do not move.
*/
#ifndef RAD_BLOCK_MUSEGLIMMER_VISION_H
#define RAD_BLOCK_MUSEGLIMMER_VISION_H
#include "rad_arch.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct MuseTower {
/* Geometry, from the container's vision_config (never aliased: only the full prefix). The
* adapter's widths are top-level keys of the family config. */
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0;
int64_t merge = 0, side = 0, npos = 0, proj_ff = 0, out_hidden = 0, n_embd = 0;
int64_t patch_dim = 0, P = 0;
double eps = 1e-5; /* ln_pre / ln_post; the blocks hard-code 1e-5 */
float theta = 10000.0f;
bool on = false;
struct Layer {
bool full = false; /* full_attention: frame-wide attention, NoPE-free (rotary runs
* on every layer of this tower, full or window) */
rad_weight n1w = 0, n1b = 0, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
rad_weight n2w = 0, n2b = 0, up_w = 0, up_b = 0, down_w = 0, down_b = 0;
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
int64_t max_seg = 0; /* the kernel band's longest segment */
};
std::vector<Layer> L;
rad_weight w_patch = 0, w_pos = 0, lw_pre = 0, lb_pre = 0, lw_post = 0, lb_post = 0;
rad_weight w_a1 = 0, w_a2 = 0, w_proj = 0;
rad_op op_patch = 0, op_pos = 0, op_lpre = 0, op_wo = 0, op_gidx = 0, op_ginv = 0;
rad_op op_lpost = 0, op_merge = 0, op_m1 = 0, op_g1 = 0, op_m2 = 0, op_g2 = 0, op_proj = 0,
op_perc = 0;
rad_buf b_x = 0, b_h = 0, b_p = 0, b_qkv = 0, b_att = 0, b_ff = 0;
rad_buf b_idx = 0, b_inv = 0, b_pos = 0, b_cuw = 0;
rad_buf b_mh = 0, b_m1 = 0, b_m2 = 0, b_out = 0;
char sec[48] = {};
/* Whether the container carries this family's tower. */
static bool present(const RadModelMeta* m) {
return rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
Names& nm, int64_t model_embd, int first_group) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
temporal = rad_meta_geti(m, "vision_config.patch_temporal", 2);
merge = rad_meta_geti(m, "vision_config.merge_size", 2);
side = rad_meta_geti(m, "vision_config.pos_emb_height", 0);
npos = rad_meta_geti(m, "vision_config.pos_emb_height", 0) *
rad_meta_geti(m, "vision_config.pos_emb_width", 0);
eps = rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-5);
theta = (float)rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0);
proj_ff = rad_meta_geti(m, "projector_hidden_size", 4096);
out_hidden = rad_meta_geti(m, "out_hidden_size", 6144);
n_embd = model_embd;
/* Bounds the walk and the host allocations below take at face value, set against published
* maxima rather than round numbers: the deepest vision encoder ever shipped is 48 layers
* (ViT-22B, InternViT-6B; this family's towers are SigLIP-class, tens), and the largest
* stored position table a side of 92 (SigLIP at 1292 px over patch 14; CLIP 16, SAM 64 --
* native-resolution towers store no side x side table at all). The caps sit ~2.6x and
* ~5.5x past those maxima, so they never bite an honest container, and at the cap the
* guarded shapes are harmless: the depth vectors cost KiB and the grid products reach 2^18
* at most. Past the caps the container is not describing a model but a vector size
* (full.assign(depth) and L.assign(depth) would throw past max_size, and the grid products
* below overflow signed 64 before any comparison could notice). Refuse like every other
* bad config: say so and RAD_E_INVAL. */
if (depth <= 0 || depth > 128 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 ||
temporal <= 0 || merge <= 0 || side <= 0 || side > 512 || proj_ff <= 0 ||
out_hidden <= 0 || width % heads ||
rad_meta_geti(m, "vision_config.pos_emb_width", 0) != side) {
fprintf(stderr, "radiance: museglimmer: the container's vision_config is incomplete, "
"inconsistent, or past what this tower walks (depth %lld, hidden %lld, "
"heads %lld, ff %lld, patch %lld, "
"temporal %lld, merge %lld, position grid %lld x %lld, projector %lld, "
"merged %lld)\n", (long long)depth, (long long)width, (long long)heads,
(long long)ff, (long long)patch, (long long)temporal, (long long)merge,
(long long)side, (long long)rad_meta_geti(m, "vision_config.pos_emb_width", 0),
(long long)proj_ff, (long long)out_hidden);
return RAD_E_INVAL;
}
/* The merge is `pixtral_merge`, whose kernels fold a 2x2 block: the only factor Muse Glimmer
* ships and the only one the op serves. */
if (merge != 2) {
fprintf(stderr, "radiance: museglimmer: this vision tower states merge_size %lld; the "
"merge op folds a 2x2 block\n", (long long)merge);
return RAD_E_UNSUPPORTED;
}
/* The exact-erf GELU is what this tower and its adapter state; another activation is another
* tower (the reference would compute a different function). */
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu");
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial");
if (std::strcmp(act, "gelu") || std::strcmp(pact, "gelu")) {
fprintf(stderr, "radiance: museglimmer: this vision tower has hidden_act '%s' and "
"projector_hidden_act '%s'; it serves the exact gelu both call for\n",
act, pact);
return RAD_E_UNSUPPORTED;
}
/* `axial` is Meta's spelling and `default` NVIDIA's ModelOpt export of the same tower: the
* reference's vision embedder has one rotary (axial), so both name it. Anything else is
* another tower. */
if (std::strcmp(rt, "axial") && std::strcmp(rt, "default")) {
fprintf(stderr, "radiance: museglimmer: this vision tower states rope_type '%s'; it "
"serves the axial 2-D rotary the tower's rotary embedder raises on "
"leaving\n", rt);
return RAD_E_UNSUPPORTED;
}
/* The tower's full layers: every fourth, counted from the start, plus the last (the config's
* own rule, MuseGlimmerVisionConfig.__post_init__). The shipped array must say the same
* thing; a window layer where the rule puts a full one changes what the model saw. */
std::vector<int> full;
const char* kinds = rad_meta_gets(m, "vision_config.layer_types", "");
if (kinds && *kinds) {
RAD_ARCH_TRY(parse_layer_kinds("museglimmer vision", kinds, {"full_attention"},
"window_attention", &full));
if ((int64_t)full.size() != depth) {
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types names %zu layers "
"and the tower has %lld\n", full.size(), (long long)depth);
return RAD_E_INVAL;
}
for (int64_t l = 0; l < depth; ++l) {
const bool rule = is_full_attention(l, 4) || l == depth - 1;
if ((full[(size_t)l] != 0) != rule) {
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types makes tower "
"layer %lld %s and the family rule (every fourth from the first, "
"plus the last) makes it %s\n", (long long)l,
full[(size_t)l] ? "full" : "window", rule ? "full" : "window");
return RAD_E_UNSUPPORTED;
}
}
} else {
full.assign((size_t)depth, 0);
for (int64_t l = 0; l < depth; ++l)
full[(size_t)l] = is_full_attention(l, 4) || l == depth - 1;
}
head_dim = width / heads;
patch_dim = 3 * temporal * patch * patch;
/* The 2-D rotary: half the head a side, each on its own ladder (arange(0, head_dim/2, 2)
* frequencies, sections head_dim/4 a side). */
if (head_dim % 4) return RAD_E_SHAPE;
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4),
(long long)(head_dim / 4));
/* The merger's rows replace token embeddings, so they must be the model's width. */
if (out_hidden != merge * merge * width) {
fprintf(stderr, "radiance: museglimmer: out_hidden_size %lld is not merge %lld squared "
"times the tower's width %lld, whose view the adapter's first layer "
"reads\n", (long long)out_hidden, (long long)merge, (long long)width);
return RAD_E_INVAL;
}
/* The tower emits merged rows the width of the model's tokens: the caller passes the model's
* width and the projection is declared at it, so no separate check exists. */
const int64_t mm = merge * merge;
P = ctx->max_enc_patches;
if (ctx->shape_probe) {
/* A sizing declare: rows follow the probe's step (rounded to whole merged rows), keeping
* the activations out of the levels a decode step runs at. The kernel bands stay at the
* real pass: the engine runs the real declare's kernels at every level. */
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(mm, r / mm * mm);
}
if (P % mm) return RAD_E_SHAPE;
const int64_t R = P / mm;
const int64_t ACC = RAD_ACCESS_PER_REQUEST;
/* The window side in patches (the reference states it in pixels and divides by patch_size).
* A window_attention layer's longest segment is one window. */
const int64_t win_seg = side * side;
/* ---- weights, replicated. Model-level groups for the stem and the adapter; one group per
* block from `first_group` on, so a tower block is its own movement unit. */
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
};
w_patch = bw(nm.f("v.patch.weight"),
nm.ckpt("model.vision_tower.patch_embedder.patch_embedding.weight"),
{ width, patch_dim }, grp_model());
w_pos = bw(nm.f("v.pos.weight"),
nm.ckpt("model.vision_tower.patch_embedder.position_embedding_table.weight"),
{ npos, width }, grp_model());
lw_pre = bw(nm.f("v.lnpre.weight"), nm.ckpt("model.vision_tower.ln_pre.weight"), { width },
grp_model());
lb_pre = bw(nm.f("v.lnpre.bias"), nm.ckpt("model.vision_tower.ln_pre.bias"), { width },
grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const RadWeightGroup g = grp_layer(first_group + (int)i);
const int li = (int)i;
auto src = [&](const char* s) { return nm.ckpt("model.vision_tower.layers.%d.%s", li, s); };
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
l.n1w = bw(dn("norm1.weight"), src("norm1.weight"), { width }, g);
l.n1b = bw(dn("norm1.bias"), src("norm1.bias"), { width }, g);
/* The reference's three biased projections, joined q | k | v into one GEMM. */
if (map_concat(b, dn("qkv.weight"),
{ src("attn.q_proj.weight"), src("attn.k_proj.weight"),
src("attn.v_proj.weight") }) < 0)
return RAD_E_INVAL;
l.qkv_w = decl_w(b, dn("qkv.weight"), RAD_BF16, { 3 * width, width }, ACC,
RAD_SHARD_NONE, g, 0, { width, width, width });
if (map_concat(b, dn("qkv.bias"),
{ src("attn.q_proj.bias"), src("attn.k_proj.bias"),
src("attn.v_proj.bias") }) < 0)
return RAD_E_INVAL;
l.qkv_b = decl_w(b, dn("qkv.bias"), RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g, 0,
{ width, width, width });
l.out_w = bw(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g);
l.out_b = bw(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
l.n2w = bw(dn("norm2.weight"), src("norm2.weight"), { width }, g);
l.n2b = bw(dn("norm2.bias"), src("norm2.bias"), { width }, g);
l.up_w = bw(dn("fc1.weight"), src("mlp.fc1.weight"), { ff, width }, g);
l.up_b = bw(dn("fc1.bias"), src("mlp.fc1.bias"), { ff }, g);
l.down_w= bw(dn("fc2.weight"), src("mlp.fc2.weight"), { width, ff }, g);
l.down_b= bw(dn("fc2.bias"), src("mlp.fc2.bias"), { width }, g);
if (!l.n1w || !l.n1b || !l.qkv_w || !l.qkv_b || !l.out_w || !l.out_b || !l.n2w || !l.n2b ||
!l.up_w || !l.up_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
l.full = full[(size_t)i] != 0;
l.max_seg = l.full ? ctx->max_enc_patches : win_seg;
}
lw_post = bw(nm.f("v.lnpost.weight"), nm.ckpt("model.vision_tower.ln_post.weight"), { width },
grp_model());
lb_post = bw(nm.f("v.lnpost.bias"), nm.ckpt("model.vision_tower.ln_post.bias"), { width },
grp_model());
w_a1 = bw(nm.f("v.mlp.fc1.weight"), nm.ckpt("model.vision_adapter.fc1.weight"),
{ proj_ff, out_hidden }, grp_model());
w_a2 = bw(nm.f("v.mlp.fc2.weight"), nm.ckpt("model.vision_adapter.fc2.weight"),
{ proj_ff, proj_ff }, grp_model());
w_proj = bw(nm.f("v.proj.weight"), nm.ckpt("model.vision_projection.weight"),
{ n_embd, proj_ff }, grp_model());
if (!w_patch || !w_pos || !lw_pre || !lb_pre || !lw_post || !lb_post || !w_a1 || !w_a2 ||
!w_proj)
return RAD_E_INVAL;
/* ---- activations. `mh` holds the merged rows: `pixtral_merge` folds each 2x2 block's four
* patch rows into one row of mm * width in the reference's pixel_shuffle layout, and the
* adapter's first layer reads it. */
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
b_p = decl_b(b, nm.f("v.p"), RAD_BF16, { P, width });
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_idx = decl_b(b, nm.f("v.idx"), RAD_I32, { P });
b_inv = decl_b(b, nm.f("v.inv"), RAD_I32, { P });
b_pos = decl_b(b, nm.f("v.pos"), RAD_I32, { 2, P });
b_cuw = decl_b(b, nm.f("v.cuw"), RAD_I32, { P + 1 });
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mm * width });
b_m1 = decl_b(b, nm.f("v.m1"), RAD_BF16, { R, proj_ff });
b_m2 = decl_b(b, nm.f("v.m2"), RAD_BF16, { R, proj_ff });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_p || !b_qkv || !b_att || !b_ff || !b_idx || !b_inv || !b_pos || !b_cuw ||
!b_mh || !b_m1 || !b_m2 || !b_out)
return RAD_E_INVAL;
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
rad_weight bias) -> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
RAD_WEIGHTS(w, bias));
};
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
return RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto lnorm = [&](int64_t rows, int64_t n, double e, rad_weight w, rad_weight bias) -> rad_op {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", e),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
auto attn_op = [&](int64_t max_seg) -> rad_op {
return RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
RAD_INT("max_seqlen", max_seg)),
RAD_NOWEIGHTS);
};
/* The stem is bias-less (the reference's patch_embedding states no bias). */
op_patch = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_patch)),
{}, { b_x });
op_pos = rw(b, RAD_OP(b, "grid_embed_pad",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_pos)),
{ b_x }, { b_x });
op_lpre = rw(b, lnorm(P, width, eps, lw_pre, lb_pre), { b_x }, { b_h });
op_wo = rw(b, RAD_OP(b, "window_order",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("window", side)),
RAD_NOWEIGHTS),
{}, { b_idx, b_inv, b_pos, b_cuw });
op_gidx = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_h, b_idx }, { b_p });
for (Layer& l : L) {
l.ln1 = rw(b, lnorm(P, width, 1e-5, l.n1w, l.n1b), { b_p }, { b_h });
l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.rope = rw(b, RAD_OP(b, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
RAD_F64("theta", theta), RAD_F64("scale", 1.0),
RAD_STR("mode", "axial"),
RAD_INT("rotary_dim", head_dim),
RAD_STR("sections", sec)),
RAD_NOWEIGHTS),
{ b_qkv, b_pos }, { b_qkv });
/* A window layer's segment bounds are the order op's per-window cu; a full layer's are
* the pass's frame bounds, raw (the permutation is within frames, so they read the same
* values in permuted order). */
l.attn = rw(b, attn_op(l.max_seg),
l.full ? std::initializer_list<rad_buf>{ b_qkv }
: std::initializer_list<rad_buf>{ b_qkv, b_cuw },
{ b_att });
l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_p }, { b_p });
l.ln2 = rw(b, lnorm(P, width, 1e-5, l.n2w, l.n2b), { b_p }, { b_h });
l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff });
l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_p }, { b_p });
}
op_ginv = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_p, b_inv }, { b_x });
op_lpost = rw(b, lnorm(P, width, eps, lw_post, lb_post), { b_x }, { b_x });
/* The reference's pixel_shuffle: each 2x2 block's four patches fold into one row with the
* channels interleaved (block, channel, sub-patch), which is `pixtral_merge`'s layout. A view
* over four consecutive rows cannot produce it: the concatenated form is a different tensor. */
op_merge = rw(b, RAD_OP(b, "pixtral_merge",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("merge", merge), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_x }, { b_mh });
/* The adapter: both linears bias-less, gelu between and after (the reference's
* act(fc2(act(fc1(x))))). */
op_m1 = rw(b, gemm(R, proj_ff, mm * width, w_a1), { b_mh }, { b_m1 });
op_g1 = rw(b, RAD_OP(b, "gelu",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_m1 }, { b_m2 });
op_m2 = rw(b, gemm(R, proj_ff, proj_ff, w_a2), { b_m2 }, { b_m1 });
op_g2 = rw(b, RAD_OP(b, "gelu",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_m1 }, { b_m2 });
op_proj = rw(b, gemm(R, n_embd, proj_ff, w_proj), { b_m2 }, { b_out });
/* perception_emb_norm: MuseGlimmerRMSNorm(eps = the TEXT model's rms_norm_eps, with_scale
* False) -- no gain operand, no centered 1+. */
op_perc = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
RAD_F64("eps", m->rms_eps), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_out }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = ctx->max_enc_patches;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
int64_t nfull = 0;
for (int64_t l = 0; l < depth; ++l) nfull += full[(size_t)l];
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x "
"%lld x %lld, merge %lld, windows of %lld patches (%lld full attention); "
"%lld patches a pass -> %lld rows of %lld",
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
(long long)ff, (long long)temporal, (long long)patch, (long long)patch,
(long long)merge, (long long)side, (long long)nfull, (long long)P, (long long)R,
(long long)n_embd);
}
on = true;
return RAD_OK;
}
/* Stage taps, the same protocol as rad_block_sam.h's: RADIANCE_DEBUG_MM_BUFFERS names stages
* (comma separated, matched as substrings) and RADIANCE_DEBUG_MM_DUMP's directory receives
* tap.<tag>.bf16 -- raw bf16 rows, one file a stage. The copy is issued on the pass's stream
* behind the producing op and synced, so it reads that op's output rather than whatever writes
* the buffer later (the after-pass dump in core/engine_mm.cpp cannot see intermediates). */
inline void muse_tap(RadCtx* c, const char* tag, rad_buf b, int64_t rows, int64_t cols) {
static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP");
static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
if (!dir || !*dir || !env || !*env || rows <= 0 || cols <= 0 || rad_rank(c) != 0) return;
bool want = false;
const size_t tl = std::strlen(tag);
for (const char* s = env; *s && !want;) {
const char* e = s;
while (*e && *e != ',') ++e;
const size_t l = (size_t)(e - s);
for (size_t i = 0; l && i + l <= tl && !want; ++i)
want = std::strncmp(tag + i, s, l) == 0;
s = *e ? e + 1 : e;
}
if (!want) return;
void* p = rad_buf_ptr(c, b);
if (!p) return;
std::vector<uint16_t> h((size_t)(rows * cols));
if (rad_memcpy_async(h.data(), p, (size_t)(rows * cols * 2), rad_stream(c)) < 0) return;
rad_stream_sync(rad_stream(c));
char path[512];
std::snprintf(path, sizeof path, "%s/tap.%s.bf16", dir, tag);
if (FILE* f = std::fopen(path, "wb")) {
std::fwrite(h.data(), sizeof(uint16_t), h.size(), f);
std::fclose(f);
}
}
inline void MuseTower::step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
const int64_t mm = merge * merge, Rn = Pn / mm;
if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0 || !batch->enc_coord || !batch->enc_cu ||
!batch->enc_seg_h || !batch->enc_seg_w || !batch->enc_pixels) {
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or "
"more patches than it was declared for, or not whole merged rows");
return;
}
/* Windows per frame, from the pass's host grids: the window layers' cu is the per-window
* boundaries among permuted rows, `n_win + 1` entries of the order op's output. */
int64_t n_win = 0;
for (int64_t s = 0; s < S; ++s)
n_win += (batch->enc_seg_h[s] + side - 1) / side * ((batch->enc_seg_w[s] + side - 1) / side);
if (n_win > P) {
rad_step_fail(c, "an encoder pass whose window count exceeds the tower's declared rows");
return;
}
/* Patches, coordinates (planes 0-3: row, column, segment height, segment width, in patches)
* and the frame boundaries, staged by the core. The full layers read the frame boundaries
* unchanged: the window permutation is within frames, so the boundaries among permuted rows
* are these values (the reference passes its cu_seqlens the same way). */
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RadOperand cuw = RAD_B(b_cuw);
cuw.rows = n_win + 1;
RadOperand pos = RAD_B(b_pos);
pos.rows = 2;
pos.cols = Pn;
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
muse_tap(c, "v.patchpos", b_x, Pn, width);
RAD_ISSUE_N(c, op_lpre, Pn, brows(b_x, Pn), RAD_W(lw_pre), RAD_W(lb_pre), brows(b_h, Pn));
muse_tap(c, "v.lnpre", b_h, Pn, width);
RAD_ISSUE_N(c, op_wo, Pn, crd, cu, brows(b_idx, Pn), brows(b_inv, Pn), pos, cuw);
RAD_ISSUE_N(c, op_gidx, Pn, brows(b_h, Pn), brows(b_idx, Pn), brows(b_p, Pn));
for (size_t li = 0; li < L.size(); ++li) {
const Layer& l = L[li];
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_p, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Pn));
RAD_ISSUE_N(c, l.rope, Pn, brows(b_qkv, Pn), pos);
RAD_ISSUE_N(c, l.attn, Pn,
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn),
l.full ? cu : cuw, brows(b_att, Pn));
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
brows(b_p, Pn), brows(b_p, Pn));
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_p, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
brows(b_ff, Pn));
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_p, Pn), brows(b_p, Pn));
if (li == 0) muse_tap(c, "v.blk0", b_p, Pn, width);
if (li + 1 == L.size()) muse_tap(c, "v.blkL", b_p, Pn, width);
}
RAD_ISSUE_N(c, op_ginv, Pn, brows(b_p, Pn), brows(b_inv, Pn), brows(b_x, Pn));
muse_tap(c, "v.ginv", b_x, Pn, width);
/* ln_post over the P patches, then the reference's pixel_shuffle into merged rows. */
RAD_ISSUE_N(c, op_lpost, Pn, brows(b_x, Pn), RAD_W(lw_post), RAD_W(lb_post), brows(b_x, Pn));
muse_tap(c, "v.lnpost", b_x, Pn, width);
RAD_ISSUE_N(c, op_merge, Pn, brows(b_x, Pn), crd, brows(b_mh, Rn));
muse_tap(c, "v.merge", b_mh, Rn, mm * width);
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(w_a1), brows(b_m1, Rn));
muse_tap(c, "v.fc1", b_m1, Rn, proj_ff);
RAD_ISSUE_N(c, op_g1, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
RAD_ISSUE_N(c, op_m2, Rn, brows(b_m2, Rn), RAD_W(w_a2), brows(b_m1, Rn));
RAD_ISSUE_N(c, op_g2, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
RAD_ISSUE_N(c, op_proj, Rn, brows(b_m2, Rn), RAD_W(w_proj), brows(b_out, Rn));
muse_tap(c, "v.proj", b_out, Rn, n_embd);
RAD_ISSUE_N(c, op_perc, Rn, brows(b_out, Rn), RAD_NONE, brows(b_out, Rn));
muse_tap(c, "v.out", b_out, Rn, n_embd);
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_MUSEGLIMMER_VISION_H */
+129 -22
View File
@@ -98,12 +98,24 @@ struct PleLayer {
rad_weight w_table = 0, w_scale = 0, w_mult = 0, w_vsz = 0, w_off = 0;
/* The table is plain bf16 as shipped (no scale weight) rather than E4M3. */
bool table_bf16 = false;
rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
rad_weight w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
/* The two projections of the gathered embedding, each in the encoding its container stores:
* plain bf16 as the checkpoint ships them, or rotated int8 (or a narrower rotated form), which
* halves the bytes a pass waits for once the rows are on the card. `a_embd` is their input and
* `a_fed` the same planes for the second projection, whose codes the first one's quantiser
* wrote. */
LinearFP8 key{}, value{};
ActFP8 a_embd{}, a_fed{};
rad_kvgroup kv_tok = 0, kv_conv = 0;
rad_buf b_ids = 0, b_emb = 0, b_embd = 0, b_k = 0, b_v = 0, b_gv = 0, b_gvn = 0, b_out = 0;
rad_op op_ids = 0, op_gather = 0, op_embd = 0, op_key = 0, op_value = 0;
rad_op op_ids = 0, op_gather = 0, op_embd = 0;
rad_op op_gate = 0, op_conv = 0, op_add = 0;
/* The draft passes' hint (hint_ids, hint_fetch), where a drafter and `ngram_hint` exist: the
* per-slot tails the hash continues from, the hinted ids (host domain, as `ple_ids`) and the
* rows fetched for them, which nothing reads. */
rad_buf b_tail = 0, b_hint_ids = 0, b_hint_emb = 0;
rad_op op_hint_hist = 0, op_hint_round = 0, op_hint_gather = 0;
int64_t hn() const { return c.hc * g.n_embd; }
/* The read-ahead queue's depth in steps: batch.cpp's k_ahead_chunks steps of the following
@@ -123,6 +135,14 @@ struct PleLayer {
/* The hash, issued at the top of the step; the rest at the layer (see ids()). */
void ids(RadCtx* c_, const RadBatch* batch) const;
void step(RadCtx* c_, const RadBatch* batch) const;
/* On a draft head's pass: the ids of each sequence's newest token, first in the pass, and
* the fetch of their rows, last in it (see hint_ids()). */
void hint_ids(RadCtx* c_, const RadBatch* batch) const;
void hint_fetch(RadCtx* c_, const RadBatch* batch) const;
bool hints(const RadBatch* batch) const {
return op_hint_gather != 0 &&
(batch->draft_pass > 1 || (batch->draft_pass < 0 && batch->n_draft_out > 0));
}
};
inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg,
@@ -178,7 +198,7 @@ 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) or read as that release ships it (its shards under
* recipe (data/recipes/qwen4exp-w4nl64-i8-hc8m.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. */
@@ -212,13 +232,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* ---- the projections and the three gains ------------------------------------------------ */
/* bf16: the FP8 checkpoint's `modules_to_not_convert` names both projections. */
/* bf16 as shipped (the FP8 checkpoint's `modules_to_not_convert` names both projections); a
* recipe may store them rotated int8. The name maps come first: the encodings, looked up
* through them, say whether the input needs its int8 pair. They are declared below, with the
* buffers they read and write. */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_key.weight", layer), src.key_proj));
w_key = decl_w(b, nm.f("blk.%d.ple_key.weight", layer), RAD_BF16, {HN, c.embed_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_value.weight", layer), src.value_proj));
w_value = decl_w(b, nm.f("blk.%d.ple_value.weight", layer), RAD_BF16,
{g.n_embd, c.embed_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_key.weight", layer), src.norm_key));
w_nk = decl_w(b, nm.f("blk.%d.ple_norm_key.weight", layer), RAD_F32, {HN},
@@ -236,7 +255,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
w_conv = decl_w(b, nm.f("blk.%d.ple_conv.weight", layer), RAD_BF16, {HN, c.conv_width},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off || !w_key || !w_value ||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off ||
!w_nk || !w_nq || !w_nc || !w_conv) return RAD_E_INVAL;
/* ---- the two rolling windows ------------------------------------------------------------ */
@@ -337,22 +356,83 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
{b_ids}, {b_emb});
}
/* ---- the draft passes' hint. A verify step's rows are the token the last verify chose and
* the drafter's proposals, each known a draft pass or more before the verify hashes it,
* except the last. Each draft pass hashes its sequences' newest token (`ngram_hint`) and
* gathers those rows through the same row source, which for a table on a drive reads them
* into its row cache; the verify step's gather then waits for the last proposal's rows
* only. All three ops or none: without a drafter, or where no library hashes the hint,
* nothing is declared and the verify step reads every row itself, as before. */
if (g.max_spec > 0 && rad_op_declared(b, "ngram_hint")) {
const int64_t ctx = c.ngram - 1;
b_tail = decl_b(b, nm.f("ple_hint_tail"), RAD_I32, {g.max_seqs, 2 * ctx}, RAD_BUF_PERSIST);
RadBufDecl hi{};
hi.dtype = RAD_I32; hi.rank = 2;
hi.shape[0] = g.max_seqs; hi.shape[1] = c.heads;
hi.kind = RAD_BUF_PERSIST; hi.domain = RAD_DOMAIN_HOST;
b_hint_ids = rad_decl_buffer(b, nm.f("ple_hint_ids"), &hi);
/* PERSIST although nothing reads it: a transient's bytes are shared by declared op
* order, and the fetch runs on the host while the draft pass's other buffers are live. */
RadBufDecl he{};
he.dtype = g.act_dtype; he.rank = 2;
he.shape[0] = g.max_seqs; he.shape[1] = c.embed_dim;
he.kind = RAD_BUF_PERSIST; he.domain = RAD_DOMAIN_HOST;
b_hint_emb = rad_decl_buffer(b, nm.f("ple_hint_emb"), &he);
if (!b_tail || !b_hint_ids || !b_hint_emb) return RAD_E_INVAL;
for (const int hist : { 1, 0 })
(hist ? op_hint_hist : op_hint_round) =
rw(b, RAD_OP(b, "ngram_hint",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("heads", c.heads),
RAD_INT("ngram", c.ngram), RAD_INT("eos", c.eos),
RAD_INT("hist", hist)),
RAD_WEIGHTS(w_mult, w_vsz, w_off)),
{b_tail}, {b_tail, b_hint_ids});
const rad_weight wt[2] = { w_table, w_scale };
op_hint_gather = rw(b, RAD_OP(b, "embed_lookup_q",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs * c.heads),
RAD_INT("n_embd", HD), RAD_INT("n_vocab", c.rows),
RAD_STR("dtype", g.dtype)),
wt, table_bf16 ? 1 : 2),
{b_hint_ids}, {b_hint_emb});
if (!op_hint_hist || !op_hint_round || !op_hint_gather)
op_hint_hist = op_hint_round = op_hint_gather = 0;
}
op_embd = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{b_emb}, {b_embd});
op_key = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", HN),
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_key)),
{b_embd}, {b_k});
op_value = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_value)),
{b_embd}, {b_v});
/* The projections. An int8 one reads the embedding's int8 codes at its own scale group; the
* first such quantises the bf16 plane and a second reads those codes, so two int8 projections
* must agree in rotation and group (LinearFP8 refuses the pair otherwise). */
{
const char* kb = nm.f("blk.%d.ple_key", layer);
const char* vb = nm.f("blk.%d.ple_value", layer);
RadEncoding ke{}, ve{};
const bool kk = weight_enc(b, nm.f("%s.weight", kb), &ke);
const bool vk = weight_enc(b, nm.f("%s.weight", vb), &ve);
const bool k8 = !g.w_bf16 && kk && (linear_is_w8(ke) || linear_is_w8h(ke));
const bool v8 = !g.w_bf16 && vk && (linear_is_w8(ve) || linear_is_w8h(ve));
a_embd.x = b_embd;
if (k8 || v8)
RAD_ARCH_TRY(a_embd.declare_qs(b, nm, g, "ple_emb_dev", c.embed_dim, 0, true, false,
linear_w8h_group(k8 ? ke : ve)));
a_fed = a_embd;
if (k8 && v8) {
a_fed.q8_fed = true;
a_fed.q8_rot = linear_is_w8h(ke);
}
key.mapped = value.mapped = true;
/* Anything but an int8 form is the plain bf16 GEMM, in a quantised model too. */
Geom gb = g;
gb.w_bf16 = true;
RAD_ARCH_TRY(key.declare(b, nm, k8 ? g : gb, kb, HN, c.embed_dim, RAD_SHARD_NONE,
grp_model(), { src.key_proj }, a_embd, b_k));
RAD_ARCH_TRY(value.declare(b, nm, v8 ? g : gb, vb, g.n_embd, c.embed_dim, RAD_SHARD_NONE,
grp_model(), { src.value_proj }, a_fed, b_v));
}
/* `q` is the incoming stream, un-normed; the op applies all three norms because the third is
* over bytes it writes. */
@@ -378,7 +458,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_NOWEIGHTS),
{w.h, b_out}, {w.h});
if (!op_ids || !op_gather || !op_embd || !op_key || !op_value || !op_gate || !op_conv ||
if (!op_ids || !op_gather || !op_embd || !key.op || !value.op || !op_gate || !op_conv ||
!op_add)
return RAD_E_INVAL;
return RAD_OK;
@@ -433,6 +513,33 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
}
/* The hint of a draft head's pass. The history pass ends at the token the verify chose and each
* later round reads the proposal before it (RadBatch::draft_pass), so the pass's newest token per
* sequence is one the next verify step runs. hint_ids() hashes it first in the pass, so the ids
* are in host memory as the pass starts; hint_fetch() goes last, where the host has issued the
* whole pass and only waits for that one kernel, and the rows it reads arrive while the card
* drafts. A history pass that drafts nothing gets neither. */
inline void PleLayer::hint_ids(RadCtx* c_, const RadBatch* batch) const {
if (!hints(batch)) return;
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadKVGroupBatch* tk = kv_batch(batch, kv_tok);
const int32_t* tk_idx = tk ? tk->state_index : nullptr;
RAD_ISSUE_N(c_, batch->draft_pass < 0 ? op_hint_hist : op_hint_round, S,
praw(batch->token_ids, RAD_I32, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
tk_idx ? praw(tk_idx, RAD_I32, S) : RAD_NONE,
RAD_B(b_tail), brows(b_hint_ids, S));
}
inline void PleLayer::hint_fetch(RadCtx* c_, const RadBatch* batch) const {
if (!hints(batch)) return;
const int64_t S = batch->n_seq;
RAD_ISSUE_N(c_, op_hint_gather, S * c.heads,
brows(b_hint_ids, S), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
brows(b_hint_emb, S), RAD_NONE);
}
inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int64_t S = batch->n_seq;
@@ -454,8 +561,8 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
RAD_ISSUE_N(c_, op_embd, T, brows(b_emb, T), brows(b_embd, T));
RAD_ISSUE_N(c_, op_key, T, brows(b_embd, T), RAD_W(w_key), brows(b_k, T));
RAD_ISSUE_N(c_, op_value, T, brows(b_embd, T), RAD_W(w_value), brows(b_v, T));
key.step(c_, a_embd, b_k, T, 0, T);
value.step(c_, a_fed, b_v, T, 0, T);
RAD_ISSUE_N(c_, op_gate, T,
brows(b_k, T), brows(w.h, T), brows(b_v, T),
+214 -39
View File
@@ -48,6 +48,9 @@ namespace arch {
/* The scale block in both dimensions, fixed by the checkpoint (`weight_block_size`). libr4d
* compiles it in and its rows carry C_EQ("group", 128), so other widths resolve to no kernel. */
enum { RAD_FP8_BLOCK = 128 };
/* IQ8R's scale group: an int8 weight rotated 128 wide with one bf16 scale per row per 256 of K,
* met by an int8 activation with one f32 scale per (token, 256). */
enum { RAD_I8_GROUP_WIDE = 256 };
/* Rows of the scale plane for an N-row weight, and columns for a K-wide one. */
inline int64_t fp8_blocks(int64_t n) { return (n + RAD_FP8_BLOCK - 1) / RAD_FP8_BLOCK; }
@@ -63,6 +66,9 @@ struct ActFP8 {
* by the linear's own quant_act_i8g from `x`, or by the producer when `q8_fed`. */
rad_buf q8 = 0;
rad_buf s8 = 0;
/* The int8 pair's scale group: RAD_FP8_BLOCK, or RAD_I8_GROUP_WIDE for an IQ8R trunk, whose
* producers and quantisers write one scale per (row, 256). s8 has ceil(n / g8) columns. */
int64_t g8 = RAD_FP8_BLOCK;
/* The producer writes q8/s8 instead of the E4M3 pair (a connection read with
* HyperConn::Config::codes_i8, a gated quantiser, the attention gate or delta-net output
* epilogue), so an int8 linear reading it declares no quantiser. Set by the model when it
@@ -76,6 +82,8 @@ struct ActFP8 {
/* The code pair the producer writes: int8 when the model fed it, E4M3 otherwise. */
rad_buf cq() const { return q8_fed ? q8 : q; }
rad_buf cs() const { return q8_fed ? s8 : s; }
/* The scale group of cs(). */
int64_t cg() const { return q8_fed ? g8 : (int64_t)RAD_FP8_BLOCK; }
/* Declares the codes: the E4M3 pair with `fp8_pair`, the int8 pair with `i8` (an int8 model's
* activations need no E4M3 plane taking arena); `x` is set by the caller.
@@ -84,7 +92,9 @@ struct ActFP8 {
* (a MoE expert plane is `rows * top_k`, an encoder tower's its patch count); too small a value
* overruns the arena (core/runtime/issue.cpp refuses such an issue). */
int declare_qs(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
int64_t rows = 0, bool i8 = false, bool fp8_pair = true) {
int64_t rows = 0, bool i8 = false, bool fp8_pair = true,
int64_t i8_group = RAD_FP8_BLOCK) {
g8 = i8_group;
/* bf16 linears read only `x` (Geom::w_bf16), so declare no codes; an unused plane would
* still take arena space. */
if (g.w_bf16) { q = s = q8 = s8 = 0; return RAD_OK; }
@@ -96,11 +106,30 @@ struct ActFP8 {
}
if (i8) {
q8 = decl_b(b, nm.f("%s.q8", name), RAD_I8, { m, n });
s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, fp8_blocks(n) });
s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, (n + g8 - 1) / g8 });
if (!q8 || !s8) return RAD_E_INVAL;
}
return (fp8_pair || i8) ? RAD_OK : RAD_E_INVAL;
}
/* The code pair of a model that learned from a probe whether its linears are rotated int8
* (`i8`, at `i8_group` columns a scale): declare_qs's E4M3 pair for a block-fp8 model, and for
* an int8 one int8 codes. Those are written by the producer's own rotating quantiser `fed_op`
* (had_quant_act_i8g, or gated_had_quant_i8g behind a gated product) where the kernels serve
* it, and the linears reading them declare none; where they do not (the CPU kernels) the
* producer keeps its E4M3 pair and each linear quantises its own input from the bf16 plane.
* `x` is set by the caller. */
int declare_pair(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
int64_t rows, bool i8, int64_t i8_group, const char* fed_op) {
if (i8 && (i8_group <= 0 || n % i8_group)) {
fprintf(stderr, "radiance: the int8 linears keep one scale a %lld of K, which does not "
"divide this rank's %lld-wide '%s'\n",
(long long)i8_group, (long long)n, name);
return RAD_E_UNSUPPORTED;
}
if (i8 && rad_op_declared(b, fed_op)) q8_fed = q8_rot = true;
return declare_qs(b, nm, g, name, n, rows, i8, !q8_fed, i8 ? i8_group : RAD_FP8_BLOCK);
}
};
/* The fused attention prologue's row band, shared by the block issuing it, the rope table fill,
@@ -145,7 +174,7 @@ inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, in
* are rotated (ActFP8::q8_rot). */
op = rw(b, RAD_OP(b, a.q8_fed ? (a.q8_rot ? "had_quant_act_i8g" : "quant_act_i8g") : "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
return RAD_OK;
@@ -155,7 +184,7 @@ inline void QuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const
if (!op) return;
if (rows <= 0) rows = T - r0;
RAD_ISSUE(c, op, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
brow_slice(a.cs(), r0, rows, n / a.cg()));
}
/* ================================== the quantiser folded into the op that produces the row
@@ -466,7 +495,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
op = RAD_OP(b, hi8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype),
RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(w));
if (!op) return RAD_E_INVAL;
@@ -489,7 +518,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
op_arn = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_INT("group", a.cg()),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(w));
@@ -504,7 +533,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
op_arn6 = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_INT("group", a.cg()),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd),
RAD_INT("wire", 6)),
@@ -549,7 +578,7 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n),
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
brow_slice(hi8 ? a.q8 : a.q, r0, rows, n),
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / RAD_FP8_BLOCK),
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / (hi8 ? a.g8 : (int64_t)RAD_FP8_BLOCK)),
brow_slice(a.x, r0, rows, n));
}
@@ -637,11 +666,14 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
return op_q ? RAD_OK : RAD_E_INVAL;
}
if (clipped) {
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated; and no clamp
* with `silu_only`. */
if (!gate_up || !a.x || n <= 0 || rot || silu_only || (a.q8_fed && a.q8_rot) ||
std::strcmp(act_name, "silu"))
/* The clamp writes the bf16 plane and a quantiser reads it: E4M3, plain int8, or the
* rotated int8 codes an i8a8h consumer reads (had_quant_act_i8g at that consumer's
* group, the quantiser the rotated trunk's other inputs use). Against the unclamped
* gated_had_quant_i8g that is one launch more, in the clamped layers only. No clamp
* with `silu_only`, and none into a rotated E4M3 consumer (`rot`). */
if (!gate_up || !a.x || n <= 0 || rot || silu_only || std::strcmp(act_name, "silu"))
return RAD_E_INVAL;
const bool hi8 = a.q8_fed && a.q8_rot;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
if (fuse_clamped && !step && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
rad_op_declared(b, "swiglu_clamped_quant_fp8")) {
@@ -667,11 +699,13 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
{ gate_up }, { a.x });
if (!bf16) {
if (!a.cq() || !a.cs()) return RAD_E_INVAL;
const char* qn = hi8 ? "had_quant_act_i8g" : a.q8_fed ? "quant_act_i8g"
: "quant_act_fp8";
op_quant =
rw(b,
RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
RAD_OP(b, qn,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
if (!op_quant) return RAD_E_INVAL;
@@ -703,7 +737,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
if (!rot || rad_op_declared(b, "gated_had_quant_fp8"))
op = RAD_OP(b, gq,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype),
RAD_STR("act", act_name)),
RAD_NOWEIGHTS);
/* The rotated op's chain, which writes the bf16 plane whether or not a consumer asked. */
@@ -742,7 +776,7 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
if (clamped_fused) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK),
brow_slice(a.cs(), r0, rows, n / a.cg()),
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
return;
}
@@ -752,7 +786,7 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
if (op_quant)
RAD_ISSUE_N(c, op_quant, rows, brow_slice(a.x, r0, rows, n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
brow_slice(a.cs(), r0, rows, n / a.cg()));
return;
}
if (bf16 || op_q) {
@@ -760,12 +794,12 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
if (op_q)
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
brow_slice(a.cs(), r0, rows, n / a.cg()));
return;
}
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK),
brow_slice(a.cs(), r0, rows, n / a.cg()),
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
}
@@ -865,6 +899,9 @@ 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;
/* With probed_i8: the weight's scale group along K (linear_w8h_group), which the model's int8
* activation pairs must share (ActFP8::g8). */
int64_t probed_g8 = RAD_FP8_BLOCK;
/* 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
@@ -1022,7 +1059,26 @@ inline bool linear_w8h_scale2(const RadEncoding& e) {
s2->kind == RAD_PLANE_TILED && (s2->dtype == RAD_F32 || s2->dtype == RAD_BF16) &&
(s2->block[0] == 0 || s2->block[0] == 1) && s2->block[1] == 0;
}
/* IQ8R: int8 codes rotated 128 wide with a u8 scale per [1 x 256] under one bf16 scale a row
* (libquant `codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128`), served as the
* I8 form at twice the scale group. */
inline bool linear_is_iq8r(const RadEncoding& e) {
if (!rad_enc_is(&e, "affine") || e.n_planes != 3 ||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
return false;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
const RadEncPlane* s2 = rad_enc_plane(&e, "scale.1");
return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_U8 &&
sc->kind == RAD_PLANE_TILED && sc->block[0] == 1 && sc->block[1] == RAD_I8_GROUP_WIDE &&
s2 && s2->dtype == RAD_BF16 && s2->kind == RAD_PLANE_TILED && s2->block[0] == 1 &&
s2->block[1] == 0;
}
/* The scale group along K of a weight served at i8a8 / i8a8h. */
inline int64_t linear_w8h_group(const RadEncoding& e) {
return linear_is_iq8r(e) ? (int64_t)RAD_I8_GROUP_WIDE : (int64_t)RAD_FP8_BLOCK;
}
inline W8hForm linear_w8h_form(const RadEncoding& e) {
if (linear_is_iq8r(e)) return W8hForm::I8;
const bool trellis = rad_enc_is(&e, "trellis");
if ((!rad_enc_is(&e, "affine") && !trellis) ||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
@@ -1087,6 +1143,17 @@ inline bool linear_is_wnh(const RadEncoding& e) {
zp->block[1] == RAD_FP8_BLOCK;
}
/* Whether a trunk whose first linear probed as `e` is rotated int8 -- w8h or wnh -- and if so
* how wide its activation codes' scale group is: 256 for IQ8R, 128 for the other rotated forms
* (linear_w8h_group spells the rule). An arch learns this by probing layer 0's q projection
* before declaring activations; the probe and the fields are the arch's, the question belongs
* beside the predicates it is made of. */
inline bool trunk_rotation(const RadEncoding& e, int64_t* g8) {
if (!linear_is_w8h(e) && !linear_is_wnh(e)) return false;
*g8 = linear_w8h_group(e);
return true;
}
/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes and an E8M0 exponent per [1 x 32],
* no transform (libr4d's MXFP4 layout hook). */
enum { RAD_MX_GROUP = 32 };
@@ -1145,6 +1212,32 @@ inline bool linear_is_paro_m2xfp4(const RadEncoding& e) {
mt->block[1] == RAD_MX_GROUP;
}
/* The weight formats rad-convert reads and the engine does not serve: block fp8 (E4M3
* codes under a scale per 128 x 128), OCP MXFP4, M2XFP4 and the ParoQuant-rotated forms of the
* last two. The format's name, or nullptr for one that is served. */
inline const char* linear_retired(const RadEncoding& e) {
if (linear_is_paro_m2xfp4(e)) return "ParoQuant M2XFP4";
if (linear_is_paro_mxfp4(e)) return "ParoQuant MXFP4";
if (linear_is_givens(e)) return "ParoQuant";
if (linear_is_m2xfp4(e)) return "M2XFP4";
if (linear_is_mxfp4(e)) return "MXFP4";
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
if (rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
e.plane[0].dtype == RAD_F8E4M3 && sc && (sc->dtype == RAD_BF16 || sc->dtype == RAD_F32) &&
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK)
return "block fp8";
return nullptr;
}
/* The refusal of a weight stored in one of them, by name, with what serves the model instead. */
inline int linear_refuse_retired(const char* weight, const char* format) {
fprintf(stderr, "radiance: '%s' is stored as %s, which this build does not serve. Convert "
"the checkpoint again with an int8 recipe (the IQ8R ones in data/recipes); if "
"the weight belongs to the container's drafter, `num-speculative-tokens: 0` "
"serves the model without it\n", weight, format);
return RAD_E_UNSUPPORTED;
}
/* A 4-bit weight with a zero point and no transform: u4 codes, an f16 scale and a u4 or u8 zero
* point per 128 of K (libquant `codes=u4 zero=u4 group=128 scale=f16`, or rad-convert's import rule
* over an int4 release). At decode w4a16_asym narrows the BF16 input to F16 on load; larger
@@ -1179,6 +1272,7 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16;
probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc) || linear_is_wnh(enc));
probed_g8 = known ? linear_w8h_group(enc) : (int64_t)RAD_FP8_BLOCK;
/* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or
* quantises it. */
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc) ||
@@ -1302,6 +1396,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
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;
if (known && !plain)
if (const char* gone = linear_retired(enc)) return linear_refuse_retired(sw, gone);
/* ---- bf16 weight, `gemm_nt` over `a.x`: every linear of a bf16 model, or one a quantised
* container keeps at checkpoint precision (e.g. the QSA indexer's projection, whose top-k is a
@@ -1375,10 +1471,18 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
"int8)\n", wn, a.q8_fed ? "" : " or the bf16 plane it quantises");
return RAD_E_DTYPE;
}
if (N % 16 || K % RAD_FP8_BLOCK) {
/* The scale group: 128, or 256 for IQ8R, which the input's int8 pair must share. */
const int64_t wg = linear_w8h_group(enc);
if (wg != a.g8) {
fprintf(stderr, "radiance: '%s' has a scale per %lld columns and its input's int8 codes "
"one per %lld; a trunk mixes IQ8R and 128-group int8 weights\n",
wn, (long long)wg, (long long)a.g8);
return RAD_E_DTYPE;
}
if (N % 16 || K % wg) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an int8 weight takes rows in "
"16s and K in whole %d-column scale groups\n",
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
"16s and K in whole %lld-column scale groups\n",
base, (long long)N, (long long)K, (long long)wg);
return RAD_E_INVAL;
}
RowParts rp;
@@ -1402,42 +1506,42 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
rp.w, rp.n);
/* A view of two planes is declared at the weight's logical extents and sliced in its
* columns, the stored planes left to the layout hook. */
const bool two = linear_w8h_scale2(enc) || linear_w8h_rowf(enc);
const bool iq8r = linear_is_iq8r(enc);
const bool two = linear_w8h_scale2(enc) || linear_w8h_rowf(enc) || iq8r;
ws = asym ? decl_view(b, sn, wn, "scale,zero", RAD_F16, { N, K }, access, shard, grp,
rp.w, rp.n)
: linear_w8h_rowf(enc) ? decl_view(b, sn, wn, "scale,scale.col", RAD_F32, { N, K },
access, shard, grp, rp.w, rp.n)
: two ? decl_view(b, sn, wn, "scale,scale.1", RAD_F8E4M3, { N, K }, access, shard,
grp, rp.w, rp.n)
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, access,
: two ? decl_view(b, sn, wn, "scale,scale.1", iq8r ? RAD_U8 : RAD_F8E4M3, { N, K },
access, shard, grp, rp.w, rp.n)
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / wg }, access,
shard, grp, rp.w, rp.n);
if (!w || !ws) return RAD_E_INVAL;
if (span_hi > 0) {
/* The (scale, zero) and (scale, scale.1) views are at the logical extents, sliced as
* the codes are. */
const bool col = shard == RAD_SHARD_COL && !asym && !two;
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
if (col && (span_lo % wg || span_hi % wg)) {
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
"%d-column scale group\n", base, (long long)span_lo,
(long long)span_hi, RAD_FP8_BLOCK);
"%lld-column scale group\n", base, (long long)span_lo,
(long long)span_hi, (long long)wg);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
if ((asym || two) && shard == RAD_SHARD_COL &&
(span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
if ((asym || two) && shard == RAD_SHARD_COL && (span_lo % wg || span_hi % wg)) {
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
"%d-column scale group\n", base, (long long)span_lo,
(long long)span_hi, RAD_FP8_BLOCK);
"%lld-column scale group\n", base, (long long)span_lo,
(long long)span_hi, (long long)wg);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / RAD_FP8_BLOCK : span_lo,
col ? span_hi / RAD_FP8_BLOCK : span_hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / wg : span_lo,
col ? span_hi / wg : span_hi));
}
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
if (!a.q8_fed)
op_q = rw(b, RAD_OP(b, rot8 ? "had_quant_act_i8g" : "quant_act_i8g",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("n", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
RAD_INT("group", wg), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ a.x }, { a.q8, a.s8 });
const char* qdt = asym ? (enc.plane[0].dtype == RAD_U5 ? "w5a8i8" : "w4a8i8_asym")
@@ -1452,7 +1556,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
{ a.q8, a.s8 }, { y })
: rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", qdt)),
RAD_INT("group", wg), RAD_STR("dtype", qdt)),
RAD_WEIGHTS(w, ws)),
{ a.q8, a.s8 }, { y });
return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL;
@@ -1770,9 +1874,9 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
if (i8) {
if (op_q)
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, K), brow_slice(a.q8, r0, rows, K),
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK));
brow_slice(a.s8, r0, rows, K / a.g8));
RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K),
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK),
brow_slice(a.s8, r0, rows, K / a.g8),
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
return;
}
@@ -1846,6 +1950,17 @@ struct DenseFP8 {
bool mx = false;
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand. */
bool m2x = false;
/* Or a weight served at i8a8h (linear_w8h_form): IQ8R, the rotated int8 grid at 128, or a
* narrower form on it (signed codes, a zero point, a codebook, a trellis), its views as
* LinearFP8 declares them. It reads an INT8 activation pair with one scale per (row, `g8`) under
* the same rotation (had_quant_act_i8g at that group); the block declares that pair where it
* would the E4M3 one. `w_rb`: a trellis on a grid of several rows a scale says how many. */
bool w8h = false;
int64_t g8 = RAD_FP8_BLOCK;
int64_t w_rb = 0;
/* Set before declare by a block that declares the int8 activation pair such a weight reads;
* any other block's activations are E4M3, so declare refuses the weight there. */
bool w8h_ok = false;
/* `mapped`: the caller made the name map already, to ask the encoding before choosing this
* struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */
@@ -1900,6 +2015,19 @@ struct DenseFP8 {
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes,
int64_t split_n = 0) const {
if (w8h && w_rb > 0)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", g8), RAD_STR("dtype", "i8a8h"),
RAD_INT("w_rb", w_rb)),
RAD_WEIGHTS(w, s)),
reads, writes);
if (w8h)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", g8), RAD_STR("dtype", "i8a8h")),
RAD_WEIGHTS(w, s)),
reads, writes);
if (mx || m2x)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
@@ -1941,6 +2069,53 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
const bool known = weight_enc(b, wn, &enc);
mx = known && linear_is_mxfp4(enc);
m2x = known && linear_is_m2xfp4(enc);
/* Plain MXFP4 is still read here: the published IQR-V4 containers carry their DFlash2
* drafter in it. */
if (known && !mx)
if (const char* gone = linear_retired(enc)) return linear_refuse_retired(wn, gone);
const W8hForm form = known ? linear_w8h_form(enc) : W8hForm::None;
w8h = form != W8hForm::None;
if (w8h && !w8h_ok) {
fprintf(stderr, "radiance: '%s' is a rotated int8 weight, which reads an int8 "
"activation; this block quantises its activations to E4M3 and takes "
"block fp8 or MXFP4 weights\n", base);
return RAD_E_DTYPE;
}
if (w8h) {
g8 = linear_w8h_group(enc);
if (N % 16 || K % g8) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a rotated int8 weight takes "
"rows in 16s and K in whole %lld-column scale groups\n",
base, (long long)N, (long long)K, (long long)g8);
return RAD_E_INVAL;
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "int8 tiles"));
/* The views LinearFP8's i8a8h branch declares: a narrower form's codes take the plane
* that decodes them, and a scale of two planes is one view at the weight's logical
* extents, which the kernel's layout combines. */
const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis");
w_rb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1 ? tpl->block[1] : 0;
const char* cv = form == W8hForm::Zero ? "codes,zero"
: form == W8hForm::Table ? "codes,table"
: form == W8hForm::Grid ? "codes,grid"
: form == W8hForm::Trellis ? (linear_w8h_mad(enc) ? "codes,trellis,trellis.mad"
: "codes,trellis")
: "codes";
const char* sn = nm.f("%s.scale", base);
const bool iq8r = linear_is_iq8r(enc);
w = decl_view(b, wn, nullptr, cv, enc.plane[0].dtype, { N, K }, access, shard, grp,
rp.w, rp.n);
s = linear_w8h_rowf(enc)
? decl_view(b, sn, wn, "scale,scale.col", RAD_F32, { N, K }, access, shard, grp,
rp.w, rp.n)
: (linear_w8h_scale2(enc) || iq8r)
? decl_view(b, sn, wn, "scale,scale.1", iq8r ? RAD_U8 : RAD_F8E4M3, { N, K },
access, shard, grp, rp.w, rp.n)
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / g8 }, access, shard, grp,
rp.w, rp.n);
return w && s ? RAD_OK : RAD_E_INVAL;
}
if (mx || m2x) {
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s weight takes rows "
+71
View File
@@ -0,0 +1,71 @@
/* Muse Glimmer's reply format: the ATEM channel protocol its chat template renders.
*
* The template's generation prompt ends at `<|start|>assistant`, so the model opens its own
* channels: `<to=self>` reasoning first, then the answer:
*
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=user<|message|> ...answer...
*
* `reasoning_close` carries the whole channel transition, so the answer's own header is consumed
* with the reasoning block's close and the content begins at the answer's first byte. A reply
* that skips the reasoning opens on the answer's channel directly (`to=user<|message|> ...`);
* `content_open` names that header so it is dropped there too.
*
* Tool calls are the template's ATEM dialect, emitted as their own assistant turn whose channel
* names the tool (chat_template.jinja, render_atem):
*
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=NAME<|message|>
* <atem:function_calls>
* <atem:invoke name="NAME">
* <atem:parameter name="k">value</atem:parameter>
* </atem:invoke>
* </atem:function_calls>
*
* String parameters are written raw, everything else as JSON (the template's `tojson`); the
* section opener is the constrained-decoding trigger, and it is also the reasoning break: a call
* turn's channel header names the tool rather than `user`, so the answer's `reasoning_close`
* does not match there and the reasoning block runs to the section, swallowing the `<|eom|>` and
* the header.
*/
#pragma once
#include "rad_builder.h"
namespace museglimmer {
inline const RadChatFormat* muse_chat_format() {
static const RadChatFormat f = [] {
RadChatFormat x{};
x.struct_size = sizeof(x);
x.name = "plugin:museglimmer";
x.reasoning_open = "to=self<|message|>";
x.reasoning_close = "<|eom|><|start|>assistant to=user<|message|>";
static const char* const kBreaks[] = {"<atem:function_calls>"};
x.reasoning_breaks = kBreaks;
x.n_reasoning_breaks = 1;
/* The model opens its own channel; the prompt carries none. */
x.reasoning_in_prompt = RAD_CHAT_THINK_NEVER;
x.content_open = "to=user<|message|>";
x.section_open = "<atem:function_calls>";
x.section_close = "</atem:function_calls>";
x.call_open = "<atem:invoke ";
x.name_prefix = "name=\"";
x.name_suffix = "\">";
x.call_end = "</atem:invoke>";
x.arg_prefix = "<atem:parameter name=\"";
x.arg_name_suffix = "\">";
x.arg_value_suffix = "</atem:parameter>";
x.string_value = RAD_CHAT_VALUE_RAW; /* the template writes string arguments raw */
x.other_value = RAD_CHAT_VALUE_JSON; /* booleans, numbers, arrays, objects as tojson */
x.value_newlines = 1;
/* No grammar triggers: the reference deployment (vLLM's --tool-call-parser muse) runs
* unconstrained and parses whatever the model writes. A trigger arms the lazy tool-call
* grammar, and with the DFlash drafter the trigger fires mid-verify -- inside drafted
* text -- at the reasoning-to-call boundary, which spins the sampler and loops the
* channel header (measured: drafter on = the header repeats 3-4x and the reply stalls;
* drafter off = one header, clean call). The streaming parser reads natural ATEM as
* it is. */
return x;
}();
return &f;
}
} /* namespace museglimmer */
+80 -21
View File
@@ -9,7 +9,8 @@
* Contents: the projection and query path, the block-key path with its two states, and the score
* and selection. Below `budget + ratio - 1` tokens of context every visible block is selected, so
* the sparse path must reproduce the dense path's text byte for byte; that is the test for any
* change here.
* change here. A step entirely at or below that bound therefore needs no selection at all, and
* step() issues only the block-key path for it (its `use`; docs/QSA.md, "Below the bound").
*/
#ifndef RAD_QSA_H
#define RAD_QSA_H
@@ -121,13 +122,43 @@ struct QsaIndexer {
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
/* `win_cu`, device: {0, plane_rows}, the one sequence of a window of a step wider than the
* score plane (Config::plane_rows); null where no step is. */
* score plane (Config::plane_rows); null where no step is.
*
* `use` is what the layer's attention reads of the selection this step (QsaUse, rad_arch.h;
* AttnGatedFP8::qsa_use): the default issues the query, the scores and the selection as every
* step did before. `first` is whether this is the first full-attention layer the pass issues:
* at or below the bound the selection is made there once and read by every layer after it (the
* buffers are the model's, live across its layers, and nothing else writes them). The default
* makes it at every layer. */
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch,
const int32_t* win_cu = nullptr) const;
const int32_t* win_cu = nullptr, int use = kQsaSelect, bool first = true) const;
/* Stores the pass's block keys and tail exactly as step() does, with no query, score or
* selection (see AttnGatedFP8::store_kv). */
void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
bool store_keys(RadCtx* c, const RadBatch* batch) const;
/* `part` 0 issues all of it; 1, 2 and 3 its three stages apart and in that order (the work
* list, the block keys, the tail store), for a caller that issues them behind another block's
* launches (deferrable, below). */
bool store_keys(RadCtx* c, const RadBatch* batch, int part = 0) const;
/* Whether this step's keys and tail may be issued behind the attention block's launches
* instead of in front of them (SideOps, rad_arch.h): nothing reads a selection of this
* layer's (`use` as step() resolves it), so the attention reads nothing the three ops write.
* The caller answers for the buffers (Wire: qk, stage, page, bpos, nc excluded from
* sharing). */
bool deferrable(const RadBatch* batch, int use, bool first) const {
if (!on() || qsa_eager()) return false;
/* step() stores no keys for a batch without the attention's group; leave that to it. */
if (!kv_batch(batch, c.kv_attn)) return false;
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
return use == kQsaUnread;
}
/* What step() issues on a deferrable step, a piece at a time: the projection, then
* store_keys's stages 1..3. */
void step_proj(RadCtx* c, const ActFP8& in, const RadBatch* batch) const {
proj.step(c, in, w.qk, batch->n_tok);
}
void step_part(RadCtx* c, const RadBatch* batch, int part) const {
(void)store_keys(c, batch, part);
}
};
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -267,7 +298,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
/* Stores the block keys of the blocks the pass completes and the tail of raw keys after them,
* from the projection's raw-key head. False when the step has no batch for the indexer's
* groups. */
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch, int part) const {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t nw = (c.heads + 1) * c.head_dim;
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
@@ -289,20 +320,24 @@ inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
const bool mc = g.rope_mc && batch->rope_pos;
RadOperand bpos = g.rope_mc ? RAD_B_COL(w.bpos, 0, mc ? 3 : 1) : brows(w.bpos, work);
if (g.rope_mc) bpos.rows = work;
RAD_ISSUE_N(c_, op_work, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw),
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
brows(w.nc, S));
RAD_ISSUE_N(c_, op_bkey, work,
brows(w.stage, work * c.ratio), RAD_W(w_kn),
brows(w.page, work), bpos,
kv_cache(kv_bk, layer));
if (part <= 1)
RAD_ISSUE_N(c_, op_work, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw),
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
brows(w.nc, S));
if (part == 1) return true;
if (part == 0 || part == 2)
RAD_ISSUE_N(c_, op_bkey, work,
brows(w.stage, work * c.ratio), RAD_W(w_kn),
brows(w.page, work), bpos,
kv_cache(kv_bk, layer));
if (part == 2) return true;
RAD_ISSUE_N(c_, op_tail, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
@@ -319,13 +354,31 @@ inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batc
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch,
const int32_t* win_cu) const {
const int32_t* win_cu, int use, bool first) const {
if (!on()) return;
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t qw = c.heads * c.head_dim;
const int64_t nw = (c.heads + 1) * c.head_dim;
/* What the attention reads this step (QsaUse); anything asked of a step that cannot give it is
* the full issue, which every reader accepts.
*
* kQsaOnce: the attention reads a selection on a step entirely at or below the exactness
* bound. A row there has at most `topk` complete blocks, so qsa_select takes every one whose
* key is not 0 -- every block with a page and a score that is a number, whatever the number --
* and what it writes (the pages in block order, the partial page, their count, seqused) is a
* function of the positions and the block table: the same bytes from every layer's scores. So
* the pass's first full-attention layer issues the selection exactly as it always did, and
* every later layer reads that one and issues none of its own: no query, no score. */
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
if (use != kQsaUnread) use = kQsaSelect;
/* RADIANCE_DEBUG_QSA_EAGER: the issue sequence as it was, every layer its own. */
if (qsa_eager()) use = kQsaSelect;
/* The projection always: its raw-key head is the block keys' and the tail's. */
proj.step(c_, in, w.qk, T);
/* The query heads are read by the score alone. */
if (use == kQsaSelect) {
/* One fused launch or `heads` + 1 unfused. The fused form takes the whole projection at its
* row pitch and writes the query heads contiguous and rotated. `n_head` 0 is the k-only form:
* no q_gate, q_w or q_out, and `gate_out` absent. `T <= qprep_rows` is a correctness bound
@@ -342,8 +395,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
}
/* The keys first: the selection below reads the blocks they complete. */
/* The keys first: the selection below reads the blocks they complete. The stateful half runs
* whatever the attention reads: later steps score the block keys and build on the tail. */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
if (!atb || !store_keys(c_, batch)) return;
@@ -352,6 +407,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
* is a query row, so each query of a prefill chunk selects from the shared history, as the
* checkpoint does. */
if (!c.emit_sel) return;
/* Nothing reads a selection of this layer's: the step is at or below the exactness bound and
* its attention reads the block table, or the selection the pass's first full-attention layer
* made (AttnGatedFP8::qsa_use). */
if (use == kQsaUnread) return;
/* Narrow the score columns to the live history. Both kernels size their grid from the
* operand's width (the live count is device data), so the full `max_ctx` width would make a