Merge upstream main (v1.15.1 -> v1.17.0, 152 commits) into the SYCL port

Conflicts, both sides kept:
- abi: RAD_ABI_VERSION 37 (upstream); the fork's RadBuildCtx.plain_norm after upstream's
  expert_file_tier, widened to int64_t so it starts past ABI 37's 208-byte struct instead of in
  its tail padding (abi_layout_test); RadSyclStream rows after RadShapeGen*.
- arch/common/rad_block_gdn_fp8.h: upstream's q8_rot guard and the fork's o_plain guard
  combined; the decode-row q_o.step only where q_o is declared (!o_plain).
- docs/OPS.md: upstream's optional params on sample_logprobs, the fork's q_temp on
  mtp_couple_propose.

Also ignores /baseline-models/ (local model copies).

Host tests: arch_test's MTP lint/graph-pin failures are unchanged from before the merge (the
fork's mtp.fc LinearFP8, 10a99a5); avx_check's hand-built moe_gemm_q w4a8 case also fails on
upstream's own files; images/videos need FFmpeg; three binaries over their CPU budget on this VM.
SYCL card tests 3/3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-07 22:13:08 +01:00
commit 45f3b510c7
365 files changed
+56942 -6331

No files matched your search

+47 -3
View File
@@ -17,6 +17,7 @@
#include "rad_yarn.h"
#include "rad_abi_layout.h"
#include <cctype>
#include <cstdarg>
#include <cstdio>
#include <cstring>
@@ -123,6 +124,36 @@ inline const char* calib_dir() {
return d && *d ? d : nullptr;
}
/* Whether layer `layer` taps (RADIANCE_CALIB_LAYERS: comma-separated layers and "lo-hi" ranges;
* unset, every layer). A model whose per-expert Hessians do not fit the host at once (Nemotron-3.5
* Bolt's are 169 GiB) calibrates in several runs over disjoint ranges; each run writes only its
* layers' files, so the runs share one directory. */
inline bool calib_layer_on(int layer) {
static const std::vector<std::pair<int, int>> ranges = [] {
std::vector<std::pair<int, int>> r;
const char* s = std::getenv("RADIANCE_CALIB_LAYERS");
while (s && *s) {
char* e = nullptr;
const long lo = std::strtol(s, &e, 10);
if (e == s) break;
long hi = lo;
if (*e == '-') {
const char* h = e + 1;
hi = std::strtol(h, &e, 10);
if (e == h) break;
}
r.emplace_back((int)lo, (int)hi);
s = *e == ',' ? e + 1 : e;
if (*s && *s != ',' && !std::isdigit((unsigned char)*s)) break;
}
return r;
}();
if (!std::getenv("RADIANCE_CALIB_LAYERS")) return true;
for (const auto& r : ranges)
if (layer >= r.first && layer <= r.second) return true;
return false;
}
/* Token count at which the tap dumps and switches itself off (RADIANCE_CALIB_TOKENS, default
* 65536). Whether the tap runs at all is calib_dir()'s decision. */
inline long long calib_target() {
@@ -980,7 +1011,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
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;
g.plain_norm = c->plain_norm != 0;
g.eps = m->rms_eps;
g.theta = m->rope_theta;
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
@@ -1504,7 +1535,12 @@ inline const char* drafter_layer_prefix(const RadModelMeta* meta) {
return "draft.transformer_layer_config.";
return "draft.";
}
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) {
/* `kv_repl_ok`: the drafter block reads its k and v at Geom::kv_off (rad_block_dflash2.h does), so
* fewer KV heads than ranks are replicated as geom_from replicates the target's: world a multiple
* of the head count, one KV head a rank, `kv_off` its first row in the unsharded k/v projection.
* Otherwise such a world is refused, as before. */
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what,
bool kv_repl_ok = false) {
dg = target;
const char* pre = drafter_layer_prefix(meta);
char key[160];
@@ -1529,7 +1565,15 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
}
RAD_ARCH_TRY(yarn_from(dg, meta, pre, dg.head_dim));
RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head));
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv));
/* The target's kv_off is the target's; the drafter's is set here or zero. */
dg.kv_off = 0;
if (kv_repl_ok && dg.world > dg.n_head_kv_all && dg.world % dg.n_head_kv_all == 0) {
dg.n_head_kv = 1; /* world / n_head_kv_all ranks share each KV head */
dg.kv_off = (dg.rank / (dg.world / dg.n_head_kv_all)) * dg.head_dim;
} else {
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads",
&dg.n_head_kv));
}
RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff));
const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all);
if (dvocab != dg.n_vocab_all) {
+24 -11
View File
@@ -9,6 +9,9 @@
* the GEMM output directly.
* - No output gate. The attention output goes straight into the out-projection.
*
* `rotary_dim` 0 is attention without positions (NoPE, Nemotron-H's attention layers): no `rope`
* is declared, and position reaches the model through its recurrent layers alone.
*
* That allows a fused q|k|v, which the gated block cannot have (its query projection is [q|gate]
* interleaved per head). The three weights concatenate along dim 0 into one
* [q_dim + 2*kv_dim, n_embd], and `rope` takes that row as is: q heads, then k heads, v untouched
@@ -81,19 +84,21 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
const int64_t q_dim = g.q_dim();
const int64_t kv_dim = g.kv_dim();
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
if (n_rot < 0 || n_rot > g.head_dim || (n_rot & 1)) {
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
(long long)n_rot, (long long)g.head_dim);
return RAD_E_INVAL;
}
/* No KV-head replication: the fused [q|k|v] uses the plain even row shard, so above the KV head
* count a rank would read the wrong rows. rad_block_attn_gated_fp8.h is the block that uses
* geom_from's `kv_off`. */
if (g.world > g.n_head_kv_all) {
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
"with n_head_kv = %lld.\n", __func__, g.world,
(long long)g.n_head_kv_all);
/* Above the KV head count geom_from replicates KV heads (rad_arch.h): each of the fused row's
* three parts takes its own span (as gemma4's q|k|v does), q this rank's heads and k and v the
* shared head at `kv_off`, where the even shard would hand a rank part of a head. A smaller
* attention world (Geom::attn_world) is not served here. */
const bool kv_repl = g.world > g.n_head_kv_all;
if (kv_repl && g.attn_world != g.world) {
fprintf(stderr, "radiance: %s replicates KV heads but declares no attention-zero ranks; "
"world_size = %d must be a multiple of n_head_kv = %lld.\n", __func__,
g.world, (long long)g.n_head_kv_all);
return RAD_E_UNSUPPORTED;
}
@@ -107,9 +112,17 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
0, { q_dim, kv_dim, kv_dim }));
if (kv_repl) {
const int64_t lo[3] = { g.rank * q_dim, g.kv_off, g.kv_off };
const int64_t hi[3] = { lo[0] + q_dim, lo[1] + kv_dim, lo[2] + kv_dim };
const int64_t tot[3] = { g.n_head_all * g.head_dim, g.n_head_kv_all * g.head_dim,
g.n_head_kv_all * g.head_dim };
RAD_ARCH_TRY(qkv.span_parts(b, lo, hi, tot, 3));
}
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
{w.qkv}, {w.qkv});
if (n_rot > 0)
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
{w.qkv}, {w.qkv});
/* Copies the query out of the fused row: libr4d's paged attention reads `q` as a dense
* [total_q, n_head, head_dim] block with no pitch argument (r4d_attn_args.h, fill_paged), so a
@@ -179,7 +192,7 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
qkv.step(c, w.h, w.qkv, T);
/* In place over the fused row: rotates n_head query heads, then n_head_kv key heads, and
* leaves the value heads alone. */
RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
if (op_rope) RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
/* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */
RAD_ISSUE(c, op_kv_store,
+5 -3
View File
@@ -458,8 +458,10 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
if (g.w_bf16) {
RAD_ARCH_TRY(gate_pair(w.gate));
} else {
if (rad_op_declared(b, "gate_quant_fp8"))
op_gq = rw(b, RAD_OP(b, "gate_quant_fp8",
/* Rotated int8 codes (ActFP8::q8_rot): gate_had_quant_i8g, had_quant_act_i8g's codes. */
const char* gq = w.attn.q8_rot ? "gate_had_quant_i8g" : "gate_quant_fp8";
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_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
@@ -487,7 +489,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
* 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 &&
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",
RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
+129 -58
View File
@@ -47,6 +47,13 @@
* hp = hidden_projection(x) the selector's query, rank 256
* tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor)
*
* ============================== LILICORR ==============================
*
* Config::lili is NVIDIA's LiLiCorr backbone (Nemotron-3.5-Bolt's drafter): the same layers with a
* learned sink logit a query head in the attention (attn_paged_sink, `attention_sink_bias`), and no
* selector or draft head here. The query pass ends with the gather into `sel_h`; the plugin then
* runs rad_block_lilicorr.h's correlator over those rows, which reads the target's own head.
*
* ============================== WHAT IS SHARED WITH THE TARGET ==============================
*
* The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and
@@ -68,6 +75,8 @@
*
* q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per
* draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor.
* Fewer KV heads than ranks are replicated (drafter_geom's `kv_repl_ok`): each rank reads its
* head's k/v rows at `kv_off` and keeps that head in its cache.
*
* fc [n_embd, n_taps*n_embd], 262 MiB in fp8 at Qwen3.8's width, read whole by the
* context pass every step. Split by rows over the ranks and all-gathered, and
@@ -152,6 +161,9 @@ struct Dflash2 {
* acceptance, sum min(P, Q). */
double q_temp = 1.0;
int64_t short_rows = 0;
/* 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;
int64_t steps() const { return block - 1; }
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
@@ -294,6 +306,9 @@ struct Dflash2 {
int64_t block_lo = 0;
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
/* LiLiCorr: the attention with each layer's sinks, a weight, so one op a layer. */
rad_weight w_sink[MAX_LAYERS] = {};
rad_op op_attn_sink[MAX_LAYERS] = {};
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
* that norm where it resolves: op_afn[i] after layer i's attention (its feed-forward norm),
@@ -353,7 +368,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
(long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.block < 2 || cfg.n_taps <= 0 || cfg.sel_rank <= 0 || cfg.sel_topk <= 0)
if (cfg.block < 2 || cfg.n_taps <= 0 || (!cfg.lili && (cfg.sel_rank <= 0 || cfg.sel_topk <= 0)))
return RAD_E_INVAL;
const int64_t NG = cfg.ng(g.n_embd);
@@ -401,23 +416,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
}
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
/* The 2-bit draft head, declared as the MTP head's is (rad_block_mtp_fp8.h):
* `dflash.draft_head.weight` is the target's lm_head under its own name, quantised by the
@@ -427,35 +429,53 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* When sharded, each rank's `row_topk` reports global ids, an all_gather moves R pairs a row,
* and `row_topk_merge` reduces them to exactly the unsharded global top-R, ties included
* (docs/OPS.md). This runs before the selector, so every rank holds the same candidates for
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16). */
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16).
*
* LiLiCorr has neither the selector nor this head (its correlator reads the target's). */
enum { DF_W2_GROUP = 128 };
const bool dh_shard = head_sharded(g);
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
const char* dhn = nm.f("dflash.draft_head.weight");
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 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 &&
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
if (!cfg.lili) {
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
const char* dhn = nm.f("dflash.draft_head.weight");
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 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 &&
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
}
if (head_i8) {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
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 {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split,
grp_model());
}
if (!w_dh || !w_dhs) return RAD_E_INVAL;
}
if (head_i8) {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
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 {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
}
if (!w_dh || !w_dhs) return RAD_E_INVAL;
/* ---------------------------------------------------------------- per-layer weights */
for (int64_t l = 0; l < g.n_layer; ++l) {
@@ -492,6 +512,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
/* Fewer KV heads than ranks (drafter_geom's `kv_repl_ok`): k and v are this rank's
* replicated head, rows [kv_off, kv_off + kv_dim) of the unsharded projection, where the
* even shard would hand a rank part of a head. q stays an even share of the heads. */
if (g.world > g.n_head_kv_all) {
RAD_ARCH_TRY(w_k[i].span(b, g.kv_off, g.kv_off + kvd));
RAD_ARCH_TRY(w_v[i].span(b, g.kv_off, g.kv_off + kvd));
}
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
@@ -520,6 +547,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
w_fcb[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_base", i), RAD_BF16,
{2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(first_layer + i));
/* LiLiCorr's sink logit a query head, split with the heads. */
if (cfg.lili) {
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_sinks", i),
nm.ckpt("%s.layers.%d.self_attn.attention_sink_bias", ck, i)));
w_sink[i] = decl_w(b, nm.f("dflash.blk.%d.attn_sinks", i), RAD_F32, {g.n_head},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i));
if (!w_sink[i]) return RAD_E_INVAL;
}
}
@@ -529,15 +564,35 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
*
* Declared before both kv_stores, which read the resolved `block_size` back with
* rad_kv_block_size(); before this declaration it returns zero. */
op_attn = rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
if (!cfg.lili) {
op_attn = rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
} else {
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_attn_sink[i] = rw(b, RAD_OP(b, "attn_paged_sink",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block),
RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("window", cfg.window),
RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_sink[i])),
{w.q}, {w.attn});
if (!op_attn_sink[i]) return RAD_E_INVAL;
}
}
/* ---------------------------------------------------------------- the context pass */
/* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
@@ -555,12 +610,15 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
if (fc_rows) {
/* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of
* them gathered into `c`. The GEMM takes its K split from the whole width. The gather
* rides the trunk's all-reduce instance (the same numel bound, so the same instance). */
* rides the trunk's all-reduce instance (the same numel bound, so the same instance).
* The message is a range, as the all-reduce's: a fixed numel follows max_tok, and the
* arena's sizing declare (RadBuildCtx::shape_probe) refuses a fixed parameter that
* changes with the step size. */
op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart},
g.n_embd);
op_cgath = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", crows * g.n_embd),
RAD_RANGE("numel", g.n_embd, crows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)),
RAD_NOWEIGHTS),
{w.cpart}, {w.c});
@@ -884,6 +942,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{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)),
@@ -1090,7 +1150,8 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
if (fc_rows) {
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.cpart, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cgath, T, bcol(w.cpart, fc_off, fc_share, T), brows(w.c, T));
RAD_ISSUE_N(c, op_cgath, T * g.n_embd, bcol(w.cpart, fc_off, fc_share, T),
brows(w.c, T));
} else {
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, w_fc.bref());
@@ -1188,13 +1249,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
}
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T));
if (cfg.lili)
RAD_ISSUE_N(c, op_attn_sink[i], batch->max_q_len,
brows(w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
RAD_W(w_sink[i]), brows(w.attn, T));
else
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
@@ -1238,6 +1308,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
const int64_t S = batch->n_out;
if (S <= 0) return;
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
if (cfg.lili) return; /* the plugin's correlator takes sel_h from here */
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
* whole. */
+958
View File
@@ -0,0 +1,958 @@
/* rad_block_dspark_bf16.h -- the DSpark drafter over bf16 weights, at the widths a Spark layer
* uses: a few plain attention layers that denoise a whole block of masked positions in one pass,
* conditioned on the trunk's residual stream at a handful of layers, with a rank-N Markov head
* over the target's own output table.
*
* ============================== WHY A SECOND DSPARK BLOCK ==============================
*
* rad_block_dspark.h is the same drafter shape for a block-fp8 release: its linears are DenseFP8
* behind `quant_act_fp8`, its feed-forward is `silu_mul`, its norms carry q/k gains, and its draft
* head is a 2-bit copy of the target's. The published Spark drafts (`dflash` GGUFs, and the HF
* Spark drafter releases behind them) ship the other way: bf16 linears, no q/k norms, one sigmoid
* gate a head on the attention output, exact-erf GELU, one RMS gain per tap, and a sliding window.
* Those are different ops, not different parameters, so this block declares its own graph and
* uses an explicit anchor-window attention op and a full-vocabulary Markov selector so neither
* semantic distinction is silently folded into the generic per-row window or candidate-lattice ops.
*
* Nothing here is quantised. The drafter is 624M parameters read whole a draft pass, so bf16 costs
* 1.2 GiB of residency and one extra weight pass a step; quantising it is a separate measurement
* (it can only move acceptance, since every draft is verified by the target).
*
* ============================== THE FORWARD PASS ==============================
*
* The reference is llama.cpp's `llama_model_dflash::graph<false>` (XHToken/llama.cpp
* 22c0ae1871b, the branch the Spark draft cards name), which mirrors the HF export:
*
* tap(l) = rmsnorm(residual after trunk layer l) * fc_norm[l] one gain row per tap
* ctx = rmsnorm(fc(concat_l tap(l))) hidden_norm
* per draft layer (x5):
* h_n = input_layernorm(h)
* q,k,v = q_proj/k_proj/v_proj(h_n); k_ctx, v_ctx = k_proj/v_proj(ctx)
* rope(q, k); attention over [the layer's context K/V, this block] non-causally,
* inside a `window` positions
* h += o_proj(sigmoid(g_proj(h)) * attn) one gate a head, no q/k norms
* h += mlp(post_attention_layernorm(h)) gelu(gate) * up, then down
* logits = target.lm_head(output_norm(h)) + markov_w2 @ markov_w1[prev]
*
* The two projections of `ctx` are the drafter's own k_proj and v_proj, one pair per layer, and
* they run over every committed token; the drafter's layers never see the context rows. That is
* the context pass below, and the block above is the query pass -- the same split
* rad_block_dspark.h makes, and the same `RAD_DRAFT_BLOCK` drive.
*
* ============================== THE TAPS ARE NORMED, NOT JUST READ ==================
*
* `fc_norm` is [n_taps, n_embd]: the residual entering each tap layer is normed with its own gain
* before the concatenation, so `fc` sees n_taps unit-scaled streams instead of one sum whose
* magnitudes the trunk happens to have. One `rmsnorm` per tap over that tap's column slice of the
* tap buffer, into the same slice layout of a normed copy; `fc` then reads one contiguous
* [n_taps * n_embd] row.
*
* ============================== THE SHARED ANCHOR WINDOW ==========================
*
* The pinned llama.cpp oracle increments the configured history from 512 to 513 and repeats the
* anchor row's mask for every row in the denoising block. `attn_paged_anchor_window` implements
* that exact predicate: every row sees keys through the end of the staged context whose absolute
* position is less than 513 behind the anchor. The query row does not move the lower cutoff. The
* same 513-token width is passed to the KV group and scheduler, so rollback, cache recycling and
* block staging all retain the exact history the drafter reads.
*
* ============================== ROW ALIGNMENT ==============================
*
* Every row predicts, the anchor included (`dflash.sample_from_anchor`, which the GGUF import
* refuses when false): row j of [anchor, MASK x (block-1)] proposes the token at the anchor's
* position plus j + 1, so `steps()` is `block` and the head runs over all the block's rows. The
* core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
* rows, which covers this and Dflash2's shift-by-one convention (abi/rad_builder.h).
*
* ============================== THE MARKOV HEAD ==============================
*
* The draft logits get a learned bigram bias
*
* score[l, token] = logits[l, token] + markov_w2[token] . markov_w1[prev(l)]
* prev(0) = the anchor; prev(l) = the greedy token chosen at l - 1
*
* `dflash_markov_greedy` scans the full vocabulary at every position and greedily chooses the
* largest biased score, following the structure of the pinned reference's serial Markov walk.
* Base logits are F32; reduction order and tie behavior can still differ from the reference. It
* does not prune to the base head's top K, use a joint-path heap, or apply confidence to logits.
*
* The confidence head (`conf_proj`, one sigmoid a position predicting acceptance) is imported and
* ignored: it exists to let a serving loop cut the block short, this engine's depth is fixed at
* declare, and it changes nothing the drafter proposes.
*
* ============================== PRECISION ==============================
*
* bf16 for every weight and activation except the residual stream, which is f32 exactly as the
* Spark trunk keeps it (rad_block_dspark.h's fp8 graphs fold the residual into the norm; here the
* norms read the f32 stream and write bf16, and `add` keeps the sum in f32). The reference runs
* bf16 weights against an f32 residual, so rounding the drafter's stream to bf16 would be a third
* opinion on every layer's output for no saved bytes worth having at `block` rows.
*
* ============================== NOT DONE ==============================
*
* The head and full-vocabulary Markov scan are read replicated, so a vocab-sharded deployment
* cannot draft with them. The plugin refuses `world > 1` rather than scoring only one rank's
* slice of the vocabulary.
*
* The drafter's linears are four GEMMs and one attention a layer with no folding: the norms are
* plain `rmsnorm`, not a fused norm-add-quantise, because nothing here quantises. At seven rows
* a pass the launches, not the bytes, are the cost.
*/
#ifndef RAD_BLOCK_DSPARK_BF16_H
#define RAD_BLOCK_DSPARK_BF16_H
#include "rad_arch.h"
namespace rad {
namespace arch {
/* The builder refuses a declaration it cannot serve and says why in its own words; this names which
* handle did not come back, so that message reads against a line of this file. An op that resolves
* to no kernel is recorded and handed back null -- it is only an error if the block issues it -- so
* without this a missing kernel surfaces as a bare "invalid argument" at startup. */
#define DS_REFUSED(...) ::rad::arch::drafter_refused({ __VA_ARGS__ })
inline int drafter_refused(std::initializer_list<const char*> what) {
std::string list;
for (const char* w : what) { if (!list.empty()) list += ", "; list += w; }
std::fprintf(stderr, "DSpark drafter: the builder gave no handle for %s\n", list.c_str());
return RAD_E_INVAL;
}
struct DsparkBF16 {
enum { MAX_LAYERS = 8 };
/* The drafter's config beyond its geometry. Everything here comes from the container's
* `draft.` keys; nothing is defaulted quietly, because a silently ignored gate or window only
* moves acceptance, which is the one number the user cannot see. */
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* noise rows a sequence, and drafts (one per row) */
int64_t rank = 0; /* markov_rank: the codebooks' width */
int64_t window = 0; /* reference's anchor-aligned n_swa (configured history + 1) */
int64_t rot = 0; /* rotary dimensions a head; 0 for all of head_dim */
int causal = 0;
int tap_norm = 0; /* `fc_norm`: one RMS gain a tap before the concatenation */
int qk_norm = 0; /* per-head q/k gains, and no output gate */
int gate = 0; /* one sigmoid gate a head on the attention output */
const char* act = "gelu"; /* the feed-forward's activation */
int64_t steps() const { return block; } /* every row predicts */
};
struct Wire {
/* ---- the context pass, one row per committed token */
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
rad_buf srcn = 0; /* [max_tok, n_taps * n_embd] each tap normed, same layout */
rad_buf c = 0, cn = 0; /* [max_tok, n_embd] fc output and separately normed context */
rad_buf ck = 0, ckn = 0; /* [max_tok, kv_dim] projected and optionally normed K */
rad_buf cv = 0; /* [max_tok, kv_dim] and its V */
/* ---- the query pass, `block` rows per sequence */
rad_buf x = 0; /* [qrows, n_embd] f32 the drafter's residual stream */
rad_buf delta = 0; /* [qrows, n_embd] f32 the block a projection just wrote */
rad_buf h = 0; /* [qrows, n_embd] bf16 the normed stream, and every linear's output */
rad_buf q = 0, k = 0, v = 0, qn = 0, kn = 0;
rad_buf gate = 0, gaten = 0; /* [qrows, n_head] projection and sigmoid */
rad_buf attn = 0, attng = 0; /* [qrows, q_dim] attention and gated attention */
rad_buf gate_up = 0; rad_buf ff = 0;
/* ---- the head and the walk, one row per draft position */
rad_buf dlog = 0; /* [srows, n_vocab] f32 full-vocabulary draft logits */
rad_buf best_score = 0; /* [max_seqs, ceil(n_vocab/64)] f32 partial argmax scores */
rad_buf best_token = 0; /* [max_seqs, ceil(n_vocab/64)] i32 partial argmax ids */
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
};
Geom g{}; /* the drafter's geometry, not the trunk's */
Config cfg{};
Wire w{};
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
int64_t qrows = 0, crows = 0, srows = 0;
rad_kvgroup kv = 0;
/* ---- model-scope weights */
rad_weight w_fc = 0, w_hnorm = 0, w_norm = 0;
rad_weight w_fcnorm[MAX_LAYERS] = {}; /* one row of `fc_norm` a tap */
rad_weight w_mk1 = 0, w_mk2 = 0; /* markov_w1 (pred), markov_w2 (succ) */
rad_weight w_tok = 0; /* the target's embedding table */
rad_weight w_head = 0; /* the target's output table */
/* ---- per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
rad_weight w_q[MAX_LAYERS] = {}, w_k[MAX_LAYERS] = {}, w_v[MAX_LAYERS] = {}, w_o[MAX_LAYERS] = {};
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}, w_gate[MAX_LAYERS] = {};
rad_weight w_gu[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
/* ---- the context pass */
rad_op op_tapn[MAX_LAYERS] = {}; /* one per tap, not per layer */
rad_op op_cfc = 0, op_cnorm = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
rad_op op_crope = 0, op_cstore = 0;
/* ---- the query pass. The weightless ops are declared once and issued per layer; the ones
* with weights are per layer, since a weight's prefetch interval and residency class come
* from the op that declares it. */
rad_op op_embed = 0, op_widen = 0, op_add = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}, op_gp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {}, op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_widen2 = 0, op_widen3 = 0;
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
rad_op op_sig = 0, op_gate_heads = 0, op_act = 0;
/* ---- the head and the walk */
rad_op op_dlogits = 0, op_markov = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck, const char* ck_head,
const Wire& wire);
/* The context pass, one row per committed token. */
void context(RadCtx* c, const RadBatch* batch) const;
/* The query pass, the head and the Markov walk, `block` rows per sequence. */
void step(RadCtx* c, const RadBatch* batch) const;
private:
int64_t q_dim() const { return g.n_head * g.head_dim; }
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
};
/* ------------------------------------------------------------------------------ declare */
inline int DsparkBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
int base_layer, rad_kvgroup group, rad_weight tok_embd,
const char* ck, const char* ck_head, const Wire& wire) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !ck_head || !w_tok) return DS_REFUSED("ck", "ck_head", "w_tok");
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: the bf16 DSpark drafter has %lld layers; this block carries at "
"most %d\n", (long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.n_taps <= 0 || cfg.n_taps > MAX_LAYERS || cfg.block < 2 || cfg.rank <= 0)
return RAD_E_INVAL;
if (cfg.qk_norm && cfg.gate) {
fprintf(stderr, "radiance: the drafter declares both per-head q/k norms and a per-head "
"output gate; no published drafter ships both, and this block would have "
"to guess which one the checkpoint trained with\n");
return RAD_E_UNSUPPORTED;
}
/* The full-vocabulary head and Markov scan are read replicated; partial-vocabulary drafting
* would need an exact distributed argmax and replicated codebook access. */
if (g.world > 1) {
fprintf(stderr, "radiance: the bf16 DSpark drafter reads the target's whole output table "
"and cannot draft at tp %d; run it at tp 1\n", g.world);
return RAD_E_UNSUPPORTED;
}
const int64_t qd = q_dim(), kvd = kv_dim(), E = g.n_embd;
crows = g.max_tok;
qrows = g.max_seqs * cfg.block;
if (qrows > g.max_tok) qrows = g.max_tok;
srows = g.max_seqs * cfg.steps(); /* every row predicts */
if (qrows <= 0 || srows <= 0 || cfg.rot < 0 || cfg.rot > g.head_dim || cfg.rot % 2)
return RAD_E_INVAL;
const int64_t rot = cfg.rot ? cfg.rot : g.head_dim;
/* One op declaration per kernel shape, shared by the layers: `rmsnorm`'s and `gemm_nt`'s
* parameters are geometry, and only the weights differ per layer. */
auto gemm = [&](int64_t rows, int64_t n, int64_t k, rad_weight wt, rad_buf x, rad_buf y) {
return rw(b, 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(wt)),
{x}, {y});
};
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.fc.weight"), nm.ckpt("%s.fc.weight", ck)));
w_fc = decl_w(b, nm.f("dspark.fc.weight"), RAD_BF16, {E, cfg.n_taps * E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
nm.ckpt("%s.hidden_norm.weight", ck)));
w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_fc || !w_hnorm || !w_norm) return DS_REFUSED("w_fc", "w_hnorm", "w_norm");
/* `fc_norm` is [n_taps, n_embd]: one gain row a tap, read as that tap's slice. */
if (cfg.tap_norm) {
const char* src = nm.ckpt("%s.fc_norm.weight", ck);
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
RAD_ARCH_TRY(map_rows(b, nm.f("dspark.fc_norm.%d.weight", i),
{ { src, (int)t, 1 } }));
w_fcnorm[i] = decl_w(b, nm.f("dspark.fc_norm.%d.weight", i), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_fcnorm[i]) return DS_REFUSED("w_fcnorm[i]");
}
}
/* The Markov codebooks, bf16, replicated over the whole vocabulary: both are [vocab, rank], so
* `w2 @ w1[prev]` is `<w1[prev], w2[token]>`. RAD_ACCESS_VOCAB: each walk position reads one
* predecessor row and scans every successor row. */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
nm.ckpt("%s.markov_head.markov_w2.weight", ck)));
w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
if (!w_mk1 || !w_mk2) return DS_REFUSED("w_mk1", "w_mk2");
/* The target's output table under the drafter's own name: one stored tensor, two arch weights,
* as rad_block_dspark.h does for its 2-bit copy. bf16 and replicated here, since the drafter
* reads it as the head its full-vocabulary walk scores (see NOT DONE for sharding). */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.head.weight"), ck_head));
w_head = decl_w(b, nm.f("dspark.head.weight"), RAD_BF16, {g.n_vocab_all, E},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
if (!w_head) return DS_REFUSED("w_head");
/* ---------------------------------------------------------------- per-layer weights
*
* One name map and one declaration a weight, spelled out: the list is the readable form of
* which checkpoint tensor feeds which matmul, and a drafter has few enough of them that a
* table would only hide it. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const RadWeightGroup grp = grp_layer(first_layer + i);
/* A norm gain: f32, read whole, never sharded. */
auto norm_w = [&](rad_weight* out, const char* suffix, const char* from,
std::initializer_list<int64_t> shape) -> int {
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
RAD_ARCH_TRY(map_copy(b, name, nm.ckpt("%s.layers.%d.%s", ck, i, from)));
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
return *out ? RAD_OK : RAD_E_INVAL;
};
/* A linear: bf16. More than one source is a concatenation, whose row parts say where each
* piece begins (RadWeightDecl::row_parts), so `act_mul` can read [gate | up] as one
* weight. */
auto lin_w = [&](rad_weight* out, const char* suffix,
std::initializer_list<const char*> srcs,
std::initializer_list<int64_t> shape,
std::initializer_list<int64_t> parts = {}) -> int {
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
if (srcs.size() > 1) RAD_ARCH_TRY(map_concat(b, name, srcs));
else RAD_ARCH_TRY(map_copy(b, name, *srcs.begin()));
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp, 0,
parts);
return *out ? RAD_OK : RAD_E_INVAL;
};
#define SRC(path) nm.ckpt("%s.layers.%d." path, ck, i)
RAD_ARCH_TRY(norm_w(&w_anorm[i], "attn_norm.weight", "input_layernorm.weight", {E}));
RAD_ARCH_TRY(norm_w(&w_fnorm[i], "ffn_norm.weight", "post_attention_layernorm.weight", {E}));
RAD_ARCH_TRY(lin_w(&w_q[i], "attn_q", { SRC("self_attn.q_proj.weight") }, {qd, E}));
RAD_ARCH_TRY(lin_w(&w_k[i], "attn_k", { SRC("self_attn.k_proj.weight") }, {kvd, E}));
RAD_ARCH_TRY(lin_w(&w_v[i], "attn_v", { SRC("self_attn.v_proj.weight") }, {kvd, E}));
RAD_ARCH_TRY(lin_w(&w_o[i], "attn_output", { SRC("self_attn.o_proj.weight") }, {E, qd}));
RAD_ARCH_TRY(lin_w(&w_gu[i], "ffn_gate_up",
{ SRC("mlp.gate_proj.weight"), SRC("mlp.up_proj.weight") },
{2 * g.n_ff, E}, { g.n_ff, g.n_ff }));
RAD_ARCH_TRY(lin_w(&w_dn[i], "ffn_down", { SRC("mlp.down_proj.weight") },
{E, g.n_ff}));
if (cfg.gate)
RAD_ARCH_TRY(lin_w(&w_gate[i], "attn_gate", { SRC("self_attn.g_proj.weight") },
{g.n_head, E}));
if (cfg.qk_norm) {
RAD_ARCH_TRY(norm_w(&w_qn[i], "attn_q_norm.weight", "self_attn.q_norm.weight",
{g.head_dim}));
RAD_ARCH_TRY(norm_w(&w_kn[i], "attn_k_norm.weight", "self_attn.k_norm.weight",
{g.head_dim}));
}
#undef SRC
}
/* Non-causal: every query row sees its whole block and the context the trunk committed
* (`causal` comes from `draft.is_causal`). Declared before both kv_stores, which read the
* resolved `block_size` back with rad_kv_block_size(); before it, that returns zero. */
op_attn = rw(b, RAD_OP(b, cfg.window > 0 ? "attn_paged_anchor_window" : "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.qn : w.q}, {w.attn});
if (!op_attn) return DS_REFUSED("op_attn");
/* ---------------------------------------------------------------- the context pass
*
* One row per committed token, run once per trunk step: the taps become the drafter's own K
* and V. Nothing here is per query row, so its cost follows the trunk's token count, not the
* block's. */
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
op_tapn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_fcnorm[i])),
{w.src}, {w.srcn});
if (!op_tapn[i]) return DS_REFUSED("op_tapn[i]");
}
op_cfc = gemm(crows, E, cfg.n_taps * E, w_fc, w.srcn, w.c);
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.cn});
if (!op_cfc || !op_cnorm) return DS_REFUSED("op_cfc", "op_cnorm");
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] = gemm(crows, kvd, E, w_k[i], w.cn, w.ck);
op_cv[i] = gemm(crows, kvd, E, w_v[i], w.cn, w.cv);
if (!op_ck[i] || !op_cv[i]) return DS_REFUSED("op_ck[i]", "op_cv[i]");
if (cfg.qk_norm) {
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ckn});
if (!op_cknorm[i]) return DS_REFUSED("op_cknorm[i]");
}
}
/* K-only rope: `rope` rotates the first n_head + n_head_kv heads, so a K-only tensor is
* n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer. Each context
* row is rotated by its own absolute position, as the reference's single concatenated rope
* does. */
op_crope = rw(b, decl_rope(b, g, crows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
{cfg.qk_norm ? w.ckn : w.ck}, {cfg.qk_norm ? w.ckn : w.ck});
op_cstore = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.ckn : w.ck, w.cv}, {});
if (!op_crope || !op_cstore) return DS_REFUSED("op_crope", "op_cstore");
/* ---------------------------------------------------------------- the query pass
*
* `block` rows per sequence, through the drafter's layers. The residual stream is f32 and the
* linears read bf16, exactly as the trunk keeps them: `rmsnorm` reads the stream and writes the
* activations, `cast` widens a projection's output, and `add` keeps the sum in f32. */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.h});
op_widen = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{w.h}, {w.x});
/* One widen and one add serve both residual sites a layer: same shapes, same buffers. */
op_widen2 = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{w.h}, {w.delta});
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{w.x, w.delta}, {w.x});
if (!op_embed || !op_widen || !op_widen2 || !op_add)
return DS_REFUSED("op_embed", "op_widen", "op_widen2", "op_add");
/* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
* planner's liveness (core/build/rad_bufplan.cpp), and the stream `x` lives over the ops that
* touch it: each layer's two norms in the loop, the final one after everything the layers
* issue. Declared up front, the stream's lifetime would end before the layers and the planner
* could overlay a feed-forward temporary on it. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_anorm[i])),
{w.x}, {w.h});
op_qp[i] = gemm(qrows, qd, E, w_q[i], w.h, w.q);
op_kp[i] = gemm(qrows, kvd, E, w_k[i], w.h, w.k);
op_vp[i] = gemm(qrows, kvd, E, w_v[i], w.h, w.v);
op_op[i] = gemm(qrows, E, qd, w_o[i], cfg.gate ? w.attng : w.attn, w.h);
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_fnorm[i])),
{w.x}, {w.h});
op_gu[i] = gemm(qrows, 2 * g.n_ff, E, w_gu[i], w.h, w.gate_up);
op_dn[i] = gemm(qrows, E, g.n_ff, w_dn[i], w.ff, w.h);
if (!op_anorm[i] || !op_qp[i] || !op_kp[i] || !op_vp[i] || !op_op[i] || !op_fnorm[i] ||
!op_gu[i] || !op_dn[i])
return RAD_E_INVAL;
if (cfg.qk_norm) {
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_qn[i])),
{w.q}, {w.qn});
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.kn});
if (!op_qn[i] || !op_kn[i]) return DS_REFUSED("op_qn[i]", "op_kn[i]");
}
if (cfg.gate) {
op_gp[i] = gemm(qrows, g.n_head, E, w_gate[i], w.h, w.gate);
if (!op_gp[i]) return DS_REFUSED("op_gp[i]");
}
}
op_qrope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head, 0, rot, "neox"),
{cfg.qk_norm ? w.qn : w.q}, {cfg.qk_norm ? w.qn : w.q});
op_krope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
{cfg.qk_norm ? w.kn : w.k}, {cfg.qk_norm ? w.kn : w.k});
op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.kn : w.k, w.v}, {});
/* The gate the trunk uses too: one sigmoid a head, then one scale a head's whole row. */
if (cfg.gate) {
op_sig = rw(b, RAD_OP(b, "sigmoid",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_head),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.gate}, {w.gaten});
op_gate_heads = rw(b, RAD_OP(b, "scale_rows",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
RAD_INT("n", g.head_dim), RAD_STR("act", "none"),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.attn, w.gaten}, {w.attng});
if (!op_sig || !op_gate_heads) return DS_REFUSED("op_sig", "op_gate_heads");
}
/* `act_mul` with the activation the drafter was trained with: exact-erf gelu for the Spark
* drafts (`hidden_activation: gelu`), silu for a Qwen3-shaped one. `gelu_mul` is the tanh
* approximation and is not what the reference runs. */
op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("act", cfg.act), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ff});
op_outnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
if (!op_qrope || !op_krope || !op_store || !op_act || !op_outnorm)
return DS_REFUSED("op_qrope", "op_krope", "op_store", "op_act", "op_outnorm");
/* ---------------------------------------------------------------- the head and full-vocabulary walk
*
* Every row predicts, so the head scores all `steps` rows, anchor included. The row order is
* sequence-major, which is the selector's [sequence, position, vocabulary] contract. The
* greedy Markov op scans all vocabulary entries at every position and feeds each winning id
* into the next position's bigram bias.
*/
op_dlogits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_head)),
{w.h}, {w.dlog});
op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy_f32",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
RAD_INT("steps", cfg.steps()), RAD_INT("rank", cfg.rank),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_mk1, w_mk2)),
{w.dlog}, {w.best_score, w.best_token, w.tokens});
if (!op_dlogits || !op_markov) return DS_REFUSED("op_dlogits", "op_markov");
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void DsparkBF16::context(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int64_t E = g.n_embd;
/* Each tap's slice of the residual the trunk just tapped, normed with its own gain into the
* same slice layout of one row-per-token buffer. */
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
if (!cfg.tap_norm) continue;
RAD_ISSUE_N(c, op_tapn[i], T, bcol(w.src, t * E, E, T), RAD_W(w_fcnorm[i]),
bcol(w.srcn, t * E, E, T));
}
RAD_ISSUE_N(c, op_cfc, T, cfg.tap_norm ? brows(w.srcn, T) : brows(w.src, T), RAD_W(w_fc),
brows(w.c, T));
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.cn, 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.cn, T), RAD_W(w_k[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cn, T), RAD_W(w_v[i]), brows(w.cv, T));
if (cfg.qk_norm)
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
brows(w.ckn, T));
RAD_ISSUE_N(c, op_crope, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_cstore, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), brows(w.cv, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void DsparkBF16::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
/* The block the core staged: the token the sampler just chose, then the mask token in every
* unfilled slot. */
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.h, T));
RAD_ISSUE_N(c, op_widen, T, brows(w.h, T), brows(w.x, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h, T), RAD_W(w_q[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h, T), RAD_W(w_k[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h, T), RAD_W(w_v[i]), brows(w.v, T));
if (cfg.qk_norm) {
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.qn, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]),
brows(w.kn, T));
}
RAD_ISSUE_N(c, op_qrope, T, brows(cfg.qk_norm ? w.qn : w.q, T), pos);
RAD_ISSUE_N(c, op_krope, T, brows(cfg.qk_norm ? w.kn : w.k, T), pos);
/* The block's own K and V go into the cache past `seqused`, which is how every row of the
* block attends to every other; the next context pass overwrites them, which is the
* reference's `crop(start)`. */
RAD_ISSUE_N(c, op_store, T, brows(cfg.qk_norm ? w.kn : w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(cfg.qk_norm ? w.qn : w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T));
if (cfg.gate) {
/* One gate a head, applied to that head's whole row of the attention output, before
* o_proj. View [rows, heads * dim] and [rows, heads] as one row a head. */
RAD_ISSUE_N(c, op_gp[i], T, brows(w.h, T), RAD_W(w_gate[i]), brows(w.gate, T));
RAD_ISSUE_N(c, op_sig, T, brows(w.gate, T), brows(w.gaten, T));
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, w.attn), RAD_BF16, T * g.n_head,
g.head_dim);
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, w.gaten), RAD_BF16, T * g.n_head, 1);
const RadOperand gated = RAD_P_T2(rad_buf_ptr(c, w.attng), RAD_BF16, T * g.n_head,
g.head_dim);
RAD_ISSUE_N(c, op_gate_heads, T * g.n_head, heads, gates, RAD_NONE, gated);
}
RAD_ISSUE_N(c, op_op[i], T, brows(cfg.gate ? w.attng : w.attn, T), RAD_W(w_o[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h, T), RAD_W(w_gu[i]), brows(w.gate_up, T));
RAD_ISSUE_N(c, op_act, T, bcol(w.gate_up, 0, g.n_ff, T),
bcol(w.gate_up, g.n_ff, g.n_ff, T), brows(w.ff, T));
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ff, T), RAD_W(w_dn[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
}
RAD_ISSUE_N(c, op_outnorm, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
/* The predicting rows, named by the scheduler through `out_ids`. */
const int64_t S = batch->n_out;
if (S <= 0) return;
RAD_ISSUE_N(c, op_dlogits, S, brows(w.h, S), RAD_W(w_head), brows(w.dlog, S));
RAD_ISSUE_N(c, op_markov, batch->n_seq, brows(w.dlog, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
brows(w.best_score, batch->n_seq), brows(w.best_token, batch->n_seq),
brows(w.tokens, batch->n_seq));
}
/* ================================================================== the trunk's side of it
*
* The taps, and one call a target plugin makes to put a drafter on. Both live here because both
* are the drafter's contract with the trunk: which residual streams it reads, where its blocks
* live, and how deep a proposal it makes. */
/* The residual streams a drafter reads, captured as the trunk passes them. */
struct DsparkTaps {
enum { MAX_TAPS = DsparkBF16::MAX_LAYERS };
int n = 0;
int layer[MAX_TAPS] = {}; /* the trunk layer whose OUTPUT is tapped */
rad_buf src = 0; /* [rows, n * n_embd] f32, one column slice a tap */
rad_op op = 0; /* the residual stream, copied into that slice */
/* Read `draft.target_layer_ids`, which names the layers whose output is tapped. Zero taps when
* the container carries no drafter, or one that reads no trunk stream. Out-of-range ids are
* dropped, not clamped: a drafter naming a layer this model lacks belongs to another target. */
int read(const RadModelMeta* meta, int64_t n_layer) {
n = 0;
const char* ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.gguf_target_layers", nullptr);
n = parse_layer_ids(ids, n_layer, layer, MAX_TAPS);
return n;
}
/* The copy that saves a tap. A drafter reads the trunk's own residual stream, which is f32
* here and stays f32: the widening the fp8 graphs do is theirs, not this one's. */
int declare(RadBuilder* b, Names& nm, const Geom& g, int64_t rows, rad_buf residual) {
if (n <= 0) return RAD_OK;
src = decl_b(b, nm.f("draft_src"), RAD_F32, {rows, (int64_t)n * g.n_embd});
if (!src) return DS_REFUSED("src");
/* Declared over the trunk's own residual buffer: the op's operand pair is the stream and a
* tap's slice, and every issue site passes the slice it is writing. */
op = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_STR("from", "f32"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{residual}, {src});
return op ? RAD_OK : RAD_E_INVAL;
}
/* The tap that follows trunk layer `l`, if any. Issued on prefill and decode alike: the
* drafter conditions on every committed token's residual stream. */
void step(RadCtx* c, rad_buf residual, int64_t rows, int64_t l, int64_t n_embd) const {
if (!op) return;
for (int t = 0; t < n; ++t)
if (layer[t] == l)
RAD_ISSUE(c, op, brows(residual, rows),
bcol(src, (int64_t)t * n_embd, n_embd, rows));
}
};
/* Put a DSpark drafter on a trunk: its config from the container's `draft.` keys, its own KV
* group, its graph, and the drafter declaration the core drives. `base_layer` is the absolute
* layer its first block takes, one past the trunk's last.
*
* Nothing is defaulted quietly. A `draft.` key that describes a drafter this file does not
* implement is refused by name, because a silently ignored gate, window or block length only moves
* acceptance -- the one number a user cannot see in the output.
*
* The plugin calls it last, after its own head and logits: a drafter's passes run after the whole
* trunk, and the buffer planner lays an op's lifetimes out in declaration order, so declaring it
* earlier would let a trunk temporary land on the stream the drafter is still reading. */
inline int declare_dspark(DsparkBF16* ds, DsparkBF16::Wire* w, rad_kvgroup* kv, RadBuilder* b,
Names& nm, const RadModelMeta* meta, const RadBuildCtx* ctx,
const Geom& target, const DsparkTaps& taps, int base_layer,
rad_weight tok_embd, const char* ck_head) {
Geom dg{};
RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DSpark"));
/* The width the drafter concatenates and projects is the trunk's, and `drafter_geom` keeps the
* target's -- so a draft that disagrees is a draft for another model, and its `fc` would be
* read at a shape it was not trained at. */
const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size",
rad_meta_geti(meta, "draft.dflash_config.hidden_size",
dg.n_embd));
if (want_embd != dg.n_embd) {
fprintf(stderr, "radiance: the drafter reads a %lld-wide trunk and this target is %lld "
"wide; they are not the same model\n", (long long)want_embd,
(long long)dg.n_embd);
return RAD_E_UNSUPPORTED;
}
DsparkBF16::Config c{};
c.n_taps = taps.n;
c.rank = rad_meta_geti(meta, "draft.markov_rank", 0);
c.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
c.tap_norm = rad_meta_geti(meta, "draft.fc_norm", 0) ? 1 : 0;
c.qk_norm = rad_meta_geti(meta, "draft.qk_norm", 0) ? 1 : 0;
c.gate = rad_meta_geti(meta, "draft.headwise_attn_output_gate", 0) ? 1 : 0;
const char* act = rad_meta_gets(meta, "draft.hidden_act", "silu");
c.act = (!std::strcmp(act, "gelu") || !std::strcmp(act, "none")) ? "gelu"
: (!std::strcmp(act, "silu")) ? "silu" : nullptr;
if (!c.act) {
fprintf(stderr, "radiance: the drafter's feed-forward is '%s'; this block runs exact-erf "
"gelu (what the Spark drafts train with) or silu, and the two are not the "
"same function\n", act);
return RAD_E_UNSUPPORTED;
}
const char* gate_mode = rad_meta_gets(meta, "draft.gate_attn_act_mode", "sigmoid");
if (c.gate && std::strcmp(gate_mode, "sigmoid")) {
fprintf(stderr, "radiance: the drafter gates its attention output with '%s'; this block "
"applies a sigmoid\n", gate_mode);
return RAD_E_UNSUPPORTED;
}
/* Every row predicts, the anchor included. Without it a block row's worth of proposals is
* missing and the head reads rows the drafter never filled. */
if (!rad_meta_geti(meta, "draft.sample_from_anchor", 1)) {
fprintf(stderr, "radiance: the drafter declares sample_from_anchor false, whose bonus "
"anchor slot this block has no rows for\n");
return RAD_E_UNSUPPORTED;
}
/* The reference applies the bigram bias to the full vocabulary before each greedy choice. */
if (c.rank <= 0 || c.rank % 32 || c.rank > 512) {
fprintf(stderr, "radiance: the drafter's Markov head has rank %lld; the walk that applies "
"the bigram bias takes a multiple of 32 up to 512\n", (long long)c.rank);
return RAD_E_UNSUPPORTED;
}
/* The block is both the number of noise rows and the number of drafts: every row, the anchor
* included, predicts the token after it, so the depth is `block_size` rather than the
* `block_size - 1` a DFlash2 container's is. A block-diffusion drafter is trained for one
* block length and has no partial block, so any other depth is refused. */
const int64_t trained = rad_meta_geti(meta, "draft.block_size", 0);
if (trained < 2) {
fprintf(stderr, "radiance: this drafter declares no draft.block_size; the number of masked "
"positions it denoises is not a number this engine may choose.\n");
return RAD_E_FORMAT;
}
if ((long long)ctx->max_spec != trained) {
fprintf(stderr, "radiance: the drafter was trained at block_size %lld, which is %lld draft "
"tokens, and this serve asks for %d. A block-diffusion drafter denoises a "
"fixed number of mask positions; run it at %lld.\n",
(long long)trained, (long long)trained, ctx->max_spec, (long long)trained);
return RAD_E_UNSUPPORTED;
}
c.block = trained;
/* The reference gives every row of the block the anchor's history. `window` is the configured
* number of preceding positions; llama.cpp sets n_swa to window + 1 and masks when
* anchor - key >= n_swa. Keep that exact width in attention, the KV group and scheduler. */
int64_t window = 0;
if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
window = rad_meta_geti(meta, "draft.sliding_window", 0);
if (window < 0 || (window && window < c.block)) {
fprintf(stderr, "radiance: the drafter's %lld-token window does not cover the %lld-token "
"block it denoises\n", (long long)window, (long long)c.block);
return RAD_E_UNSUPPORTED;
}
if (window > 0 && window == INT64_MAX) return RAD_E_INVAL;
c.window = window > 0 ? window + 1 : 0; /* llama.cpp dflash: n_swa += 1 */
const double prf = rad_meta_getf(meta, "draft.partial_rotary_factor",
rad_meta_getf(meta,
"draft.rope_parameters.partial_rotary_factor", 1.0));
const double rot = (double)dg.head_dim * prf;
if (!(prf > 0.0) && prf != 0.0) {
fprintf(stderr, "radiance: the drafter's partial_rotary_factor is %g\n", prf);
return RAD_E_INVAL;
}
if (std::floor(rot) != rot || (int64_t)rot % 2 || rot > (double)dg.head_dim) {
fprintf(stderr, "radiance: the drafter rotates %g of %lld head dimensions\n", rot,
(long long)dg.head_dim);
return RAD_E_INVAL;
}
c.rot = (int64_t)rot ? (int64_t)rot : dg.head_dim;
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, c.window, base_layer, kv));
/* Activations: one row per committed token for the context pass, one row per block position
* for the query pass. Both are small; the drafter's cost is its weights. */
const int64_t qd = dg.n_head * dg.head_dim, kvd = dg.n_head_kv * dg.head_dim;
int64_t qr = dg.max_seqs * c.block;
if (qr > dg.max_tok) qr = dg.max_tok;
const int64_t sr = dg.max_seqs * c.steps();
DsparkBF16::Wire& dw = *w;
dw.src = taps.src;
dw.srcn = decl_b(b, nm.f("ds_srcn"), RAD_BF16, {dg.max_tok, c.n_taps * dg.n_embd});
dw.c = decl_b(b, nm.f("ds_c"), RAD_BF16, {dg.max_tok, dg.n_embd});
dw.cn = decl_b(b, nm.f("ds_cn"), RAD_BF16, {dg.max_tok, dg.n_embd});
dw.ck = decl_b(b, nm.f("ds_ck"), RAD_BF16, {dg.max_tok, kvd});
dw.cv = decl_b(b, nm.f("ds_cv"), RAD_BF16, {dg.max_tok, kvd});
if (c.qk_norm) dw.ckn = decl_b(b, nm.f("ds_ckn"), RAD_BF16, {dg.max_tok, kvd});
dw.x = decl_b(b, nm.f("ds_x"), RAD_F32, {qr, dg.n_embd});
dw.delta = decl_b(b, nm.f("ds_delta"), RAD_F32, {qr, dg.n_embd});
dw.h = decl_b(b, nm.f("ds_h"), RAD_BF16, {qr, dg.n_embd});
dw.q = decl_b(b, nm.f("ds_q"), RAD_BF16, {qr, qd});
dw.k = decl_b(b, nm.f("ds_k"), RAD_BF16, {qr, kvd});
dw.v = decl_b(b, nm.f("ds_v"), RAD_BF16, {qr, kvd});
if (c.qk_norm) {
dw.qn = decl_b(b, nm.f("ds_qn"), RAD_BF16, {qr, qd});
dw.kn = decl_b(b, nm.f("ds_kn"), RAD_BF16, {qr, kvd});
}
dw.gate = decl_b(b, nm.f("ds_gate"), RAD_BF16, {qr, dg.n_head});
dw.attn = decl_b(b, nm.f("ds_attn"), RAD_BF16, {qr, qd});
if (c.gate) {
dw.gaten = decl_b(b, nm.f("ds_gaten"), RAD_BF16, {qr, dg.n_head});
dw.attng = decl_b(b, nm.f("ds_attng"), RAD_BF16, {qr, qd});
}
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), RAD_BF16, {qr, 2 * dg.n_ff});
dw.ff = decl_b(b, nm.f("ds_ff"), RAD_BF16, {qr, dg.n_ff});
dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab});
const int64_t n_markov_tiles = (dg.n_vocab_all + 63) / 64;
dw.best_score = decl_b(b, nm.f("ds_markov_score"), RAD_F32,
{dg.max_seqs, n_markov_tiles});
dw.best_token = decl_b(b, nm.f("ds_markov_token"), RAD_I32,
{dg.max_seqs, n_markov_tiles});
/* The proposal buffer (RadDrafterDecl::proposal): a block pass proposes through the drafter's
* own walk, never through the sampler's token buffer. */
dw.tokens = decl_b(b, nm.f("ds_tokens"), RAD_I32, {dg.max_seqs, c.steps()});
if (!dw.srcn || !dw.c || !dw.cn || !dw.ck || !dw.cv ||
(c.qk_norm && (!dw.ckn || !dw.qn || !dw.kn)) ||
(c.gate && (!dw.gaten || !dw.attng)) || !dw.x || !dw.delta || !dw.h || !dw.q || !dw.k ||
!dw.v || !dw.gate || !dw.attn || !dw.gate_up || !dw.ff || !dw.dlog ||
!dw.best_score || !dw.best_token || !dw.tokens)
return RAD_E_INVAL;
RAD_ARCH_TRY(ds->declare(b, nm, dg, c, base_layer, *kv, tok_embd, "draft", ck_head, dw));
RadDrafterDecl drf{};
drf.name = "dspark";
drf.kind = RAD_DRAFT_BLOCK;
drf.depth = ctx->max_spec;
drf.block = c.block;
drf.proposal = dw.tokens;
drf.proposal_pitch = c.steps();
drf.window = c.window;
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.mask_token_id", -1);
if (drf.mask_token < 0)
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1);
if (drf.mask_token < 0) {
fprintf(stderr, "radiance: this drafter declares no mask_token_id, which every unfilled "
"block position embeds\n");
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
rad_note(b, "DSpark drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
"ffn %lld, %s attention with a %lld-token anchor-aligned window (%lld configured "
"history + 1), %lld of %lld rotary dimensions, %s, %s a head, %d trunk tap(s); one "
"forward over %lld noise row(s), the anchor included, proposes %lld tokens",
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
(long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
(long long)dg.n_ff, c.causal ? "causal" : "non-causal", (long long)c.window,
(long long)window, (long long)c.rot, (long long)dg.head_dim, c.act,
c.gate ? "sigmoid gate" : "no gate", (int)c.n_taps, (long long)c.block,
(long long)c.steps());
rad_note(b, "the rank-%lld Markov bigram head greedily scans all %lld vocabulary tokens at "
"each draft position; confidence is not applied to logits%s",
(long long)c.rank, (long long)dg.n_vocab_all,
rad_meta_geti(meta, "draft.has_confidence_head", 0)
? " (its reference role is adaptive depth, which this fixed-depth graph does not use)"
: "");
return RAD_OK;
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_DSPARK_BF16_H */
+9 -5
View File
@@ -336,12 +336,14 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)),
{w.q, w.k, w.v, w.ab, w.in.x}, {w.o.x});
/* The epilogue's codes for an fp8 or int8 out-projection (int8 when ActFP8::q8_fed; the codes
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent. */
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent.
* Rotated int8 codes (ActFP8::q8_rot) only the conv fold writes (gdn_conv_recurrent_update_had);
* rows this update serves are quantised by q_o. */
if (g.plain_norm) {
RAD_ARCH_TRY(out.probe(b, nm, g, nm.f("blk.%d.ssm_out", l), { s.out }));
o_plain = out.codes_free && out.reads_x;
}
if (op_recur && w.o.cq() && !o_plain) {
if (op_recur && w.o.cq() && !o_plain && !w.o.q8_rot) {
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
}
@@ -349,7 +351,7 @@ 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, "gdn_conv_recurrent_update",
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),
@@ -530,8 +532,10 @@ 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);
w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cs(), DT) : RAD_NONE);
/* Rotated codes come only from the fold; here the decode rows take the quantiser. */
if (w.o.q8_rot && !o_plain) q_o.step(c, T, 0, DT);
}
/* The output a piece at a time where the caller takes the all-reduce that way (ArPieces): the
+263
View File
@@ -0,0 +1,263 @@
/* rad_block_gemma4_unified.h -- the media embedders of Gemma 4 12B ("unified", transformers'
* Gemma4UnifiedVisionEmbedder and the audio Gemma4UnifiedMultimodalEmbedder), served by gemma4_bf16.
* Neither has an encoder: the language model sees each patch or audio frame after a few norms and
* linears.
*
* image: a patch is 48 x 48 x 3 (3 x 3 of the processor's 16-pixel patches), staged by the core's
* Gemma 4 processor as u / 255 in bf16, (y, x, channel); a LayerNorm over the patch, a linear with
* a bias, a LayerNorm, plus a learned row for the patch's column and one for its row (the
* checkpoint's [npos, 2, width] table, read as its two taps of dimension 1), a LayerNorm, then the
* multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. The LayerNorms are
* nn.LayerNorm's default eps 1e-5, which no config states. One patch is one row.
* audio: a frame is 640 samples at 16 kHz as they are, the last zero-padded, in bf16; an RMS norm
* with no gain and a 640 -> n_embd linear. One frame is one row.
*
* Their rows replace the placeholders' embeddings unscaled, as the vision tower's do. Every rank
* runs them whole (RAD_SHARD_NONE). */
#ifndef RAD_BLOCK_GEMMA4_UNIFIED_H
#define RAD_BLOCK_GEMMA4_UNIFIED_H
#include "rad_arch.h"
#include <cstdio>
#include <cstring>
namespace rad {
namespace arch {
struct Gemma4UnifiedVision {
bool on = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = false;
int64_t P = 0, width = 0, patch_dim = 0, npos = 0, n_embd = 0;
rad_weight w_ln1 = 0, w_ln1b = 0, w_in = 0, w_inb = 0, w_ln2 = 0, w_ln2b = 0, w_px = 0, w_py = 0;
rad_weight w_pn = 0, w_pnb = 0, w_proj = 0;
rad_op op_ln1 = 0, op_in = 0, op_ln2 = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0;
rad_op op_pn = 0, op_norm = 0, op_out = 0;
rad_buf b_n = 0, b_x = 0, b_h = 0, b_px = 0, b_py = 0, b_out = 0;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "gemma4_unified_vision");
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, const char* who) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
width = rad_meta_geti(m, "vision_config.mm_embed_dim", 0);
npos = rad_meta_geti(m, "vision_config.mm_posemb_size", 0);
const int64_t side = rad_meta_geti(m, "vision_config.model_patch_size", 0);
const int64_t outd = rad_meta_geti(m, "vision_config.output_proj_dims", width);
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
if (width <= 0 || npos <= 0 || side <= 0 || outd != width) {
fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
"embedder this plugin serves (mm_embed_dim %lld, mm_posemb_size %lld, "
"model_patch_size %lld, output_proj_dims %lld)\n", who,
(long long)width, (long long)npos, (long long)side, (long long)outd);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
patch_dim = 3 * side * side;
P = ctx->max_enc_patches;
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
const char* V = "model.vision_embedder";
struct { const char* to; const char* from; } cp[] = {
{ "v.ln1.weight", "patch_ln1.weight" }, { "v.ln1.bias", "patch_ln1.bias" },
{ "v.in.weight", "patch_dense.weight" }, { "v.in.bias", "patch_dense.bias" },
{ "v.ln2.weight", "patch_ln2.weight" }, { "v.ln2.bias", "patch_ln2.bias" },
{ "v.pn.weight", "pos_norm.weight" }, { "v.pn.bias", "pos_norm.bias" } };
for (const auto& e : cp)
RAD_ARCH_TRY(map_copy(b, nm.f("%s", e.to), nm.ckpt("%s.%s", V, e.from)));
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_x.weight"), nm.ckpt("%s.pos_embedding", V), 1, 0));
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_y.weight"), nm.ckpt("%s.pos_embedding", V), 1, 1));
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight")));
w_ln1 = decl_w(b, nm.f("v.ln1.weight"), RAD_BF16, {patch_dim}, A, N, grp_model());
w_ln1b = decl_w(b, nm.f("v.ln1.bias"), RAD_BF16, {patch_dim}, A, N, grp_model());
w_in = decl_w(b, nm.f("v.in.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
w_inb = decl_w(b, nm.f("v.in.bias"), RAD_BF16, {width}, A, N, grp_model());
w_ln2 = decl_w(b, nm.f("v.ln2.weight"), RAD_BF16, {width}, A, N, grp_model());
w_ln2b = decl_w(b, nm.f("v.ln2.bias"), RAD_BF16, {width}, A, N, grp_model());
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_pn = decl_w(b, nm.f("v.pn.weight"), RAD_BF16, {width}, A, N, grp_model());
w_pnb = decl_w(b, nm.f("v.pn.bias"), RAD_BF16, {width}, A, N, grp_model());
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
b_n = decl_b(b, nm.f("v.n"), RAD_BF16, {P, patch_dim});
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_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {P, n_embd});
auto ln = [&](int64_t n, rad_weight w, rad_weight bias) {
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
auto lookup = [&](rad_weight w) {
return RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
RAD_WEIGHTS(w));
};
auto add = [&]() {
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
op_ln1 = rw(b, ln(patch_dim, w_ln1, w_ln1b), {}, {b_n});
op_in = rw(b, RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16"),
RAD_STR("act", "none")),
RAD_WEIGHTS(w_in, w_inb)),
{b_n}, {b_x});
op_ln2 = rw(b, ln(width, w_ln2, w_ln2b), {b_x}, {b_h});
op_px = rw(b, lookup(w_px), {}, {b_px});
op_py = rw(b, lookup(w_py), {}, {b_py});
op_padd = rw(b, add(), {b_px, b_py}, {b_px});
op_add = rw(b, add(), {b_h, b_px}, {b_h});
op_pn = rw(b, ln(width, w_pn, w_pnb), {b_h}, {b_x});
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_x}, {b_h});
op_out = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
RAD_INT("K", width), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_proj)),
{b_h}, {b_out});
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = 1;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision embedder (no tower): %lldx%lld patches of %lld values -> %lld, "
"positions %lld a side; %lld patches a pass -> %lld rows of %lld",
(long long)side, (long long)side, (long long)patch_dim, (long long)width,
(long long)npos, (long long)P, (long long)P, (long long)n_embd);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch;
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
rad_step_fail(c, "an encoder pass this program's vision embedder cannot serve: none "
"declared, or more patches than it was declared for");
return;
}
const int32_t* crd = batch->enc_coord;
RAD_ISSUE_N(c, op_ln1, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim), RAD_W(w_ln1),
RAD_W(w_ln1b), brows(b_n, Pn));
RAD_ISSUE_N(c, op_in, Pn, brows(b_n, Pn), RAD_W(w_in), RAD_W(w_inb), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_ln2, Pn, brows(b_x, Pn), RAD_W(w_ln2), RAD_W(w_ln2b), brows(b_h, Pn));
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
RAD_ISSUE_N(c, op_add, Pn, brows(b_h, Pn), brows(b_px, Pn), brows(b_h, Pn));
RAD_ISSUE_N(c, op_pn, Pn, brows(b_h, Pn), RAD_W(w_pn), RAD_W(w_pnb), brows(b_x, Pn));
RAD_ISSUE_N(c, op_norm, Pn, brows(b_x, Pn), RAD_NONE, brows(b_h, Pn));
RAD_ISSUE_N(c, op_out, Pn, brows(b_h, Pn), RAD_W(w_proj), brows(b_out, Pn));
}
};
struct Gemma4UnifiedAudio {
bool on = false;
int64_t P = 0, frame = 0, n_embd = 0;
rad_weight w_proj = 0;
rad_op op_norm = 0, op_out = 0;
rad_buf b_n = 0, b_out = 0;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
return t && !std::strcmp(t, "gemma4_unified_audio");
}
/* Samples a frame: the extractor's audio_samples_per_token, else the embedder's input width. */
static int64_t frame_for(const RadModelMeta* m) {
return rad_meta_geti(m, "processor.feature_extractor.audio_samples_per_token",
rad_meta_geti(m, "audio_config.audio_embed_dim", 0));
}
/* The longest clip in frames: processor_config.json's audio_seq_length, else 30 s. */
static int64_t frames_for(const RadModelMeta* m) {
const int64_t f = frame_for(m);
const int64_t rate = rad_meta_geti(m, "processor.feature_extractor.sampling_rate", 16000);
if (f <= 0 || rate <= 0) return 0;
return rad_meta_geti(m, "processor.audio_seq_length", (30 * rate + f - 1) / f);
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, const char* who) {
on = false;
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
frame = frame_for(m);
const int64_t width = rad_meta_geti(m, "audio_config.audio_embed_dim", 0);
const double eps = rad_meta_getf(m, "audio_config.rms_norm_eps", 1e-6);
if (frame <= 0 || width != frame) {
fprintf(stderr, "radiance: %s: the container's audio frame (%lld samples) is not the "
"embedder's input (audio_embed_dim %lld)\n", who, (long long)frame,
(long long)width);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
P = ctx->max_audio_frames;
RAD_ARCH_TRY(map_copy(b, nm.f("a.embed.weight"), nm.ckpt("model.embed_audio.embedding_projection.weight")));
w_proj = decl_w(b, nm.f("a.embed.weight"), RAD_BF16, {n_embd, frame}, RAD_ACCESS_PER_REQUEST,
RAD_SHARD_NONE, grp_model());
b_n = decl_b(b, nm.f("a.n"), RAD_BF16, {P, frame});
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {P, n_embd});
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", frame),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{}, {b_n});
op_out = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
RAD_INT("K", frame), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_proj)),
{b_n}, {b_out});
RadEncoderDecl e{};
e.name = "audio";
e.modalities = RAD_MM_AUDIO;
e.patch_dim = frame;
e.merge = 1;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "audio embedder (no encoder): frames of %lld samples -> %lld; %lld frames a pass",
(long long)frame, (long long)n_embd, (long long)P);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch;
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
rad_step_fail(c, "an audio pass this program's audio embedder cannot serve: none "
"declared, or more frames than it was declared for");
return;
}
RAD_ISSUE_N(c, op_norm, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, frame), RAD_NONE,
brows(b_n, Pn));
RAD_ISSUE_N(c, op_out, Pn, brows(b_n, Pn), RAD_W(w_proj), brows(b_out, Pn));
}
};
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_GEMMA4_UNIFIED_H */
+4
View File
@@ -56,6 +56,9 @@ struct Gemma4Vision {
rad_op op_c[C_N] = {};
};
bool on = false, standardize = false, clip = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = false;
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
int64_t npos = 0, n_embd = 0;
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
@@ -321,6 +324,7 @@ struct Gemma4Vision {
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
+65 -16
View File
@@ -27,6 +27,9 @@ struct DsaCache {
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
rad_buf score = 0, selected = 0, nsel = 0, length = 0;
/* A taking-all step's zero scores, [max_tok, topk + 1]: such a step does not split, and
* the score plane holds only a run of rows when the step may. */
rad_buf unscored = 0;
/* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */
rad_buf cu_part = 0, sel_part = 0, len_part = 0;
};
@@ -44,6 +47,7 @@ struct DsaCache {
rad_kvgroup index = 0, tail = 0, attention = 0;
rad_weight ape = 0;
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
rad_op op_unscored = 0, op_select_all = 0;
rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
@@ -112,6 +116,15 @@ struct DsaCache {
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.kg }, {});
/* A step whose every row reaches topk or fewer blocks selects them all (takes_all), and
* qsa_select takes any finite scores in block order then: zeros serve as well as the
* scorer's. The fill spans topk + 1 columns, at least the live reach of such a step. */
op_unscored = rw(b,
RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("n", unscored_cols()), RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{}, { w.unscored });
op_score = rw(b,
RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
@@ -139,6 +152,14 @@ struct DsaCache {
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc }, { w.selected, w.nsel, w.length });
op_select_all = rw(b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("blocks", unscored_cols()),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.unscored, w.nc }, { w.selected, w.nsel, w.length });
if (split) {
op_select_part = rw(
b,
@@ -165,8 +186,12 @@ struct DsaCache {
if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len)
return RAD_E_INVAL;
}
return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL;
return op_query && op_work && op_tail && op_unscored && op_score && op_select &&
op_select_all
? RAD_OK
: RAD_E_INVAL;
}
int64_t unscored_cols() const { return c.topk + 1 < c.blocks ? c.topk + 1 : c.blocks; }
/* The columns a step scores: the live reach the batch bounds on the host. */
int64_t live_blocks(const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index);
@@ -179,13 +204,19 @@ struct DsaCache {
}
/* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by
* the core), so every rank takes the same path and a recorded decode pass changes it only when
* that bound moves. */
* that bound moves. A step that takes all its blocks never splits: with nothing to score, every
* rank selects the whole step itself, and the gathers have nothing to save. */
bool splits(const RadBatch* batch) const {
const int64_t T = batch->n_tok;
return op_score_part && (GlmTp::splits(T, g.world) ||
(T >= GlmTp::kSplitWorkRows &&
T * live_blocks(batch) >= GlmTp::kSplitWork));
return op_score_part && live_blocks(batch) > c.topk &&
(GlmTp::splits(T, g.world) ||
(T >= GlmTp::kSplitWorkRows && T * live_blocks(batch) >= GlmTp::kSplitWork));
}
/* Every row's history fits the selection, so the query side (projection, head gates,
* quantiser, scorer) has nothing to decide: the selected table is every live block in order,
* bit for bit what scoring would select. Read from the same host bound as splits(), so every
* rank agrees. */
bool takes_all(const RadBatch* batch) const { return live_blocks(batch) <= c.topk; }
/* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of).
* A rank whose run lies wholly past a small step runs the step's first R rows instead: no
* sequence holds its run, so its scores are -inf, and its answers land past T. The caller's
@@ -210,11 +241,13 @@ struct DsaCache {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t work = (T + 3) / 4 + S,
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
const bool all = takes_all(batch);
int64_t q0 = 0, qn = T;
query_rows(batch, &q0, &qn);
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
brow_slice(w.codes, q0 * 32, qn * 32, 128),
brow_slice(w.scales, q0 * 32, qn * 32, 1));
if (!all)
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
brow_slice(w.codes, q0 * 32, qn * 32, 128),
brow_slice(w.scales, q0 * 32, qn * 32, 1));
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch),
@@ -232,6 +265,16 @@ struct DsaCache {
step_split(ctx, batch, live);
return;
}
if (all) {
const int64_t U = unscored_cols();
RAD_ISSUE_N(ctx, op_unscored, T, brows(w.unscored, T));
RAD_ISSUE_N(ctx, op_select_all, T, bcol_at(w.unscored, 0, U, 0, live, T),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch),
brows(w.nc, S), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.selected, T),
brows(w.nsel, T), brows(w.length, T));
return;
}
// dsa_score declares ten operands, cu_part the optional tenth; the engine counts them.
RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32),
brows(w.gate, T), kv_cache(index, layer), RAD_NONE,
@@ -348,23 +391,29 @@ struct GlmIndexer {
};
int64_t r0 = 0, rows = T;
cache.query_rows(batch, &r0, &rows);
/* The key side runs on every step, since the index cache must stay current; the query
* side only where the selection is a choice (DsaCache::takes_all). */
const bool all = cache.takes_all(batch);
/* Every output row of these ops is independent of the others and of how many there are,
* except the bf16 projection's at 64 rows and under, a band whose split count a tuned
* configuration may set: it stays on the step's rows unless every run is wider. */
const bool runs = cache.splits(batch);
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
else
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
if (!all) {
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
else
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
}
key_gate.step(ctx, act(w.input), w.kg_raw, T);
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
bcol(w.cache.kg, 0, 128, T));
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
bcol(w.cache.kg, 128, 128, T));
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096), RAD_W(head_weight),
brow_slice(w.cache.gate, r0, rows, 32));
if (!all)
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096),
RAD_W(head_weight), brow_slice(w.cache.gate, r0, rows, 32));
cache.step(ctx, batch);
}
};
+30 -22
View File
@@ -19,6 +19,7 @@
#include "rad_glm_tp.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
namespace rad {
@@ -27,6 +28,25 @@ struct MlaLatent {
struct Config {
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
};
/* The attention over the latent cache, `rows` rows of `heads` heads. The cache is Geom::kv_dtype
* (bf16, or fp8_e4m3 under --kv-cache-dtype fp8); `kv_dtype` is stated only for a cache that is
* not bf16, so a bf16 build declares the op it always did. */
static rad_op attn_op(RadBuilder* b, const Geom& g, int64_t rows, int64_t heads,
int64_t blocks, double scale) {
if (g.kv_dtype && std::strcmp(g.kv_dtype, "bf16"))
return RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
RAD_INT("block_size", 4), RAD_F64("scale", scale),
RAD_STR("dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS);
return RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
RAD_INT("block_size", 4), RAD_F64("scale", scale),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
}
struct Wire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
/* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`.
@@ -68,16 +88,10 @@ struct MlaLatent {
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.q }, { w.q_latent });
op_attn =
rw(b,
RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim),
RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks),
RAD_INT("block_size", 4),
RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
op_attn = rw(b,
attn_op(b, g, g.max_tok, c.heads, c.blocks,
1.0 / std::sqrt((double)c.head_dim)),
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL;
op_expand = rw(
b,
@@ -172,12 +186,13 @@ struct GlmMla {
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world),
1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
w.q_low, w.core.q));
// Cache stores contiguous halves of the normalized latent, with no duplicated K/V.
/* Cache stores contiguous halves of the normalized latent, with no duplicated K/V. An E4M3
* cache (Geom::kv_dtype) stores at kv_store's default descale of 1, which mla_attn reads. */
op_store = rw(b,
RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4),
RAD_STR("kv_dtype", "bf16")),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{ w.latent }, {});
if (!op_store) return RAD_E_INVAL;
@@ -200,7 +215,7 @@ struct GlmMla {
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("head_dim", 256), RAD_INT("n_head_kv", 1),
RAD_INT("block_size", 4),
RAD_STR("kv_dtype", "bf16")),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{ w.latent }, {});
/* Issued in finish, after this layer's indexer selects and before the attention reads
@@ -239,15 +254,8 @@ struct GlmMla {
{ in }, { out });
};
op_rows_absorb = project("absorb", r.q, r.q_latent);
op_rows_attn =
rw(b,
RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512),
RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks),
RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
op_rows_attn = rw(b, MlaLatent::attn_op(b, g, R, 64, core.c.blocks, 1.0 / std::sqrt(256.0)),
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
op_rows_expand = project("expand", r.attn_latent, r.attn.x);
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
+34 -25
View File
@@ -16,7 +16,11 @@
* before the layer's attention, `join` (the residual add and the proposal rows' selection) between
* its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's.
* Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass.
*
* The same head serves another DeepSeek-style drafter by its checkpoint layout, set before
* declare_inputs: the residual width, the layer's checkpoint prefix and index, and the name of the
* head's final norm (Ling-3.0: 2560, `model.layers.42`, 42, `final_layernorm.weight`). */
#ifndef RAD_BLOCK_GLM_MTP_H
#define RAD_BLOCK_GLM_MTP_H
#include "rad_glm_tp.h"
@@ -31,6 +35,10 @@ struct GlmMtp {
rad_weight token = 0, head = 0;
};
static constexpr int kDepth = 3; /* --num-speculative-tokens auto */
int64_t width = 4096;
const char* prefix = "model.language_model.layers.45";
int layer = 45;
const char* norm_src = "shared_head.norm.weight";
Names nm{ "mtp" };
Geom g{};
Wire w{};
@@ -50,47 +58,48 @@ struct GlmMtp {
w = wire;
if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1)
return RAD_E_INVAL;
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 });
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST);
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 });
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 });
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 });
const char* pre = "model.language_model.layers.45";
const int64_t E = width;
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, E });
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, E }, RAD_BUF_PERSIST);
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, E });
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 2 * E });
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, E });
const char* pre = prefix;
auto gain = [&](const char* n, const char* src) {
const char* name = nm.f("%s", n);
if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(45));
return decl_w(b, name, RAD_F32, { E }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(layer));
};
en = gain("enorm.weight", "enorm.weight");
hn = gain("hnorm.weight", "hnorm.weight");
norm = gain("output_norm.weight", "shared_head.norm.weight");
norm = gain("output_norm.weight", norm_src);
RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre)));
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(45));
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { E, 2 * E }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh)
return RAD_E_INVAL;
op_prev = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", E),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.final_hidden }, { hidden });
op_embed = rw(b,
RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w.token)),
{}, { embedding });
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, 4096, embedding));
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, E, embedding));
op_embed_ar = GlmTp::reduce(b, g, embedding, true);
op_en = rmsnorm(b, en, embedding, concat);
op_hn = rmsnorm(b, hn, hidden, concat);
op_eh = rw(b,
RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096),
RAD_INT("K", 8192), RAD_STR("dtype", "bf16")),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", E),
RAD_INT("K", 2 * E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(eh)),
{ concat }, { x });
return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar)
@@ -102,14 +111,14 @@ struct GlmMtp {
int declare_join(RadBuilder* b, rad_buf y) {
op_residual = rw(b,
RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x, y }, { x });
// All history rows fill the draft cache; only proposal rows need its FFN.
op_select = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x }, { hidden });
@@ -124,7 +133,7 @@ struct GlmMtp {
op_head = rw(b,
RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", 4096),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", width),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w.head)),
{ hidden }, { w.logits });
@@ -150,9 +159,9 @@ struct GlmMtp {
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token),
brows(embedding, T));
mrows.step(c, batch, embedding, T);
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE);
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T));
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T));
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * width, brows(embedding, T), RAD_NONE);
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, width, T));
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, width, width, T));
RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T));
}
void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const {
@@ -175,7 +184,7 @@ private:
rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain)),
{ in }, { out });
@@ -183,7 +192,7 @@ private:
rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ in }, { out });
+25 -12
View File
@@ -1,5 +1,6 @@
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. With `groups`
* above 1 the selection is group-limited (router_sigmoid_group_topk, Ling-3.0's 8 groups, 4 kept). */
#ifndef RAD_BLOCK_GLM_ROUTER_H
#define RAD_BLOCK_GLM_ROUTER_H
#include "rad_glm_tp.h"
@@ -9,7 +10,7 @@ namespace rad {
namespace arch {
struct GlmRouter {
struct Config {
int64_t experts = 288, top_k = 8, rows = 32;
int64_t experts = 288, top_k = 8, rows = 32, groups = 1, topk_groups = 1;
int norm = 1;
double route_scale = 2.5;
};
@@ -33,8 +34,9 @@ struct GlmRouter {
w = wire;
if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 ||
c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 ||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 || !w.input ||
!w.logits || !w.ids || !w.weights || w.logits == w.weights)
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 ||
c.groups < 1 || c.experts % c.groups || c.topk_groups < 1 || c.topk_groups > c.groups ||
!w.input || !w.logits || !w.ids || !w.weights || w.logits == w.weights)
return RAD_E_INVAL;
const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name);
RAD_ARCH_TRY(map_copy(b, pn, src.weight));
@@ -52,14 +54,25 @@ struct GlmRouter {
{ w.input }, { w.logits });
RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input,
w.logits));
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
if (c.groups > 1)
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_group_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("n_group", c.groups),
RAD_INT("topk_group", c.topk_groups), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
else
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
return op_project && op_select ? RAD_OK : RAD_E_INVAL;
}
void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
+395
View File
@@ -0,0 +1,395 @@
/* rad_block_lilicorr.h -- LiLiCorr's head: the candidate correlator after a DFlash2 backbone.
*
* NVIDIA's drafter for Nemotron-3.5-Bolt (vLLM's model_executor/models/lilicorr.py). The backbone is
* rad_block_dflash2.h's, with attention sinks (Dflash2::Config::lili). Its final hidden states at
* the block's draft rows go here instead of to DFlash2's selector:
*
* candidates each draft position's top-k from the target's own lm_head (log-softmax values,
* vocab-parallel: each rank's shard, all-gathered, merged)
* lattice steps x k rows a sequence, row s * k + j:
* token_proj(embed(cand)) + pass_hidden_proj(h_s)
* + feature_mlp(layernorm(five rank features)) + slot[s] + rank[j]
* 2 layers rmsnorm, attention over the lattice with a learned slot bias (lili_attn), the
* in/out projections; rmsnorm, silu MLP with biases; residuals
* factor x = output_norm(lattice), a = anchor_norm(context_proj(the anchor's context row))
* f = silu(W [x | a | x * a] + b), [out | in] = edge heads of f
* walk normalised dot products, start from the anchor's own outgoing head, greedy
* (lili_walk)
*
* The anchor's context row is hidden_norm(fc(taps)) at the last committed position, which the
* context pass left in Dflash2's `c` (RadBatch::anchor_rows names the row). The head reads the
* target's embedding and lm_head, and its own 25 linears are bf16: ModelOpt ships them NVFP4,
* which no kernel serves, and the recipe decodes them (`cast dtype=bf16`).
*
* Every rank computes the whole lattice (vLLM: "candidate IDs and embeddings are replicated across
* TP ranks"); only the head's logits and the embedding lookup are per rank, with the merge in
* lili_cand and an exact all-reduce after the lookup.
*/
#ifndef RAD_BLOCK_LILICORR_H
#define RAD_BLOCK_LILICORR_H
#include "rad_arch.h"
namespace rad {
namespace arch {
struct LiliCorr {
enum { MAX_LAYERS = 4 };
struct Config {
int64_t steps = 0; /* draft positions a sequence: the block less the anchor */
int64_t k = 8; /* candidates a position (lilicorr_candidate_topk) */
int64_t hs = 1024; /* the lattice's width (lilicorr_hidden_size) */
int64_t n_head = 8;
int64_t mlp = 2048; /* hs * lilicorr_mlp_ratio */
int64_t fdim = 1024; /* lilicorr_factor_dim */
int64_t n_layer = 2;
double eps = 1e-6; /* rms_norm_eps, the lattice's RMS norms */
double vec_eps = 1e-4; /* lilicorr_vector_eps, F.normalize's floor */
double scale = 8.0; /* lilicorr_logit_scale */
};
/* row_k: the pairs a rank's logprob row carries, k rounded up so 2 + 2 row_k floats are whole
* 16-byte words (the all-gather's unit): 9 for k = 8. */
static int64_t row_k(int64_t k) { return (k % 2) ? k : k + 1; }
struct Wire {
/* Dflash2's */
rad_buf sel_h = 0; /* [srows, n_embd] the drafter's final hidden states, draft rows */
rad_buf c = 0; /* [max_tok, n_embd] hidden_norm(fc(taps)), the context pass's rows */
rad_buf tokens = 0; /* [max_seqs, steps] i32, the proposal */
/* the head's own */
rad_buf logits = 0; /* [srows, n_vocab] f32, this rank's shard */
rad_buf stats = 0; /* [srows, 2 + 2 row_k] f32 */
rad_buf sgath = 0; /* [srows, world * (2 + 2 row_k)] f32, world > 1 */
rad_buf pas = 0; /* [srows, hs] */
rad_buf cand = 0; /* [srows * k] i32 */
rad_buf feat = 0; /* [lrows, hs] */
rad_buf hh = 0; /* [lrows, hs] the lattice's residual stream; starts as lili_cand's base */
rad_buf emb = 0; /* [lrows, n_embd] the candidates' embeddings */
rad_buf y = 0; /* [lrows, hs] */
rad_buf qkv = 0; /* [lrows, 3 hs] */
rad_buf att = 0; /* [lrows, hs] */
rad_buf up = 0; /* [lrows, mlp] */
rad_buf ups = 0; /* [lrows, mlp] */
rad_buf cat = 0; /* [lrows, 3 hs] */
rad_buf fh = 0; /* [lrows, hs] */
rad_buf fhs = 0; /* [lrows, hs] */
rad_buf edges = 0; /* [lrows, 2 fdim] */
rad_buf anc = 0; /* [max_seqs, n_embd] */
rad_buf ast = 0; /* [max_seqs, hs] */
rad_buf an = 0; /* [max_seqs, hs] */
rad_buf aout = 0; /* [max_seqs, fdim] */
};
Geom g{};
Config cfg{};
Wire w{};
int64_t srows = 0, lrows = 0, rk = 0;
rad_weight w_lm = 0, w_tok = 0; /* the target's */
rad_weight w_tokp = 0, b_tokp = 0, w_pass = 0, b_pass = 0, w_ctx = 0, b_ctx = 0;
rad_weight w_fdn = 0, b_fdn = 0, ln_w = 0, ln_b = 0, up_w = 0, up_b = 0, w_slot = 0, w_rank = 0;
rad_weight w_anorm[MAX_LAYERS] = {}, w_in[MAX_LAYERS] = {}, b_in[MAX_LAYERS] = {};
rad_weight w_out[MAX_LAYERS] = {}, b_out[MAX_LAYERS] = {}, w_mnorm[MAX_LAYERS] = {};
rad_weight w_up[MAX_LAYERS] = {}, b_up[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
rad_weight b_dn[MAX_LAYERS] = {};
rad_weight w_rel = 0, w_same = 0, w_onorm = 0, w_annorm = 0;
rad_weight w_fac = 0, b_fac = 0, w_edge = 0, b_edge = 0, w_aout = 0, b_aout = 0;
rad_op op_logits = 0, op_stats = 0, op_sgath = 0, op_pas = 0, op_cand = 0;
rad_op op_emb = 0, op_emb_ar = 0, op_tokp = 0, op_fdn = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_in[MAX_LAYERS] = {}, op_attn = 0;
rad_op op_out[MAX_LAYERS] = {}, op_mnorm[MAX_LAYERS] = {}, op_up[MAX_LAYERS] = {};
rad_op op_dn[MAX_LAYERS] = {}, op_silu_up = 0;
rad_op op_onorm = 0, op_anc = 0, op_ctx = 0, op_annorm = 0, op_factor = 0, op_fac = 0;
rad_op op_silu_f = 0, op_edge = 0, op_aout = 0, op_walk = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, rad_weight lm_head,
rad_weight tok_embd, const char* ck, const Wire& wire);
/* After Dflash2::step, on the same query batch: `sel_h` holds the draft rows. */
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int LiliCorr::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
rad_weight lm_head, rad_weight tok_embd, const char* ck,
const Wire& wire) {
g = geom; cfg = c; w = wire; w_lm = lm_head; w_tok = tok_embd;
if (!w_lm || !w_tok || !ck || cfg.steps < 1 || cfg.k < 2 || cfg.n_layer < 1 ||
cfg.n_layer > MAX_LAYERS || cfg.hs % cfg.n_head)
return RAD_E_INVAL;
const int64_t K = cfg.k, S = cfg.steps, hs = cfg.hs, fd = cfg.fdim, E = g.n_embd;
srows = g.max_seqs * S;
lrows = srows * K;
rk = row_k(K);
const int ACC = RAD_ACCESS_PER_TOKEN;
const RadWeightGroup grp = grp_model();
/* The head's weights, all replicated. Linears and tables bf16, biases, norms and the
* feature layer f32. */
auto wt = [&](const char* dn, const char* src, uint32_t dt,
std::initializer_list<int64_t> shp) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, grp);
};
const char* L = nm.ckpt("%s.lilicorr", ck);
auto src = [&](const char* tail) { return nm.ckpt("%s.%s", L, tail); };
w_tokp = wt(nm.f("dflash.lili.token_proj.weight"), src("token_proj.weight"), RAD_BF16, { hs, E });
b_tokp = wt(nm.f("dflash.lili.token_proj.bias"), src("token_proj.bias"), RAD_F32, { hs });
w_pass = wt(nm.f("dflash.lili.pass_proj.weight"), src("pass_hidden_proj.weight"), RAD_BF16,
{ hs, E });
b_pass = wt(nm.f("dflash.lili.pass_proj.bias"), src("pass_hidden_proj.bias"), RAD_F32, { hs });
w_ctx = wt(nm.f("dflash.lili.context_proj.weight"), src("context_proj.weight"), RAD_BF16,
{ hs, E });
b_ctx = wt(nm.f("dflash.lili.context_proj.bias"), src("context_proj.bias"), RAD_F32, { hs });
ln_w = wt(nm.f("dflash.lili.feature_norm.weight"), src("feature_norm.weight"), RAD_F32, { 5 });
ln_b = wt(nm.f("dflash.lili.feature_norm.bias"), src("feature_norm.bias"), RAD_F32, { 5 });
up_w = wt(nm.f("dflash.lili.feature_up.weight"), src("feature_mlp.up_proj.weight"), RAD_F32,
{ hs, 5 });
up_b = wt(nm.f("dflash.lili.feature_up.bias"), src("feature_mlp.up_proj.bias"), RAD_F32,
{ hs });
w_fdn = wt(nm.f("dflash.lili.feature_down.weight"), src("feature_mlp.down_proj.weight"),
RAD_BF16, { hs, hs });
b_fdn = wt(nm.f("dflash.lili.feature_down.bias"), src("feature_mlp.down_proj.bias"), RAD_F32,
{ hs });
/* [1, 1, steps, 1, hs] and [1, 1, 1, k, hs], read as tables (a reshape of one whole plane). */
w_slot = wt(nm.f("dflash.lili.slot_embedding"), src("slot_embedding"), RAD_BF16, { S, hs });
w_rank = wt(nm.f("dflash.lili.rank_embedding"), src("rank_embedding"), RAD_BF16, { K, hs });
w_rel = wt(nm.f("dflash.lili.relative_slot_bias"), src("relative_slot_bias"), RAD_F32,
{ cfg.n_head, 2 * (S + 1) - 1 });
w_same = wt(nm.f("dflash.lili.same_slot_bias"), src("same_slot_bias"), RAD_F32, { cfg.n_head });
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
auto ls = [&](const char* tail) { return nm.ckpt("%s.layers.%d.%s", L, i, tail); };
w_anorm[i] = wt(nm.f("dflash.lili.blk.%d.attn_norm.weight", i), ls("attn_norm.weight"),
RAD_F32, { hs });
w_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.weight", i), ls("attn.in_proj_weight"),
RAD_BF16, { 3 * hs, hs });
b_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.bias", i), ls("attn.in_proj_bias"), RAD_F32,
{ 3 * hs });
w_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.weight", i), ls("attn.out_proj.weight"),
RAD_BF16, { hs, hs });
b_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.bias", i), ls("attn.out_proj.bias"),
RAD_F32, { hs });
w_mnorm[i] = wt(nm.f("dflash.lili.blk.%d.mlp_norm.weight", i), ls("mlp_norm.weight"),
RAD_F32, { hs });
w_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.weight", i), ls("mlp.up_proj.weight"),
RAD_BF16, { cfg.mlp, hs });
b_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.bias", i), ls("mlp.up_proj.bias"), RAD_F32,
{ cfg.mlp });
w_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.weight", i), ls("mlp.down_proj.weight"),
RAD_BF16, { hs, cfg.mlp });
b_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.bias", i), ls("mlp.down_proj.bias"),
RAD_F32, { hs });
if (!w_anorm[i] || !w_in[i] || !b_in[i] || !w_out[i] || !b_out[i] || !w_mnorm[i] ||
!w_up[i] || !b_up[i] || !w_dn[i] || !b_dn[i])
return RAD_E_INVAL;
}
w_onorm = wt(nm.f("dflash.lili.output_norm.weight"), src("output_norm.weight"), RAD_F32, { hs });
w_annorm = wt(nm.f("dflash.lili.anchor_norm.weight"), src("anchor_norm.weight"), RAD_F32, { hs });
w_fac = wt(nm.f("dflash.lili.factor_proj.weight"), src("factor_input_proj.weight"), RAD_BF16,
{ hs, 3 * hs });
b_fac = wt(nm.f("dflash.lili.factor_proj.bias"), src("factor_input_proj.bias"), RAD_F32,
{ hs });
/* [out_head | in_head] as one linear, as vLLM fuses them (`_fused_edge_weight`). */
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.weight"),
{ src("out_head.weight"), src("in_head.weight") }, 0));
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.bias"),
{ src("out_head.bias"), src("in_head.bias") }, 0));
w_edge = decl_w(b, nm.f("dflash.lili.edge.weight"), RAD_BF16, { 2 * fd, hs }, ACC,
RAD_SHARD_NONE, grp);
b_edge = decl_w(b, nm.f("dflash.lili.edge.bias"), RAD_F32, { 2 * fd }, ACC, RAD_SHARD_NONE,
grp);
w_aout = wt(nm.f("dflash.lili.anchor_out.weight"), src("anchor_out_head.weight"), RAD_BF16,
{ fd, hs });
b_aout = wt(nm.f("dflash.lili.anchor_out.bias"), src("anchor_out_head.bias"), RAD_F32, { fd });
if (!w_tokp || !b_tokp || !w_pass || !b_pass || !w_ctx || !b_ctx || !ln_w || !ln_b || !up_w ||
!up_b || !w_fdn || !b_fdn || !w_slot || !w_rank || !w_rel || !w_same || !w_onorm ||
!w_annorm || !w_fac || !b_fac || !w_edge || !b_edge || !w_aout || !b_aout)
return RAD_E_INVAL;
/* ---------------------------------------------------------------- ops */
auto gemm_b = [&](int64_t rows, int64_t N, int64_t Kd, rad_weight wgt, 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", Kd),
RAD_STR("dtype", "bf16"), RAD_STR("act", "none")),
RAD_WEIGHTS(wgt, bias));
};
auto rms = [&](int64_t rows, int64_t n, rad_weight gain) -> rad_op {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", cfg.eps),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain));
};
auto silu = [&](int64_t rows, int64_t n) -> rad_op {
return RAD_OP(b, "silu",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
const int64_t sw = 2 + 2 * rk;
/* The candidates: this rank's shard of the target's logits, its logprob row, the exchange. */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_lm)),
{ w.sel_h }, { w.logits });
/* Replicated, `vocab_off` is omitted: an optional parameter present at 0 is a different
* declaration from an absent one. */
op_stats = g.world > 1
? rw(b, RAD_OP(b, "sample_logprobs",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("k", rk), RAD_INT("vocab_off", g.vocab_off)),
RAD_NOWEIGHTS),
{ w.logits }, { w.stats })
: rw(b, RAD_OP(b, "sample_logprobs",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("k", rk)),
RAD_NOWEIGHTS),
{ w.logits }, { w.stats });
if (g.world > 1)
op_sgath = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * sw), RAD_STR("dtype", "f32"),
RAD_INT("row", sw)),
RAD_NOWEIGHTS),
{ w.stats }, { w.sgath });
op_pas = rw(b, gemm_b(srows, hs, E, w_pass, b_pass), { w.sel_h }, { w.pas });
op_cand = rw(b, RAD_OP(b, "lili_cand",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("k", K),
RAD_INT("world", g.world), RAD_INT("steps", S),
RAD_INT("n", hs), RAD_STR("dtype", "bf16"),
RAD_F64("eps", 1e-5), RAD_INT("row_k", rk)),
RAD_WEIGHTS(ln_w, ln_b, up_w, up_b, w_slot, w_rank)),
{ g.world > 1 ? w.sgath : w.stats, w.pas }, { w.cand, w.feat, w.hh });
/* The lattice: candidates' embeddings (the trunk's vocab-sharded table, exact reduce), the
* token and feature projections added onto lili_cand's base in their GEMMs' residual. */
op_emb = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{ w.cand }, { w.emb });
if (g.world > 1)
op_emb_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", E, lrows * E),
RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{ w.emb }, { w.emb });
op_tokp = rw(b, gemm_b(lrows, hs, E, w_tokp, b_tokp), { w.emb, w.hh }, { w.hh });
op_fdn = rw(b, gemm_b(lrows, hs, hs, w_fdn, b_fdn), { w.feat, w.hh }, { w.hh });
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, rms(lrows, hs, w_anorm[i]), { w.hh }, { w.y });
op_in[i] = rw(b, gemm_b(lrows, 3 * hs, hs, w_in[i], b_in[i]), { w.y }, { w.qkv });
op_out[i] = rw(b, gemm_b(lrows, hs, hs, w_out[i], b_out[i]), { w.att, w.hh }, { w.hh });
op_mnorm[i] = rw(b, rms(lrows, hs, w_mnorm[i]), { w.hh }, { w.y });
op_up[i] = rw(b, gemm_b(lrows, cfg.mlp, hs, w_up[i], b_up[i]), { w.y }, { w.up });
op_dn[i] = rw(b, gemm_b(lrows, hs, cfg.mlp, w_dn[i], b_dn[i]), { w.ups, w.hh }, { w.hh });
}
op_attn = rw(b, RAD_OP(b, "lili_attn",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("steps", S), RAD_INT("k", K),
RAD_INT("n_head", cfg.n_head),
RAD_INT("head_dim", hs / cfg.n_head),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_rel, w_same)),
{ w.qkv }, { w.att });
op_silu_up = rw(b, silu(lrows, cfg.mlp), { w.up }, { w.ups });
op_onorm = rw(b, rms(lrows, hs, w_onorm), { w.hh }, { w.y });
/* The anchor: the context pass's row at each drafting sequence's last committed position. */
op_anc = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.c }, { w.anc });
op_ctx = rw(b, gemm_b(g.max_seqs, hs, E, w_ctx, b_ctx), { w.anc }, { w.ast });
op_annorm = rw(b, rms(g.max_seqs, hs, w_annorm), { w.ast }, { w.an });
op_factor = rw(b, RAD_OP(b, "lili_factor",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("L", S * K),
RAD_INT("n", hs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.y, w.an }, { w.cat });
op_fac = rw(b, gemm_b(lrows, hs, 3 * hs, w_fac, b_fac), { w.cat }, { w.fh });
op_silu_f = rw(b, silu(lrows, hs), { w.fh }, { w.fhs });
op_edge = rw(b, gemm_b(lrows, 2 * fd, hs, w_edge, b_edge), { w.fhs }, { w.edges });
op_aout = rw(b, gemm_b(g.max_seqs, fd, hs, w_aout, b_aout), { w.an }, { w.aout });
op_walk = rw(b, RAD_OP(b, "lili_walk",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", S),
RAD_INT("k", K), RAD_INT("n", fd), RAD_STR("dtype", "bf16"),
RAD_F64("eps", cfg.vec_eps), RAD_F64("scale", cfg.scale)),
RAD_NOWEIGHTS),
{ w.edges, w.aout, w.cand }, { w.tokens });
if (!op_logits || !op_stats || (g.world > 1 && (!op_sgath || !op_emb_ar)) || !op_pas ||
!op_cand || !op_emb || !op_tokp || !op_fdn || !op_attn || !op_silu_up || !op_onorm ||
!op_anc || !op_ctx || !op_annorm || !op_factor || !op_fac || !op_silu_f || !op_edge ||
!op_aout || !op_walk)
return RAD_E_INVAL;
return RAD_OK;
}
inline void LiliCorr::step(RadCtx* c, const RadBatch* batch) const {
const int64_t n = batch->n_seq, S = n * cfg.steps, Lr = S * cfg.k;
if (n <= 0) return;
if (!batch->anchor_rows) {
rad_step_fail(c, "lilicorr: the query pass carries no anchor rows (RadBatch::anchor_rows): "
"this engine does not position a block drafter's anchor");
return;
}
const int64_t E = g.n_embd, hs = cfg.hs, fd = cfg.fdim;
const int64_t sw = 2 + 2 * rk;
RAD_ISSUE_N(c, op_logits, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.logits, S));
RAD_ISSUE_N(c, op_stats, S, brows(w.logits, S), RAD_NONE, brows(w.stats, S));
if (op_sgath) RAD_ISSUE(c, op_sgath, brows(w.stats, S), brows(w.sgath, S));
RAD_ISSUE_N(c, op_pas, S, brows(w.sel_h, S), RAD_W(w_pass), RAD_W(b_pass), RAD_NONE,
brows(w.pas, S));
RAD_ISSUE_N(c, op_cand, S, op_sgath ? brows(w.sgath, S) : brows(w.stats, S), brows(w.pas, S),
RAD_W(ln_w), RAD_W(ln_b), RAD_W(up_w), RAD_W(up_b), RAD_W(w_slot), RAD_W(w_rank),
brow_slice(w.cand, 0, Lr, 1), brows(w.feat, Lr), brows(w.hh, Lr));
(void)sw;
RAD_ISSUE_N(c, op_emb, Lr, brow_slice(w.cand, 0, Lr, 1), RAD_W(w_tok), brows(w.emb, Lr));
if (op_emb_ar) RAD_ISSUE_N(c, op_emb_ar, Lr * E, brows(w.emb, Lr), RAD_NONE);
RAD_ISSUE_N(c, op_tokp, Lr, brows(w.emb, Lr), RAD_W(w_tokp), RAD_W(b_tokp), brows(w.hh, Lr),
brows(w.hh, Lr));
RAD_ISSUE_N(c, op_fdn, Lr, brows(w.feat, Lr), RAD_W(w_fdn), RAD_W(b_fdn), brows(w.hh, Lr),
brows(w.hh, Lr));
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_anorm[i], Lr, brows(w.hh, Lr), RAD_W(w_anorm[i]), brows(w.y, Lr));
RAD_ISSUE_N(c, op_in[i], Lr, brows(w.y, Lr), RAD_W(w_in[i]), RAD_W(b_in[i]), RAD_NONE,
brows(w.qkv, Lr));
RAD_ISSUE_N(c, op_attn, Lr, brows(w.qkv, Lr), RAD_W(w_rel), RAD_W(w_same), brows(w.att, Lr));
RAD_ISSUE_N(c, op_out[i], Lr, brows(w.att, Lr), RAD_W(w_out[i]), RAD_W(b_out[i]),
brows(w.hh, Lr), brows(w.hh, Lr));
RAD_ISSUE_N(c, op_mnorm[i], Lr, brows(w.hh, Lr), RAD_W(w_mnorm[i]), brows(w.y, Lr));
RAD_ISSUE_N(c, op_up[i], Lr, brows(w.y, Lr), RAD_W(w_up[i]), RAD_W(b_up[i]), RAD_NONE,
brows(w.up, Lr));
RAD_ISSUE_N(c, op_silu_up, Lr, brows(w.up, Lr), brows(w.ups, Lr));
RAD_ISSUE_N(c, op_dn[i], Lr, brows(w.ups, Lr), RAD_W(w_dn[i]), RAD_W(b_dn[i]),
brows(w.hh, Lr), brows(w.hh, Lr));
}
RAD_ISSUE_N(c, op_onorm, Lr, brows(w.hh, Lr), RAD_W(w_onorm), brows(w.y, Lr));
RAD_ISSUE_N(c, op_anc, n, RAD_B(w.c), praw(batch->anchor_rows, RAD_I32, n), brows(w.anc, n));
RAD_ISSUE_N(c, op_ctx, n, brows(w.anc, n), RAD_W(w_ctx), RAD_W(b_ctx), RAD_NONE, brows(w.ast, n));
RAD_ISSUE_N(c, op_annorm, n, brows(w.ast, n), RAD_W(w_annorm), brows(w.an, n));
RAD_ISSUE_N(c, op_factor, Lr, brows(w.y, Lr), brows(w.an, n), brows(w.cat, Lr));
RAD_ISSUE_N(c, op_fac, Lr, brows(w.cat, Lr), RAD_W(w_fac), RAD_W(b_fac), RAD_NONE,
brows(w.fh, Lr));
RAD_ISSUE_N(c, op_silu_f, Lr, brows(w.fh, Lr), brows(w.fhs, Lr));
RAD_ISSUE_N(c, op_edge, Lr, brows(w.fhs, Lr), RAD_W(w_edge), RAD_W(b_edge), RAD_NONE,
brows(w.edges, Lr));
RAD_ISSUE_N(c, op_aout, n, brows(w.an, n), RAD_W(w_aout), RAD_W(b_aout), RAD_NONE,
brows(w.aout, n));
RAD_ISSUE_N(c, op_walk, n, brows(w.edges, Lr), brows(w.aout, n),
brow_slice(w.cand, 0, Lr, 1), brows(w.tokens, n), RAD_NONE);
(void)E; (void)hs; (void)fd;
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_LILICORR_H */
+16 -7
View File
@@ -132,9 +132,9 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
swiglu_limit));
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
* MXFP4 at one to 16 rows (eight where K is short). Other gate_up encodings (M2XFP4 included),
* and a clamped (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would
* take it, which would pin the layer's weights to the host. */
* MXFP4 at one to 16 rows (eight where K is short), decl_gated_fold_iqr for an IQR weight
* whose input and output are the rotated int8 trunk's fed pairs, to 16 rows. Other gate_up
* encodings (M2XFP4 included), and a clamped (swiglu_limit) product, take the pair. */
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
!gate_up.i8)
@@ -144,6 +144,14 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
&gated_rows, wide_fold);
else if (fold_ok && gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.ffn.q8_fed && w.ffn.q8_rot)
op_gated = decl_gated_fold_iqr(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
{ w.h.q8, w.h.s8 },
gq_ffn.want_x
? std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8,
w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8 },
&gated_rows);
else if (fold_ok && gate_up.mx && !gate_up.paro)
op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
gate_up.wref, { w.h.q, w.h.s },
@@ -207,10 +215,11 @@ inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
} else if (op_gated && rows <= gated_rows) {
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
/* The fp8a8 fold's E4M3 pairs, or the IQR fold's int8 ones (cq / cs: the fed pair). */
RAD_ISSUE_N(c, op_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(gate_up.w),
RAD_W(gate_up.ws), brow_slice(w.ffn.cq(), r0, rows, g.n_ff),
brow_slice(w.ffn.cs(), r0, rows, g.n_ff / RAD_FP8_BLOCK),
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
} else {
gate_up.step(c, w.h, w.gate_up, T, r0, rows);
+85 -33
View File
@@ -182,8 +182,19 @@ struct MoeFP8 {
/* Block-fp8 experts whose scale plane is f32 (format 9, dtype fp8a8f32). */
int expert_f32_scale = 0;
double route_scale = 1.0;
/* With `sigmoid_router`: group-limited selection over `n_group` groups, `topk_group` kept
* (router_sigmoid_group_topk; Ling-3.0). 1 is GLM's single group. The fused selection and
* sort is single-group, so a grouped router runs the separate pair. */
int64_t n_group = 1, topk_group = 1;
/* Clamp of the SwiGLU product (swiglu_clamped); 0 is none. */
double swiglu_limit = 0.0;
/* The shared arm's clamp where it differs from the routed one (Ling-3.0 clamps its shared
* expert at 5 or 7 and its routed ones at 4, in different layers); negative: the routed
* arm's. */
double shared_swiglu_limit = -1.0;
/* Clip after the SiLU (`swiglu_step`) rather than before it (`swiglu_clamped`), for both
* arms. */
int swiglu_step = 0;
/* With `swiglu_limit`: the clamped product and its quantiser as one launch
* (GateQuantFP8::fuse_clamped), for the routed and the shared arm. */
int swiglu_quant = 0;
@@ -196,6 +207,19 @@ struct MoeFP8 {
* At TP1 the ungated gather preserves both roundings; TP>1 reduces each arm separately
* before combining, so its gather cannot fold the shared output. */
int shared_fp32_combine = 0;
/* Experts without a gate (Nemotron-H): one projection up (`up_proj`), relu(x)^2, and down,
* so the first GEMM is n_ff_exp wide rather than 2 * n_ff_exp and the quantiser between
* the GEMMs squares rather than gates (GateQuantFP8's "relu2"). The routed arm only: such a
* family's shared expert is the caller's. */
int ungated = 0;
/* The router's input width when it is not the experts' (Nemotron-H's latent experts: the
* router scores the full hidden state, the experts read a narrower projection of it, and
* this block's Geom is the experts'). 0 means n_embd. With it the router reads
* Wire::route. The sigmoid router only. */
int64_t router_k = 0;
/* The caller reduces the block's delta across ranks, because it applies more linear work
* to it first (Nemotron-H's latent up-projection); no all-reduce is declared. */
int no_reduce = 0;
/* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for
* Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8`
* registry row). It is the stored encoding: probe() reads it from the first expert's
@@ -267,6 +291,8 @@ struct MoeFP8 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the block's delta */
/* The router's input when Config::router_k is set; `h` otherwise. */
rad_buf route = 0; /* [max_tok, router_k] bf16 */
/* Rotated codes of the same input (only `q` and `s`; `x` is `h`'s). Declared only with
* `expert_rot`: the routed gate_up reads them, the shared expert reads `h`'s. */
ActFP8 hr{}; /* [max_tok, n_embd] q + scale only */
@@ -547,17 +573,19 @@ inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const c
/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the
* checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */
inline int moe_map_gate_up(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
long long ge) {
long long ge, bool ungated = false) {
if (src.experts_gate_up) return map_slice(b, guw, src.experts_gate_up, (int)ge);
if (src.experts_gate && src.experts_up)
return map_slice_concat(b, guw, {src.experts_gate, src.experts_up}, (int)ge);
/* Ungated experts (Nemotron-H) have no gate_proj: the first GEMM is up_proj alone. */
if (ungated) return map_copy(b, guw, nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge));
return map_concat(b, guw, {nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge),
nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge)});
}
inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
const char* dnw, long long ge, bool gate_up) {
if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge, src.cfg.ungated));
if (src.experts_gate_up || src.experts_gate)
return map_slice(b, dnw, src.experts_down, (int)ge);
return map_copy(b, dnw, nm.ckpt("%s.%lld.down_proj.weight", src.experts, ge));
@@ -584,7 +612,7 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
int f = 0;
for (long long ge = g0; ge < gn && ge <= g0 + kMaxProtected; ++ge) {
const char* guw = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge);
RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge, cfg->ungated));
cfg->probed_count = ge - g0 + 1;
RadEncoding e{};
f = 0;
@@ -618,6 +646,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
int ar_in, bool ar_out_) {
g = geom; c = src.cfg; w = wire; layer = l;
ar_out = ar_out_;
if (c.n_group > 1) c.router_fuse = 0;
const double sh_limit = c.shared_swiglu_limit < 0 ? c.swiglu_limit : c.shared_swiglu_limit;
/* 0 means not expert-parallel: this rank owns every expert. */
if (c.n_expert_all <= 0) c.n_expert_all = c.n_expert;
if (c.n_expert <= 0 || c.top_k <= 0 || c.top_k > c.n_expert_all || c.n_ff_exp <= 0)
@@ -639,6 +669,21 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
"BF16 shared arm and routed output\n", l);
return RAD_E_INVAL;
}
/* The first GEMM's rows per intermediate column (gate and up, or up alone) and the activation
* between the GEMMs. */
const int64_t gu = c.ungated ? 1 : 2;
const char* const gact = c.ungated ? "relu2" : "silu";
if (c.ungated && (shared || src.experts_gate_up || src.experts_gate ||
c.swiglu_limit > 0)) {
fprintf(stderr, "radiance: ungated experts are served one by one (`up_proj`), unclamped and "
"without a shared arm in this block\n");
return RAD_E_INVAL;
}
if (c.router_k && (!c.sigmoid_router || !w.route)) {
fprintf(stderr, "radiance: a router over another input than the experts' is the sigmoid "
"router reading Wire::route\n");
return RAD_E_INVAL;
}
/* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by
* the fused router's gate write (see there). */
bool sgate_concurrent = false;
@@ -764,9 +809,13 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rc.rows = c.rows;
rc.norm = c.norm_topk;
rc.route_scale = c.route_scale;
const GlmRouter::Wire wire{ w.h.x, w.logits, w.ids, w.ew };
rc.groups = c.n_group;
rc.topk_groups = c.topk_group;
const GlmRouter::Wire wire{ c.router_k ? w.route : w.h.x, w.logits, w.ids, w.ew };
const GlmRouter::Src rs{ src.router, src.router_bias };
RAD_ARCH_TRY(glm_router.declare(b, nm, g, l, nm.f("blk.%d.glm_router", l), rc, wire, rs));
Geom rg = g;
if (c.router_k) rg.n_embd = c.router_k;
RAD_ARCH_TRY(glm_router.declare(b, nm, rg, l, nm.f("blk.%d.glm_router", l), rc, wire, rs));
w_router = glm_router.projection;
op_router = glm_router.op_project;
op_topk = glm_router.op_select;
@@ -931,7 +980,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
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 : 2;
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. */
@@ -969,10 +1018,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
return RAD_E_INVAL;
}
for (int64_t e = 0; e < ne; ++e) {
const int64_t parts[2] = { c.n_ff_exp, c.n_ff_exp };
const int64_t parts[2] = { c.n_ff_exp, c.n_ff_exp }; /* gate, up (up alone: one) */
w_gu[(size_t)e] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
RAD_BF16, {2 * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL,
RAD_BF16, {gu * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL,
sh_row, grp_expert_slot(l, (int)e, 0), 0, parts, n_parts);
if (!w_gu[(size_t)e]) return RAD_E_INVAL;
}
@@ -986,7 +1035,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* Row orders as for the quantised GEMMs (see `a_order` below): gate_up gathers token rows,
* down reads sorted rows. */
op_gu = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * c.n_ff_exp),
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * c.n_ff_exp),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", ne),
RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"),
RAD_STR("dtype", "bf16")),
@@ -996,8 +1045,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* (rad_fp8.h: GateQuantFP8). */
Geom gx = g;
gx.w_bf16 = true;
RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k,
true, false, c.swiglu_limit));
RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
true, false, c.swiglu_limit, c.swiglu_step != 0));
op_dn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", c.n_ff_exp), RAD_INT("n_expert", ne),
@@ -1015,7 +1064,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], {2 * wq[q], g.n_embd},
nullptr, ecodes, edt[0], {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;
@@ -1031,7 +1080,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
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) ? 2 * wq[q] : fp8_blocks(2 * wq[q]),
{(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)},
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
parts, n_parts);
@@ -1107,22 +1156,22 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const std::vector<rad_weight> tab = tables(w_gu, w_gus);
rad_op h = ncls == 4
? rad_decl_op(b, "moe_gemm_q_mod4",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]),
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", 2 * wq[1]), RAD_INT("K_1", g.n_embd),
RAD_INT("N_2", 2 * wq[2]), RAD_INT("K_2", g.n_embd),
RAD_INT("N_3", 2 * wq[3]), RAD_INT("K_3", g.n_embd),
RAD_INT("parts", 2)),
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", 2 * wq[0]),
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", 2 * wq[1]), RAD_INT("K_odd", g.n_embd),
RAD_INT("parts", 2)),
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});
}
@@ -1130,8 +1179,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* 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, "silu", c.rows * c.top_k,
false, rot, c.swiglu_limit));
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));
{
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
rad_op h = ncls == 4
@@ -1184,7 +1233,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* the plain even split with no span. */
psh_row = RAD_SHARD_ROW;
psh_col = RAD_SHARD_COL;
pparts = 2;
pparts = (int)gu;
if (full % g.world == 0 && (full / g.world) % 64 == 0) {
wp = full / g.world;
} else if (full % 64 || full / 64 < g.world) {
@@ -1206,7 +1255,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const int64_t parts[2] = { wp, wp };
w_pgu[(size_t)j] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + prot[(size_t)j])),
RAD_BF16, {2 * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN,
RAD_BF16, {gu * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN,
psh_row, grp_layer(l), 0, parts, pparts);
if (!w_pgu[(size_t)j]) return RAD_E_INVAL;
if (phi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w_pgu[(size_t)j], plo, phi));
@@ -1221,11 +1270,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
/* The gate_up and gate outputs, bf16, one sorted row each; regular experts' rows are
* unused. */
b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, 2 * wp});
b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, gu * wp});
pff.x = decl_b(b, nm.f("blk.%d.moe_prot_ff", l), RAD_BF16, {c.rows * c.top_k, wp});
if (!b_pgu || !pff.x) return RAD_E_INVAL;
op_pgu = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wp),
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wp),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", np),
RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"),
RAD_STR("dtype", "bf16")),
@@ -1233,8 +1282,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
{w.h.x, w.sorted, w.eoff}, {b_pgu});
Geom gx = g;
gx.w_bf16 = true;
RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, "silu", c.rows * c.top_k, true,
false, c.swiglu_limit));
RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, gact, c.rows * c.top_k, true,
false, c.swiglu_limit, c.swiglu_step != 0));
op_pdn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wp), RAD_INT("n_expert", np),
@@ -1374,7 +1423,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.q8));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.s8));
}
if (!w.sff.q || c.swiglu_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
if (!w.sff.q || sh_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate));
@@ -1391,7 +1440,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
gq_sh.fuse_clamped = c.swiglu_quant != 0;
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,
c.swiglu_limit));
sh_limit, c.swiglu_step != 0));
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 },
@@ -1515,7 +1564,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
}
if (g.world > 1) {
if (g.world > 1 && !c.no_reduce) {
const auto all_reduce = [&](const char* dtype, rad_buf buffer) {
return rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -1536,7 +1585,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
/* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
* prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
if (g.world > 1 && ar_overlap > 0)
if (g.world > 1 && !c.no_reduce && ar_overlap > 0)
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
@@ -1784,6 +1833,9 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
(!calib_dne_failed &&
calib_dne.write(gram_dn_stem, c.expert_base, gram_domain,
rad_rank(c_)));
/* Written: the host sums are done with (a layer's can be gigabytes). */
calib_dne.acc = {};
calib_dne.rows = {};
calib_done = true;
if (layer == 0)
std::fprintf(stderr, "radiance: calibration wrote layer Hessians after %lld "
+42 -3
View File
@@ -25,7 +25,13 @@
* safetensors file per input, <dir>/<stem>.safetensors, holding `hessian_upper`, f32
* [k * (k + 1) / 2], row i's entries k2 = i .. k-1 after row i-1's, and metadata naming `k`, the
* rows summed and the checkpoint linears that read the input. H is the raw sum; divide by `rows`
* for the mean second moment. */
* for the mean second moment.
*
* An int8 trunk (site_i8, one rank only) is recorded from the codes and scales its GEMMs actually
* read, so H includes what the model's own quantisation did to the input -- the input a quantised
* model feeds each layer, for GPTQ against the error it inherits. Codes a rotating producer wrote
* are in the rotated domain; the file's metadata then names it (`domain`: the Hadamard width), as
* RADGRAM2's header does, and the reader converts. */
#pragma once
#include <arch/rad_arch.h>
@@ -52,6 +58,8 @@ struct CalibFull {
rad_op op_gather = 0; /* the columns of every rank into `gathered`; 0 when replicated */
rad_op op_gram = 0; /* declared on the owner only */
bool owner = false;
rad_buf q8 = 0, s8 = 0; /* site_i8: the int8 codes and their f32 (row, 128) scales */
uint32_t domain = 0; /* site_i8: the codes' rotation width, 0 for none */
std::vector<float> tri; /* the owner's accumulator, upper triangle packed */
};
@@ -156,6 +164,32 @@ struct CalibFull {
return RAD_OK;
}
/* One input of layer `layer` from an int8 trunk's codes `q8` and scales `s8` (see the file
* comment): the whole input on one rank, `domain` the Hadamard width the codes were rotated by
* (0 for none). */
int site_i8(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
rad_buf q8, rad_buf s8, int64_t K, uint32_t domain) {
if (world > 1 || !q8 || !s8 || K > kmax) return RAD_E_INVAL;
Site s;
s.stem = std::move(stem);
s.linears = std::move(linears);
s.K = s.k_local = K;
s.owner = true;
s.q8 = q8;
s.s8 = s8;
s.domain = domain;
(void)layer;
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
RAD_INT("group", 128), RAD_STR("dtype", "i8a8"),
RAD_INT("upper", 1)),
RAD_NOWEIGHTS),
{ q8, s8, scratch }, { scratch });
if (!s.op_gram) return RAD_E_INVAL;
sites.push_back(std::move(s));
return RAD_OK;
}
/* Site `i` over a step's T rows: gather (every rank), then on the owner the Gram into the
* scratch, copied to a free square, the scratch zeroed, and the square handed to the worker. */
void tap(RadCtx* c, size_t i, int64_t T) {
@@ -186,7 +220,10 @@ struct CalibFull {
}
}
const int64_t K = s.K;
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
if (s.q8)
RAD_ISSUE_N(c, s.op_gram, T, brows(s.q8, T), brows(s.s8, T), praw2(dev, RAD_F32, K, K));
else
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
/* `upper` 1 writes no entry below the diagonal, so only the upper triangle comes back:
* band by band of kBand rows, each from its first row's diagonal on, about half the
* square's bytes. The link is what a step's taps wait on, 25 GB a step on each rank of
@@ -317,7 +354,9 @@ private:
const uint64_t bytes = (uint64_t)s.tri.size() * 4;
std::string hdr = "{\"__metadata__\":{\"k\":\"" + std::to_string(s.K) + "\",\"rows\":\"" +
std::to_string(seen) + "\",\"layout\":\"upper triangle, row-major, packed\","
"\"linears\":\"" + s.linears + "\"},\"hessian_upper\":{\"dtype\":\"F32\","
"\"linears\":\"" + s.linears + "\"" +
(s.domain ? ",\"domain\":\"" + std::to_string(s.domain) + "\"" : std::string()) +
"},\"hessian_upper\":{\"dtype\":\"F32\","
"\"shape\":[" + std::to_string(s.tri.size()) + "],\"data_offsets\":[0," +
std::to_string(bytes) + "]}}";
while (hdr.size() % 8) hdr += ' ';
+92 -6
View File
@@ -141,8 +141,9 @@ inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, in
if (g.w_bf16) { op = 0; return a.x ? RAD_OK : RAD_E_INVAL; }
if (!a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
/* `dtype` is the input's (bf16); the op name gives the output format. An input fed at int8
* codes is quantised by quant_act_i8g into its int8 pair. */
op = rw(b, RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
* codes is quantised by quant_act_i8g into its int8 pair, or by had_quant_act_i8g where they
* 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_NOWEIGHTS),
@@ -580,14 +581,20 @@ struct GateQuantFP8 {
* not resolve: `silu_mul` into the bf16 plane (`op`), then `had_quant_act_fp8` over it into the
* codes (`op_q`). */
rad_op op_q = 0;
/* act "relu2" (Nemotron-H's ungated experts): `gate_up` is one part, n wide, and `op` is
* act_mul's relu over it twice, relu(x)^2 into the bf16 plane, which `op_q` quantises (rotated
* for a rotated weight). No fused form yet: the plane is written either way. */
bool ungated = false;
/* Set before declare: the product in bf16 alone, as for bf16 linears, for a consumer that
* quantises its input itself (an int8 linear's op_q). */
bool silu_only = false;
/* `step`: with `limit`, clip after the SiLU (`swiglu_step`, Ling-3.0) rather than before it
* (`swiglu_clamped`, GLM-5.3). It has no fused quantiser, so the pair runs. */
int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n,
const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true,
bool rot = false, double limit = 0);
bool rot = false, double limit = 0, bool step = false);
void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
};
@@ -596,7 +603,7 @@ struct GateQuantFP8 {
* bf16 output is unrotated either way. */
inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act,
int64_t n, const char* act_name, int64_t max_rows,
bool bf16_out, bool rot, double limit) {
bool bf16_out, bool rot, double limit, bool step) {
a = act;
want_x = bf16_out;
op_quant = 0;
@@ -607,6 +614,28 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
clipped = limit > 0;
clamped_fused = false;
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
ungated = std::strcmp(act_name, "relu2") == 0;
if (ungated) {
if (!gate_up || !a.x || n <= 0 || clipped || (!bf16 && (!a.cq() || !a.cs())) ||
(rot && a.q8_fed))
return RAD_E_INVAL;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
want_x = true;
op = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("act", "relu"),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ gate_up }, { a.x });
if (!op) return RAD_E_INVAL;
if (bf16) return RAD_OK;
const char* qn = rot ? "had_quant_act_fp8" : a.q8_fed ? "quant_act_i8g" : "quant_act_fp8";
op_q = rw(b, 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_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
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`. */
@@ -614,7 +643,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
std::strcmp(act_name, "silu"))
return RAD_E_INVAL;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
if (fuse_clamped && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
if (fuse_clamped && !step && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
rad_op_declared(b, "swiglu_clamped_quant_fp8")) {
op =
RAD_OP(b, "swiglu_clamped_quant_fp8",
@@ -631,7 +660,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
}
want_x = true;
op = rw(b,
RAD_OP(b, "swiglu_clamped",
RAD_OP(b, step ? "swiglu_step" : "swiglu_clamped",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
@@ -701,6 +730,15 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0,
int64_t rows) const {
if (rows <= 0) rows = T - r0;
if (ungated) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, n), brow_slice(gate_up, r0, rows, n),
brow_slice(a.x, r0, rows, n));
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));
return;
}
if (clamped_fused) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.cq(), r0, rows, n),
@@ -779,6 +817,13 @@ struct LinearFP8 {
* writes E4M3. Read from the weight's encoding. */
bool i8 = false;
rad_op op_q = 0;
/* An int8 weight stored rotated (i8a8h, or a rotated four- or five-bit one): its activation
* codes are in the 128-wide Hadamard domain, whoever wrote them (had_quant_act_i8g or a
* rotating producer). */
bool i8_rot = false;
/* With i8_rot: an IQR weight (libr4d's r4d_iqr.h), whose codes decode where they are read: a
* u6 code under a zero, a table, a grid or a trellis. Read from the weight's encoding. */
bool iqr = false;
/* OCP-MXFP4 weight read by `gemm_nt_q` at dtype mxfp4a8 against the usual E4M3 activation pair:
* e2m1 codes with one E8M0 exponent per 32 of K (libquant `codes=fp4_e2m1 group=32
* scale=e8m0`). libr4d folds each block's exponent into the e4m3 operand against a per-row
@@ -1310,6 +1355,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const bool asym = known && linear_is_wnh(enc);
const bool rot8 = known && (linear_is_w8h(enc) || asym);
i8 = known && (linear_is_w8(enc) || rot8);
i8_rot = i8 && rot8;
if (i8) {
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
@@ -1340,6 +1386,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const char* sn = nm.f("%s.scale", base);
/* A narrower i8a8h weight's codes view takes the plane that decodes it too. */
const W8hForm form = linear_w8h_form(enc);
iqr = rot8 && !asym && (form == W8hForm::Zero || form == W8hForm::Table ||
form == W8hForm::Grid || form == W8hForm::Trellis);
const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis");
const bool trb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1;
const char* cv = form == W8hForm::Zero ? "codes,zero"
@@ -1829,6 +1877,23 @@ struct DenseFP8 {
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
}
/* This rank's rows [lo, hi) of a RAD_SHARD_ROW weight where the even shard is the wrong cut: a
* KV head replicated over ranks (Geom::kv_off), the same rows on every rank that shares it.
* Call after declare(), whose N is already hi - lo. The fp8 scale plane takes the span in its
* 128-row blocks; the MXFP4 and M2XFP4 planes are one row a weight row, as in LinearFP8. */
int span(RadBuilder* b, int64_t lo, int64_t hi) const {
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
if (mx || m2x) {
RAD_ARCH_TRY(rad_weight_shard_span(b, s, lo, hi));
return rad_weight_shard_span(b, ref, lo, hi);
}
if (lo % RAD_FP8_BLOCK || hi % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: a row span [%lld, %lld) is not whole %d-row scale blocks\n",
(long long)lo, (long long)hi, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
}
/* `gemm_nt_q` over this weight, `fp8a8`, `mxfp4a8` or `m2xfp4` as it was declared, ranged
* M 1..hi. `split_n`, when set, is the stored width a row slice takes its K split from
* (docs/OPS.md). */
@@ -1968,6 +2033,27 @@ inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t
return 0;
}
/* The same fold over an IQR [2n, K] gate_up weight under the rotated int8 trunk (`gemm_nt_q_gated`
* at i8a8h: the codes and scale views gemm_nt_q reads, the input's and the output's int8 pairs, both
* in the Hadamard domain), declared for M up to min(rows, 16): libr4d's gemm_iqr_gated serves its
* GEMV and 16-token tile, each byte-identical to the GEMM row of its band followed by
* gated_had_quant_i8g. Optional like decl_gated_fold, and asked for only when a loaded library
* declares the op at that dtype: a CPU-only engine takes the pair. */
inline rad_op decl_gated_fold_iqr(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
rad_weight ws, std::initializer_list<rad_buf> reads,
std::initializer_list<rad_buf> writes, int64_t* gated_rows) {
if (rows <= 0 || N % 256 || K % 256) return 0;
const int64_t hi = rows < 16 ? rows : 16;
const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "i8a8h"),
RAD_STR("act", "silu")),
RAD_WEIGHTS(w, ws)),
reads, writes);
if (op) *gated_rows = hi;
return op;
}
/* ================================================== a calibration tap */
/* One tap of the GPTQ calibration (calib_dir): the Gram of a linear's bf16 input, summed over the
* corpus in a PERSIST [K, K] f32 buffer that calib_write() saves. */