Archived
radiance 2.1.0
New models. Recursive Flint (39.8B, about 2.5B active) by everplays (#422): `arch/flint`, as an IQ8R container with rotated int8 experts or a four-bit one, with a sink-aware WMMA prefill attention and the fused attention prologue at `rotary_dim` 0. Meta Muse Glimmer 30B by launch80_assets (#423): bf16, an int4 trunk or IQ8R, its windowed vision tower, its DFlash drafter, the ATEM tool dialect and context extension. Ling-3.0-tiny by RikshaDriver (#441): served from its GGUF releases or as IQ8R on `bailing_hybrid`, with six more libr3d kernels. Block FP8, MXFP4 and NVFP4 conversions of the three are not served. IQ8R containers of all three (round to nearest, no calibration) are on Hugging Face under StillDeadcode: flint-iq8r, muse-glimmer-30b-iq8r-dflash and ling-3.0-tiny-iq8r. They were checked for sane answers on two R9700; nothing was benchmarked, and Muse Glimmer's pictures, video and tool calls were not tried. Speech. Breeze-TTS-2 clones a voice from a reference recording and its transcript, with an optional delivery direction, by farcryjohn (#436). The published Breeze container needs converting again with the updated recipe before it can. Tools. A model entry with `diagnose: DIR` runs a fixed workload on the engine instead of serving and writes a report: step times, tokens a step, draft acceptance, TTFT and prefill rates by category, concurrency and prompt length, and with `diagnose-baseline` a token-for-token comparison against an earlier report (docs/DIAGNOSE.md), by Code000 (#418). Scheduler. `mixed-step-target-ms` holds a mixed prefill and decode step to a service time, off by default, by tnhnyzc (#413). `scheduler.stuck-exit` (60s by default, 0 never) ends the process when the device has advanced nothing for that long, so a restart policy brings a hung server back (#409, #415, #428). Fixed. Draft trees with the int8 KV cache, which stopped Gemma 4 31B with DFlash2 on its first request (#454, diagnosed by aelfwyne). The expert loan held at zero by a few leftover cache blocks after long sessions (#455, diagnosed by thekk1). The mapped tier's pages kept in the page cache across a load and a restore, by C_Tamas (#421). Replayed tool calls with blank arguments, and arguments that are not JSON refused naming the call, by dschmitz (#444). The dashboard's card temperature reads the junction sensor, by dschmitz (#453). The VRAM shortfall report says what the KL mode needs, by baKon (#448). The out-of-tree plugin test builds its plugins in parallel and takes its toolchain from the tree. Plugin ABI 40: out-of-tree plugins need to be rebuilt. Thanks to @everplays, @launch80_assets, @RikshaDriver, @farcryjohn, @Code000, @tnhnyzc, @C_Tamas, @dschmitz, @baKon, @aelfwyne and @thekk1.
This commit is contained in:
1 parent
ddcb9c69bb
commit
2a2b756371
166 files changed
+20749
-327
No files matched your search
@@ -1,25 +1,52 @@
|
||||
/* bailing_hybrid -- Ling-3.0-flash and its fine-tunes (`model_type: bailing_hybrid`,
|
||||
* BailingMoeV3ForCausalLM), from the bf16 checkpoint, the routed experts as a recipe stores them
|
||||
* (data/recipes/ling3-w4a8-rtn.recipe, ling3-w4a8-gptq.recipe).
|
||||
/* bailing_hybrid -- Ling-3.0-flash, Ling-3.0-tiny and their fine-tunes (`model_type:
|
||||
* bailing_hybrid`, BailingMoeV3ForCausalLM), from the bf16 checkpoint, the routed experts as a
|
||||
* recipe stores them (data/recipes/ling3-w4a8-rtn.recipe, ling3-w4a8-gptq.recipe), an IQ8R trunk
|
||||
* with rotated int8 experts (data/recipes/ling-3.0-tiny-iq8r.recipe; below), and the tiny
|
||||
* family's GGUF releases (arch/bailing_hybrid_gguf and kin: IQ4_NL, Q8_0, Q4_K_M, Q5_K_M, Q6_K,
|
||||
* the iq4 release's codes through data/recipes/ling-3.0-tiny-iq4.recipe).
|
||||
*
|
||||
* ============================== WHAT IT SERVES ==============================
|
||||
*
|
||||
* layers 42 in groups of six: five Kimi delta attention (KDA) layers, then one dense
|
||||
* latent attention (MLA) layer, so layers 5, 11, ..., 41 are MLA
|
||||
* KDA 32 heads of 128, separate q/k/v projections each with its own causal
|
||||
* convolution, a full-rank per-channel forget gate (`f_proj`) and output gate
|
||||
* (`g_proj`), lower bound -5
|
||||
* MLA no query LoRA, a 512-wide latent and a 64-wide rotary part (interleaved pairs),
|
||||
* heads of 128 + 64, values of 128, a sigmoid gate per head
|
||||
* feed-forward layers 0-1 dense (6144); from layer 2, 512 experts of 768 at top-8 under
|
||||
* group-limited sigmoid routing (8 groups, 4 kept, a correction bias, x2.5), an
|
||||
* ungated shared expert, and a SwiGLU clipped after the SiLU in the last layers
|
||||
* (`expert_swiglu_limit_list`, `share_expert_swiglu_limit_list`, as vLLM and
|
||||
* SGLang serve it; HF's reference ignores it)
|
||||
* layers flash: 42 in groups of six -- five Kimi delta attention (KDA) layers, then one
|
||||
* dense latent attention (MLA) layer, so layers 5, 11, ..., 41 are MLA.
|
||||
* tiny: 24 in groups of four, MLA at 3, 7, ..., 23.
|
||||
* KDA flash: 32 heads of 128; tiny: 16. Separate q/k/v projections each with its own
|
||||
* causal convolution, a full-rank per-channel forget gate (`f_proj`) and output
|
||||
* gate (`g_proj`), lower bound -5
|
||||
* MLA a 512-wide latent and a 64-wide rotary part (interleaved pairs), heads of
|
||||
* 128 + 64, values of 128, a sigmoid gate per head. flash has no query LoRA;
|
||||
* tiny projects through one: q_a and its norm feed q_b, whose rows serve the
|
||||
* two query parts.
|
||||
* feed-forward flash: layers 0-1 dense (6144); from layer 2, 512 experts of 768 at top-8.
|
||||
* tiny: layer 0 dense (4608); from layer 1, 128 experts of 512 at top-8. Both
|
||||
* under group-limited sigmoid routing (8 groups, 4 kept, a correction bias,
|
||||
* x2.5), an ungated shared expert, and a SwiGLU clipped after the SiLU in the
|
||||
* last layers (`expert_swiglu_limit_list`, `share_expert_swiglu_limit_list`, as
|
||||
* vLLM and SGLang serve it; HF's reference ignores it)
|
||||
*
|
||||
* The KDA core is GLM-5.3's (KdaState), the router GLM-5.3's with groups (GlmRouter), the
|
||||
* feed-forward MoeFP8. The KDA and MLA blocks around them are in this file.
|
||||
*
|
||||
* ============================== THE TRUNK'S FORM ==============================
|
||||
*
|
||||
* Read from layer 0's fused q|k|v before any activation buffer is declared. Two forms:
|
||||
*
|
||||
* - a rotated int8 trunk (data/recipes/ling-3.0-tiny-iq8r.recipe: IQ8R, int8 codes rotated by
|
||||
* a 128-wide Hadamard under a u8 scale a (row, 256 of K) and a bf16 one a row): the block
|
||||
* norms write rmsnorm_had_quant_i8g's codes at the trunk's group, read by every KDA
|
||||
* projection, the shared expert's gate/up and the routed gate/up; the KDA core's gated norm
|
||||
* and the MLA's expanded values are quantised by had_quant_act_i8g for their out projections;
|
||||
* the dense and shared gated products write gated_had_quant_i8g's codes (the shared one at
|
||||
* the group its own down weight is stored at), and the routed arm is int8 at one scale a 128
|
||||
* (MoeFP8::a8), so the rotated int8 experts read those codes at i8a8h. Where no loaded
|
||||
* library serves the rotating norm, each linear quantises the norm's bf16 output itself and
|
||||
* the routed experts read a rotated copy written once a layer. The linears the recipe keeps
|
||||
* bf16 (the KDA beta, the MLA's low-rank q and kv and its head gate) read the norm's bf16
|
||||
* output in either case. Unclamped SwiGLU only: the int8 gated products have no clamped form.
|
||||
* - any other (bf16, the four-bit experts of ling3-w4a8-rtn and ling-3.0-tiny-iq4, the GGUF
|
||||
* releases): the norms write E4M3 codes, each linear reads the bf16 plane or quantises it
|
||||
* itself, and four-bit experts read the E4M3 pair (rotated ones a rotated copy of it).
|
||||
*
|
||||
* ============================== THE LATENT ATTENTION ==============================
|
||||
*
|
||||
* The MLA attends in the latent. The query projection is served as two, its heads' rotary rows and
|
||||
@@ -55,11 +82,20 @@ using namespace rad::arch;
|
||||
struct Shape {
|
||||
int64_t n_embd = 0, n_layer = 0, heads = 0, head_dim = 0, nope = 0, rope = 0, v_dim = 0,
|
||||
latent = 0, experts = 0, top_k = 0, groups = 0, topk_groups = 0, ff_exp = 0,
|
||||
ff_shared = 0, ff_dense = 0, dense_layers = 0, group_size = 0, conv = 0;
|
||||
ff_shared = 0, ff_dense = 0, dense_layers = 0, group_size = 0, conv = 0, q_lora = 0;
|
||||
double lower = -5, route_scale = 1;
|
||||
bool gguf = false; /* the checkpoint spells its tensors blk. and ssm. names (the release GGUF) */
|
||||
std::vector<double> lim_exp, lim_shared;
|
||||
};
|
||||
|
||||
/* A projection's checkpoint name: config.json's spelling under the layer prefix `pre`
|
||||
* (`model.layers.%d.attention`) for the safetensors, the blk./ssm. spelling with the layer as %d
|
||||
* for the release GGUF. */
|
||||
static const char* ck_name(Names& nm, const Shape& sh, int l, const char* pre, const char* hf,
|
||||
const char* gg) {
|
||||
return sh.gguf ? nm.ckpt(gg, l) : nm.ckpt(hf, pre);
|
||||
}
|
||||
|
||||
/* A KDA layer: the q/k/v, beta, forget and output-gate projections into KdaState, then o_proj and
|
||||
* its all-reduce. */
|
||||
struct LingKda {
|
||||
@@ -76,40 +112,63 @@ struct LingKda {
|
||||
QuantFP8 out_quant{};
|
||||
rad_op op_ar = 0;
|
||||
|
||||
/* Maps layer l's fused q|k|v and reads its stored form (LinearFP8::probe); declare() then does
|
||||
* not map it again. The model learns from it whether the trunk is rotated int8 before it
|
||||
* declares any activation buffer. */
|
||||
int probe_qkv(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l,
|
||||
const char* pre) {
|
||||
return qkv.probe(b, nm, geom, nm.f("blk.%d.attn_qkv", l),
|
||||
{ ck_name(nm, sh, l, pre, "%s.q_proj.weight", "blk.%d.attn_q.weight"),
|
||||
ck_name(nm, sh, l, pre, "%s.k_proj.weight", "blk.%d.attn_k.weight"),
|
||||
ck_name(nm, sh, l, pre, "%s.v_proj.weight", "blk.%d.attn_v.weight") });
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l,
|
||||
const Wire& wire, const char* pre, rad_kvgroup state, rad_kvgroup history) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
const int64_t heads = sh.heads / g.world, width = heads * sh.head_dim;
|
||||
const auto grp = grp_layer(l);
|
||||
/* One name a projection, the checkpoint's spelling (ck_name). */
|
||||
auto ck = [&](const char* hf, const char* gg) -> const char* {
|
||||
return ck_name(nm, sh, l, pre, hf, gg);
|
||||
};
|
||||
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), 3 * width, g.n_embd,
|
||||
RAD_SHARD_ROW, grp,
|
||||
{ nm.ckpt("%s.q_proj.weight", pre), nm.ckpt("%s.k_proj.weight", pre),
|
||||
nm.ckpt("%s.v_proj.weight", pre) },
|
||||
{ ck("%s.q_proj.weight", "blk.%d.attn_q.weight"),
|
||||
ck("%s.k_proj.weight", "blk.%d.attn_k.weight"),
|
||||
ck("%s.v_proj.weight", "blk.%d.attn_v.weight") },
|
||||
w.input, w.core.qkv, 0, { width, width, width }));
|
||||
RAD_ARCH_TRY(beta.declare(b, nm, g, nm.f("blk.%d.attn_beta", l), heads, g.n_embd,
|
||||
RAD_SHARD_ROW, grp, { nm.ckpt("%s.b_proj.weight", pre) },
|
||||
RAD_SHARD_ROW, grp, { ck("%s.b_proj.weight", "blk.%d.ssm_beta.weight") },
|
||||
w.input, w.core.beta));
|
||||
RAD_ARCH_TRY(forget.declare(b, nm, g, nm.f("blk.%d.attn_forget", l), width, g.n_embd,
|
||||
RAD_SHARD_ROW, grp, { nm.ckpt("%s.f_proj.weight", pre) },
|
||||
RAD_SHARD_ROW, grp, { ck("%s.f_proj.weight", "blk.%d.ssm_f_a.weight") },
|
||||
w.input, w.core.a));
|
||||
RAD_ARCH_TRY(gate.declare(b, nm, g, nm.f("blk.%d.attn_gate", l), width, g.n_embd,
|
||||
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
|
||||
RAD_SHARD_ROW, grp, { ck("%s.g_proj.weight", "blk.%d.ssm_g_a.weight") },
|
||||
w.input, w.core.gate));
|
||||
KdaState::Config kc;
|
||||
kc.heads = heads;
|
||||
kc.dim = sh.head_dim;
|
||||
kc.width = sh.conv;
|
||||
kc.lower = sh.lower;
|
||||
KdaState::Src ks{ nm.ckpt("%s.q_conv1d.weight", pre), nm.ckpt("%s.k_conv1d.weight", pre),
|
||||
nm.ckpt("%s.v_conv1d.weight", pre), nm.ckpt("%s.A_log", pre),
|
||||
nm.ckpt("%s.dt_bias", pre), nm.ckpt("%s.o_norm.weight", pre) };
|
||||
KdaState::Src ks{ ck("%s.q_conv1d.weight", "blk.%d.ssm_conv1d_q.weight"),
|
||||
ck("%s.k_conv1d.weight", "blk.%d.ssm_conv1d_k.weight"),
|
||||
ck("%s.v_conv1d.weight", "blk.%d.ssm_conv1d_v.weight"),
|
||||
ck("%s.A_log", "blk.%d.ssm_a_raw"),
|
||||
ck("%s.dt_bias", "blk.%d.ssm_dt.bias"),
|
||||
ck("%s.o_norm.weight", "blk.%d.ssm_norm.weight") };
|
||||
RAD_ARCH_TRY(core.declare(b, nm, g, l, state, history, kc, w.core, ks));
|
||||
const char* on = nm.f("blk.%d.attn_output", l);
|
||||
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.o_proj.weight", pre) }));
|
||||
if (!output.reads_x) RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, width));
|
||||
RAD_ARCH_TRY(output.probe(b, nm, g, on, { ck("%s.o_proj.weight", "blk.%d.attn_output.weight") }));
|
||||
/* The out projection's input codes: on a rotated int8 trunk (ActFP8::q8_fed) an int8 out
|
||||
* projection reads had_quant_act_i8g's, written here; otherwise a quantiser runs only for
|
||||
* a weight that does not read the bf16 plane. */
|
||||
if (w.core_out.q8_fed ? output.probed_i8 : !output.reads_x)
|
||||
RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, width));
|
||||
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, width, RAD_SHARD_COL, grp,
|
||||
{ nm.ckpt("%s.o_proj.weight", pre) }, w.core_out, w.out));
|
||||
{ ck("%s.o_proj.weight", "blk.%d.attn_output.weight") }, w.core_out, w.out));
|
||||
op_ar = GlmTp::reduce(b, g, w.out);
|
||||
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
|
||||
}
|
||||
@@ -131,6 +190,8 @@ struct LingKda {
|
||||
struct LingMla {
|
||||
struct Wire {
|
||||
ActFP8 input{};
|
||||
ActFP8 qa{}; /* [T, q_lora], the tiny query LoRA's normed latent (the trunk's,
|
||||
projected through q_a, for the parts' GEMMs) */
|
||||
rad_buf q_rope = 0; /* [T, heads * rope] */
|
||||
rad_buf q_nope = 0; /* [T, heads * nope] */
|
||||
rad_buf row = 0; /* [T, latent + rope], the cache row */
|
||||
@@ -146,11 +207,11 @@ struct LingMla {
|
||||
int layer = 0;
|
||||
int64_t heads = 0, qw = 0, cw = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
LinearFP8 q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{};
|
||||
QuantFP8 value_quant{};
|
||||
rad_weight kv_gain = 0, kv_b = 0;
|
||||
rad_op op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0, op_absorb = 0, op_attn = 0,
|
||||
op_expand = 0, op_ar = 0;
|
||||
LinearFP8 q_a_proj{}, q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{};
|
||||
QuantFP8 value_quant{}, qa_quant{};
|
||||
rad_weight kv_gain = 0, qa_gain = 0, kv_b = 0;
|
||||
rad_op op_qa_norm = 0, op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0,
|
||||
op_absorb = 0, op_attn = 0, op_expand = 0, op_ar = 0;
|
||||
int64_t block = 0;
|
||||
|
||||
static constexpr int64_t kBlock = 16;
|
||||
@@ -169,7 +230,17 @@ struct LingMla {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
|
||||
/* One row map a part, a piece a head: [h * (nope + rope) + off, + width). Successive ROWS
|
||||
* maps for one name extend it in call order (rad_builder.h), eight pieces a map. */
|
||||
const char* qsrc = nm.ckpt("%s.q_proj.weight", pre);
|
||||
/* flash projects the query from the trunk; tiny runs it through a LoRA first (q_a, its
|
||||
* norm, then q_b), and the parts' rows come off q_b against the normed latent. */
|
||||
const int64_t qk = s.q_lora ? s.q_lora : g.n_embd;
|
||||
const ActFP8& qin = s.q_lora ? w.qa : w.input;
|
||||
auto ck = [&](const char* hf, const char* gg) -> const char* {
|
||||
/* The safetensors names are the layer prefix plus the projection (`pre`, `model.layers.%d`);
|
||||
* the release GGUF spells them blk./ssm. with the layer as %d. */
|
||||
return s.gguf ? nm.ckpt(gg, l) : nm.ckpt(hf, pre);
|
||||
};
|
||||
const char* qsrc = s.q_lora ? ck("%s.q_b_proj.weight", "blk.%d.attn_q_b.weight")
|
||||
: ck("%s.q_proj.weight", "blk.%d.attn_q.weight");
|
||||
auto part = [&](const char* name, int64_t off, int64_t width) -> int {
|
||||
for (int64_t h0 = 0; h0 < s.heads; h0 += 8) {
|
||||
RadNameMap m = map_base(name, RAD_MAP_ROWS);
|
||||
@@ -183,18 +254,49 @@ struct LingMla {
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_rope.weight", l), s.nope, s.rope));
|
||||
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_nope.weight", l), 0, s.nope));
|
||||
if (s.gguf) {
|
||||
/* The reader split the quantised q_b into plain blocks a row map cannot see. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_rope.weight", l),
|
||||
nm.ckpt("blk.%d.attn_q_b_rope.weight", l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_nope.weight", l),
|
||||
nm.ckpt("blk.%d.attn_q_b_nope.weight", l)));
|
||||
} else {
|
||||
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_rope.weight", l), s.nope, s.rope));
|
||||
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_nope.weight", l), 0, s.nope));
|
||||
}
|
||||
if (s.q_lora) {
|
||||
RAD_ARCH_TRY(q_a_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), s.q_lora, g.n_embd,
|
||||
RAD_SHARD_NONE, grp,
|
||||
{ ck("%s.q_a_proj.weight", "blk.%d.attn_q_a.weight") }, w.input, w.qa.x));
|
||||
const char* an = nm.f("blk.%d.attn_q_a_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, an, ck("%s.q_a_layernorm.weight", "blk.%d.attn_q_a_norm.weight")));
|
||||
qa_gain = decl_w(b, an, RAD_F32, { s.q_lora }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp);
|
||||
if (!qa_gain) return RAD_E_INVAL;
|
||||
op_qa_norm = rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", s.q_lora),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(qa_gain)),
|
||||
{ w.qa.x }, { w.qa.x });
|
||||
if (!op_qa_norm) return RAD_E_INVAL;
|
||||
}
|
||||
q_rope_proj.mapped = q_nope_proj.mapped = true;
|
||||
RAD_ARCH_TRY(q_rope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_rope", l), heads * s.rope,
|
||||
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_rope));
|
||||
qk, RAD_SHARD_ROW, grp, { qsrc }, qin, w.q_rope));
|
||||
RAD_ARCH_TRY(q_nope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_nope", l), heads * s.nope,
|
||||
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_nope));
|
||||
qk, RAD_SHARD_ROW, grp, { qsrc }, qin, w.q_nope));
|
||||
/* On a rotated int8 trunk the LoRA's latent carries an int8 pair that a part stored int8
|
||||
* quantises itself (LinearFP8's own had_quant_act_i8g) and no E4M3 pair, so no quantiser
|
||||
* runs here. */
|
||||
if (s.q_lora && !q_nope_proj.reads_x && !w.qa.q8)
|
||||
RAD_ARCH_TRY(qa_quant.declare(b, g, w.qa, s.q_lora));
|
||||
RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), cw, g.n_embd,
|
||||
RAD_SHARD_NONE, grp, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", pre) },
|
||||
RAD_SHARD_NONE, grp,
|
||||
{ ck("%s.kv_a_proj_with_mqa.weight", "blk.%d.attn_kv_a_mqa.weight") },
|
||||
w.input, w.row));
|
||||
const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy(b, kn, ck("%s.kv_a_layernorm.weight", "blk.%d.attn_kv_a_norm.weight")));
|
||||
kv_gain = decl_w(b, kn, RAD_F32, { s.latent }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
|
||||
if (!kv_gain) return RAD_E_INVAL;
|
||||
op_kv_norm = rw(b,
|
||||
@@ -217,7 +319,8 @@ struct LingMla {
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.row }, {});
|
||||
const char* bn = nm.f("blk.%d.attn_kv_b.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.kv_b_proj.weight", pre)));
|
||||
/* The GGUF keeps k_b and v_b head-last; the reader fuses them into this name. */
|
||||
RAD_ARCH_TRY(map_copy(b, bn, ck("%s.kv_b_proj.weight", "blk.%d.attn_kv_b.weight")));
|
||||
kv_b = decl_w(b, bn, RAD_BF16, { heads * (s.nope + s.v_dim), s.latent }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_ROW, grp);
|
||||
if (!op_kv_norm || !op_q_rope || !op_k_rope || !op_store || !kv_b) return RAD_E_INVAL;
|
||||
@@ -229,7 +332,8 @@ struct LingMla {
|
||||
RAD_WEIGHTS(kv_b)),
|
||||
{ w.q_nope }, { w.q_lat });
|
||||
RAD_ARCH_TRY(g_proj.declare(b, nm, g, nm.f("blk.%d.attn_head_gate", l), heads, g.n_embd,
|
||||
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
|
||||
RAD_SHARD_ROW, grp,
|
||||
{ ck("%s.g_proj.weight", "blk.%d.attn_gate.weight") },
|
||||
w.input, w.gate));
|
||||
op_attn = rw(b,
|
||||
RAD_OP(b, "mla_attn_paged",
|
||||
@@ -255,10 +359,12 @@ struct LingMla {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const char* on = nm.f("blk.%d.attn_output", l);
|
||||
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.dense.weight", pre) }));
|
||||
if (!output.reads_x) RAD_ARCH_TRY(value_quant.declare(b, g, w.value, heads * s.v_dim));
|
||||
RAD_ARCH_TRY(output.probe(b, nm, g, on, { ck("%s.dense.weight", "blk.%d.attn_output.weight") }));
|
||||
/* As the KDA out projection's input (LingKda::declare). */
|
||||
if (w.value.q8_fed ? output.probed_i8 : !output.reads_x)
|
||||
RAD_ARCH_TRY(value_quant.declare(b, g, w.value, heads * s.v_dim));
|
||||
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, heads * s.v_dim, RAD_SHARD_COL, grp,
|
||||
{ nm.ckpt("%s.dense.weight", pre) }, w.value, w.out));
|
||||
{ ck("%s.dense.weight", "blk.%d.attn_output.weight") }, w.value, w.out));
|
||||
op_ar = GlmTp::reduce(b, g, w.out);
|
||||
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
|
||||
}
|
||||
@@ -271,8 +377,14 @@ struct LingMla {
|
||||
}
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
q_rope_proj.step(c, w.input, w.q_rope, T);
|
||||
q_nope_proj.step(c, w.input, w.q_nope, T);
|
||||
const ActFP8& qin = s.q_lora ? w.qa : w.input;
|
||||
if (s.q_lora) {
|
||||
q_a_proj.step(c, w.input, w.qa.x, T);
|
||||
RAD_ISSUE_N(c, op_qa_norm, T, brows(w.qa.x, T), RAD_W(qa_gain), brows(w.qa.x, T));
|
||||
qa_quant.step(c, T);
|
||||
}
|
||||
q_rope_proj.step(c, qin, w.q_rope, T);
|
||||
q_nope_proj.step(c, qin, w.q_nope, T);
|
||||
kv_a.step(c, w.input, w.row, T);
|
||||
g_proj.step(c, w.input, w.gate, T);
|
||||
RAD_ISSUE_N(c, op_kv_norm, T, bcol(w.row, 0, s.latent, T), RAD_W(kv_gain),
|
||||
@@ -308,6 +420,11 @@ struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
Shape s{};
|
||||
/* The trunk is rotated int8 (rad_fp8.h's linear_is_w8h or linear_is_wnh), its activation codes
|
||||
* one scale a `trunk_g8` columns: 256 for IQ8R, 128 for the other rotated forms. `norm_fed`:
|
||||
* the block norms write those codes themselves (rmsnorm_had_quant_i8g is served). */
|
||||
bool trunk_rot = false, norm_fed = false;
|
||||
int64_t trunk_g8 = RAD_FP8_BLOCK;
|
||||
std::vector<Layer> layers;
|
||||
rad_kvgroup latent = 0, state = 0, conv = 0;
|
||||
rad_buf x = 0, y = 0, final_hidden = 0, logit_input = 0, logits = 0;
|
||||
@@ -370,6 +487,8 @@ static int read_shape(const RadModelMeta* meta, Shape& s) {
|
||||
s.dense_layers = cfg(meta, "first_k_dense_replace", 0);
|
||||
s.group_size = cfg(meta, "layer_group_size", 0);
|
||||
s.conv = cfg(meta, "short_conv_kernel_size", 0);
|
||||
s.q_lora = cfg(meta, "q_lora_rank", 0);
|
||||
s.gguf = cfg(meta, "gguf_source", 0) != 0;
|
||||
s.lower = rad_meta_getf(meta, "kda_lower_bound", 0.0);
|
||||
s.route_scale = rad_meta_getf(meta, "routed_scaling_factor", 0.0);
|
||||
s.lim_exp = cfg_list(meta, "expert_swiglu_limit_list");
|
||||
@@ -382,7 +501,11 @@ static int read_shape(const RadModelMeta* meta, Shape& s) {
|
||||
{ "qk_nope_head_dim == v_head_dim (mla_project's head)", s.nope > 0 && s.nope == s.v_dim },
|
||||
{ "an even qk_rope_head_dim", s.rope > 0 && !(s.rope & 1) },
|
||||
{ "an even kv_lora_rank + qk_rope_head_dim", s.latent > 0 && !((s.latent + s.rope) & 1) },
|
||||
{ "q_lora_rank null", cfg(meta, "q_lora_rank", 0) == 0 },
|
||||
{ "q_lora_rank null, or 256 for the tiny family's query LoRA",
|
||||
s.q_lora == 0 || s.q_lora == 256 },
|
||||
{ "the tiny family's query LoRA in a GGUF release (the reader splits its quantised q_b; "
|
||||
"a full-rank attn_q has no GGUF path)",
|
||||
!s.gguf || s.q_lora != 0 },
|
||||
{ "no_kda_lora", cfg(meta, "no_kda_lora", 0) != 0 },
|
||||
{ "kda_safe_gate", cfg(meta, "kda_safe_gate", 1) != 0 },
|
||||
{ "a negative kda_lower_bound", s.lower < 0 && std::isfinite(s.lower) },
|
||||
@@ -423,18 +546,38 @@ static void slice_of(int64_t blocks, int world, int rank, int first, int64_t* lo
|
||||
|
||||
/* ============================== The trunk's buffers ============================== */
|
||||
|
||||
/* The activation code pairs follow the trunk's form (the file's head comment). On a rotated int8
|
||||
* trunk every pair is int8 at the trunk's group and is declared before the wires are copied, so
|
||||
* each block sees whether its producer writes the codes (ActFP8::q8_fed): the norms where
|
||||
* `norm_fed`, the out projections' quantisers always, the gated products where gated_had_quant_i8g
|
||||
* is served (ActFP8::declare_pair). A producer whose rotating form is not served keeps an E4M3 pair
|
||||
* that no linear reads, and each int8 linear then quantises the bf16 plane itself. */
|
||||
static int buffers(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
auto& s = m.s;
|
||||
auto& nm = m.nm;
|
||||
const int64_t T = g.max_tok, E = g.n_embd, H = s.heads / g.world, W = H * s.head_dim;
|
||||
const bool rot = m.trunk_rot;
|
||||
const int64_t g8 = m.trunk_g8;
|
||||
auto bf = [&](const char* n, std::initializer_list<int64_t> shape) {
|
||||
return decl_b(b, nm.f("%s", n), RAD_BF16, shape);
|
||||
};
|
||||
/* A rotated int8 trunk's pair on `a`, written by its producer (`fed`) or by each int8 linear
|
||||
* reading it. */
|
||||
auto i8_pair = [&](ActFP8& a, const char* n, int64_t width, bool fed) -> int {
|
||||
RAD_ARCH_TRY(a.declare_qs(b, nm, g, n, width, 0, true, false, g8));
|
||||
a.q8_fed = a.q8_rot = fed;
|
||||
return RAD_OK;
|
||||
};
|
||||
m.x = bf("residual", { T, E });
|
||||
m.y = bf("attn_delta", { T, E });
|
||||
m.act.x = bf("normed", { T, E });
|
||||
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E));
|
||||
if (rot) {
|
||||
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E, 0, true, !m.norm_fed, g8));
|
||||
m.act.q8_fed = m.act.q8_rot = m.norm_fed;
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E));
|
||||
}
|
||||
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, E }, RAD_BUF_PERSIST);
|
||||
m.logit_input = bf("logit_input", { g.max_logit_rows, E });
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
|
||||
@@ -450,7 +593,10 @@ static int buffers(RadBuilder* b, Model& m) {
|
||||
kw.core.gate = bf("kda_gate", { T, W });
|
||||
kw.core.out = bf("kda_out", { T, W });
|
||||
kw.core_out.x = kw.core.out;
|
||||
RAD_ARCH_TRY(kw.core_out.declare_qs(b, nm, g, "kda_out", W));
|
||||
if (rot)
|
||||
RAD_ARCH_TRY(i8_pair(kw.core_out, "kda_out", W, true));
|
||||
else
|
||||
RAD_ARCH_TRY(kw.core_out.declare_qs(b, nm, g, "kda_out", W));
|
||||
|
||||
auto& aw = m.aw;
|
||||
aw.input = m.act;
|
||||
@@ -461,19 +607,35 @@ static int buffers(RadBuilder* b, Model& m) {
|
||||
aw.q_lat = bf("mla_q_latent", { T, H * s.latent });
|
||||
aw.gate = bf("mla_gate", { T, H });
|
||||
aw.attn = bf("mla_attn_latent", { T, H * s.latent });
|
||||
if (s.q_lora) {
|
||||
aw.qa.x = bf("mla_q_a", { T, s.q_lora });
|
||||
if (rot)
|
||||
RAD_ARCH_TRY(i8_pair(aw.qa, "mla_q_a", s.q_lora, false));
|
||||
else
|
||||
RAD_ARCH_TRY(aw.qa.declare_qs(b, nm, g, "mla_q_a", s.q_lora));
|
||||
}
|
||||
aw.value.x = bf("mla_value", { T, H * s.v_dim });
|
||||
RAD_ARCH_TRY(aw.value.declare_qs(b, nm, g, "mla_value", H * s.v_dim));
|
||||
if (rot)
|
||||
RAD_ARCH_TRY(i8_pair(aw.value, "mla_value", H * s.v_dim, true));
|
||||
else
|
||||
RAD_ARCH_TRY(aw.value.declare_qs(b, nm, g, "mla_value", H * s.v_dim));
|
||||
|
||||
auto& dw = m.dw;
|
||||
dw.x = m.x;
|
||||
dw.h = m.act;
|
||||
dw.gate_up = bf("dense_gate_up", { T, 2 * g.n_ff });
|
||||
dw.ffn.x = bf("dense_ff", { T, g.n_ff });
|
||||
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
|
||||
if (rot)
|
||||
RAD_ARCH_TRY(dw.ffn.declare_pair(b, nm, g, "dense_ff", g.n_ff, 0, true, g8,
|
||||
"gated_had_quant_i8g"));
|
||||
else
|
||||
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
|
||||
/* `shared_g8`: on a rotated int8 trunk, the scale group of the shared expert's stored down weight,
|
||||
* which its input codes take. */
|
||||
static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc, int64_t shared_g8) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
const int64_t T = g.max_tok, E = g.n_embd, F = mc.n_ff_exp, k = mc.top_k;
|
||||
@@ -491,9 +653,25 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
|
||||
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * k });
|
||||
mw.egu = bf("expert_gate_up", { T * k, 2 * F });
|
||||
mw.eff.x = bf("expert_ff", { T * k, F });
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k));
|
||||
if (m.trunk_rot) {
|
||||
/* The routed arm of a rotated trunk is int8 throughout: the gated product's rotated codes
|
||||
* at one scale a 128 of K, which the grouped GEMM's int8 rows read (MoeFP8::a8). */
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
mw.eff.q8_fed = mw.eff.q8_rot = true;
|
||||
} else {
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k));
|
||||
}
|
||||
mw.edn = bf("expert_down", { T * k, E });
|
||||
if (mc.expert_rot) {
|
||||
if (m.trunk_rot) {
|
||||
/* The routed gate_up reads the norm's own codes where it writes them, else a rotated int8
|
||||
* copy of the block input that MoeFP8 writes once a layer (Wire::hr). */
|
||||
if (!m.norm_fed) {
|
||||
RAD_ARCH_TRY(mw.hr.declare_qs(b, nm, g, "normed_rot", E, 0, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
mw.hr.q8_fed = mw.hr.q8_rot = true;
|
||||
}
|
||||
} else if (mc.expert_rot) {
|
||||
mw.hr.q = decl_b(b, nm.f("normed_rot.q"), RAD_F8E4M3, { T, E });
|
||||
mw.hr.s = decl_b(b, nm.f("normed_rot.s"), RAD_F32, { T, E / RAD_FP8_BLOCK });
|
||||
if (!mw.hr.q || !mw.hr.s) return RAD_E_INVAL;
|
||||
@@ -501,7 +679,11 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
|
||||
if (mc.n_ff_shared > 0) {
|
||||
mw.sgu = bf("shared_gate_up", { T, 2 * mc.n_ff_shared });
|
||||
mw.sff.x = bf("shared_ff", { T, mc.n_ff_shared });
|
||||
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", mc.n_ff_shared));
|
||||
if (m.trunk_rot)
|
||||
RAD_ARCH_TRY(mw.sff.declare_pair(b, nm, g, "shared_ff", mc.n_ff_shared, 0, true,
|
||||
shared_g8, "gated_had_quant_i8g"));
|
||||
else
|
||||
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", mc.n_ff_shared));
|
||||
mw.sout = bf("shared_out", { T, E });
|
||||
mw.sgate = bf("shared_one", { T, 1 });
|
||||
}
|
||||
@@ -614,11 +796,23 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ms.cfg = mc;
|
||||
ms.cfg.swiglu_limit = limit_at(s.lim_exp, l);
|
||||
ms.cfg.shared_swiglu_limit = limit_at(s.lim_shared, l);
|
||||
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.mlp.gate.weight", pre);
|
||||
ms.router_bias = nm.ckpt("%s.mlp.gate.expert_bias", pre);
|
||||
ms.experts = nm.ckpt("%s.mlp.experts", pre);
|
||||
ms.shared = nm.ckpt("%s.mlp.shared_experts", pre);
|
||||
ms.norm = s.gguf ? nm.ckpt("blk.%d.ffn_norm.weight", l)
|
||||
: nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ms.router = s.gguf ? nm.ckpt("blk.%d.ffn_gate_inp.weight", l)
|
||||
: nm.ckpt("%s.mlp.gate.weight", pre);
|
||||
ms.router_bias = s.gguf ? nm.ckpt("blk.%d.exp_probs_b.bias", l)
|
||||
: nm.ckpt("%s.mlp.gate.expert_bias", pre);
|
||||
if (s.gguf) {
|
||||
/* The release GGUF stacks the experts expert-last, the block's split-stacked
|
||||
* source slicing one expert off each: [E, ff, emb] gate and up, [E, emb, ff] down. */
|
||||
ms.experts_gate = nm.ckpt("blk.%d.ffn_gate_exps.weight", l);
|
||||
ms.experts_up = nm.ckpt("blk.%d.ffn_up_exps.weight", l);
|
||||
ms.experts_down = nm.ckpt("blk.%d.ffn_down_exps.weight", l);
|
||||
} else {
|
||||
ms.experts = nm.ckpt("%s.mlp.experts", pre);
|
||||
}
|
||||
ms.shared = s.gguf ? nm.ckpt("blk.%d.mlp.shared_experts", l)
|
||||
: nm.ckpt("%s.mlp.shared_experts", pre);
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, ms, &ms.cfg));
|
||||
if (ms.cfg.expert_rot) mc.expert_rot = 1;
|
||||
if (ms.cfg.expert_bf16) mc.expert_bf16 = 1;
|
||||
@@ -645,8 +839,66 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
g.rank, (long long)mc.expert_base, (long long)(mc.expert_base + per),
|
||||
(long long)s.experts);
|
||||
}
|
||||
|
||||
/* ---- the trunk's stored form, read from layer 0's fused q|k|v through that layer's own
|
||||
* LinearFP8 (layer 0 is KDA: the last of each group of `layer_group_size` > 1 is MLA). The
|
||||
* activations below carry rotated int8 codes only for a rotated trunk. */
|
||||
m.layers.resize((size_t)s.n_layer);
|
||||
RAD_ARCH_TRY(m.layers[0].kda.probe_qkv(b, nm, g, s, 0,
|
||||
nm.ckpt("%s.attention", nm.ckpt("model.layers.%d", 0))));
|
||||
{
|
||||
RadEncoding enc{};
|
||||
m.trunk_rot = weight_enc(b, nm.f("blk.0.attn_qkv.weight"), &enc) &&
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
if (m.trunk_rot) m.trunk_g8 = linear_w8h_group(enc);
|
||||
}
|
||||
int64_t shared_g8 = m.trunk_g8;
|
||||
if (m.trunk_rot) {
|
||||
/* The routed experts read the trunk's rotated int8 codes (MoeFP8::a8), which only a
|
||||
* rotated expert meets; and the int8 gated products have no clamped form. */
|
||||
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
|
||||
const MoeFP8::Config& c = msrc[(size_t)l].cfg;
|
||||
if (c.expert_bf16 || !c.expert_rot) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: the trunk is rotated int8 and layer %d's "
|
||||
"routed experts are %s; a rotated trunk's experts read its int8 codes "
|
||||
"and are stored rotated (data/recipes/ling-3.0-tiny-iq8r.recipe)\n",
|
||||
l, c.expert_bf16 ? "plain bf16" : "unrotated");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (c.swiglu_limit > 0 || c.shared_swiglu_limit > 0) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: layer %d clamps its SwiGLU (routed %g, "
|
||||
"shared %g) and the trunk is rotated int8, whose gated products "
|
||||
"write int8 codes with no clamped form; this checkpoint is served "
|
||||
"with a bf16 or four-bit trunk\n",
|
||||
l, c.swiglu_limit, c.shared_swiglu_limit);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
m.norm_fed = rad_op_declared(b, "rmsnorm_had_quant_i8g") != 0;
|
||||
/* The shared expert's down projection is a trunk linear whose input codes take the group
|
||||
* its own weight is stored at, read from the first routed layer's through that layer's
|
||||
* own LinearFP8 (which MoeFP8 then does not map again). */
|
||||
const int lm = (int)s.dense_layers;
|
||||
if (lm < (int)s.n_layer && mc.n_ff_shared > 0) {
|
||||
LinearFP8& sd = m.layers[(size_t)lm].moe.sh_down;
|
||||
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.%d.ffn_down_shexp", lm),
|
||||
{ nm.ckpt("%s.down_proj.weight", msrc[(size_t)lm].shared) }));
|
||||
if (sd.probed_i8) shared_g8 = sd.probed_g8;
|
||||
}
|
||||
} else {
|
||||
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
|
||||
const MoeFP8::Config& c = msrc[(size_t)l].cfg;
|
||||
if (c.expert_i8 || c.expert_iqr) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: layer %d's routed experts are rotated "
|
||||
"int8 and the trunk is not; they read the trunk's rotated int8 codes, "
|
||||
"so convert the trunk with them "
|
||||
"(data/recipes/ling-3.0-tiny-iq8r.recipe)\n", l);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(buffers(b, m));
|
||||
RAD_ARCH_TRY(moe_buffers(b, m, mc));
|
||||
RAD_ARCH_TRY(moe_buffers(b, m, mc, shared_g8));
|
||||
|
||||
/* ---- the caches: the MLA layers' latent rows, the KDA layers' state and convolution
|
||||
* history. */
|
||||
@@ -674,9 +926,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
/* ---- the embedding, the layers, the final norm and the head. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.word_embeddings.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
/* The release GGUF already spells the head tensors under the container's names; the first
|
||||
* source the container holds wins. */
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("token_embd.weight"), nm.ckpt("model.word_embeddings.weight"),
|
||||
nm.ckpt("token_embd.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("output.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"),
|
||||
nm.ckpt("output_norm.weight")));
|
||||
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, g.n_embd },
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, g.n_embd }, RAD_ACCESS_VOCAB,
|
||||
@@ -699,7 +956,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
lay.dense = l < s.dense_layers;
|
||||
const char* pre = nm.ckpt("model.layers.%d", l);
|
||||
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy(b, nn, s.gguf ? nm.ckpt("blk.%d.attn_norm.weight", l)
|
||||
: nm.ckpt("%s.input_layernorm.weight", pre)));
|
||||
lay.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
RAD_ARCH_TRY(lay.norm.declare(b, g, lay.gain, m.x, m.act, g.n_embd));
|
||||
@@ -719,10 +977,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{ m.x, m.y }, { m.x });
|
||||
if (!lay.op_add) return RAD_E_INVAL;
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
|
||||
nm.ckpt("%s.mlp.gate_proj.weight", pre),
|
||||
nm.ckpt("%s.mlp.up_proj.weight", pre),
|
||||
nm.ckpt("%s.mlp.down_proj.weight", pre) };
|
||||
MlpFP8::Src ds{ s.gguf ? nm.ckpt("blk.%d.ffn_norm.weight", l)
|
||||
: nm.ckpt("%s.post_attention_layernorm.weight", pre),
|
||||
s.gguf ? nm.ckpt("blk.%d.ffn_gate.weight", l)
|
||||
: nm.ckpt("%s.mlp.gate_proj.weight", pre),
|
||||
s.gguf ? nm.ckpt("blk.%d.ffn_up.weight", l)
|
||||
: nm.ckpt("%s.mlp.up_proj.weight", pre),
|
||||
s.gguf ? nm.ckpt("blk.%d.ffn_down.weight", l)
|
||||
: nm.ckpt("%s.mlp.down_proj.weight", pre) };
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, l, m.dw, ds));
|
||||
} else {
|
||||
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, m.mw, msrc[(size_t)l]));
|
||||
@@ -780,10 +1042,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
rad_note(b,
|
||||
"Ling-3.0 (bailing_hybrid): TP%d, %lld layers, %lld KDA + %lld dense MLA, %lld experts "
|
||||
"top-%lld in %lld groups (%lld kept), MTP %s",
|
||||
"top-%lld in %lld groups (%lld kept), MTP %s, %s trunk",
|
||||
world, (long long)s.n_layer, (long long)(s.n_layer - s.n_layer / s.group_size),
|
||||
(long long)(s.n_layer / s.group_size), (long long)s.experts, (long long)s.top_k,
|
||||
(long long)s.groups, (long long)s.topk_groups, m.have_mtp ? "enabled" : "not declared");
|
||||
(long long)s.groups, (long long)s.topk_groups, m.have_mtp ? "enabled" : "not declared",
|
||||
!m.trunk_rot ? "unrotated"
|
||||
: m.trunk_g8 == RAD_I8_GROUP_WIDE ? "IQ8R (rotated int8)" : "rotated int8");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -879,10 +1143,36 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
} /* namespace bailing_hybrid */
|
||||
|
||||
/* The GGUF release wrappers (arch/bailing_hybrid_gguf* and kin) define these to their file's
|
||||
* `general.file_type` and plugin name and include the file; the base plugin keeps the empty
|
||||
* quant. The name is spelled by a macro, not by RAD_ARCH_PLUGIN's stringifier: a macro argument
|
||||
* that reaches `#` expands as written, and a wrapper that only renames the namespace would ship
|
||||
* five plugins all called "bailing_hybrid". */
|
||||
#ifndef BAILING_HYBRID_QUANT
|
||||
#define BAILING_HYBRID_QUANT ""
|
||||
#endif
|
||||
#ifndef BAILING_HYBRID_PLUGIN
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid"
|
||||
#endif
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(bailing_hybrid)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(bailing_hybrid, "bailinghybrid", "", "0.1.0",
|
||||
"Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts")
|
||||
extern "C" const char* rad_arch_id(void) { return "bailinghybrid"; }
|
||||
extern "C" const char* rad_arch_quant(void) { return BAILING_HYBRID_QUANT; }
|
||||
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
|
||||
return bailing_hybrid::declare(b, m, c);
|
||||
}
|
||||
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
|
||||
bailing_hybrid::step(c, batch);
|
||||
}
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
extern "C" uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); }
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) {
|
||||
static const RadPluginInfo info = {
|
||||
RAD_PLUGIN_ARCH, BAILING_HYBRID_PLUGIN, "0.1.0",
|
||||
"Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts", "" };
|
||||
return &info;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf -- the GGUF variant of bailing_hybrid for the tiny family's IQ4_NL release: the same
|
||||
* declaration and step, claiming the ftype-25 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_25"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q4km -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q4km LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q4km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q4km.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q4km -- the GGUF variant of bailing_hybrid for the tiny family's Q4_K_M release: the same
|
||||
* declaration and step, claiming the ftype-15 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q4km
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q4km"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_15"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q5km -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q5km LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q5km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q5km.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q5km -- the GGUF variant of bailing_hybrid for the tiny family's Q5_K_M release: the same
|
||||
* declaration and step, claiming the ftype-17 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q5km
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q5km"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_17"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q6k -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q6k LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q6k architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q6k.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q6k -- the GGUF variant of bailing_hybrid for the tiny family's Q6_K release: the same
|
||||
* declaration and step, claiming the ftype-18 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q6k
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q6k"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_18"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q80 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q80 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q80 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q80.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q80 -- the GGUF variant of bailing_hybrid for the tiny family's Q8_0 release: the same
|
||||
* declaration and step, claiming the ftype-7 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q80
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q80"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_7"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
+138
-30
@@ -1,8 +1,9 @@
|
||||
/* breeze -- Breeze-TTS-2: speech from text, with an optional description of the voice; 24 kHz mono.
|
||||
/* breeze -- Breeze-TTS-2: speech from text, voice design or a reference recording; 24 kHz mono.
|
||||
*
|
||||
* ============================== THE MODEL ==============================
|
||||
*
|
||||
* Four networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer):
|
||||
* Four generation networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer),
|
||||
* plus the reference-audio encoder in reference.h for voice cloning:
|
||||
*
|
||||
* Text encoder: T5Gemma 2's text encoder, Gemma 3 1B's shape (26 layers of 1152, 4 query heads
|
||||
* over one KV head of 256, gelu-tanh GLU 6912, sandwich RMS norms with a (1 + w) gain), read
|
||||
@@ -85,6 +86,8 @@ constexpr int64_t kVocChunk = 4, kConvCtx = 12, kAttnWin = 72;
|
||||
constexpr int64_t kVocContext = 2 + (kAttnWin - 1) + kConvCtx;
|
||||
constexpr int64_t kConvFrames = kConvCtx + kVocChunk;
|
||||
constexpr int64_t kCbBins = 2048, kCbDim = 256;
|
||||
/* One clean reference of at most ten seconds (rounded to complete codec frames). */
|
||||
constexpr int64_t kMaxRefFrames = 125, kMaxRefSamples = kMaxRefFrames * kSamplesPerFrame;
|
||||
/* The codec's sequence rates, rows a frame: the transformer's frames, the convolutions' frames,
|
||||
* the two upsamplings', and each decoder block's output (8, 5, 4, 3 times). */
|
||||
constexpr int kRates = 8;
|
||||
@@ -160,7 +163,34 @@ struct Llama3 {
|
||||
double factor = 0, low = 0, high = 0, orig = 0;
|
||||
};
|
||||
|
||||
struct RefConv {
|
||||
rad_weight w = 0, b = 0;
|
||||
rad_op op = 0;
|
||||
};
|
||||
struct RefLayer {
|
||||
rad_weight n1 = 0, b1 = 0, n2 = 0, b2 = 0, qkv = 0, o = 0, fc1 = 0, fc2 = 0;
|
||||
rad_weight ls1 = 0, ls2 = 0;
|
||||
rad_op norm1 = 0, norm2 = 0, proj = 0, rope = 0, attn = 0, out = 0;
|
||||
rad_op f1 = 0, act = 0, f2 = 0, scale1 = 0, scale2 = 0, add1 = 0, add2 = 0;
|
||||
};
|
||||
struct Reference {
|
||||
RefConv first{}, res1[4]{}, res2[4]{}, down[4]{}, last{}, sample{};
|
||||
rad_buf x[5]{}, a[5]{}, h[4]{}, z = 0, pad = 0, sampled = 0;
|
||||
rad_op elu[5]{}, elu_h[4]{};
|
||||
rad_buf th = 0, qkv = 0, attn = 0, o = 0, ff = 0, act = 0;
|
||||
RefLayer layer[8]{};
|
||||
rad_buf index = 0, cu = 0, text_pos = 0, text_cu = 0;
|
||||
rad_op indices = 0, copy_i = 0, copy_f = 0, text_indices = 0;
|
||||
rad_buf q[2]{}, codes = 0, eos_codes = 0;
|
||||
rad_weight qi[2]{}, cb[16]{};
|
||||
rad_op project[2]{}, quant[16]{}, embed = 0, eos = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Reference ref{};
|
||||
/* The model holds the reference encoder (reference_stored), whose first weight is then already
|
||||
* in the name map. */
|
||||
bool ref_stored = false;
|
||||
Names nm{""};
|
||||
Llama3 l3{};
|
||||
Geom ge{}, gl{}, gd{}; /* the text encoder's, the backbone's, the depth decoder's */
|
||||
@@ -1183,6 +1213,8 @@ static int check_format(const RadModelMeta* meta) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#include "reference.h"
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
@@ -1214,6 +1246,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(declare_encoder(b, meta, m));
|
||||
RAD_ARCH_TRY(declare_frame(b, meta, m));
|
||||
RAD_ARCH_TRY(declare_codec(b, meta, m));
|
||||
/* A container converted before the reference encoder was in the recipe holds the generator
|
||||
* alone: it serves speech as before, and with no reference templates declared below the
|
||||
* server refuses a request that brings references, saying the model clones no voice. */
|
||||
m.ref_stored = reference_stored(b, m);
|
||||
if (m.ref_stored) RAD_ARCH_TRY(declare_reference(b, meta, m));
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadAudioGenDecl d{};
|
||||
@@ -1221,6 +1258,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.tmpl = kTemplate;
|
||||
d.tmpl_plain = kPlain;
|
||||
d.neg_tmpl = kPlain;
|
||||
d.branches = 2;
|
||||
if (m.ref_stored) {
|
||||
d.tmpl_ref = "{references}<bos>[S0]{input}";
|
||||
d.tmpl_ref_instruct = "{references}<bos>[S0]<ins_bos>{instructions}<ins_eos>{input}";
|
||||
d.neg_tmpl_ref = d.tmpl_ref;
|
||||
d.ref_item = "<bos>[S0]{text}{audio}<|audio_eos|>";
|
||||
d.ref_rate = kSampleRate;
|
||||
d.ref_hop = kSamplesPerFrame;
|
||||
d.ref_max_samples = kMaxRefSamples;
|
||||
d.ref_max = 1;
|
||||
}
|
||||
d.prompt_whole = 1;
|
||||
d.first_frame = 0;
|
||||
d.max_prompt = kMaxPrompt;
|
||||
@@ -1267,34 +1315,91 @@ static void step_backbone(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
m.b_h2, m.b_gu, m.b_ff, pos, cu, layer++);
|
||||
}
|
||||
|
||||
static void step_text(RadCtx* c, const Model& m, int64_t T, RadOperand tokens,
|
||||
RadOperand pos, RadOperand cu, RadOperand output) {
|
||||
const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim;
|
||||
/* The encoder over each branch's prompt, bidirectional within it; its projection is the
|
||||
* backbone's input. */
|
||||
RAD_ISSUE_N(c, m.op_eembed, T, tokens, RAD_W(m.w_etok),
|
||||
brows(m.b_ex, T));
|
||||
for (const EncLayer& L : m.enc) {
|
||||
RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_qkv, T, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T));
|
||||
RAD_ISSUE_N(c, L.op_qknr, T, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn));
|
||||
RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T),
|
||||
bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T));
|
||||
RAD_ISSUE_N(c, L.op_o, T, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T));
|
||||
RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
RAD_ISSUE_N(c, L.op_n3, T, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_gu, T, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T));
|
||||
RAD_ISSUE_N(c, L.op_act, T, brows(m.b_egu, T), brows(m.b_eff, T));
|
||||
RAD_ISSUE_N(c, L.op_down, T, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T));
|
||||
RAD_ISSUE_N(c, L.op_n4, T, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_enorm, T, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, m.op_eproj, T, brows(m.b_eh, T), RAD_W(m.w_eproj), output);
|
||||
}
|
||||
|
||||
/* rvq_embed reads codebook 0 from its first table and codebooks 1..15 from its
|
||||
* second table, whose row zero must therefore be the start of codebook 1. */
|
||||
static RadOperand residual_codebooks(const Model& m) {
|
||||
RadOperand t = RAD_W(m.w_cb);
|
||||
t.offset = (int64_t)kVocab * m.gl.n_embd;
|
||||
t.rows = (int64_t)(kCodes - 1) * kVocab;
|
||||
return t;
|
||||
}
|
||||
|
||||
static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadAudioGenBatch* A = batch->agen_b;
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim;
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1);
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
/* The encoder over each branch's prompt, bidirectional within it; its projection is the
|
||||
* backbone's input. */
|
||||
RAD_ISSUE(c, m.op_eembed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_etok),
|
||||
brows(m.b_ex, T));
|
||||
for (const EncLayer& L : m.enc) {
|
||||
RAD_ISSUE(c, L.op_n1, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_qkv, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T));
|
||||
RAD_ISSUE(c, L.op_qknr, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn));
|
||||
RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T),
|
||||
bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T));
|
||||
RAD_ISSUE(c, L.op_o, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T));
|
||||
RAD_ISSUE(c, L.op_n2, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_add1, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
RAD_ISSUE(c, L.op_n3, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_gu, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T));
|
||||
RAD_ISSUE(c, L.op_act, brows(m.b_egu, T), brows(m.b_eff, T));
|
||||
RAD_ISSUE(c, L.op_down, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T));
|
||||
RAD_ISSUE(c, L.op_n4, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_add2, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
if (A->n_ref) {
|
||||
if (!A->prompt_cu_h || A->prompt_cu_h[0] != 0 ||
|
||||
A->prompt_cu_h[batch->n_seq] != T) {
|
||||
rad_step_fail(c, "breeze: reference prompt needs its host branch boundaries");
|
||||
return;
|
||||
}
|
||||
step_reference(c, batch, m);
|
||||
const Reference& E = m.ref;
|
||||
RAD_ISSUE_N(c, E.text_indices, kMaxPrompt, brows(E.text_pos, kMaxPrompt));
|
||||
RAD_ISSUE_N(c, E.eos, 16, brows(E.eos_codes, 16));
|
||||
/* Each branch has two independent text-encoder segments around its audio. The
|
||||
* backbone alone attends across the concatenation. Never encode audio placeholders
|
||||
* or the audio EOS as text, and reset rotary positions for each text segment. */
|
||||
for (int64_t branch = 0; branch < batch->n_seq; ++branch) {
|
||||
const int64_t end = A->prompt_cu_h[branch + 1];
|
||||
for (int64_t t = A->prompt_cu_h[branch]; t < end;) {
|
||||
const int32_t f = A->ref_frame_h[t];
|
||||
if (f >= 0) {
|
||||
int64_t n = 1;
|
||||
while (t + n < end && A->ref_frame_h[t + n] == f + n) ++n;
|
||||
if (t + n >= end) {
|
||||
rad_step_fail(c, "breeze: reference frames need their audio EOS row");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, E.embed, n, bcol(E.codes, f, n, 16), RAD_W(m.w_cb),
|
||||
residual_codebooks(m), brow_slice(m.b_x, t, n, m.gl.n_embd));
|
||||
t += n;
|
||||
RAD_ISSUE_N(c, E.embed, 1, brows(E.eos_codes, 16), RAD_W(m.w_cb),
|
||||
residual_codebooks(m), brow_slice(m.b_x, t, 1, m.gl.n_embd));
|
||||
++t;
|
||||
} else {
|
||||
int64_t n = 1;
|
||||
while (t + n < end && A->ref_frame_h[t + n] < 0) ++n;
|
||||
ref_bounds(c, E, E.text_cu, n);
|
||||
step_text(c, m, n, praw(batch->token_ids + t, RAD_I32, n),
|
||||
brows(E.text_pos, n), brows(E.text_cu, 2),
|
||||
brow_slice(m.b_x, t, n, m.gl.n_embd));
|
||||
t += n;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
step_text(c, m, T, praw(batch->token_ids, RAD_I32, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(m.b_x, T));
|
||||
}
|
||||
RAD_ISSUE(c, m.op_enorm, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, m.op_eproj, brows(m.b_eh, T), RAD_W(m.w_eproj), brows(m.b_x, T));
|
||||
step_backbone(c, batch, m);
|
||||
bool any_last = false;
|
||||
for (int64_t i = 0; i < A->n_lane; ++i) any_last = any_last || A->last_h[i];
|
||||
@@ -1358,10 +1463,8 @@ static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
/* 3. the frame into its lane's history, and the backbone over the frame's embedding */
|
||||
RAD_ISSUE_N(c, m.op_store, n, brows(m.b_codes, kCodes), lanes, frame,
|
||||
brows(m.b_status, m.lanes), brows(m.b_codes_all, m.lanes * kCodes));
|
||||
RadOperand t1 = RAD_W(m.w_cb);
|
||||
t1.offset = (int64_t)kVocab * D;
|
||||
t1.rows = (int64_t)(kCodes - 1) * kVocab;
|
||||
RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), t1, brows(m.b_x, S));
|
||||
RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), residual_codebooks(m),
|
||||
brows(m.b_x, S));
|
||||
step_backbone(c, batch, m);
|
||||
store_hidden(c, m, A, S, A->last_row, S);
|
||||
}
|
||||
@@ -1504,6 +1607,11 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
if (!in) return RAD_E_INVAL;
|
||||
std::string r = in;
|
||||
if (field == RAD_TEXT_REFERENCE) {
|
||||
for (const char* marker : {"<bos>", "<eos>", "<|AUDIO|>", "<|audio_eos|>",
|
||||
"<ins_bos>", "<ins_eos>"})
|
||||
if (r.find(marker) != std::string::npos) return RAD_E_INVAL;
|
||||
}
|
||||
if (field == RAD_TEXT_INSTRUCTIONS) {
|
||||
const size_t a = r.find_first_not_of(" \t\r\n"), z = r.find_last_not_of(" \t\r\n");
|
||||
r = a == std::string::npos ? std::string() : r.substr(a, z - a + 1);
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
/* Breeze's Qwen3-TTS/Mimi reference encoder. Included inside namespace breeze after the
|
||||
* ordinary networks. Kept in f32, as the released audio tokenizer encodes references. */
|
||||
static rad_op ref_rows(RadBuilder* b, const char* op, int64_t rows, int64_t n,
|
||||
std::initializer_list<rad_buf> in, std::initializer_list<rad_buf> out,
|
||||
const char* dtype = "f32") {
|
||||
return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", dtype)), RAD_NOWEIGHTS), in, out);
|
||||
}
|
||||
|
||||
static rad_op ref_gemm(RadBuilder* b, int64_t rows, int64_t n, int64_t k, rad_weight w,
|
||||
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", "f32")), RAD_WEIGHTS(w)), {x}, {y});
|
||||
}
|
||||
|
||||
static int ref_conv(RadBuilder* b, Model& m, RefConv& C, const char* name, const char* src,
|
||||
int64_t ci, int64_t co, int64_t k, int64_t st, int64_t rate, int64_t rows,
|
||||
rad_buf x, rad_buf res, rad_buf y, bool bias = true) {
|
||||
/* The first convolution's weight is mapped by reference_stored when that ran. */
|
||||
C.w = (m.ref_stored && &C == &m.ref.first)
|
||||
? decl_w(b, m.nm.f("ref.%s.weight", name), RAD_F32, {co, ci, k}, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(kGrpCodec + 1))
|
||||
: wcopy(b, m.nm, m.nm.f("ref.%s.weight", name), m.nm.ckpt("%s.weight", src),
|
||||
RAD_F32, {co, ci, k}, kGrpCodec + 1);
|
||||
if (bias) C.b = wcopy(b, m.nm, m.nm.f("ref.%s.bias", name), m.nm.ckpt("%s.bias", src),
|
||||
RAD_F32, {co}, kGrpCodec + 1);
|
||||
const rad_weight weights[] = {C.w, C.b};
|
||||
C.op = rw(b, RAD_OP(b, "conv1d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", ci),
|
||||
RAD_INT("cout", co), RAD_INT("k", k), RAD_INT("dil", 1),
|
||||
RAD_INT("causal", 1), RAD_INT("stride", st), RAD_INT("cu_div", rate),
|
||||
RAD_STR("dtype", "f32")), weights, bias ? 2 : 1),
|
||||
{x, m.ref.cu, res}, {y});
|
||||
return C.w && (!bias || C.b) && C.op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Whether the model holds the reference encoder, asked of its first convolution through the name
|
||||
* map entry declared here (the one ref_conv would declare). A builder with no model behind it
|
||||
* answers no. */
|
||||
static bool reference_stored(RadBuilder* b, Model& m) {
|
||||
const std::string dn = m.nm.f("ref.first.weight");
|
||||
if (map_copy(b, dn.c_str(),
|
||||
m.nm.ckpt("%s.weight", "audio_tokenizer.encoder.encoder.layers.0.conv")) < 0)
|
||||
return false;
|
||||
RadEncoding enc{};
|
||||
return weight_enc(b, dn.c_str(), &enc);
|
||||
}
|
||||
|
||||
static int declare_reference(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
Reference& E = m.ref;
|
||||
Names& nm = m.nm;
|
||||
const char* ec = "audio_tokenizer.encoder_config";
|
||||
if (rad_meta_geti(meta, nm.f("%s.hidden_size", ec), 0) != 512 ||
|
||||
rad_meta_geti(meta, nm.f("%s.num_hidden_layers", ec), 0) != 8 ||
|
||||
rad_meta_geti(meta, nm.f("%s.num_filters", ec), 0) != 64 ||
|
||||
rad_meta_geti(meta, nm.f("%s.use_causal_conv", ec), 1) != 1 ||
|
||||
rad_meta_geti(meta, nm.f("%s.use_conv_shortcut", ec), 0) != 0) {
|
||||
fprintf(stderr, "radiance: breeze: reference encoder is not the released Qwen3-TTS encoder\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
constexpr int64_t R = kMaxRefSamples / 960; /* SEANet's 25 Hz output */
|
||||
constexpr int64_t NI = 2 * kMaxPrompt + 3;
|
||||
E.index = decl_b(b, nm.f("ref.index"), RAD_I32, {NI}, RAD_BUF_PERSIST);
|
||||
E.indices = iota_op(b, NI, 0, 1, E.index);
|
||||
E.cu = decl_b(b, nm.f("ref.cu"), RAD_I32, {2}, RAD_BUF_PERSIST);
|
||||
E.text_pos = decl_b(b, nm.f("ref.text_pos"), RAD_I32, {kMaxPrompt}, RAD_BUF_PERSIST);
|
||||
E.text_cu = decl_b(b, nm.f("ref.text_cu"), RAD_I32, {2}, RAD_BUF_PERSIST);
|
||||
E.text_indices = iota_op(b, kMaxPrompt, 0, 1, E.text_pos);
|
||||
E.copy_i = rw(b, RAD_OP(b, "int_affine", RAD_PARAMS(RAD_INT("M", 1), RAD_STR("src", "0"),
|
||||
RAD_STR("mul", "1"), RAD_STR("add", "0")), RAD_NOWEIGHTS),
|
||||
{E.index}, {E.cu, E.text_cu});
|
||||
E.copy_f = rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512),
|
||||
RAD_STR("from", "f32"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {}, {});
|
||||
int64_t rows = kMaxRefSamples, ch = 64, rate = 1;
|
||||
static const int64_t stride[] = {4, 5, 6, 8};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
E.x[i] = decl_b(b, nm.f("ref.x%d", i), RAD_F32, {rows, ch});
|
||||
E.a[i] = decl_b(b, nm.f("ref.a%d", i), RAD_F32, {rows, ch});
|
||||
E.elu[i] = ref_rows(b, "elu", rows, ch, {E.x[i]}, {E.a[i]});
|
||||
if (i < 4) {
|
||||
E.h[i] = decl_b(b, nm.f("ref.h%d", i), RAD_F32, {rows, ch / 2});
|
||||
E.elu_h[i] = ref_rows(b, "elu", rows, ch / 2, {E.h[i]}, {E.h[i]});
|
||||
rows /= stride[i]; ch *= 2;
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.first, "first", "audio_tokenizer.encoder.encoder.layers.0.conv",
|
||||
1, 64, 7, 1, 1, kMaxRefSamples, 0, 0, E.x[0]));
|
||||
rows = kMaxRefSamples; ch = 64; rate = 1;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const int li = 1 + 3 * i;
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.res1[i], nm.f("res%d.1", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.1.conv", li),
|
||||
ch, ch / 2, 3, 1, rate, rows, E.a[i], 0, E.h[i]));
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.res2[i], nm.f("res%d.2", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.3.conv", li),
|
||||
ch / 2, ch, 1, 1, rate, rows, E.h[i], E.x[i], E.x[i]));
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.down[i], nm.f("down%d", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.conv", li + 2),
|
||||
ch, 2 * ch, 2 * stride[i], stride[i], rate, rows,
|
||||
E.a[i], 0, E.x[i + 1]));
|
||||
rows /= stride[i]; rate *= stride[i]; ch *= 2;
|
||||
}
|
||||
E.z = decl_b(b, nm.f("ref.z"), RAD_F32, {R, 512});
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.last, "last", "audio_tokenizer.encoder.encoder.layers.14.conv",
|
||||
1024, 512, 3, 1, 960, R, E.a[4], 0, E.z));
|
||||
E.th = decl_b(b, nm.f("ref.th"), RAD_F32, {R, 512});
|
||||
E.qkv = decl_b(b, nm.f("ref.qkv"), RAD_F32, {R, 1536});
|
||||
E.attn = decl_b(b, nm.f("ref.attn"), RAD_F32, {R, 512});
|
||||
E.o = decl_b(b, nm.f("ref.o"), RAD_F32, {R, 512});
|
||||
E.ff = decl_b(b, nm.f("ref.ff"), RAD_F32, {R, 2048});
|
||||
E.act = decl_b(b, nm.f("ref.act"), RAD_F32, {R, 2048});
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
RefLayer& L = E.layer[i];
|
||||
auto w = [&](const char* dn, const char* sn, std::initializer_list<int64_t> sh) {
|
||||
return wcopy(b, nm, nm.f("ref.t%d.%s", i, dn),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.%s", i, sn),
|
||||
RAD_F32, sh, kGrpCodec + 1);
|
||||
};
|
||||
L.n1 = w("n1", "input_layernorm.weight", {512});
|
||||
L.b1 = w("b1", "input_layernorm.bias", {512});
|
||||
L.n2 = w("n2", "post_attention_layernorm.weight", {512});
|
||||
L.b2 = w("b2", "post_attention_layernorm.bias", {512});
|
||||
L.ls1 = w("ls1", "self_attn_layer_scale.scale", {512});
|
||||
L.ls2 = w("ls2", "mlp_layer_scale.scale", {512});
|
||||
const char* qn = nm.f("ref.t%d.qkv", i);
|
||||
RAD_ARCH_TRY(map_concat(b, qn, {
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.q_proj.weight", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.k_proj.weight", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.v_proj.weight", i)}));
|
||||
L.qkv = decl_w(b, qn, RAD_F32, {1536, 512}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(kGrpCodec + 1));
|
||||
L.o = w("out", "self_attn.o_proj.weight", {512, 512});
|
||||
L.fc1 = w("fc1", "mlp.fc1.weight", {2048, 512});
|
||||
L.fc2 = w("fc2", "mlp.fc2.weight", {512, 2048});
|
||||
auto ln = [&](rad_weight nw, rad_weight nb) {
|
||||
return rw(b, RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512),
|
||||
RAD_F64("eps", 1e-5), RAD_STR("dtype", "f32")), RAD_WEIGHTS(nw, nb)),
|
||||
{E.z}, {E.th});
|
||||
};
|
||||
L.norm1 = ln(L.n1, L.b1); L.norm2 = ln(L.n2, L.b2);
|
||||
L.proj = ref_gemm(b, R, 1536, 512, L.qkv, E.th, E.qkv);
|
||||
L.rope = rw(b, RAD_OP(b, "rope", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", 64),
|
||||
RAD_INT("n_head", 8), RAD_INT("n_head_kv", 8), RAD_F64("theta", 10000),
|
||||
RAD_F64("scale", 1), RAD_STR("mode", "neox")), RAD_NOWEIGHTS),
|
||||
{E.qkv, E.index}, {E.qkv});
|
||||
L.attn = rw(b, RAD_OP(b, "attn_dense", RAD_PARAMS(RAD_RANGE("M", 1, R),
|
||||
RAD_INT("head_dim", 64), RAD_INT("gqa", 1), RAD_INT("causal", 1),
|
||||
RAD_F64("scale", 0.125), RAD_INT("window", 250), RAD_INT("max_seqlen", R),
|
||||
RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {E.qkv, E.cu}, {E.attn});
|
||||
L.out = ref_gemm(b, R, 512, 512, L.o, E.attn, E.o);
|
||||
L.f1 = ref_gemm(b, R, 2048, 512, L.fc1, E.th, E.ff);
|
||||
L.act = ref_rows(b, "gelu", R, 2048, {E.ff}, {E.act});
|
||||
L.f2 = ref_gemm(b, R, 512, 2048, L.fc2, E.act, E.o);
|
||||
auto scale = [&](rad_weight sw) {
|
||||
return rw(b, RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R),
|
||||
RAD_INT("n", 512), RAD_STR("dtype", "f32")), RAD_WEIGHTS(sw)), {E.o}, {E.o});
|
||||
};
|
||||
L.scale1 = scale(L.ls1); L.scale2 = scale(L.ls2);
|
||||
L.add1 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z});
|
||||
L.add2 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z});
|
||||
if (!L.n1 || !L.b1 || !L.n2 || !L.b2 || !L.qkv || !L.o || !L.fc1 || !L.fc2 ||
|
||||
!L.ls1 || !L.ls2 || !L.norm1 || !L.norm2 || !L.proj || !L.rope || !L.attn ||
|
||||
!L.out || !L.f1 || !L.act || !L.f2 || !L.scale1 || !L.scale2 || !L.add1 || !L.add2)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The last downsample uses replicate padding. Prepending two copies of the first row,
|
||||
* using the ordinary causal conv, then dropping its first output is exactly that pad. */
|
||||
E.pad = decl_b(b, nm.f("ref.pad"), RAD_F32, {R + 2, 512});
|
||||
E.sampled = decl_b(b, nm.f("ref.sampled"), RAD_F32, {kMaxRefFrames + 1, 512});
|
||||
RAD_ARCH_TRY(rad_op_reads(b, E.copy_f, &E.z, 1));
|
||||
RAD_ARCH_TRY(rad_op_writes(b, E.copy_f, &E.pad, 1));
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.sample, "sample", "audio_tokenizer.encoder.downsample.conv",
|
||||
512, 512, 4, 2, 1, R + 2, E.pad, 0, E.sampled, false));
|
||||
E.codes = decl_b(b, nm.f("ref.codes"), RAD_I32, {16, kMaxRefFrames}, RAD_BUF_PERSIST);
|
||||
E.eos_codes = decl_b(b, nm.f("ref.eos_codes"), RAD_I32, {16, 1}, RAD_BUF_PERSIST);
|
||||
for (int part = 0; part < 2; ++part) {
|
||||
const char* qs = part ? "acoustic_residual_vector_quantizer" : "semantic_residual_vector_quantizer";
|
||||
E.q[part] = decl_b(b, nm.f("ref.q%d", part), RAD_F32, {kMaxRefFrames, 256});
|
||||
E.qi[part] = wcopy(b, nm, nm.f("ref.q%d.in", part),
|
||||
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.input_proj.weight", qs),
|
||||
RAD_F32, {256, 512}, kGrpCodec + 1);
|
||||
/* A 1x1 Conv1d weight's trailing singleton is immaterial to GEMM's matrix view. */
|
||||
E.project[part] = ref_gemm(b, kMaxRefFrames, 256, 512, E.qi[part], E.sampled, E.q[part]);
|
||||
const int first = part ? 1 : 0, count = part ? 15 : 1;
|
||||
for (int j = 0; j < count; ++j) {
|
||||
const int k = first + j;
|
||||
const char* dn = nm.f("ref.cb%d", k);
|
||||
RAD_ARCH_TRY(map_ema(b, dn,
|
||||
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.embed_sum", qs, j),
|
||||
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.cluster_usage", qs, j)));
|
||||
E.cb[k] = decl_w(b, dn, RAD_F32, {2048, 256}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(kGrpCodec + 1));
|
||||
E.quant[k] = rw(b, RAD_OP(b, "vq_euclidean", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames),
|
||||
RAD_INT("n", 256), RAD_INT("bins", 2048), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(E.cb[k])), {E.q[part]}, {E.q[part], E.codes});
|
||||
if (!E.cb[k] || !E.quant[k]) return RAD_E_INVAL;
|
||||
}
|
||||
if (!E.qi[part] || !E.project[part]) return RAD_E_INVAL;
|
||||
}
|
||||
E.embed = rw(b, RAD_OP(b, "rvq_embed", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames),
|
||||
RAD_INT("n_embd", m.gl.n_embd), RAD_INT("n_codes", 16), RAD_INT("vocab", kVocab),
|
||||
RAD_INT("off0", 0), RAD_F64("scale", 1), RAD_INT("round", 1),
|
||||
RAD_STR("dtype", "bf16")), RAD_WEIGHTS(m.w_cb, m.w_cb)), {E.codes}, {m.b_x});
|
||||
E.eos = iota_op(b, 16, 0, 0, E.eos_codes);
|
||||
RAD_ARCH_TRY(rad_op_reads(b, E.embed, &E.eos_codes, 1));
|
||||
/* Both branches' text segments are encoded separately at position zero. These buffers must
|
||||
* remain live through each segment's encoder, projection and the backbone prefill. */
|
||||
for (const EncLayer& L : m.enc) {
|
||||
RAD_ARCH_TRY(rad_op_reads(b, L.op_qknr, &E.text_pos, 1));
|
||||
RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &E.text_cu, 1));
|
||||
}
|
||||
return E.indices && E.copy_i && E.copy_f && E.text_indices && E.embed && E.eos ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Copy the endpoints of an iota into a two-entry cu, without a host upload or ABI change. */
|
||||
static void ref_bounds(RadCtx* c, const Reference& E, rad_buf cu, int64_t len) {
|
||||
RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, 0, 1, 1), brow_slice(cu, 0, 1, 1));
|
||||
RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, len, 1, 1), brow_slice(cu, 1, 1, 1));
|
||||
}
|
||||
|
||||
static void step_reference(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const Reference& E = m.ref;
|
||||
const auto* A = batch->agen_b;
|
||||
const int64_t L = A->ref_samples, R = L / 960, F = R / 2;
|
||||
RAD_ISSUE_N(c, E.indices, 2 * kMaxPrompt + 3, brows(E.index, 2 * kMaxPrompt + 3));
|
||||
const RadOperand raw_cu = praw(A->ref_cu, RAD_I32, 2);
|
||||
auto conv = [&](const RefConv& C, RadOperand x, RadOperand res, RadOperand y,
|
||||
int64_t rows, RadOperand cu) {
|
||||
RAD_ISSUE_N(c, C.op, rows, x, RAD_W(C.w), cu, res, y, C.b ? RAD_W(C.b) : RAD_NONE);
|
||||
};
|
||||
conv(E.first, praw(A->ref_audio, RAD_F32, L), RAD_NONE, brows(E.x[0], L), L, raw_cu);
|
||||
static const int64_t stride[] = {4, 5, 6, 8};
|
||||
int64_t rows = L;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows));
|
||||
conv(E.res1[i], brows(E.a[i], rows), RAD_NONE, brows(E.h[i], rows), rows, raw_cu);
|
||||
RAD_ISSUE_N(c, E.elu_h[i], rows, brows(E.h[i], rows), brows(E.h[i], rows));
|
||||
conv(E.res2[i], brows(E.h[i], rows), brows(E.x[i], rows), brows(E.x[i], rows), rows, raw_cu);
|
||||
RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows));
|
||||
conv(E.down[i], brows(E.a[i], rows), RAD_NONE, brows(E.x[i + 1], rows / stride[i]), rows, raw_cu);
|
||||
rows /= stride[i];
|
||||
}
|
||||
RAD_ISSUE_N(c, E.elu[4], R, brows(E.x[4], R), brows(E.a[4], R));
|
||||
conv(E.last, brows(E.a[4], R), RAD_NONE, brows(E.z, R), R, raw_cu);
|
||||
ref_bounds(c, E, E.cu, R);
|
||||
const RadOperand cu = brows(E.cu, 2), pos = brows(E.index, R);
|
||||
for (const RefLayer& T : E.layer) {
|
||||
auto norm = [&](rad_op op, rad_weight w, rad_weight bias) {
|
||||
RAD_ISSUE_N(c, op, R, brows(E.z, R), RAD_W(w), RAD_W(bias), brows(E.th, R));
|
||||
};
|
||||
auto gemm = [&](rad_op op, rad_buf x, rad_weight w, rad_buf y) {
|
||||
RAD_ISSUE_N(c, op, R, brows(x, R), RAD_W(w), brows(y, R));
|
||||
};
|
||||
norm(T.norm1, T.n1, T.b1);
|
||||
gemm(T.proj, E.th, T.qkv, E.qkv);
|
||||
RAD_ISSUE_N(c, T.rope, R, brows(E.qkv, R), pos);
|
||||
RAD_ISSUE_N(c, T.attn, R, bcol(E.qkv, 0, 512, R), bcol(E.qkv, 512, 512, R),
|
||||
bcol(E.qkv, 1024, 512, R), cu, brows(E.attn, R));
|
||||
gemm(T.out, E.attn, T.o, E.o);
|
||||
RAD_ISSUE_N(c, T.scale1, R, brows(E.o, R), RAD_W(T.ls1), brows(E.o, R));
|
||||
RAD_ISSUE_N(c, T.add1, R, brows(E.z, R), brows(E.o, R), brows(E.z, R));
|
||||
norm(T.norm2, T.n2, T.b2);
|
||||
gemm(T.f1, E.th, T.fc1, E.ff);
|
||||
RAD_ISSUE_N(c, T.act, R, brows(E.ff, R), brows(E.act, R));
|
||||
gemm(T.f2, E.act, T.fc2, E.o);
|
||||
RAD_ISSUE_N(c, T.scale2, R, brows(E.o, R), RAD_W(T.ls2), brows(E.o, R));
|
||||
RAD_ISSUE_N(c, T.add2, R, brows(E.z, R), brows(E.o, R), brows(E.z, R));
|
||||
}
|
||||
RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 0, 1, 512));
|
||||
RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 1, 1, 512));
|
||||
RAD_ISSUE_N(c, E.copy_f, R, brows(E.z, R), brow_slice(E.pad, 2, R, 512));
|
||||
ref_bounds(c, E, E.cu, R + 2);
|
||||
conv(E.sample, brows(E.pad, R + 2), RAD_NONE, brows(E.sampled, F + 1), R + 2, cu);
|
||||
for (int p = 0; p < 2; ++p) {
|
||||
RAD_ISSUE_N(c, E.project[p], F, brow_slice(E.sampled, 1, F, 512), RAD_W(E.qi[p]), brows(E.q[p], F));
|
||||
for (int k = p ? 1 : 0; k < (p ? 16 : 1); ++k) {
|
||||
RadOperand codes = brow_slice(E.codes, k, 1, kMaxRefFrames);
|
||||
codes.cols = F;
|
||||
RAD_ISSUE_N(c, E.quant[k], F, brows(E.q[p], F), RAD_W(E.cb[k]), codes);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,571 @@
|
||||
/* rad_block_museglimmer_vision.h -- Muse Glimmer's vision tower (transformers'
|
||||
* MuseGlimmerVisionModel, an InternVit-shaped stack), its adapter and the perception norm, served
|
||||
* by museglimmer.
|
||||
*
|
||||
* What it computes, per encoder pass (RadBatch::enc), in the reference's order:
|
||||
*
|
||||
* x = patches @ Wp^T the patch embedding as a linear layer, bias-less;
|
||||
* a patch row is (temporal, channel, y, x)
|
||||
* x += position table resampled to the grid `grid_embed_pad`, bilinear at half-pixel
|
||||
* centres, align_corners=False, out-of-range taps
|
||||
* zero-weighted (grid_sample padding zeros)
|
||||
* x = LN_pre(x) LayerNorm, eps `layer_norm_eps`
|
||||
* x = x[window order] `window_order`: the 32x32-patch window permutation
|
||||
* (per frame, ragged edges smaller windows), its
|
||||
* inverse, per-slot rotary positions and the
|
||||
* per-window cumulative boundaries
|
||||
* depth times:
|
||||
* h = LN1(x) LayerNorm, eps 1e-5 (the blocks hard-code it)
|
||||
* q|k|v = qkv(h) the reference's three biased projections, joined
|
||||
* q first into one GEMM as the reference's fused
|
||||
* tensors would read
|
||||
* rope(q, k) `rope` axial, the whole head, sections
|
||||
* head_dim/4 a side on theta^(-j/(head_dim/4)),
|
||||
* positions (column + 1, row + 1) -- HF's
|
||||
* position_ids.flip(-1) + 1
|
||||
* x += proj(attn(q, k, v)) non-causal, scale 1/sqrt(head_dim). A
|
||||
* window_attention layer attends within one window
|
||||
* (cu = the per-window boundaries in permuted
|
||||
* order); a full_attention layer attends within
|
||||
* its frame (cu = the frame boundaries). The
|
||||
* window permutation never moves a patch across
|
||||
* frames, so the frame boundaries among permuted
|
||||
* rows are the boundaries among natural rows:
|
||||
* `enc_cu` is passed unchanged, exactly what the
|
||||
* reference passes (modeling_muse_glimmer.py maps
|
||||
* full_attention to the frame cu_seqlens while the
|
||||
* rows stay permuted).
|
||||
* x += fc2(gelu(fc1(LN2(x)))) both biased; `gelu` the exact erf form the
|
||||
* config's hidden_act names, in gemm_nt_bias's
|
||||
* epilogue
|
||||
* x = x[inv] the window order undone (gather_rows)
|
||||
* x = LN_post(x) LayerNorm, eps `layer_norm_eps`
|
||||
* y = pixel_shuffle(x) the merge (`pixtral_merge`): each 2x2 block's
|
||||
* four patches fold into one row of merge^2 *
|
||||
* width, channels interleaved -- the reference's
|
||||
* [block, merge^2, dim].permute(0, 2, 1)
|
||||
* y = gelu(fc2(gelu(fc1(y)))) the adapter: both linears bias-less, TWO
|
||||
* activations (projector_hidden_act)
|
||||
* y = y @ Wproj^T the projection, bias-less, the model's width
|
||||
* out = rms(y) `perception_emb_norm`, a weightless RMS norm at
|
||||
* the TEXT model's rms_norm_eps
|
||||
*
|
||||
* The reference permutes AFTER ln_pre, so the tower works in window order and un-permutes before
|
||||
* ln_post, exactly as above. The processor stages patches in the reference's raster order; the
|
||||
* merge is a real fold (not a view: the reference interleaves the four patches' channels, which
|
||||
* four consecutive rows do not spell), and its output is what the adapter reads.
|
||||
*
|
||||
* Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the
|
||||
* weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx::
|
||||
* max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's
|
||||
* step; the attention's longest segment stays at the real pass so the kernel rows do not move.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MUSEGLIMMER_VISION_H
|
||||
#define RAD_BLOCK_MUSEGLIMMER_VISION_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct MuseTower {
|
||||
/* Geometry, from the container's vision_config (never aliased: only the full prefix). The
|
||||
* adapter's widths are top-level keys of the family config. */
|
||||
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0;
|
||||
int64_t merge = 0, side = 0, npos = 0, proj_ff = 0, out_hidden = 0, n_embd = 0;
|
||||
int64_t patch_dim = 0, P = 0;
|
||||
double eps = 1e-5; /* ln_pre / ln_post; the blocks hard-code 1e-5 */
|
||||
float theta = 10000.0f;
|
||||
bool on = false;
|
||||
|
||||
struct Layer {
|
||||
bool full = false; /* full_attention: frame-wide attention, NoPE-free (rotary runs
|
||||
* on every layer of this tower, full or window) */
|
||||
rad_weight n1w = 0, n1b = 0, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
|
||||
rad_weight n2w = 0, n2b = 0, up_w = 0, up_b = 0, down_w = 0, down_b = 0;
|
||||
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
|
||||
int64_t max_seg = 0; /* the kernel band's longest segment */
|
||||
};
|
||||
std::vector<Layer> L;
|
||||
rad_weight w_patch = 0, w_pos = 0, lw_pre = 0, lb_pre = 0, lw_post = 0, lb_post = 0;
|
||||
rad_weight w_a1 = 0, w_a2 = 0, w_proj = 0;
|
||||
rad_op op_patch = 0, op_pos = 0, op_lpre = 0, op_wo = 0, op_gidx = 0, op_ginv = 0;
|
||||
rad_op op_lpost = 0, op_merge = 0, op_m1 = 0, op_g1 = 0, op_m2 = 0, op_g2 = 0, op_proj = 0,
|
||||
op_perc = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_p = 0, b_qkv = 0, b_att = 0, b_ff = 0;
|
||||
rad_buf b_idx = 0, b_inv = 0, b_pos = 0, b_cuw = 0;
|
||||
rad_buf b_mh = 0, b_m1 = 0, b_m2 = 0, b_out = 0;
|
||||
char sec[48] = {};
|
||||
|
||||
/* Whether the container carries this family's tower. */
|
||||
static bool present(const RadModelMeta* m) {
|
||||
return rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
|
||||
Names& nm, int64_t model_embd, int first_group) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
|
||||
depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
|
||||
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
|
||||
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
|
||||
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
|
||||
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
|
||||
temporal = rad_meta_geti(m, "vision_config.patch_temporal", 2);
|
||||
merge = rad_meta_geti(m, "vision_config.merge_size", 2);
|
||||
side = rad_meta_geti(m, "vision_config.pos_emb_height", 0);
|
||||
npos = rad_meta_geti(m, "vision_config.pos_emb_height", 0) *
|
||||
rad_meta_geti(m, "vision_config.pos_emb_width", 0);
|
||||
eps = rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-5);
|
||||
theta = (float)rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0);
|
||||
proj_ff = rad_meta_geti(m, "projector_hidden_size", 4096);
|
||||
out_hidden = rad_meta_geti(m, "out_hidden_size", 6144);
|
||||
n_embd = model_embd;
|
||||
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || temporal <= 0 ||
|
||||
merge <= 0 || side <= 0 || proj_ff <= 0 || out_hidden <= 0 || width % heads ||
|
||||
rad_meta_geti(m, "vision_config.pos_emb_width", 0) != side) {
|
||||
fprintf(stderr, "radiance: museglimmer: the container's vision_config is incomplete or "
|
||||
"inconsistent (depth %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
|
||||
"temporal %lld, merge %lld, position grid %lld x %lld, projector %lld, "
|
||||
"merged %lld)\n", (long long)depth, (long long)width, (long long)heads,
|
||||
(long long)ff, (long long)patch, (long long)temporal, (long long)merge,
|
||||
(long long)side, (long long)rad_meta_geti(m, "vision_config.pos_emb_width", 0),
|
||||
(long long)proj_ff, (long long)out_hidden);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The merge is `pixtral_merge`, whose kernels fold a 2x2 block: the only factor Muse Glimmer
|
||||
* ships and the only one the op serves. */
|
||||
if (merge != 2) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower states merge_size %lld; the "
|
||||
"merge op folds a 2x2 block\n", (long long)merge);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The exact-erf GELU is what this tower and its adapter state; another activation is another
|
||||
* tower (the reference would compute a different function). */
|
||||
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu");
|
||||
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
|
||||
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial");
|
||||
if (std::strcmp(act, "gelu") || std::strcmp(pact, "gelu")) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower has hidden_act '%s' and "
|
||||
"projector_hidden_act '%s'; it serves the exact gelu both call for\n",
|
||||
act, pact);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* `axial` is Meta's spelling and `default` NVIDIA's ModelOpt export of the same tower: the
|
||||
* reference's vision embedder has one rotary (axial), so both name it. Anything else is
|
||||
* another tower. */
|
||||
if (std::strcmp(rt, "axial") && std::strcmp(rt, "default")) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower states rope_type '%s'; it "
|
||||
"serves the axial 2-D rotary the tower's rotary embedder raises on "
|
||||
"leaving\n", rt);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The tower's full layers: every fourth, counted from the start, plus the last (the config's
|
||||
* own rule, MuseGlimmerVisionConfig.__post_init__). The shipped array must say the same
|
||||
* thing; a window layer where the rule puts a full one changes what the model saw. */
|
||||
std::vector<int> full;
|
||||
const char* kinds = rad_meta_gets(m, "vision_config.layer_types", "");
|
||||
if (kinds && *kinds) {
|
||||
RAD_ARCH_TRY(parse_layer_kinds("museglimmer vision", kinds, {"full_attention"},
|
||||
"window_attention", &full));
|
||||
if ((int64_t)full.size() != depth) {
|
||||
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types names %zu layers "
|
||||
"and the tower has %lld\n", full.size(), (long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int64_t l = 0; l < depth; ++l) {
|
||||
const bool rule = is_full_attention(l, 4) || l == depth - 1;
|
||||
if ((full[(size_t)l] != 0) != rule) {
|
||||
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types makes tower "
|
||||
"layer %lld %s and the family rule (every fourth from the first, "
|
||||
"plus the last) makes it %s\n", (long long)l,
|
||||
full[(size_t)l] ? "full" : "window", rule ? "full" : "window");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
full.assign((size_t)depth, 0);
|
||||
for (int64_t l = 0; l < depth; ++l)
|
||||
full[(size_t)l] = is_full_attention(l, 4) || l == depth - 1;
|
||||
}
|
||||
|
||||
head_dim = width / heads;
|
||||
patch_dim = 3 * temporal * patch * patch;
|
||||
/* The 2-D rotary: half the head a side, each on its own ladder (arange(0, head_dim/2, 2)
|
||||
* frequencies, sections head_dim/4 a side). */
|
||||
if (head_dim % 4) return RAD_E_SHAPE;
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4),
|
||||
(long long)(head_dim / 4));
|
||||
/* The merger's rows replace token embeddings, so they must be the model's width. */
|
||||
if (out_hidden != merge * merge * width) {
|
||||
fprintf(stderr, "radiance: museglimmer: out_hidden_size %lld is not merge %lld squared "
|
||||
"times the tower's width %lld, whose view the adapter's first layer "
|
||||
"reads\n", (long long)out_hidden, (long long)merge, (long long)width);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The tower emits merged rows the width of the model's tokens: the caller passes the model's
|
||||
* width and the projection is declared at it, so no separate check exists. */
|
||||
|
||||
const int64_t mm = merge * merge;
|
||||
P = ctx->max_enc_patches;
|
||||
if (ctx->shape_probe) {
|
||||
/* A sizing declare: rows follow the probe's step (rounded to whole merged rows), keeping
|
||||
* the activations out of the levels a decode step runs at. The kernel bands stay at the
|
||||
* real pass: the engine runs the real declare's kernels at every level. */
|
||||
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
|
||||
P = std::max<int64_t>(mm, r / mm * mm);
|
||||
}
|
||||
if (P % mm) return RAD_E_SHAPE;
|
||||
const int64_t R = P / mm;
|
||||
const int64_t ACC = RAD_ACCESS_PER_REQUEST;
|
||||
/* The window side in patches (the reference states it in pixels and divides by patch_size).
|
||||
* A window_attention layer's longest segment is one window. */
|
||||
const int64_t win_seg = side * side;
|
||||
|
||||
/* ---- weights, replicated. Model-level groups for the stem and the adapter; one group per
|
||||
* block from `first_group` on, so a tower block is its own movement unit. */
|
||||
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
w_patch = bw(nm.f("v.patch.weight"),
|
||||
nm.ckpt("model.vision_tower.patch_embedder.patch_embedding.weight"),
|
||||
{ width, patch_dim }, grp_model());
|
||||
w_pos = bw(nm.f("v.pos.weight"),
|
||||
nm.ckpt("model.vision_tower.patch_embedder.position_embedding_table.weight"),
|
||||
{ npos, width }, grp_model());
|
||||
lw_pre = bw(nm.f("v.lnpre.weight"), nm.ckpt("model.vision_tower.ln_pre.weight"), { width },
|
||||
grp_model());
|
||||
lb_pre = bw(nm.f("v.lnpre.bias"), nm.ckpt("model.vision_tower.ln_pre.bias"), { width },
|
||||
grp_model());
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
const int li = (int)i;
|
||||
auto src = [&](const char* s) { return nm.ckpt("model.vision_tower.layers.%d.%s", li, s); };
|
||||
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
|
||||
l.n1w = bw(dn("norm1.weight"), src("norm1.weight"), { width }, g);
|
||||
l.n1b = bw(dn("norm1.bias"), src("norm1.bias"), { width }, g);
|
||||
/* The reference's three biased projections, joined q | k | v into one GEMM. */
|
||||
if (map_concat(b, dn("qkv.weight"),
|
||||
{ src("attn.q_proj.weight"), src("attn.k_proj.weight"),
|
||||
src("attn.v_proj.weight") }) < 0)
|
||||
return RAD_E_INVAL;
|
||||
l.qkv_w = decl_w(b, dn("qkv.weight"), RAD_BF16, { 3 * width, width }, ACC,
|
||||
RAD_SHARD_NONE, g, 0, { width, width, width });
|
||||
if (map_concat(b, dn("qkv.bias"),
|
||||
{ src("attn.q_proj.bias"), src("attn.k_proj.bias"),
|
||||
src("attn.v_proj.bias") }) < 0)
|
||||
return RAD_E_INVAL;
|
||||
l.qkv_b = decl_w(b, dn("qkv.bias"), RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g, 0,
|
||||
{ width, width, width });
|
||||
l.out_w = bw(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g);
|
||||
l.out_b = bw(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
|
||||
l.n2w = bw(dn("norm2.weight"), src("norm2.weight"), { width }, g);
|
||||
l.n2b = bw(dn("norm2.bias"), src("norm2.bias"), { width }, g);
|
||||
l.up_w = bw(dn("fc1.weight"), src("mlp.fc1.weight"), { ff, width }, g);
|
||||
l.up_b = bw(dn("fc1.bias"), src("mlp.fc1.bias"), { ff }, g);
|
||||
l.down_w= bw(dn("fc2.weight"), src("mlp.fc2.weight"), { width, ff }, g);
|
||||
l.down_b= bw(dn("fc2.bias"), src("mlp.fc2.bias"), { width }, g);
|
||||
if (!l.n1w || !l.n1b || !l.qkv_w || !l.qkv_b || !l.out_w || !l.out_b || !l.n2w || !l.n2b ||
|
||||
!l.up_w || !l.up_b || !l.down_w || !l.down_b)
|
||||
return RAD_E_INVAL;
|
||||
l.full = full[(size_t)i] != 0;
|
||||
l.max_seg = l.full ? ctx->max_enc_patches : win_seg;
|
||||
}
|
||||
lw_post = bw(nm.f("v.lnpost.weight"), nm.ckpt("model.vision_tower.ln_post.weight"), { width },
|
||||
grp_model());
|
||||
lb_post = bw(nm.f("v.lnpost.bias"), nm.ckpt("model.vision_tower.ln_post.bias"), { width },
|
||||
grp_model());
|
||||
w_a1 = bw(nm.f("v.mlp.fc1.weight"), nm.ckpt("model.vision_adapter.fc1.weight"),
|
||||
{ proj_ff, out_hidden }, grp_model());
|
||||
w_a2 = bw(nm.f("v.mlp.fc2.weight"), nm.ckpt("model.vision_adapter.fc2.weight"),
|
||||
{ proj_ff, proj_ff }, grp_model());
|
||||
w_proj = bw(nm.f("v.proj.weight"), nm.ckpt("model.vision_projection.weight"),
|
||||
{ n_embd, proj_ff }, grp_model());
|
||||
if (!w_patch || !w_pos || !lw_pre || !lb_pre || !lw_post || !lb_post || !w_a1 || !w_a2 ||
|
||||
!w_proj)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- activations. `mh` holds the merged rows: `pixtral_merge` folds each 2x2 block's four
|
||||
* patch rows into one row of mm * width in the reference's pixel_shuffle layout, and the
|
||||
* adapter's first layer reads it. */
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
|
||||
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
|
||||
b_p = decl_b(b, nm.f("v.p"), RAD_BF16, { P, width });
|
||||
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
|
||||
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
|
||||
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
|
||||
b_idx = decl_b(b, nm.f("v.idx"), RAD_I32, { P });
|
||||
b_inv = decl_b(b, nm.f("v.inv"), RAD_I32, { P });
|
||||
b_pos = decl_b(b, nm.f("v.pos"), RAD_I32, { 2, P });
|
||||
b_cuw = decl_b(b, nm.f("v.cuw"), RAD_I32, { P + 1 });
|
||||
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mm * width });
|
||||
b_m1 = decl_b(b, nm.f("v.m1"), RAD_BF16, { R, proj_ff });
|
||||
b_m2 = decl_b(b, nm.f("v.m2"), RAD_BF16, { R, proj_ff });
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
|
||||
if (!b_x || !b_h || !b_p || !b_qkv || !b_att || !b_ff || !b_idx || !b_inv || !b_pos || !b_cuw ||
|
||||
!b_mh || !b_m1 || !b_m2 || !b_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
|
||||
rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto lnorm = [&](int64_t rows, int64_t n, double e, rad_weight w, rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", e),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto attn_op = [&](int64_t max_seg) -> rad_op {
|
||||
return RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
|
||||
RAD_INT("max_seqlen", max_seg)),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
|
||||
/* The stem is bias-less (the reference's patch_embedding states no bias). */
|
||||
op_patch = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
|
||||
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_patch)),
|
||||
{}, { b_x });
|
||||
op_pos = rw(b, RAD_OP(b, "grid_embed_pad",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_pos)),
|
||||
{ b_x }, { b_x });
|
||||
op_lpre = rw(b, lnorm(P, width, eps, lw_pre, lb_pre), { b_x }, { b_h });
|
||||
op_wo = rw(b, RAD_OP(b, "window_order",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("window", side)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_idx, b_inv, b_pos, b_cuw });
|
||||
op_gidx = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_h, b_idx }, { b_p });
|
||||
for (Layer& l : L) {
|
||||
l.ln1 = rw(b, lnorm(P, width, 1e-5, l.n1w, l.n1b), { b_p }, { b_h });
|
||||
l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
|
||||
l.rope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
|
||||
RAD_F64("theta", theta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", "axial"),
|
||||
RAD_INT("rotary_dim", head_dim),
|
||||
RAD_STR("sections", sec)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_qkv, b_pos }, { b_qkv });
|
||||
/* A window layer's segment bounds are the order op's per-window cu; a full layer's are
|
||||
* the pass's frame bounds, raw (the permutation is within frames, so they read the same
|
||||
* values in permuted order). */
|
||||
l.attn = rw(b, attn_op(l.max_seg),
|
||||
l.full ? std::initializer_list<rad_buf>{ b_qkv }
|
||||
: std::initializer_list<rad_buf>{ b_qkv, b_cuw },
|
||||
{ b_att });
|
||||
l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_p }, { b_p });
|
||||
l.ln2 = rw(b, lnorm(P, width, 1e-5, l.n2w, l.n2b), { b_p }, { b_h });
|
||||
l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff });
|
||||
l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_p }, { b_p });
|
||||
}
|
||||
op_ginv = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_p, b_inv }, { b_x });
|
||||
op_lpost = rw(b, lnorm(P, width, eps, lw_post, lb_post), { b_x }, { b_x });
|
||||
/* The reference's pixel_shuffle: each 2x2 block's four patches fold into one row with the
|
||||
* channels interleaved (block, channel, sub-patch), which is `pixtral_merge`'s layout. A view
|
||||
* over four consecutive rows cannot produce it: the concatenated form is a different tensor. */
|
||||
op_merge = rw(b, RAD_OP(b, "pixtral_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("merge", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_x }, { b_mh });
|
||||
/* The adapter: both linears bias-less, gelu between and after (the reference's
|
||||
* act(fc2(act(fc1(x))))). */
|
||||
op_m1 = rw(b, gemm(R, proj_ff, mm * width, w_a1), { b_mh }, { b_m1 });
|
||||
op_g1 = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_m1 }, { b_m2 });
|
||||
op_m2 = rw(b, gemm(R, proj_ff, proj_ff, w_a2), { b_m2 }, { b_m1 });
|
||||
op_g2 = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_m1 }, { b_m2 });
|
||||
op_proj = rw(b, gemm(R, n_embd, proj_ff, w_proj), { b_m2 }, { b_out });
|
||||
/* perception_emb_norm: MuseGlimmerRMSNorm(eps = the TEXT model's rms_norm_eps, with_scale
|
||||
* False) -- no gain operand, no centered 1+. */
|
||||
op_perc = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
|
||||
RAD_F64("eps", m->rms_eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_out }, { b_out });
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = mm;
|
||||
e.max_patches = ctx->max_enc_patches;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
int64_t nfull = 0;
|
||||
for (int64_t l = 0; l < depth; ++l) nfull += full[(size_t)l];
|
||||
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x "
|
||||
"%lld x %lld, merge %lld, windows of %lld patches (%lld full attention); "
|
||||
"%lld patches a pass -> %lld rows of %lld",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
|
||||
(long long)ff, (long long)temporal, (long long)patch, (long long)patch,
|
||||
(long long)merge, (long long)side, (long long)nfull, (long long)P, (long long)R,
|
||||
(long long)n_embd);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Stage taps, the same protocol as rad_block_sam.h's: RADIANCE_DEBUG_MM_BUFFERS names stages
|
||||
* (comma separated, matched as substrings) and RADIANCE_DEBUG_MM_DUMP's directory receives
|
||||
* tap.<tag>.bf16 -- raw bf16 rows, one file a stage. The copy is issued on the pass's stream
|
||||
* behind the producing op and synced, so it reads that op's output rather than whatever writes
|
||||
* the buffer later (the after-pass dump in core/engine_mm.cpp cannot see intermediates). */
|
||||
inline void muse_tap(RadCtx* c, const char* tag, rad_buf b, int64_t rows, int64_t cols) {
|
||||
static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP");
|
||||
static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
|
||||
if (!dir || !*dir || !env || !*env || rows <= 0 || cols <= 0 || rad_rank(c) != 0) return;
|
||||
bool want = false;
|
||||
const size_t tl = std::strlen(tag);
|
||||
for (const char* s = env; *s && !want;) {
|
||||
const char* e = s;
|
||||
while (*e && *e != ',') ++e;
|
||||
const size_t l = (size_t)(e - s);
|
||||
for (size_t i = 0; l && i + l <= tl && !want; ++i)
|
||||
want = std::strncmp(tag + i, s, l) == 0;
|
||||
s = *e ? e + 1 : e;
|
||||
}
|
||||
if (!want) return;
|
||||
void* p = rad_buf_ptr(c, b);
|
||||
if (!p) return;
|
||||
std::vector<uint16_t> h((size_t)(rows * cols));
|
||||
if (rad_memcpy_async(h.data(), p, (size_t)(rows * cols * 2), rad_stream(c)) < 0) return;
|
||||
rad_stream_sync(rad_stream(c));
|
||||
char path[512];
|
||||
std::snprintf(path, sizeof path, "%s/tap.%s.bf16", dir, tag);
|
||||
if (FILE* f = std::fopen(path, "wb")) {
|
||||
std::fwrite(h.data(), sizeof(uint16_t), h.size(), f);
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
inline void MuseTower::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
const int64_t mm = merge * merge, Rn = Pn / mm;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0 || !batch->enc_coord || !batch->enc_cu ||
|
||||
!batch->enc_seg_h || !batch->enc_seg_w || !batch->enc_pixels) {
|
||||
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or "
|
||||
"more patches than it was declared for, or not whole merged rows");
|
||||
return;
|
||||
}
|
||||
/* Windows per frame, from the pass's host grids: the window layers' cu is the per-window
|
||||
* boundaries among permuted rows, `n_win + 1` entries of the order op's output. */
|
||||
int64_t n_win = 0;
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
n_win += (batch->enc_seg_h[s] + side - 1) / side * ((batch->enc_seg_w[s] + side - 1) / side);
|
||||
if (n_win > P) {
|
||||
rad_step_fail(c, "an encoder pass whose window count exceeds the tower's declared rows");
|
||||
return;
|
||||
}
|
||||
/* Patches, coordinates (planes 0-3: row, column, segment height, segment width, in patches)
|
||||
* and the frame boundaries, staged by the core. The full layers read the frame boundaries
|
||||
* unchanged: the window permutation is within frames, so the boundaries among permuted rows
|
||||
* are these values (the reference passes its cu_seqlens the same way). */
|
||||
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
|
||||
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
RadOperand cuw = RAD_B(b_cuw);
|
||||
cuw.rows = n_win + 1;
|
||||
RadOperand pos = RAD_B(b_pos);
|
||||
pos.rows = 2;
|
||||
pos.cols = Pn;
|
||||
|
||||
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
|
||||
muse_tap(c, "v.patchpos", b_x, Pn, width);
|
||||
RAD_ISSUE_N(c, op_lpre, Pn, brows(b_x, Pn), RAD_W(lw_pre), RAD_W(lb_pre), brows(b_h, Pn));
|
||||
muse_tap(c, "v.lnpre", b_h, Pn, width);
|
||||
RAD_ISSUE_N(c, op_wo, Pn, crd, cu, brows(b_idx, Pn), brows(b_inv, Pn), pos, cuw);
|
||||
RAD_ISSUE_N(c, op_gidx, Pn, brows(b_h, Pn), brows(b_idx, Pn), brows(b_p, Pn));
|
||||
for (size_t li = 0; li < L.size(); ++li) {
|
||||
const Layer& l = L[li];
|
||||
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_p, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
|
||||
brows(b_qkv, Pn));
|
||||
RAD_ISSUE_N(c, l.rope, Pn, brows(b_qkv, Pn), pos);
|
||||
RAD_ISSUE_N(c, l.attn, Pn,
|
||||
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn),
|
||||
l.full ? cu : cuw, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
|
||||
brows(b_p, Pn), brows(b_p, Pn));
|
||||
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_p, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
|
||||
brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
|
||||
brows(b_p, Pn), brows(b_p, Pn));
|
||||
if (li == 0) muse_tap(c, "v.blk0", b_p, Pn, width);
|
||||
if (li + 1 == L.size()) muse_tap(c, "v.blkL", b_p, Pn, width);
|
||||
}
|
||||
RAD_ISSUE_N(c, op_ginv, Pn, brows(b_p, Pn), brows(b_inv, Pn), brows(b_x, Pn));
|
||||
muse_tap(c, "v.ginv", b_x, Pn, width);
|
||||
/* ln_post over the P patches, then the reference's pixel_shuffle into merged rows. */
|
||||
RAD_ISSUE_N(c, op_lpost, Pn, brows(b_x, Pn), RAD_W(lw_post), RAD_W(lb_post), brows(b_x, Pn));
|
||||
muse_tap(c, "v.lnpost", b_x, Pn, width);
|
||||
RAD_ISSUE_N(c, op_merge, Pn, brows(b_x, Pn), crd, brows(b_mh, Rn));
|
||||
muse_tap(c, "v.merge", b_mh, Rn, mm * width);
|
||||
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(w_a1), brows(b_m1, Rn));
|
||||
muse_tap(c, "v.fc1", b_m1, Rn, proj_ff);
|
||||
RAD_ISSUE_N(c, op_g1, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
|
||||
RAD_ISSUE_N(c, op_m2, Rn, brows(b_m2, Rn), RAD_W(w_a2), brows(b_m1, Rn));
|
||||
RAD_ISSUE_N(c, op_g2, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
|
||||
RAD_ISSUE_N(c, op_proj, Rn, brows(b_m2, Rn), RAD_W(w_proj), brows(b_out, Rn));
|
||||
muse_tap(c, "v.proj", b_out, Rn, n_embd);
|
||||
RAD_ISSUE_N(c, op_perc, Rn, brows(b_out, Rn), RAD_NONE, brows(b_out, Rn));
|
||||
muse_tap(c, "v.out", b_out, Rn, n_embd);
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MUSEGLIMMER_VISION_H */
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(flint LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(flint architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flint.cpp)
|
||||
@@ -0,0 +1,544 @@
|
||||
/* flint -- Recursive Flint (39.8B-A2.5B): two dense layers then 47 sigmoid-routed MoE layers,
|
||||
* grouped-query attention with per-head Q/K RMSNorm, a learned per-head softmax sink, and a
|
||||
* 513-token sliding window on 35 of the 49 layers (the other 14 are full attention and NoPE).
|
||||
*
|
||||
* 2 dense layers: rmsnorm -> q/k/v -> qk-norm -> [rope] -> paged attention + sink -> o
|
||||
* rmsnorm -> gate_up -> silu_mul -> down
|
||||
* 47 MoE layers: same attention; rmsnorm -> router -> top-6 of 256 (sigmoid)
|
||||
* -> grouped gate_up -> silu_mul -> down -> gather
|
||||
* + ungated shared expert (2 x 512)
|
||||
*
|
||||
* Weights come from a BF16 or recipe-quantized Flint checkpoint; the blocks probe the stored
|
||||
* encoding. Two trunk forms, read from layer 0's q projection:
|
||||
*
|
||||
* - a rotated int8 trunk (data/recipes/flint-iq8r.recipe: IQ8R linears, i8 codes rotated by a
|
||||
* 128-wide Hadamard): the norms, the gated products and the attention output write
|
||||
* had_quant_act_i8g's codes themselves, every linear reads them at i8a8h, and the routed
|
||||
* experts are rotated int8 (or another form with an int8 row) read by the grouped GEMM's int8
|
||||
* rows from the same codes (MoeFP8::a8), as qwen35moe_w8a8 serves Qwen3.6-35B-A3B;
|
||||
* - any other (bf16, the four-bit attention of data/recipes/flint-bf16-q4.recipe, plain int8
|
||||
* linears): each linear reads the bf16 plane or quantises it itself, and four-bit experts read
|
||||
* the block input's E4M3 pair, as hyv3_bf16 serves its W4 and W8 recipes.
|
||||
*
|
||||
* No MTP head.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include "flint_attention.h"
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include "rad_abi_layout.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace flint {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool dense = false;
|
||||
bool sliding = false;
|
||||
FlintAttn attn{};
|
||||
MlpFP8 dense_mlp{};
|
||||
MoeFP8 moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
int64_t n_ff_expert = 0, n_ff_shared = 0;
|
||||
rad_kvgroup kv_full = 0, kv_win = 0;
|
||||
/* The trunk is rotated int8 (rad_fp8.h's linear_is_w8h or linear_is_wnh), its activation codes
|
||||
* one scale a `trunk_g8` columns: 256 for IQ8R, 128 for the other rotated forms. */
|
||||
bool trunk_rot = false;
|
||||
int64_t trunk_g8 = RAD_FP8_BLOCK;
|
||||
|
||||
rad_buf x = 0, h_out = 0, logits = 0;
|
||||
ActFP8 h{};
|
||||
/* The routed experts' rotated int8 copy of the block input, where a rotated trunk's norms do
|
||||
* not write the codes themselves (MoeFP8::Wire::hr). */
|
||||
ActFP8 hr{};
|
||||
rad_buf q = 0, k = 0, v = 0;
|
||||
ActFP8 attn{};
|
||||
rad_buf dense_gate_up = 0;
|
||||
ActFP8 dense_ffn{};
|
||||
MoeFP8::Wire mw{};
|
||||
|
||||
rad_weight token = 0, final_norm = 0, lm_head = 0;
|
||||
rad_op embed = 0, embed_ar = 0, shared_one = 0, final_rms = 0, gather = 0, logits_op = 0;
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
/* Every per-instance state is indexed by slot (rad_build_slot at declare, rad_slot in step). */
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* Flint's layer schedule: full attention (and NoPE) at 0, 1, 5, 9, ..., 45, 48; the other 35
|
||||
* layers are sliding (window 513) and carry RoPE. */
|
||||
static bool is_full(int64_t l) {
|
||||
return l == 0 || l == 1 || l == 48 || (l >= 5 && l <= 45 && (l - 5) % 4 == 0);
|
||||
}
|
||||
|
||||
static int64_t meta_i(const RadModelMeta* meta, const char* a, const char* b, int64_t def) {
|
||||
int64_t v = meta_text_geti(meta, a, INT64_MIN);
|
||||
if (v == INT64_MIN && b) v = meta_text_geti(meta, b, INT64_MIN);
|
||||
return v == INT64_MIN ? def : v;
|
||||
}
|
||||
|
||||
static int check_model(const RadModelMeta* meta, const Geom& g, Model& m) {
|
||||
const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513);
|
||||
const int64_t n_expert = meta_text_geti(meta, "num_experts", meta->n_expert);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
|
||||
const int64_t moe_ff = meta_i(meta, "moe_intermediate_size",
|
||||
"flint.expert_feed_forward_length", 512);
|
||||
const int64_t shared = meta_i(meta, "shared_expert_intermediate_size",
|
||||
"flint.expert_shared_feed_forward_length", 1024);
|
||||
const int64_t dense_ff = meta_i(meta, "intermediate_size",
|
||||
"flint.feed_forward_length", 6144);
|
||||
|
||||
if (g.n_layer != 49 || g.n_embd != 2048 || g.n_head_all != 32 || g.n_head_kv_all != 4 ||
|
||||
g.head_dim != 128 || g.n_vocab_all != 150144 || dense_ff != 6144 ||
|
||||
sliding != 513 || n_expert != 256 || top_k != 6 || moe_ff != 512 || shared != 1024) {
|
||||
fprintf(stderr, "radiance: flint: unsupported geometry (49 layers, 2048-wide, 32/4 "
|
||||
"heads x 128, vocab 150144, 256 experts top-6, expert width 512, shared "
|
||||
"1024, sliding 513); got %lld layers, %lld-wide, %lld/%lld heads, "
|
||||
"vocab %lld, %lld experts top-%lld, expert %lld, shared %lld, "
|
||||
"sliding %lld, dense %lld\n",
|
||||
(long long)g.n_layer, (long long)g.n_embd, (long long)g.n_head_all,
|
||||
(long long)g.n_head_kv_all, (long long)g.n_vocab_all, (long long)n_expert,
|
||||
(long long)top_k, (long long)moe_ff, (long long)shared, (long long)sliding,
|
||||
(long long)dense_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (g.world != 1 && g.world != 2) {
|
||||
fprintf(stderr, "radiance: flint supports tensor-parallel world sizes 1 and 2\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.n_ff_expert = moe_ff;
|
||||
m.n_ff_shared = shared;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
|
||||
const int64_t blocks = width / RAD_FP8_BLOCK;
|
||||
const int64_t base = blocks / world, rem = blocks % world;
|
||||
const int64_t first = rank * base + std::min<int64_t>(rank, rem);
|
||||
const int64_t count = base + (rank < rem ? 1 : 0);
|
||||
*lo = first * RAD_FP8_BLOCK;
|
||||
*hi = (first + count) * RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
|
||||
int status = geom_from(m.g, meta, ctx, "bf16", RAD_BF16);
|
||||
if (status < 0) return status;
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
status = check_model(meta, g, m);
|
||||
if (status < 0) return status;
|
||||
|
||||
if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) {
|
||||
fprintf(stderr, "radiance: flint serves a bf16 or an int8 KV cache, not %s\n",
|
||||
rad_dtype_name((uint32_t)ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
status = yarn_from(g, meta, "", g.head_dim);
|
||||
if (status < 0) return status;
|
||||
|
||||
const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513);
|
||||
const int64_t n_expert_all = meta_text_geti(meta, "num_experts", meta->n_expert);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
|
||||
if (n_expert_all % g.world != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_expert_local = n_expert_all / g.world;
|
||||
|
||||
/* Two paged groups: the 14 full layers grow with the context, the 35 sliding layers keep
|
||||
* only 513 tokens. That is what makes 262K affordable. Both take the deployment's cache
|
||||
* dtype: bf16, or with --kv-cache-dtype i8 the int8 cache (abi/rad_builder.h), K and V as
|
||||
* int8 codes with one f16 scale each per token and head. */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
kd.n_head_kv = g.n_head_kv;
|
||||
kd.head_dim = g.head_dim;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_full"), &kd);
|
||||
if (!m.kv_full) return RAD_E_INVAL;
|
||||
|
||||
RadKVGroupDecl kw = kd;
|
||||
kw.kind = RAD_KV_WINDOW;
|
||||
kw.window = sliding;
|
||||
m.kv_win = rad_decl_kv_group(b, nm.f("kv_win"), &kw);
|
||||
if (!m.kv_win) return RAD_E_INVAL;
|
||||
g.kv_dtype = rad_dtype_name(kd.dtype);
|
||||
|
||||
const int64_t T = g.max_tok, qd = g.q_dim(), kvd = g.kv_dim();
|
||||
|
||||
/* ---- the trunk's stored form, read from layer 0's q projection through that layer's own
|
||||
* LinearFP8, which then does not map it again; the activations below carry rotated int8
|
||||
* codes only for a rotated trunk. */
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
RAD_ARCH_TRY(m.layers[0].attn.q.probe(b, nm, g, nm.f("blk.0.attn_q"),
|
||||
{ nm.ckpt("model.layers.0.self_attn.q_proj.weight") }));
|
||||
{
|
||||
RadEncoding enc{};
|
||||
m.trunk_rot = weight_enc(b, nm.f("blk.0.attn_q.weight"), &enc) &&
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
if (m.trunk_rot) m.trunk_g8 = linear_w8h_group(enc);
|
||||
}
|
||||
|
||||
MoeFP8::Config mc{};
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.n_expert = n_expert_local;
|
||||
mc.expert_base = n_expert_local * g.rank;
|
||||
mc.probed_expert = mc.expert_base;
|
||||
mc.top_k = top_k;
|
||||
mc.n_ff_exp = m.n_ff_expert;
|
||||
mc.norm_topk = 1;
|
||||
mc.sigmoid_router = 1;
|
||||
mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0);
|
||||
mc.shared_ungated = 1;
|
||||
/* One combine at the gather, not two separately reduced arms: TP2 then matches the TP1
|
||||
* arithmetic (the local routed+shared sum is rounded to bf16 once and the closing
|
||||
* all-reduce reduces it), and that single collective folds into the next block's norm. */
|
||||
mc.shared_fp32_combine = 0;
|
||||
mc.shared_one_external = g.world == 1;
|
||||
mc.router_fuse = 1;
|
||||
mc.rows = T < 2048 ? T : 2048;
|
||||
block_slice_128(m.n_ff_shared, g.world, g.rank, &mc.shared_lo, &mc.shared_hi);
|
||||
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
|
||||
|
||||
/* ---- the routed experts' stored form, read from the first routed layer's first owned
|
||||
* expert; every layer is declared with it (MoeFP8::declare checks each layer's own). */
|
||||
const int64_t l_moe = 2;
|
||||
MoeFP8::Src probe_src{};
|
||||
probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l_moe);
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)l_moe, probe_src, &mc));
|
||||
if (m.trunk_rot && (mc.expert_bf16 || !mc.expert_rot)) {
|
||||
fprintf(stderr, "radiance: flint: the trunk is rotated int8 and the routed experts are "
|
||||
"%s; a rotated trunk's experts read its int8 codes and are stored rotated "
|
||||
"(data/recipes/flint-iq8r.recipe)\n",
|
||||
mc.expert_bf16 ? "plain bf16" : "unrotated");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!m.trunk_rot && (mc.expert_i8 || mc.expert_iqr)) {
|
||||
fprintf(stderr, "radiance: flint: the routed experts are rotated int8 and the trunk is "
|
||||
"not; they read the trunk's rotated int8 codes, so convert the trunk with "
|
||||
"them (data/recipes/flint-iq8r.recipe)\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- activation buffers. A rotated trunk's producers write had_quant_act_i8g's codes and
|
||||
* its linears declare no quantiser: the norms (rmsnorm_had_quant_i8g and, at two ranks, its
|
||||
* all-reduce form) where a loaded library serves them, the attention output (q_attn), and the
|
||||
* gated products (gated_had_quant_i8g). Where the norms are not served, each linear
|
||||
* quantises `h` itself and the experts read `hr`, written once a layer. Any other trunk keeps
|
||||
* both code pairs on `h`: E4M3 for four-bit experts, int8 for a plain int8 linear's own
|
||||
* quantiser. */
|
||||
const bool rot = m.trunk_rot;
|
||||
const int64_t g8 = m.trunk_g8;
|
||||
const bool h_fed = rot && rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g"));
|
||||
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, g.n_embd});
|
||||
m.h.x = decl_b(b, nm.f("h"), RAD_BF16, {T, g.n_embd});
|
||||
RAD_ARCH_TRY(m.h.declare_qs(b, nm, g, "h", g.n_embd, 0, true, !h_fed,
|
||||
rot ? g8 : (int64_t)RAD_FP8_BLOCK));
|
||||
m.h.q8_fed = m.h.q8_rot = h_fed;
|
||||
if (rot && !h_fed) {
|
||||
RAD_ARCH_TRY(m.hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
m.hr.q8_fed = m.hr.q8_rot = true;
|
||||
}
|
||||
m.q = decl_b(b, nm.f("attn_q"), RAD_BF16, {T, qd});
|
||||
m.k = decl_b(b, nm.f("attn_k"), RAD_BF16, {T, kvd});
|
||||
m.v = decl_b(b, nm.f("attn_v"), RAD_BF16, {T, kvd});
|
||||
m.attn.x = decl_b(b, nm.f("attn_out"), RAD_BF16, {T, qd});
|
||||
RAD_ARCH_TRY(m.attn.declare_qs(b, nm, g, "attn_out", qd, 0, true, false,
|
||||
rot ? g8 : (int64_t)RAD_FP8_BLOCK));
|
||||
m.attn.q8_fed = m.attn.q8_rot = rot;
|
||||
m.dense_gate_up = decl_b(b, nm.f("dense_gate_up"), RAD_BF16, {T, 2 * g.n_ff});
|
||||
m.dense_ffn.x = decl_b(b, nm.f("dense_ffn"), RAD_BF16, {T, g.n_ff});
|
||||
if (rot)
|
||||
RAD_ARCH_TRY(m.dense_ffn.declare_pair(b, nm, g, "dense_ffn", g.n_ff, 0, true, g8,
|
||||
"gated_had_quant_i8g"));
|
||||
else
|
||||
RAD_ARCH_TRY(m.dense_ffn.declare_qs(b, nm, g, "dense_ffn", g.n_ff, 0, true));
|
||||
m.h_out = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
|
||||
|
||||
const int64_t R = T, S = mc.rows * top_k;
|
||||
m.mw.x = m.x;
|
||||
m.mw.h = m.h;
|
||||
m.mw.hr = m.hr;
|
||||
m.mw.logits = decl_b(b, nm.f("moe_logits"), RAD_F32, {R, n_expert_all});
|
||||
m.mw.ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, top_k});
|
||||
m.mw.ew = decl_b(b, nm.f("moe_weights"), RAD_F32, {R, top_k});
|
||||
m.mw.eoff = decl_b(b, nm.f("moe_offsets"), RAD_I32, {n_expert_local + 1});
|
||||
m.mw.ecnt = decl_b(b, nm.f("moe_counts"), RAD_I32, {n_expert_local}, RAD_BUF_PERSIST);
|
||||
m.mw.sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {S});
|
||||
m.mw.egu = decl_b(b, nm.f("moe_gate_up"), RAD_BF16, {S, 2 * mc.n_ff_exp});
|
||||
m.mw.eff.x = decl_b(b, nm.f("moe_ffn"), RAD_BF16, {S, mc.n_ff_exp});
|
||||
if (rot) {
|
||||
/* The routed arm of a rotated trunk is int8 throughout: the gated product's rotated codes
|
||||
* at one scale a 128 of K, which the grouped GEMM's int8 rows read (MoeFP8::a8). */
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
m.mw.eff.q8_fed = m.mw.eff.q8_rot = true;
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true));
|
||||
}
|
||||
m.mw.edn = decl_b(b, nm.f("moe_down"), RAD_BF16, {S, g.n_embd});
|
||||
m.mw.sgu = decl_b(b, nm.f("shared_gate_up"), RAD_BF16, {T, 2 * mc.n_ff_shared});
|
||||
m.mw.sff.x = decl_b(b, nm.f("shared_ffn"), RAD_BF16, {T, mc.n_ff_shared});
|
||||
if (rot) {
|
||||
/* The shared expert's down projection is a trunk linear whose input codes take the group
|
||||
* its own weight is stored at, read from the first routed layer's through that layer's
|
||||
* own LinearFP8 (which then maps it once). */
|
||||
LinearFP8& sd = m.layers[(size_t)l_moe].moe.sh_down;
|
||||
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.%lld.ffn_down_shexp", (long long)l_moe),
|
||||
{ nm.ckpt("model.layers.%lld.mlp.shared_expert.down_proj.weight",
|
||||
(long long)l_moe) }));
|
||||
const int64_t sg = sd.probed_i8 ? sd.probed_g8 : g8;
|
||||
RAD_ARCH_TRY(m.mw.sff.declare_pair(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true, sg,
|
||||
"gated_had_quant_i8g"));
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.mw.sff.declare_qs(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true));
|
||||
}
|
||||
m.mw.sout = decl_b(b, nm.f("shared_out"), RAD_BF16, {T, g.n_embd});
|
||||
m.mw.sgate = decl_b(b, nm.f("shared_one"), RAD_BF16, {T, 1});
|
||||
if (mc.shared_one_external) {
|
||||
m.shared_one = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 1),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
|
||||
RAD_NOWEIGHTS), {}, {m.mw.sgate});
|
||||
if (!m.shared_one) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.embed_tokens.weight")));
|
||||
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.final_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.token)),
|
||||
{}, {m.x});
|
||||
if (g.world > 1)
|
||||
m.embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.x}, {m.x});
|
||||
|
||||
FlintAttn::Wire aw{};
|
||||
aw.x = m.x; aw.h = m.h; aw.q = m.q; aw.k = m.k; aw.v = m.v; aw.attn = m.attn;
|
||||
MlpFP8::Wire dw{};
|
||||
dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn;
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.dense = (l < 2);
|
||||
lay.sliding = !is_full(l);
|
||||
const char* pre = nm.ckpt("model.layers.%lld", (long long)l);
|
||||
|
||||
FlintAttn::Src as{};
|
||||
as.norm = nm.ckpt("%s.input_layernorm.weight", pre);
|
||||
as.q = nm.ckpt("%s.self_attn.q_proj.weight", pre);
|
||||
as.k = nm.ckpt("%s.self_attn.k_proj.weight", pre);
|
||||
as.v = nm.ckpt("%s.self_attn.v_proj.weight", pre);
|
||||
as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre);
|
||||
as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre);
|
||||
as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre);
|
||||
as.sink = nm.ckpt("%s.self_attn.softmax_offset", pre);
|
||||
as.use_rope = lay.sliding;
|
||||
as.window = lay.sliding ? sliding : 0;
|
||||
|
||||
const rad_kvgroup grp = lay.sliding ? m.kv_win : m.kv_full;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, grp));
|
||||
/* Every block after the first folds the previous block's delta and, at two ranks,
|
||||
* absorbs its all-reduce into its own norm; the last block keeps its add for the plain
|
||||
* final norm and issues its own collective. */
|
||||
const LayerFold f = layer_fold(g, l, g.n_layer, nullptr, 0, false);
|
||||
status = lay.attn.declare(b, nm, g, (int)l, grp, aw, as, f.mix_fold, false, f.mix_ar_in,
|
||||
f.mix_ar_out);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: flint: attention layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{};
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ds.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.gate_proj.weight", mlp);
|
||||
ds.up = nm.ckpt("%s.up_proj.weight", mlp);
|
||||
ds.down = nm.ckpt("%s.down_proj.weight", mlp);
|
||||
status = lay.dense_mlp.declare(b, nm, g, (int)l, dw, ds, true, f.mlp_add,
|
||||
f.mlp_ar_in, f.mlp_ar_out);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: flint: dense layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
} else {
|
||||
MoeFP8::Src ms{};
|
||||
ms.cfg = mc;
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.gate.weight", mlp);
|
||||
/* Flint has no router correction bias. The sigmoid router's bias is
|
||||
* selection-only, so the converter merges a zero [n_expert] tensor under this
|
||||
* name (data/flint-zero-bias.safetensors, `rad-convert --add`). */
|
||||
ms.router_bias = nm.ckpt("%s.expert_bias", mlp);
|
||||
ms.experts = nm.ckpt("%s.experts", mlp);
|
||||
ms.shared = nm.ckpt("%s.shared_expert", mlp);
|
||||
status = lay.moe.declare(b, nm, g, (int)l, m.mw, ms, true, f.mlp_add, f.mlp_ar_in,
|
||||
f.mlp_ar_out);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: flint: MoE layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m.final_rms = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.final_norm)),
|
||||
{m.x}, {m.h.x});
|
||||
m.gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.h.x}, {m.h_out});
|
||||
m.logits_op = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.lm_head)),
|
||||
{m.h_out}, {m.logits});
|
||||
|
||||
rad_note(b, "Flint: %lld layers (2 dense, 47 top-%lld/%lld sigmoid MoE), %lld/%lld "
|
||||
"attention/KV heads x %lld; expert width %lld, shared %lld, window %lld on %s; "
|
||||
"per-head sink on every layer; %s trunk, %s KV cache",
|
||||
(long long)g.n_layer, (long long)top_k, (long long)n_expert_all,
|
||||
(long long)g.n_head_all, (long long)g.n_head_kv_all, (long long)g.head_dim,
|
||||
(long long)m.n_ff_expert, (long long)mc.n_ff_shared, (long long)sliding,
|
||||
g.world == 2 ? "both cards" : "one card",
|
||||
rot ? (g8 == RAD_I8_GROUP_WIDE ? "IQ8R (rotated int8)" : "rotated int8") : "unrotated",
|
||||
g.kv_dtype);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
RAD_ISSUE(c, m.embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token),
|
||||
brows(m.x, batch->n_tok));
|
||||
if (m.embed_ar)
|
||||
RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.x, batch->n_tok), RAD_NONE);
|
||||
|
||||
if (m.shared_one)
|
||||
RAD_ISSUE_N(c, m.shared_one, batch->n_tok, brows(m.mw.sgate, batch->n_tok));
|
||||
for (Layer& layer : m.layers) {
|
||||
layer.attn.step(c, batch);
|
||||
if (layer.dense) layer.dense_mlp.step(c, batch);
|
||||
else layer.moe.step(c, batch);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.final_rms, brows(m.x, batch->n_tok), RAD_W(m.final_norm),
|
||||
brows(m.h.x, batch->n_tok));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.gather, batch->n_out,
|
||||
brows(m.h.x, batch->n_tok), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.h_out, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.logits_op, batch->n_out,
|
||||
brows(m.h_out, batch->n_out), RAD_W(m.lm_head),
|
||||
brows(m.logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace flint
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(flint)
|
||||
static const char* const kFlintTriggers[] = { "<tool_call>" };
|
||||
static const RadChatFormat kFlintChatFormat = {
|
||||
.struct_size = sizeof(RadChatFormat),
|
||||
.name = "flint",
|
||||
.reasoning_open = "<think>",
|
||||
.reasoning_close = "</think>",
|
||||
.reasoning_breaks = kFlintTriggers,
|
||||
.n_reasoning_breaks = 1,
|
||||
.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT,
|
||||
.section_open = nullptr,
|
||||
.section_close = nullptr,
|
||||
.call_separator = nullptr,
|
||||
.call_open = nullptr,
|
||||
.call_close = nullptr,
|
||||
.name_prefix = "<tool_call>",
|
||||
.name_suffix = "",
|
||||
.call_end = "</tool_call>",
|
||||
.arg_prefix = "<arg_key>",
|
||||
.arg_name_suffix = "</arg_key>",
|
||||
.arg_value_prefix = "<arg_value>",
|
||||
.arg_value_suffix = "</arg_value>",
|
||||
.string_value = RAD_CHAT_VALUE_RAW,
|
||||
.other_value = RAD_CHAT_VALUE_JSON,
|
||||
.value_newlines = 1,
|
||||
.triggers = kFlintTriggers,
|
||||
.n_triggers = 1,
|
||||
.args_form = RAD_CHAT_ARGS_TAGGED,
|
||||
};
|
||||
extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
|
||||
return &kFlintChatFormat;
|
||||
}
|
||||
extern "C" const char* rad_arch_id(void) { return "flint"; }
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
extern "C" const char* rad_arch_quant(void) { return ""; }
|
||||
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
|
||||
return flint::declare(b, m, c);
|
||||
}
|
||||
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
|
||||
flint::step(c, batch);
|
||||
}
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
RAD_PLUGIN_ABI_LAYOUT_EXPORT
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) {
|
||||
static const RadPluginInfo info = {
|
||||
RAD_PLUGIN_ARCH, "flint", "0.1.0",
|
||||
"Recursive Flint: 2 dense + 47 sigmoid MoE layers, sink attention, 513 window", ""
|
||||
};
|
||||
return &info;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,272 @@
|
||||
/* flint_attention.h -- Flint's grouped-query attention: per-head Q/K RMSNorm, optional NeoX
|
||||
* RoPE (sliding layers) or no positional encoding (full layers), a learned per-head softmax
|
||||
* sink, a paged bf16 or int8 KV cache, and an optional sliding window.
|
||||
*
|
||||
* Derived from arch/hyv3_common/hyv3_attention.h (the same linears and activation plumbing); the
|
||||
* differences are Flint's:
|
||||
*
|
||||
* - every layer has `self_attn.softmax_offset` (GGUF `attn_sinks`), one learned logit a query
|
||||
* head added to the scaled scores before the softmax;
|
||||
* - the full-attention layers are NoPE, the sliding layers carry NeoX RoPE;
|
||||
* - the sliding layers bound the paged attention with `window` (513).
|
||||
*
|
||||
* The sink and the window ride in attn_paged_sink, which libr4d serves at h128/gqa8 on both
|
||||
* caches. The block's closing all-reduce may be taken by the next block's norm (ar_out).
|
||||
*/
|
||||
#ifndef FLINT_ATTENTION_H
|
||||
#define FLINT_ATTENTION_H
|
||||
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct FlintAttn {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */
|
||||
rad_buf q = 0; /* [max_tok, q_dim], projected, normed and rotated */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim] */
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* q = nullptr;
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
const char* o = nullptr;
|
||||
/* `self_attn.softmax_offset` (no `.weight` suffix). Null declares no sink. */
|
||||
const char* sink = nullptr;
|
||||
bool use_rope = true;
|
||||
int64_t window = 0; /* 0: full attention */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0, w_sink = 0;
|
||||
LinearFP8 q{}, k{}, v{}, o{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
rad_op op_q_norm = 0, op_k_norm = 0;
|
||||
rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0;
|
||||
rad_op op_qkr_store = 0; /* Q/K norms, NeoX rotary (or none) and cache store, decode band */
|
||||
int64_t qkr_rows = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* The next block's norm absorbs this block's closing all-reduce (NormQuantFP8::fuse_ar), so
|
||||
* this one must not issue it. Counterpart of `ar_in`; both sides ask ar_taken(g, T, ...) on
|
||||
* the same facts, so they agree. */
|
||||
bool ar_out = false;
|
||||
int ar_out_take = kArOutNorm;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int FlintAttn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, const Wire& wire, const Src& src,
|
||||
bool fold, bool add_out, int ar_in, bool ar_out_) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
layer = l;
|
||||
kv = group;
|
||||
ar_out = ar_out_;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: flint declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld\n", g.world, (long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
if (!w_norm || !w_q_norm || !w_k_norm) return RAD_E_INVAL;
|
||||
|
||||
/* The learned softmax offset, one f32 a query head, sharded with the heads. */
|
||||
if (src.sink) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_sinks", l), src.sink));
|
||||
w_sink = decl_w(b, nm.f("blk.%d.attn_sinks", l), RAD_F32, {g.n_head},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
if (!w_sink) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
// As in the other pre-norm blocks, absorb a preceding delta into the residual stream.
|
||||
// The fused kernel normalizes the BF16-rounded sum, not an unrounded FP32 substitute.
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0, 0, ar_in));
|
||||
RAD_ARCH_TRY(q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), q_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.q}, w.h, w.q));
|
||||
RAD_ARCH_TRY(k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.k}, w.h, w.k));
|
||||
RAD_ARCH_TRY(v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.v}, w.h, w.v));
|
||||
|
||||
auto head_norm = [&](int64_t heads, rad_weight wt) {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q});
|
||||
op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
|
||||
if (src.use_rope) {
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
|
||||
"neox"),
|
||||
{w.k}, {w.k});
|
||||
}
|
||||
|
||||
const rad_op attn = w_sink
|
||||
? rw(b, RAD_OP(b, "attn_paged_sink",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", src.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)),
|
||||
{w.q}, {w.attn.x})
|
||||
: rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", src.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.x});
|
||||
op_attn = attn;
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), 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),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* The fused prologue serves the rope layers and, with `rotary_dim` 0, the NoPE ones: the
|
||||
* kernel then only copies the normed head through the rotary stage. Rows exist for the bf16
|
||||
* and the int8 cache (qkv_norm_rope_kv_store_h128_bf16, _i8); prefill heights and libraries
|
||||
* without the fold take the standalone norms, ropes and kv_store. */
|
||||
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
|
||||
(!std::strcmp(g.kv_dtype, "bf16") || !std::strcmp(g.kv_dtype, "i8")) &&
|
||||
!g.rope_mc && g.yarn.factor == 0.0f &&
|
||||
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
|
||||
qkr_rows = qk_fuse_rows(g);
|
||||
op_qkr_store = RAD_OP(b, "qkv_norm_rope_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qkr_rows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
|
||||
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("v_norm", 0),
|
||||
RAD_INT("rotary_dim", src.use_rope ? g.head_dim : 0),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm));
|
||||
if (!op_qkr_store || !rad_op_resolved(b, op_qkr_store)) op_qkr_store = 0;
|
||||
if (op_qkr_store)
|
||||
op_qkr_store = rw(b, op_qkr_store, {w.q, w.k, w.v}, {w.q, w.k, w.v});
|
||||
}
|
||||
|
||||
/* The out projection's input codes: where the model feeds them (a rotated int8 trunk,
|
||||
* ActFP8::q8_fed), q_attn writes had_quant_act_i8g's pair and the projection declares no
|
||||
* quantiser. Otherwise every form the out projection can take reads the bf16 plane or
|
||||
* quantises it itself (LinearFP8 refuses the E4M3-pair formats), so no quantiser runs here. */
|
||||
if (w.attn.q8_fed) RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
|
||||
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), {src.o}, w.attn, w.h.x));
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
if (add_out) op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
/* A rope layer needs either the fused prologue or both standalone rope ops; without this,
|
||||
* step() would silently skip the rotation. */
|
||||
const bool rope_ok = !src.use_rope || op_qkr_store || (op_rope_q && op_rope_k);
|
||||
return op_attn && op_kv_store && rope_ok && (!add_out || op_add) &&
|
||||
(op_qkr_store || (op_q_norm && op_k_norm))
|
||||
? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
inline void FlintAttn::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
nq_h.step(c, T);
|
||||
q.step(c, w.h, w.q, T);
|
||||
k.step(c, w.h, w.k, T);
|
||||
v.step(c, w.h, w.v, T);
|
||||
if (op_qkr_store && T <= qkr_rows) {
|
||||
RAD_ISSUE_N(c, op_qkr_store, T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
rope_posmc(g, batch, T), RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
if (op_rope_q) {
|
||||
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
RAD_ISSUE(c, op_kv_store, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, layer));
|
||||
}
|
||||
if (w_sink)
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
RAD_W(w_sink), brows(w.attn.x, T));
|
||||
else
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
q_attn.step(c, T);
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (issues_ar(T)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
|
||||
#endif /* FLINT_ATTENTION_H */
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/museglimmer -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(museglimmer LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(museglimmer architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/museglimmer.cpp)
|
||||
@@ -0,0 +1,71 @@
|
||||
/* Muse Glimmer's reply format: the ATEM channel protocol its chat template renders.
|
||||
*
|
||||
* The template's generation prompt ends at `<|start|>assistant`, so the model opens its own
|
||||
* channels: `<to=self>` reasoning first, then the answer:
|
||||
*
|
||||
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=user<|message|> ...answer...
|
||||
*
|
||||
* `reasoning_close` carries the whole channel transition, so the answer's own header is consumed
|
||||
* with the reasoning block's close and the content begins at the answer's first byte. A reply
|
||||
* that skips the reasoning opens on the answer's channel directly (`to=user<|message|> ...`);
|
||||
* `content_open` names that header so it is dropped there too.
|
||||
*
|
||||
* Tool calls are the template's ATEM dialect, emitted as their own assistant turn whose channel
|
||||
* names the tool (chat_template.jinja, render_atem):
|
||||
*
|
||||
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=NAME<|message|>
|
||||
* <atem:function_calls>
|
||||
* <atem:invoke name="NAME">
|
||||
* <atem:parameter name="k">value</atem:parameter>
|
||||
* </atem:invoke>
|
||||
* </atem:function_calls>
|
||||
*
|
||||
* String parameters are written raw, everything else as JSON (the template's `tojson`); the
|
||||
* section opener is the constrained-decoding trigger, and it is also the reasoning break: a call
|
||||
* turn's channel header names the tool rather than `user`, so the answer's `reasoning_close`
|
||||
* does not match there and the reasoning block runs to the section, swallowing the `<|eom|>` and
|
||||
* the header.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace museglimmer {
|
||||
|
||||
inline const RadChatFormat* muse_chat_format() {
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat x{};
|
||||
x.struct_size = sizeof(x);
|
||||
x.name = "plugin:museglimmer";
|
||||
x.reasoning_open = "to=self<|message|>";
|
||||
x.reasoning_close = "<|eom|><|start|>assistant to=user<|message|>";
|
||||
static const char* const kBreaks[] = {"<atem:function_calls>"};
|
||||
x.reasoning_breaks = kBreaks;
|
||||
x.n_reasoning_breaks = 1;
|
||||
/* The model opens its own channel; the prompt carries none. */
|
||||
x.reasoning_in_prompt = RAD_CHAT_THINK_NEVER;
|
||||
x.content_open = "to=user<|message|>";
|
||||
x.section_open = "<atem:function_calls>";
|
||||
x.section_close = "</atem:function_calls>";
|
||||
x.call_open = "<atem:invoke ";
|
||||
x.name_prefix = "name=\"";
|
||||
x.name_suffix = "\">";
|
||||
x.call_end = "</atem:invoke>";
|
||||
x.arg_prefix = "<atem:parameter name=\"";
|
||||
x.arg_name_suffix = "\">";
|
||||
x.arg_value_suffix = "</atem:parameter>";
|
||||
x.string_value = RAD_CHAT_VALUE_RAW; /* the template writes string arguments raw */
|
||||
x.other_value = RAD_CHAT_VALUE_JSON; /* booleans, numbers, arrays, objects as tojson */
|
||||
x.value_newlines = 1;
|
||||
/* No grammar triggers: the reference deployment (vLLM's --tool-call-parser muse) runs
|
||||
* unconstrained and parses whatever the model writes. A trigger arms the lazy tool-call
|
||||
* grammar, and with the DFlash drafter the trigger fires mid-verify -- inside drafted
|
||||
* text -- at the reasoning-to-call boundary, which spins the sampler and loops the
|
||||
* channel header (measured: drafter on = the header repeats 3-4x and the reply stalls;
|
||||
* drafter off = one header, clean call). The streaming parser reads natural ATEM as
|
||||
* it is. */
|
||||
return x;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace museglimmer */
|
||||
@@ -0,0 +1,847 @@
|
||||
/* museglimmer.cpp -- Meta's Muse Glimmer 30B, bf16 weights and bf16 activations.
|
||||
*
|
||||
* Muse Glimmer (HF `meta-models/Muse-Glimmer-30B`, model_type `muse_glimmer`) is a dense text
|
||||
* model with a separate vision tower. The text trunk here is served by this plugin; the tower and
|
||||
* its projector are declared at the bottom of declare() when the deployment asked for media.
|
||||
*
|
||||
* ============================== WHAT IT SERVES ==============================
|
||||
*
|
||||
* The unquantised release (quantisation descriptor ""), every projection a bf16 GEMM. The lm_head
|
||||
* is declared at whatever the model holds, so a recipe-made block-fp8 head uses the fp8 logits
|
||||
* kernel.
|
||||
*
|
||||
* ============================== THE SHAPE, AT 30B ==============================
|
||||
*
|
||||
* 52 layers, `layer_types` full_attention on every 4th layer counted back from the last
|
||||
* (3, 7, ..., 51; the shipped config states the array, and this plugin checks
|
||||
* it against full_attention_interval 4 rather than trusting either alone)
|
||||
* hidden 6656 ffn 19968 vocab 202048 (lm_head not tied)
|
||||
* 32 heads / 2 kv heads / head_dim 128 -> GQA 16
|
||||
* sliding_window 2048: the sliding layers own a RAD_KV_WINDOW pool, the full layers a
|
||||
* RAD_KV_FULL pool; a sequence holds one state per bound layer of each group
|
||||
* q and output gate are SEPARATE checkpoint tensors (`q_proj`, `gate_proj`), unlike Qwen3.5's
|
||||
* interleaved q_proj -- two GEMMs, two buffers, no fused q|gate row
|
||||
* `layer_rope_theta`: 500000 on the sliding layers, 0 on the full ones. A 0 layer is NoPE: no
|
||||
* rotary is declared or issued there (the reference passes
|
||||
* position_embeddings=None). max_position_embeddings 131072, rope_type default
|
||||
*
|
||||
* ============================== WHAT DIFFERS FROM A LLAMA-LIKE ==============================
|
||||
*
|
||||
* Every deviation from the Qwen/Llama shape below is load-bearing; getting one wrong yields
|
||||
* fluent wrong text (spec §17 refuses instead).
|
||||
*
|
||||
* * Four norms a layer, all Gemma-2 style "centered" norms, x_hat * (1 + w): the attention's
|
||||
* input (rms_norm_eps 1e-5) and its output (post_norm_eps 1e-8), then the feed-forward's input
|
||||
* (1e-5) and output (1e-8). The residual adds the *normed* branch, not the raw one.
|
||||
* * The q/k "norm" is weightless: MuseGlimmerRMSNorm(with_scale=False), a plain RMS norm over
|
||||
* head_dim at rms_norm_eps. The query is then multiplied by `qk_scale_factor` (3.87); the key
|
||||
* is not. The attention scale stays 1/sqrt(head_dim). `rmsnorm` serves both: no gain operand,
|
||||
* `mult` on the query.
|
||||
* * The embedding is normed after the lookup: a weightless RMS norm at rms_norm_eps on the
|
||||
* gathered rows (MuseGlimmerTextNormedEmbedding). It cannot be folded into the table because
|
||||
* a drafter embeds without it, so it is an op.
|
||||
* * The final norm (`model.language_model.norm.weight`) is a plain RMSNorm WITH a gain and
|
||||
* without the centered 1+: wadd 0, unlike every layer norm.
|
||||
* * The logits are pre-scaled by `output_multiplier` (1/sqrt(26)) before the Gemma-style tanh
|
||||
* softcap: 20 * tanh(logits * mult / 20). The multiplier is carried on the final norm's
|
||||
* `mult` (its output feeds only the head), the cap on `logit_softcap` over the f32 logits.
|
||||
*
|
||||
* ============================== WHAT THIS PLUGIN DOES NOT DECLARE ==============================
|
||||
*
|
||||
* The speculative drafter Meta ships beside the model (a DFlash block stack over layers
|
||||
* 1, 13, 25, 37, 49) is not declared: it lives in its own checkpoint with its own `draft.`
|
||||
* config, which this tree has no fixture for. Serving the trunk alone is a complete model.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_museglimmer_vision.h>
|
||||
#include <arch/rad_block_muse_dflash.h>
|
||||
#include <arch/rad_calib_full.h>
|
||||
#include "chat.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
|
||||
namespace museglimmer {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* ---- the checkpoint's config. A multimodal model keeps the trunk under `text_config.`; accept
|
||||
* the bare spelling too, so a text-only GGUF container of the same family reads the same way. */
|
||||
namespace {
|
||||
|
||||
double cfg_f(const RadModelMeta* m, const char* key, double dflt) {
|
||||
return rad_meta_getf(m, (std::string("text_config.") + key).c_str(),
|
||||
rad_meta_getf(m, key, dflt));
|
||||
}
|
||||
long long cfg_i(const RadModelMeta* m, const char* key, long long dflt) {
|
||||
return rad_meta_geti(m, (std::string("text_config.") + key).c_str(),
|
||||
rad_meta_geti(m, key, dflt));
|
||||
}
|
||||
const char* cfg_s(const RadModelMeta* m, const char* key, const char* dflt) {
|
||||
return rad_meta_gets(m, (std::string("text_config.") + key).c_str(),
|
||||
rad_meta_gets(m, key, dflt));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* One trunk layer. The rope ops exist only where layer_rope_theta says so; the branch is fixed
|
||||
* per layer by the model. */
|
||||
struct Layer {
|
||||
int full = 0; /* full attention (no window, no rope in this family) */
|
||||
int rope = 0; /* carries a rotary (the sliding layers) */
|
||||
|
||||
rad_weight w_norm = 0, w_post = 0, w_q = 0, w_gate = 0, w_k = 0, w_v = 0, w_o = 0;
|
||||
rad_weight w_fnorm = 0, w_fpost = 0, w_gate_up = 0, w_down = 0;
|
||||
|
||||
rad_op op_norm = 0, op_q = 0, op_gate = 0, op_k = 0, op_v = 0;
|
||||
rad_op op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0;
|
||||
rad_op op_kv = 0, op_attn = 0, op_sig = 0, op_mul = 0, op_o = 0, op_ar = 0;
|
||||
rad_op op_post = 0, op_add = 0;
|
||||
rad_op op_fnorm = 0, op_gu = 0, op_act = 0, op_down = 0, op_far = 0, op_fpost = 0, op_fadd = 0;
|
||||
|
||||
/* The layer's calibration inputs (rad_calib_full.h): -1 where the run does not record it. */
|
||||
int cs_in = -1, cs_o = -1, cs_mlp = -1, cs_down = -1;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{}; /* the trunk geometry, the rank's shard of it */
|
||||
Geom g_rope{}; /* the same, with the sliding layers' rotary base (decl_rope reads theta) */
|
||||
float qk_mult = 0; /* qk_scale_factor */
|
||||
float post_eps = 0; /* post_norm_eps */
|
||||
float out_mult = 0; /* output_multiplier */
|
||||
float softcap = 0; /* final_logit_softcapping; 0: none */
|
||||
int64_t window = 0; /* sliding_window */
|
||||
|
||||
rad_kvgroup kv_win = 0, kv_full = 0;
|
||||
|
||||
/* the residual stream and the two vocabulary edges */
|
||||
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
|
||||
rad_buf b_q = 0, b_gate = 0, b_k = 0, b_v = 0, b_attn = 0;
|
||||
rad_buf b_gu = 0, b_ffn = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_embed_norm = 0;
|
||||
rad_op op_final_norm = 0, op_gather = 0, op_logits = 0, op_cap = 0;
|
||||
|
||||
/* ---- media (arch/common/rad_block_museglimmer_vision.h): the vision tower and the scatter of
|
||||
* its rows, declared only when the container carries a tower and the deployment asked for
|
||||
* media. The tower is declared last, so its activations share the arena with every buffer
|
||||
* above. */
|
||||
bool media = false;
|
||||
rad_op op_media_rows = 0;
|
||||
MuseTower vit{};
|
||||
|
||||
/* ---- the DFlash drafter (arch/common/rad_block_muse_dflash.h): declared last, only when the
|
||||
* container carries one and the serve asks for drafts. It reads the trunk's residual stream at
|
||||
* `draft.target_layer_ids`, keeps its own KV group, and proposes `block_size - 1` tokens a
|
||||
* pass for the trunk to verify. */
|
||||
bool have_df = false;
|
||||
MuseDflash df{};
|
||||
MuseDflash::Wire dfw{};
|
||||
MuseTaps taps{};
|
||||
rad_kvgroup kv_draft = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
/* --calib-dir: the whole Hessian of every linear's input over a --calib-corpus run. */
|
||||
CalibFull calib;
|
||||
int cs_head = -1;
|
||||
};
|
||||
|
||||
/* Declare runs once per rank of an instance, on the rank's own thread (spec §1, §9); every
|
||||
* instance's state is its slot's (rad_build_slot / rad_slot). */
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
|
||||
/* A routed model is not this family. */
|
||||
if (meta->n_expert > 0) {
|
||||
fprintf(stderr, "radiance: museglimmer refuses a checkpoint with %lld experts\n",
|
||||
(long long)meta->n_expert);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
/* ---- the family's own config. Everything that changes the mathematics is required or read
|
||||
* from the family defaults the reference config class states; a wrong default yields fluent
|
||||
* wrong text, so nothing here falls back to a "reasonable" value silently. */
|
||||
m.qk_mult = (float)cfg_f(meta, "qk_scale_factor", 3.87);
|
||||
m.post_eps = (float)cfg_f(meta, "post_norm_eps", 1e-8);
|
||||
m.out_mult = (float)cfg_f(meta, "output_multiplier", 0.19611613513818404);
|
||||
m.softcap = (float)cfg_f(meta, "final_logit_softcapping", 20.0);
|
||||
m.window = cfg_i(meta, "sliding_window", 2048);
|
||||
const double theta_rope = cfg_f(meta, "rope_parameters.rope_theta",
|
||||
cfg_f(meta, "rope_theta", 0.0));
|
||||
if (!(m.qk_mult > 0.0f) || !(m.out_mult > 0.0f) || !(m.post_eps > 0.0f) || m.window <= 0 ||
|
||||
!(theta_rope > 0.0)) {
|
||||
fprintf(stderr, "radiance: museglimmer: qk_scale_factor %g output_multiplier %g "
|
||||
"post_norm_eps %g sliding_window %lld rope theta %g are all required\n",
|
||||
(double)m.qk_mult, (double)m.out_mult, (double)m.post_eps,
|
||||
(long long)m.window, theta_rope);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (g.rope_mc) {
|
||||
fprintf(stderr, "radiance: museglimmer: the trunk has one-component rotary; a container "
|
||||
"with mrope_section is not this family\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The rotary width is the full head: rope_parameters has no partial_rotary_factor and the
|
||||
* reference rotates all of head_dim. */
|
||||
const int64_t n_rot = g.head_dim;
|
||||
|
||||
/* ---- layer kinds. The config ships `layer_types`; where it does not (a GGUF container), the
|
||||
* interval rule stands in. The two must agree where both exist: the schedule decides which
|
||||
* layers keep a long context, and a wrong layer still generates fluent text. */
|
||||
std::vector<int> full;
|
||||
const char* kinds = cfg_s(meta, "layer_types", nullptr);
|
||||
if (kinds && *kinds)
|
||||
RAD_ARCH_TRY(parse_layer_kinds("museglimmer", kinds, {"full_attention"},
|
||||
"sliding_attention", &full));
|
||||
const int64_t interval = 4;
|
||||
if ((int64_t)full.size() < g.n_layer) {
|
||||
full.assign((size_t)g.n_layer, 0);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) full[(size_t)l] = is_full_attention(l, interval);
|
||||
if (kinds && *kinds)
|
||||
rad_note(b, "the container's layer_types named %zu layers and the model has %lld; "
|
||||
"building the full-attention layers by the interval %lld",
|
||||
full.size() - (size_t)g.n_layer + (size_t)g.n_layer, (long long)g.n_layer,
|
||||
(long long)interval);
|
||||
} else {
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
if ((full[(size_t)l] != 0) != is_full_attention(l, interval)) {
|
||||
fprintf(stderr, "radiance: museglimmer: layer_types makes layer %lld %s and "
|
||||
"full_attention_interval %lld makes it %s\n",
|
||||
(long long)l, full[(size_t)l] ? "full" : "sliding", (long long)interval,
|
||||
is_full_attention(l, interval) ? "full" : "sliding");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Per-layer rotary: the shipped `layer_rope_theta`, else the family pattern (theta on the
|
||||
* sliding layers, 0 -- NoPE -- on the full ones). */
|
||||
std::vector<float> theta((size_t)g.n_layer, 0.0f);
|
||||
const char* thetas = cfg_s(meta, "layer_rope_theta", nullptr);
|
||||
if (thetas && *thetas) {
|
||||
size_t i = 0;
|
||||
for_each_token(thetas, [&](const char* t, size_t n) {
|
||||
if (i >= theta.size()) return false;
|
||||
char* e = nullptr;
|
||||
const double v = std::strtod(std::string(t, n).c_str(), &e);
|
||||
theta[i++] = e == t ? -1.0f : (float)v;
|
||||
return true;
|
||||
});
|
||||
if (i < theta.size()) {
|
||||
fprintf(stderr, "radiance: museglimmer: layer_rope_theta names %zu layers and the "
|
||||
"model has %lld\n", i, (long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else {
|
||||
for (int64_t l = 0; l < g.n_layer; ++l)
|
||||
theta[(size_t)l] = full[(size_t)l] ? 0.0f : (float)theta_rope;
|
||||
}
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
if (!(theta[(size_t)l] >= 0.0f)) {
|
||||
fprintf(stderr, "radiance: museglimmer: layer_rope_theta[%lld] is not a number\n",
|
||||
(long long)l);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* Two Geoms: the trunk's for the buffers and shards, one with the sliding layers' rotary base
|
||||
* for the rope ops (decl_rope takes theta from the Geom it is given). The rotary scaling is
|
||||
* read into the rope Geom, against the sliding layers' own base: the extension reaches their
|
||||
* rope and leaves the NoPE full layers untouched (they have no rotary to scale), and the
|
||||
* mechanical extension past the trained 131072 positions -- which this family takes well, the
|
||||
* full layers carrying no positions and the sliding ones reading only in-window relative
|
||||
* offsets -- is the no-keys default this call returns. */
|
||||
m.g_rope = g;
|
||||
m.g_rope.theta = (float)theta_rope;
|
||||
RAD_ARCH_TRY(yarn_from(m.g_rope, meta, "", g.head_dim));
|
||||
|
||||
const int64_t q_dim = g.q_dim();
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
|
||||
/* ---- two KV groups (spec §7.2): the sliding layers' pool recycles blocks below the window,
|
||||
* the full layers' does not. A group with no bound layers is a declare error. */
|
||||
const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_WINDOW;
|
||||
sd.dtype = kvdt;
|
||||
sd.window = m.window;
|
||||
sd.n_head_kv = g.n_head_kv;
|
||||
sd.head_dim = g.head_dim;
|
||||
m.kv_win = rad_decl_kv_group(b, nm.f("kv_sliding"), &sd);
|
||||
RadKVGroupDecl gd{};
|
||||
gd.kind = RAD_KV_FULL;
|
||||
gd.dtype = kvdt;
|
||||
gd.n_head_kv = g.n_head_kv;
|
||||
gd.head_dim = g.head_dim;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_full"), &gd);
|
||||
g.kv_dtype = rad_dtype_name(kvdt);
|
||||
if (m.kv_win == 0 || m.kv_full == 0) {
|
||||
fprintf(stderr, "radiance: museglimmer: a KV group failed to declare\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- activation buffers, sized at max_tok and shared by every layer; liveness over the
|
||||
* declared read and write sets fits them in one arena (spec §3.1). */
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim});
|
||||
m.b_gate = decl_b(b, nm.f("attn_gate"),g.act_dtype, {g.max_tok, q_dim});
|
||||
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim});
|
||||
m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, kv_dim});
|
||||
m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim});
|
||||
m.b_gu = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
|
||||
m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
|
||||
/* The lm_head runs over the sampled rows only (RadBatch::out_ids), not the whole step. */
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
|
||||
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
|
||||
|
||||
/* ---- the drafter's taps. Declared before the trunk's layers: the buffer planner takes
|
||||
* lifetimes in declaration order, so a tap buffer declared after them could share bytes a
|
||||
* layer temporary lands on, and acceptance would collapse with no other symptom. */
|
||||
if (ctx->max_spec > 0 && m.taps.read(meta, g.n_layer) > 0) {
|
||||
RAD_ARCH_TRY(m.taps.declare(b, nm, g, g.max_tok, m.b_x, g.act_dtype));
|
||||
if (m.taps.n <= 0) {
|
||||
fprintf(stderr, "radiance: museglimmer: the container carries a drafter whose "
|
||||
"draft.target_layer_ids name no layer of this %lld-layer trunk\n",
|
||||
(long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ---- vocabulary edges, both row-sharded. The 30B does not tie its head; the second source
|
||||
* serves family members that do, first present wins. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"),
|
||||
nm.ckpt("model.language_model.norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
/* A plain RMSNorm with a gain: declared at f32, cast at load, read with wadd 0. */
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
/* The embedding norm, after the vocabulary shard's reduction: a weightless RMS norm at
|
||||
* rms_norm_eps, in place. Weightless because MuseGlimmerTextNormedEmbedding has no gain. */
|
||||
m.op_embed_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* The encoder's rows overwrite the lookup before its reduction (as rad_block_vit.h's
|
||||
* MediaRows): declared only when the tower is served, issued on the passes that carry rows,
|
||||
* so the reduction counts each row once. */
|
||||
m.media = MuseTower::present(meta) && ctx->max_enc_patches > 0;
|
||||
if (m.media)
|
||||
m.op_media_rows = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* ---- calibration: the widest split input bounds the Hessian's width. */
|
||||
RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, g.n_layer,
|
||||
std::max({g.n_embd, q_dim * g.world, g.n_ff * g.world}),
|
||||
std::max({g.n_embd, q_dim * g.world, g.n_ff * g.world})));
|
||||
|
||||
/* ---- the layers. */
|
||||
const int64_t attn_scale_num = 1; /* attention scale stays 1/sqrt(head_dim): the query's
|
||||
* qk_scale_factor rides the q norm's `mult`. */
|
||||
(void)attn_scale_num;
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.full = full[(size_t)l];
|
||||
lay.rope = theta[(size_t)l] > 0.0f;
|
||||
const bool glob = lay.full;
|
||||
rad_kvgroup kg = glob ? m.kv_full : m.kv_win;
|
||||
const char* pre = "model.language_model.layers";
|
||||
const Geom& gr = lay.rope ? m.g_rope : m.g;
|
||||
|
||||
/* -- weights. Shapes are [out, in]; gemm_nt reads B transposed. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
|
||||
nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_post.weight", l),
|
||||
nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l),
|
||||
nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_gate.weight", l),
|
||||
nm.ckpt("%s.%lld.self_attn.gate_proj.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l),
|
||||
nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l),
|
||||
nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
|
||||
nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l),
|
||||
nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_post.weight", l),
|
||||
nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up.weight", l),
|
||||
{nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l),
|
||||
nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l)},
|
||||
0));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_down.weight", l),
|
||||
nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l)));
|
||||
|
||||
lay.w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
lay.w_post = decl_w(b, nm.f("blk.%d.attn_post.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
lay.w_q = decl_w(b, nm.f("blk.%d.attn_q.weight", l), RAD_BF16, {q_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
lay.w_gate = decl_w(b, nm.f("blk.%d.attn_gate.weight", l), RAD_BF16, {q_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
lay.w_k = decl_w(b, nm.f("blk.%d.attn_k.weight", l), RAD_BF16, {kv_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
lay.w_v = decl_w(b, nm.f("blk.%d.attn_v.weight", l), RAD_BF16, {kv_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
lay.w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
lay.w_fnorm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
lay.w_fpost = decl_w(b, nm.f("blk.%d.ffn_post.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
lay.w_gate_up= decl_w(b, nm.f("blk.%d.ffn_gate_up.weight", l), RAD_BF16,
|
||||
{2 * g.n_ff, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
|
||||
grp_layer(l), 0, {g.n_ff, g.n_ff});
|
||||
lay.w_down = decl_w(b, nm.f("blk.%d.ffn_down.weight", l), RAD_BF16, {g.n_embd, g.n_ff},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
|
||||
/* -- ops, in run order except attn_paged, declared before kv_store like every family: the
|
||||
* two touch disjoint buffers and the block size comes from the resolved kernel. */
|
||||
lay.op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 1.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
lay.op_q = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_q)),
|
||||
{m.b_h}, {m.b_q});
|
||||
lay.op_gate = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_gate)),
|
||||
{m.b_h}, {m.b_gate});
|
||||
lay.op_k = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_k)),
|
||||
{m.b_h}, {m.b_k});
|
||||
lay.op_v = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_v)),
|
||||
{m.b_h}, {m.b_v});
|
||||
|
||||
/* The q/k norms are weightless (no gain operand), the query carrying qk_scale_factor on
|
||||
* `mult`. Both run in place: a row's scale is computed before the row is written. */
|
||||
lay.op_qn = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("mult", (double)m.qk_mult), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_q}, {m.b_q});
|
||||
lay.op_kn = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_k}, {m.b_k});
|
||||
|
||||
if (lay.rope) {
|
||||
lay.op_rq = rw(b, decl_rope(b, gr, g.max_tok, g.head_dim, g.n_head, 0, n_rot, "neox"),
|
||||
{m.b_q}, {m.b_q});
|
||||
lay.op_rk = rw(b, decl_rope(b, gr, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, "neox"),
|
||||
{m.b_k}, {m.b_k});
|
||||
}
|
||||
|
||||
lay.op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()),
|
||||
RAD_INT("causal", 1),
|
||||
RAD_INT("window", glob ? 0 : m.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),
|
||||
{m.b_q}, {m.b_attn});
|
||||
|
||||
lay.op_kv = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), 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, kg)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_k, m.b_v}, {});
|
||||
|
||||
/* out = attn * sigmoid(gate): two ops, as in the gated-attention block. */
|
||||
lay.op_sig = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_gate}, {m.b_gate});
|
||||
lay.op_mul = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_attn, m.b_gate}, {m.b_attn});
|
||||
|
||||
lay.op_o = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", q_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_o)),
|
||||
{m.b_attn}, {m.b_h});
|
||||
if (g.world > 1)
|
||||
lay.op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_h}, {m.b_h});
|
||||
/* The branch's own norm, at post_norm_eps, before the residual add. */
|
||||
lay.op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", m.post_eps), RAD_F64("wadd", 1.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_post)),
|
||||
{m.b_h}, {m.b_h});
|
||||
lay.op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x, m.b_h}, {m.b_x});
|
||||
|
||||
/* ---- the feed-forward, the same double norm. */
|
||||
lay.op_fnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 1.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_fnorm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
lay.op_gu = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_gate_up)),
|
||||
{m.b_h}, {m.b_gu});
|
||||
lay.op_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_gu}, {m.b_ffn});
|
||||
lay.op_down = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_down)),
|
||||
{m.b_ffn}, {m.b_h});
|
||||
if (g.world > 1)
|
||||
lay.op_far = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_h}, {m.b_h});
|
||||
lay.op_fpost = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", m.post_eps), RAD_F64("wadd", 1.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_fpost)),
|
||||
{m.b_h}, {m.b_h});
|
||||
lay.op_fadd = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x, m.b_h}, {m.b_x});
|
||||
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
|
||||
|
||||
/* -- calibration taps, the same four a dense family records. */
|
||||
if (m.calib.records(l)) {
|
||||
const std::string L = std::string(pre) + "." + std::to_string(l);
|
||||
lay.cs_in = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".input",
|
||||
L + ".self_attn.q_proj," + L + ".self_attn.k_proj," +
|
||||
L + ".self_attn.v_proj," + L + ".self_attn.gate_proj",
|
||||
m.b_h, g.n_embd, g.n_embd));
|
||||
lay.cs_o = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".self_attn.o_proj.input", L + ".self_attn.o_proj",
|
||||
m.b_attn, q_dim, q_dim * g.world));
|
||||
lay.cs_mlp = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".pre_feedforward.input",
|
||||
L + ".mlp.gate_proj," + L + ".mlp.up_proj",
|
||||
m.b_h, g.n_embd, g.n_embd));
|
||||
lay.cs_down = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".mlp.down_proj.input", L + ".mlp.down_proj",
|
||||
m.b_ffn, g.n_ff, g.n_ff * g.world));
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the head. The final norm is a plain RMSNorm (wadd 0) that also carries the logits'
|
||||
* pre-scale: its output feeds only the head, so mult here is logits * output_multiplier
|
||||
* exactly. */
|
||||
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_F64("mult", (double)m.out_mult), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
if (m.calib.on && m.calib.hi == g.n_layer) {
|
||||
m.cs_head = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, -1, "lm_head.input", "lm_head", m.b_h, g.n_embd, g.n_embd));
|
||||
}
|
||||
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_h}, {m.b_hout});
|
||||
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_lm_head)),
|
||||
{m.b_hout}, {m.b_logits});
|
||||
/* cap * tanh(x / cap) over the f32 logits, after the pre-scale. */
|
||||
if (m.softcap > 0.0f) {
|
||||
m.op_cap = rw(b, RAD_OP(b, "logit_softcap",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", g.n_vocab), RAD_F64("cap", (double)m.softcap),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_logits}, {m.b_logits});
|
||||
if (!m.op_cap)
|
||||
rad_note(b, "warning: no kernel serves `logit_softcap` (load libr4d or libavx), so "
|
||||
"the logits skip %g * tanh(x / %g): greedy output is unchanged, sampled "
|
||||
"output draws from a sharper distribution", (double)m.softcap,
|
||||
(double)m.softcap);
|
||||
}
|
||||
|
||||
/* ---- media: the vision tower, declared last so its activations share the arena with every
|
||||
* buffer above (the trunk's weights were mapped and declared first). */
|
||||
if (m.media)
|
||||
RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer));
|
||||
|
||||
/* ---- the DFlash drafter, declared last: its passes run after the whole trunk's, and the
|
||||
* planner lays lifetimes out in declaration order. */
|
||||
if (m.taps.n > 0) {
|
||||
RAD_ARCH_TRY(declare_muse_dflash(&m.df, &m.dfw, &m.kv_draft, b, nm, meta, ctx, g, m.taps,
|
||||
(int)g.n_layer, m.w_tok, m.w_lm_head));
|
||||
m.have_df = true;
|
||||
}
|
||||
|
||||
/* ---- notes for --debug-graph. */
|
||||
int64_t nfull = 0, nrope = 0;
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
nfull += full[(size_t)l];
|
||||
nrope += theta[(size_t)l] > 0.0f;
|
||||
}
|
||||
rad_note(b, "rank %d/%d: %lld layers (%lld full attention, %lld sliding over a %lld-token "
|
||||
"window; %lld with rotary at theta %g), n_head=%lld n_head_kv=%lld head_dim=%lld "
|
||||
"n_ff=%lld vocab=[%lld,%lld)",
|
||||
g.rank, g.world, (long long)g.n_layer, (long long)nfull,
|
||||
(long long)(g.n_layer - nfull), (long long)m.window, (long long)nrope,
|
||||
theta_rope, (long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim,
|
||||
(long long)g.n_ff, (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab));
|
||||
rad_note(b, "centered norms (1 + w): input/pre at eps %g, post at eps %g; the final norm is a "
|
||||
"plain gain; the embedding and the q/k norms are weightless", (double)g.eps,
|
||||
(double)m.post_eps);
|
||||
rad_note(b, "attention scale 1/sqrt(%lld) with the query pre-scaled by qk_scale_factor %g; "
|
||||
"logits pre-scaled by output_multiplier %g%s%g",
|
||||
(long long)g.head_dim, (double)m.qk_mult, (double)m.out_mult,
|
||||
m.softcap > 0.0f ? " and soft-capped at " : "", (double)m.softcap);
|
||||
if (m.g_rope.theta != g.theta)
|
||||
rad_note(b, "rotary runs on the sliding layers only (theta %g); the full-attention layers "
|
||||
"are NoPE", (double)m.g_rope.theta);
|
||||
rad_note(b, "logits for at most %lld sampled rows a step (of %lld tokens): gather_rows "
|
||||
"selects RadBatch::out_ids before the lm_head", (long long)g.max_logit_rows,
|
||||
(long long)g.max_tok);
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
|
||||
/* An encoder pass runs only the vision tower (RadBatch::enc). */
|
||||
if (batch->enc) {
|
||||
m.vit.step(c, batch);
|
||||
return;
|
||||
}
|
||||
|
||||
/* A draft pass runs only the drafter: >0 the query pass on the staged block, <0 the context
|
||||
* pass that projects and stores K/V for the tokens the trunk just committed. */
|
||||
if (batch->draft_pass != 0) {
|
||||
if (!m.have_df) {
|
||||
rad_step_fail(c, "this serve stages a draft pass but the container carries no drafter");
|
||||
return;
|
||||
}
|
||||
if (batch->draft_pass > 0) m.df.step(c, batch);
|
||||
else m.df.context(c, batch);
|
||||
return;
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
/* The encoder's rows overwrite the lookup before the vocabulary shard's reduction, so the
|
||||
* reduction counts each row once. */
|
||||
if (m.op_media_rows && batch->n_mm_rows > 0)
|
||||
RAD_ISSUE_N(c, m.op_media_rows, batch->n_mm_rows,
|
||||
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, m.g.n_embd),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
/* The vocab shard's reduction; declared only when world > 1, so tp1 is unchanged. */
|
||||
if (m.op_embed_ar)
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.b_x, batch->n_tok), RAD_NONE);
|
||||
/* The embedding norm, after the reduction: it normalises whole rows. */
|
||||
RAD_ISSUE(c, m.op_embed_norm, brows(m.b_x, batch->n_tok), RAD_NONE, brows(m.b_x, batch->n_tok));
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
for (size_t li = 0; li < m.layers.size(); ++li) {
|
||||
const Layer& l = m.layers[li];
|
||||
const rad_kvgroup kg = l.full ? m.kv_full : m.kv_win;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kg);
|
||||
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;
|
||||
|
||||
/* -- attention. */
|
||||
RAD_ISSUE(c, l.op_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, l.op_q, brows(m.b_h, T), RAD_W(l.w_q), brows(m.b_q, T));
|
||||
RAD_ISSUE(c, l.op_gate, brows(m.b_h, T), RAD_W(l.w_gate), brows(m.b_gate, T));
|
||||
RAD_ISSUE(c, l.op_k, brows(m.b_h, T), RAD_W(l.w_k), brows(m.b_k, T));
|
||||
RAD_ISSUE(c, l.op_v, brows(m.b_h, T), RAD_W(l.w_v), brows(m.b_v, T));
|
||||
RAD_ISSUE_N(c, l.op_qn, T * m.g.n_head, brows(m.b_q, T), RAD_NONE, brows(m.b_q, T));
|
||||
RAD_ISSUE_N(c, l.op_kn, T * m.g.n_head_kv, brows(m.b_k, T), RAD_NONE, brows(m.b_k, T));
|
||||
if (l.rope) {
|
||||
RAD_ISSUE(c, l.op_rq, brows(m.b_q, T), rope_posmc(m.g, batch, T));
|
||||
RAD_ISSUE(c, l.op_rk, brows(m.b_k, T), rope_posmc(m.g, batch, T));
|
||||
}
|
||||
RAD_ISSUE(c, l.op_kv,
|
||||
brows(m.b_k, T), brows(m.b_v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kg, (int)li));
|
||||
/* The longest query length, not the token count, selects the attention band. */
|
||||
RAD_ISSUE_N(c, l.op_attn, batch->max_q_len,
|
||||
brows(m.b_q, T), kv_cache(kg, (int)li),
|
||||
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(m.b_attn, T));
|
||||
RAD_ISSUE_N(c, l.op_sig, T * m.g.n_head, brows(m.b_gate, T), brows(m.b_gate, T));
|
||||
RAD_ISSUE(c, l.op_mul, brows(m.b_attn, T), brows(m.b_gate, T), brows(m.b_attn, T));
|
||||
RAD_ISSUE(c, l.op_o, brows(m.b_attn, T), RAD_W(l.w_o), brows(m.b_h, T));
|
||||
if (l.op_ar) RAD_ISSUE_N(c, l.op_ar, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, l.op_post, brows(m.b_h, T), RAD_W(l.w_post), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, l.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
|
||||
|
||||
/* -- feed-forward. */
|
||||
RAD_ISSUE(c, l.op_fnorm, brows(m.b_x, T), RAD_W(l.w_fnorm), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, l.op_gu, brows(m.b_h, T), RAD_W(l.w_gate_up), brows(m.b_gu, T));
|
||||
RAD_ISSUE(c, l.op_act, brows(m.b_gu, T), brows(m.b_ffn, T));
|
||||
RAD_ISSUE(c, l.op_down, brows(m.b_ffn, T), RAD_W(l.w_down), brows(m.b_h, T));
|
||||
if (l.op_far) RAD_ISSUE_N(c, l.op_far, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, l.op_fpost, brows(m.b_h, T), RAD_W(l.w_fpost), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, l.op_fadd, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
|
||||
|
||||
/* The drafter reads this layer's completed residual, if it taps it. */
|
||||
m.taps.step(c, m.b_x, T, (int64_t)li, m.g.n_embd);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_final_norm,
|
||||
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok));
|
||||
m.calib.after_step(c, T);
|
||||
|
||||
/* The lm_head runs only on the rows the sampler asked for; a mid-prompt prefill chunk has
|
||||
* n_out zero and skips it. */
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.b_h, batch->n_tok),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out,
|
||||
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
if (m.op_cap)
|
||||
RAD_ISSUE_N(c, m.op_cap, batch->n_out, brows(m.b_logits, batch->n_out),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
/* What the plugin says before it declares anything: this family's tower merges 4 patches into a
|
||||
* row, so an automatic --mm-max-patches rounds to whole merged rows. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
if (MuseTower::present(meta)) out->enc_merge = 4;
|
||||
/* The drafter denoises `block_size` positions and the anchor row proposes nothing, so the
|
||||
* draft width is block_size - 1. It is trained for that one block, hence fixed. */
|
||||
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
if (bs > 1) {
|
||||
out->draft_depth = (int)(bs - 1);
|
||||
out->draft_depth_fixed = 1;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static const RadChatFormat* chat_format(const RadModelMeta*) {
|
||||
return muse_chat_format();
|
||||
}
|
||||
|
||||
} /* namespace museglimmer */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(museglimmer)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(museglimmer, "museglimmer", "", "0.1.0",
|
||||
"Meta Muse Glimmer 30B dense, bf16 weights and activations, gated attention "
|
||||
"alternating sliding-window (rotary) and NoPE full-attention layers, Gemma-2 "
|
||||
"style double norms")
|
||||
RAD_ARCH_CHAT_FORMAT(museglimmer)
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/museglimmer_ct -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(museglimmer_ct LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(museglimmer_ct architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/museglimmer_ct.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user