Archived
Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port
102 upstream commits. Nine conflicts resolved. Fork side of the merge: - libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it from libavx and libref; the device libraries now each carry it). - plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table regenerated, kTableAbi = 42. Known before the PR: arch_test (MTP lint and pinned graph hashes for qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4b70a96378
850 files changed
+157819
-58519
No files matched your search
@@ -184,7 +184,7 @@ struct Model {
|
||||
std::string mul, add;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype,
|
||||
std::initializer_list<int64_t> shape, int access, int group) {
|
||||
@@ -978,8 +978,9 @@ static int find_prefix(RadBuilder* b, Model& m, const char** marker) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
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(check_format(meta, ctx));
|
||||
@@ -1335,7 +1336,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "anima is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1361,6 +1362,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(anima)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(anima, "anima", "", "0.1.0",
|
||||
"Anima (Base, Aesthetic, Turbo): Qwen3-0.6B through the LLM adapter, Cosmos-Predict2's "
|
||||
"2B diffusion transformer and the Qwen-Image VAE; bf16 or block-fp8 linears")
|
||||
|
||||
@@ -1,25 +1,53 @@
|
||||
/* 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. A clamped SwiGLU (flash's last layers) writes the bf16 product,
|
||||
* which had_quant_act_i8g quantises: one launch more than the unclamped gated product.
|
||||
* - 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 +83,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 +113,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 +191,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 +208,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 +231,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 +255,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 +320,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 +333,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 +360,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 +378,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 +421,11 @@ struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
Shape s{};
|
||||
/* Whether layer 0's probe found a rotated-int8 trunk, and its activation scale group: see
|
||||
* rad_fp8.h's trunk_rotation. `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;
|
||||
@@ -324,7 +442,7 @@ struct Model {
|
||||
Layer draft{};
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
|
||||
return rad_meta_geti(m, key, fallback);
|
||||
@@ -370,6 +488,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 +502,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 +547,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 +594,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 +608,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 +654,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 +680,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 });
|
||||
}
|
||||
@@ -511,13 +694,14 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
|
||||
/* ============================== declare ============================== */
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
/* A sizing declare writes scratch: the step reads g_model, filled by the real declare at the
|
||||
* real max_tok (RadBuildCtx::shape_probe). */
|
||||
static thread_local Model probe_model;
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[ctx->rank];
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
auto& g = m.g;
|
||||
@@ -613,11 +797,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;
|
||||
@@ -644,8 +840,57 @@ 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) &&
|
||||
trunk_rotation(enc, &m.trunk_g8);
|
||||
}
|
||||
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. A clamped layer clamps, then quantises (GateQuantFP8). */
|
||||
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;
|
||||
}
|
||||
}
|
||||
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. */
|
||||
@@ -673,9 +918,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,
|
||||
@@ -698,7 +948,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));
|
||||
@@ -718,10 +969,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]));
|
||||
@@ -779,10 +1034,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;
|
||||
}
|
||||
|
||||
@@ -831,7 +1088,7 @@ static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
const int64_t T = batch->n_tok, E = m.g.n_embd;
|
||||
if (batch->enc) {
|
||||
rad_step_fail(c, "bailing_hybrid serves text");
|
||||
@@ -878,8 +1135,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)
|
||||
RAD_ARCH_PLUGIN(bailing_hybrid, "bailinghybrid", "", "0.1.0",
|
||||
"Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts")
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
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)
|
||||
+145
-34
@@ -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 */
|
||||
@@ -225,7 +255,7 @@ struct Model {
|
||||
rad_buf b_vout = 0, b_audio = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x,
|
||||
@@ -1183,10 +1213,13 @@ 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) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
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(check_format(meta));
|
||||
@@ -1213,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{};
|
||||
@@ -1220,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;
|
||||
@@ -1266,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];
|
||||
@@ -1357,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);
|
||||
}
|
||||
@@ -1475,7 +1579,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->agen_b) {
|
||||
rad_step_fail(c, "breeze is an audio generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1503,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);
|
||||
@@ -1521,6 +1630,8 @@ RAD_ARCH_PROBE(breeze)
|
||||
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
return breeze::text_prepare(field, in, out, cap);
|
||||
}
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(breeze, "breeze", "", "0.1.0",
|
||||
"Breeze-TTS-2: a T5Gemma 2 text encoder over a Qwen3 backbone with a 16-codebook "
|
||||
"depth decoder and the Qwen3-TTS 12 Hz codec; 24 kHz mono speech")
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,11 +21,12 @@ namespace clef_bf16 {
|
||||
using namespace rad::arch;
|
||||
|
||||
/* One head per rank beside the trunk's own per-rank state (qwen35_bf16::g_model). */
|
||||
static ClefHead g_head[MAX_RANKS];
|
||||
static ClefHead g_head[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) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_bf16 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
@@ -36,13 +37,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The trunk's declare does not take part in sizing declares (no probe), so its state and the
|
||||
* head's are the real ones. The head goes after the vision tower: its buffers join the same
|
||||
* arena, and it reads the final norm's rows, the lm_head and the trunk's cache block size. */
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[ctx->rank];
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_build_slot(ctx)];
|
||||
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
|
||||
* skips the lm_head on a step every sampled row of which carries a request's words
|
||||
* (plugin_words_cover_rows) and leaves zero rows instead. */
|
||||
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
|
||||
if (!m.op_logits_fill) return RAD_E_INVAL;
|
||||
ClefHead& h = g_head[ctx->rank];
|
||||
ClefHead& h = g_head[rad_build_slot(ctx)];
|
||||
h = ClefHead{};
|
||||
return h.declare(b, meta, ctx, m.nm, m.g, m.b_h, m.b_logits, m.w_lm_head, m.kv_full,
|
||||
(int)m.g.n_layer + 256);
|
||||
@@ -52,8 +53,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
qwen35_bf16::step(c, batch);
|
||||
/* An encoder pass runs the tower alone and leaves no rows for the head. */
|
||||
if (batch->enc) return;
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_rank(c)];
|
||||
ClefHead& h = g_head[rad_rank(c)];
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_slot(c)];
|
||||
ClefHead& h = g_head[rad_slot(c)];
|
||||
/* The final norm's rows are still in `h` after the trunk's step; the logits row of each
|
||||
* sampled sequence has been written, and the head adds its values beside it. */
|
||||
h.step_tokens(c, batch, m.b_h);
|
||||
@@ -62,6 +63,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
|
||||
} /* namespace clef_bf16 */
|
||||
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(clef_bf16, "clef", "", "0.1.0",
|
||||
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_bf16, bf16, "
|
||||
"with the joint schema head on the card for /v1/systemone")
|
||||
@@ -21,11 +21,12 @@ namespace clef_fp8 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
static ClefHead g_head[MAX_RANKS];
|
||||
static ClefHead g_head[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) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_fp8 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
@@ -33,13 +34,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(qwen35_clef_fp8::declare(b, meta, ctx));
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[ctx->rank];
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_build_slot(ctx)];
|
||||
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
|
||||
* skips the lm_head on a step every sampled row of which carries a request's words
|
||||
* (plugin_words_cover_rows) and leaves zero rows instead. */
|
||||
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
|
||||
if (!m.op_logits_fill) return RAD_E_INVAL;
|
||||
ClefHead& h = g_head[ctx->rank];
|
||||
ClefHead& h = g_head[rad_build_slot(ctx)];
|
||||
h = ClefHead{};
|
||||
return h.declare(b, meta, ctx, m.nm, m.g, m.a_h.x, m.b_logits, m.w_lm_head, m.kv_full,
|
||||
(int)m.g.n_layer + 256);
|
||||
@@ -49,8 +50,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
qwen35_clef_fp8::step(c, batch);
|
||||
/* An encoder pass leaves no rows for the head, and a drafter's pass is not a trunk step. */
|
||||
if (batch->enc || batch->draft_pass != 0) return;
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_rank(c)];
|
||||
ClefHead& h = g_head[rad_rank(c)];
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_slot(c)];
|
||||
ClefHead& h = g_head[rad_slot(c)];
|
||||
/* The final norm's rows are in `a_h.x` after either of the trunk's step paths. */
|
||||
h.step_tokens(c, batch, m.a_h.x);
|
||||
if (batch->n_out > 0) h.step_heads(c, batch, m.b_logits, m.w_lm_head);
|
||||
@@ -59,6 +60,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace clef_fp8 */
|
||||
|
||||
RAD_ARCH_PROBE(qwen35_clef_fp8)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(clef_fp8, "clef", "fp8_e4m3", "0.1.0",
|
||||
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_fp8, "
|
||||
"block-scaled fp8, with the joint schema head on the card for /v1/systemone")
|
||||
+67
-22
@@ -37,9 +37,12 @@ namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* One thread per tensor-parallel rank in one process (spec §1), and declare runs once per rank,
|
||||
* so declared handles are per-rank state; a single global would let rank 1 overwrite rank 0.
|
||||
* libr4d all-reduces over 2/4/8 ranks, hence eight. */
|
||||
enum { MAX_RANKS = 8 };
|
||||
* so declared handles are per-instance state; a single global would let rank 1 overwrite rank 0.
|
||||
* libr4d all-reduces over 2/4/8 ranks, hence eight ranks. Several engines may run in the process
|
||||
* (docs/MULTIMODEL.md), each with its own ranks, so state is indexed by the instance's slot
|
||||
* (rad_build_slot at declare, rad_slot in step), unique across all of them, never by the rank two
|
||||
* engines share. */
|
||||
enum { MAX_RANKS = 8, MAX_SLOTS = RAD_MAX_SLOTS };
|
||||
|
||||
/* ================================================================== a debug residual probe
|
||||
*
|
||||
@@ -220,13 +223,14 @@ inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const c
|
||||
return calib_write_host(h.data(), k, rows, what, domain, rad_rank(c));
|
||||
}
|
||||
|
||||
/* A pinned host buffer of at least `bytes`, one per rank, held for the process lifetime, so a tap
|
||||
* that copies a scratch back every pass runs at link speed. Null (and logged) on failure. */
|
||||
/* A pinned host buffer of at least `bytes`, one per instance (slot), held for the process
|
||||
* lifetime, so a tap that copies a scratch back every pass runs at link speed. Null (and logged)
|
||||
* on failure. */
|
||||
inline float* calib_staging(RadCtx* c, int64_t bytes) {
|
||||
static std::mutex mu;
|
||||
static std::map<int, std::pair<void*, int64_t>> per_rank;
|
||||
static std::map<int, std::pair<void*, int64_t>> per_slot;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
std::pair<void*, int64_t>& s = per_rank[rad_rank(c)];
|
||||
std::pair<void*, int64_t>& s = per_slot[rad_slot(c)];
|
||||
if (s.second >= bytes) return (float*)s.first;
|
||||
if (s.first) rad_dev_free(s.first, RAD_MEM_HOST_PINNED);
|
||||
s.first = rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED);
|
||||
@@ -672,8 +676,13 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
}
|
||||
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. A plugin declares
|
||||
* none where the deployment turns the reads off (RadBuildCtx::weight_prefetch_off). */
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes, int64_t blocks = 0) {
|
||||
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
|
||||
/* `blocks`: the workgroups reading, where the architecture measured its own count (docs/OPS.md);
|
||||
* 0 leaves the kernel's. Stated only when asked, so a declaration without it is what it was. */
|
||||
if (blocks > 0)
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes), RAD_INT("blocks", blocks)),
|
||||
RAD_WEIGHTS(w));
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
|
||||
}
|
||||
|
||||
@@ -733,9 +742,6 @@ struct Geom {
|
||||
/* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as
|
||||
* `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */
|
||||
int64_t wire_min_bytes = 0;
|
||||
/* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it).
|
||||
* decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */
|
||||
int attn_prefill_fp8 = 0;
|
||||
/* RadBuildCtx::plain_norm: a block norm none of whose readers takes codes may run as `add` +
|
||||
* `rmsnorm` (rad_fp8.h, NormQuantFP8::x_only). */
|
||||
int plain_norm = 0;
|
||||
@@ -774,6 +780,12 @@ struct Geom {
|
||||
* setting because producers and consumers must agree; the plugin reads it off a trunk weight's
|
||||
* encoding and every linear checks its own against it. */
|
||||
bool w_bf16 = false;
|
||||
/* The linears are rotated int8 (rad_fp8.h's linear_is_w8h: IQ8R, or the 128-group form) with
|
||||
* one activation scale per `w_i8_group` columns, for a plugin whose producers are declared away
|
||||
* from its probe: each then declares an int8 code pair (ActFP8::declare_pair). Model-wide as
|
||||
* w_bf16 is. */
|
||||
bool w_i8h = false;
|
||||
int64_t w_i8_group = 128;
|
||||
|
||||
int64_t q_dim() const { return n_head * head_dim; }
|
||||
int64_t kv_dim() const { return n_head_kv * head_dim; }
|
||||
@@ -1010,7 +1022,6 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.world = c->world_size ? c->world_size : 1;
|
||||
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.attn_prefill_fp8 = c->attn_prefill_fp8;
|
||||
g.plain_norm = c->plain_norm != 0;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
@@ -1328,16 +1339,6 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the
|
||||
* parameters are passed unchanged, so op identities and tune keys do not change. */
|
||||
inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
|
||||
* after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
|
||||
* free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
|
||||
@@ -1474,6 +1475,45 @@ inline void batch_split(const RadBatch* b, int64_t* n_seq_dec, int64_t* n_tok_de
|
||||
}
|
||||
}
|
||||
|
||||
/* What a step's attention reads of the QSA selection (AttnGatedFP8::qsa_use), which decides what
|
||||
* the indexer issues for the layer (QsaIndexer::step, docs/QSA.md "Below the bound"):
|
||||
*
|
||||
* kQsaSelect score and select, per layer: a step past the exactness bound, a streamed group,
|
||||
* and every step of a block that did not ask for the forms below;
|
||||
* kQsaUnread nothing reads the selection: the step is entirely at or below the bound and its
|
||||
* attention is the dense one, or the sparse row over the sequence's own block table
|
||||
* (one row a sequence), which is what the selection would be. The indexer stores its
|
||||
* keys and tail and issues no query, score or select;
|
||||
* kQsaOnce the attention reads a selection (the sparse row a query) on a step entirely at or
|
||||
* below the bound: every complete block is taken whatever it scores, so the
|
||||
* selection depends on the positions and the block table alone and is the same
|
||||
* bytes at every layer. The first full-attention layer of the pass issues it as
|
||||
* always; no later layer issues a query, a score or a select. */
|
||||
enum QsaUse : int { kQsaSelect = 0, kQsaUnread = 1, kQsaOnce = 2 };
|
||||
|
||||
/* Ops of a chain that is independent of a block's own, for the block to issue behind its ordered
|
||||
* launches. A recorded pass lets a launch start beside the last ordered one when it touches
|
||||
* nothing in flight (Ctx::haz_mark). A dependent chain issued in one piece is therefore a row of
|
||||
* ordered launches, each paid in turn; issued one op behind each of the block's own ordered
|
||||
* launches, every op of it is unordered behind the block's launch in front of it, and still
|
||||
* behind its own predecessor, which that launch already waited for. The block calls `at(k)` for
|
||||
* k = 0, 1, 2, ... behind its ordered launches in turn, and the owner issues what is left once
|
||||
* the block returns. The chain must read nothing the block writes and write nothing the block
|
||||
* touches, and its buffers must be excluded from sharing (rad_buf_concurrent): they are in use at
|
||||
* launches the linear order puts after their last declared use. */
|
||||
struct SideOps {
|
||||
void (*fn)(void* u, int stage) = nullptr;
|
||||
void* u = nullptr;
|
||||
void at(int stage) const { if (fn) fn(u, stage); }
|
||||
};
|
||||
|
||||
/* RADIANCE_DEBUG_QSA_EAGER: every step is kQsaSelect, the issue sequence before the forms above
|
||||
* existed. An instrument for comparing the two (the text must not move); read once. */
|
||||
inline bool qsa_eager() {
|
||||
static const bool on = std::getenv("RADIANCE_DEBUG_QSA_EAGER") != nullptr;
|
||||
return on;
|
||||
}
|
||||
|
||||
/* The step batch's entry for one declared KV group (built once per step by the core, spec §8). */
|
||||
inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
|
||||
for (int i = 0; i < b->n_kv_groups; ++i)
|
||||
@@ -1658,6 +1698,11 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
|
||||
#define RAD_ARCH_SERVES_IMPORTS(V) \
|
||||
extern "C" int rad_arch_serves_imports(void) { return V; }
|
||||
|
||||
/* RAD_ARCH_MULTI_INSTANCE() states that the plugin keeps all per-instance state by slot, so several
|
||||
* engines in one process may run it at once (rad_builder.h, rad_arch_multi_instance). */
|
||||
#define RAD_ARCH_MULTI_INSTANCE() \
|
||||
extern "C" int rad_arch_multi_instance(void) { return 1; }
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
|
||||
/* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
|
||||
* kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
|
||||
@@ -137,7 +137,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
|
||||
* explains declare vs issue order). */
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
|
||||
@@ -195,7 +195,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
*
|
||||
* The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
|
||||
* a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* state); the gate pass quantises the out-projection's input.
|
||||
* - Per-head norms, rope, kv_store and attn_paged stay bf16.
|
||||
* - The KV cache dtype is `g.kv_dtype`, not `g.dtype`: it is a deployment choice that selects
|
||||
* libr4d's fp8kv attention family. The attention op and kv_store both take it, so they agree.
|
||||
* the attention family's cache rows. The attention op and kv_store both take it, so they agree.
|
||||
* - Optional fused prologue, QSA sparse attention and an attention-zero mode (see declare).
|
||||
*
|
||||
* The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, scale plane
|
||||
@@ -26,14 +26,6 @@
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* Whether the streamed store has a row for this cache layout: libr4d's are E4M3 and bf16 only. A
|
||||
* packed cache (fp8_v4, k6_v4) must not declare it, since a weightless op with no row is a hole
|
||||
* that refuses startup even with --kv-resident off; kvstream_configure then names the layout. */
|
||||
inline bool kv_store_streamed_dtype(const char* kv_dtype) {
|
||||
return kv_dtype && (std::strcmp(kv_dtype, "fp8_e4m3") == 0 ||
|
||||
std::strcmp(kv_dtype, "bf16") == 0);
|
||||
}
|
||||
|
||||
struct AttnGatedFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
@@ -87,6 +79,21 @@ struct AttnGatedFP8 {
|
||||
/* `sel`'s row pitch is `topk + 1`; the extra slot is the partial page
|
||||
* (r4d_qsa_select_bf16.hip). */
|
||||
int64_t qsa_topk = 0;
|
||||
/* The architecture's word that a sequence with one row in the step has that row at its
|
||||
* context's last position (`seqused - 1`: a plain decode row, a serial head's round), so at or
|
||||
* below `qsa_exact_to` such a row's selection is the head of the sequence's block table and its
|
||||
* `seqused` the sequence's (qsa_select: every complete block in block order, then the partial
|
||||
* page, and `pos + 1`). The sparse row is then issued over the table and the indexer selects
|
||||
* nothing (qsa_use). Off: such a step keeps the selection. */
|
||||
bool qsa_table_rows = false;
|
||||
/* The architecture's pass key carries whether this group's exact host bound
|
||||
* (RadBatch::kv_used_max_h, the furthest context any row of the step can read) is within
|
||||
* `qsa_exact_to`, so that bound may say whether the step needs scores (qsa_within) in place of
|
||||
* the rounded `max_ctx_len + max_q_len`, which a 4-row step leaves at 1025 tokens. It never
|
||||
* moves the choice between the dense and the sparse kernel, which stays the rounded bound's:
|
||||
* the two agree on the keys, not on the last bit of the sum. Off: the rounded bound, which the
|
||||
* core's key holds. */
|
||||
bool qsa_exact_host = false;
|
||||
/* Query rows per sparse attention launch, a scratch budget. The decode kernel's split-KV
|
||||
* partials are sized at declare from `max_seqs` and `q_len`, so issuing more rows than
|
||||
* `max_seqs` means declaring a larger value, which grows the scratch arena (the maximum over
|
||||
@@ -115,6 +122,18 @@ struct AttnGatedFP8 {
|
||||
/* The input was normed and quantised by the caller; this block declares no norm. */
|
||||
bool ext_in = false;
|
||||
LinearFP8 qg{}, kp{}, vp{}, o{};
|
||||
/* Set by the architecture after declare: a `prefetch` of the out projection's leading bytes
|
||||
* (decl_prefetch, rad_arch.h), issued behind the q, k and v projections on decode steps
|
||||
* (prefetch_beside). 0 where none is declared. */
|
||||
rad_op op_pf_o = 0;
|
||||
/* The same read as a second op for steps of at least pf_o_v_rows rows, where the
|
||||
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
|
||||
* every step takes op_pf_o. */
|
||||
rad_op op_pf_o_v = 0;
|
||||
int64_t pf_o_v_rows = 0;
|
||||
/* The most rows of a decode step whose k and v projections are issued in front of the q|gate
|
||||
* projection (step()); 0, the default, keeps the declared order on every step. */
|
||||
int64_t kv_first_rows = 0;
|
||||
NormQuantFP8 nq_h{};
|
||||
|
||||
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
|
||||
@@ -125,7 +144,7 @@ struct AttnGatedFP8 {
|
||||
int64_t fused_rows = 0; /* widest T the fused ops take */
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_gq = 0;
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 or gate_had_quant_i8g */
|
||||
/* kv_store_streamed: the host mirror always, the ring slot when `res` says the block is resident
|
||||
* (docs/OPS.md). Zero when no row serves it; a streamed group then fails the step. */
|
||||
rad_op op_kv_stream = 0;
|
||||
@@ -172,8 +191,12 @@ struct AttnGatedFP8 {
|
||||
/* The block's tail, declared last by every rank: the all-reduce and the trailing add. */
|
||||
int declare_out(RadBuilder* b, bool add_out);
|
||||
/* `own_ar` false: the caller issues the all-reduce itself (GdnFP8::step says when). */
|
||||
/* `side`: an independent chain's ops, issued behind this block's ordered launches (SideOps,
|
||||
* rad_arch.h): one behind the prologue and the store, one behind the attention, one behind
|
||||
* the gate where the gate is a launch of its own. Null, and on the paths that return early,
|
||||
* nothing is asked of it. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
|
||||
ArPieces* pieces = nullptr) const;
|
||||
ArPieces* pieces = nullptr, const SideOps* side = nullptr) const;
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
|
||||
@@ -189,6 +212,41 @@ struct AttnGatedFP8 {
|
||||
* components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and
|
||||
* the gate quantised by gate_quant_fp8. A streamed group never takes it: the pieces path's
|
||||
* plain store never writes the host mirror. */
|
||||
/* The rounded host bound of the furthest context a row of the step reads; by it a step of
|
||||
* several rows a sequence takes the dense or the sparse kernel (step(), `sparse`). */
|
||||
int64_t qsa_reach(const RadBatch* batch) const {
|
||||
return (int64_t)batch->max_ctx_len + batch->max_q_len;
|
||||
}
|
||||
/* Whether every row of the step is at or below the exactness bound, by the tightest host
|
||||
* ceiling there is: the group's exact one where the pass key holds its side of the bound
|
||||
* (qsa_exact_host), else the rounded one. Every row's position + 1 is at most either. */
|
||||
bool qsa_within(const RadBatch* batch, const RadKVGroupBatch* kvb) const {
|
||||
if (qsa_exact_to <= 0) return false;
|
||||
int64_t reach = qsa_reach(batch);
|
||||
if (qsa_exact_host && kvb && batch->kv && batch->kv_used_max_h) {
|
||||
const int64_t tight = batch->kv_used_max_h[kvb - batch->kv];
|
||||
if (tight > 0 && tight < reach) reach = tight;
|
||||
}
|
||||
return reach <= qsa_exact_to;
|
||||
}
|
||||
/* What this step's attention reads of the selection (QsaUse, rad_arch.h); the architecture
|
||||
* hands it to the indexer, which runs first, and step() takes its path by the same call. */
|
||||
int qsa_use(const RadBatch* batch) const {
|
||||
if (!qsa_sel || !qsa_sequ || op_fill || qsa_eager()) return kQsaSelect;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
/* A streamed group may be ring-bound, where every pass is sparse and the resolve rewrites
|
||||
* the selection; it keeps the selection at every context. */
|
||||
if (!kvb || kvb->stream || !kvb->block_table || !kvb->seqused) return kQsaSelect;
|
||||
if (!qsa_within(batch, kvb)) return kQsaSelect;
|
||||
/* One row a sequence is the sparse row at every context: over the table where the
|
||||
* architecture vouches for it, else over a selection. */
|
||||
if (batch->n_tok == batch->n_seq)
|
||||
return (qsa_table_rows && batch->max_q_len == 1) ? kQsaUnread : kQsaOnce;
|
||||
/* Several rows a sequence: the dense attention, which reads the table, where the rounded
|
||||
* bound is within the budget too, else the sparse row a query over a selection. */
|
||||
return qsa_reach(batch) <= qsa_exact_to ? kQsaUnread : kQsaOnce;
|
||||
}
|
||||
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
@@ -342,7 +400,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size`
|
||||
* (rad_block_attn_gated.h). */
|
||||
op_attn = decl_attn(b, g, "attn_paged",
|
||||
op_attn = rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
@@ -382,8 +440,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
|
||||
/* The streamed store: kv_store's operands and parameters plus the residency map and the layer's
|
||||
* mirror row, which the batch carries (store_cache). `block_size` does not bind the group;
|
||||
* `attn_paged` already has. Only for a layout with a row (kv_store_streamed_dtype). */
|
||||
if (kv_store_streamed_dtype(g.kv_dtype) && rad_op_declared(b, "kv_store_streamed"))
|
||||
* `attn_paged` already has. */
|
||||
if (rad_op_declared(b, "kv_store_streamed"))
|
||||
op_kv_stream = rw(b, RAD_OP(b, "kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
@@ -396,7 +454,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
/* The fused prologue with the cache store folded in: a k head's block already holds its
|
||||
* token's rotated k, so it also writes k and v into the cache, byte-identical to kv_store.
|
||||
* Declared here because the cache block size is read back from the attention op above.
|
||||
* Resolves for E4M3 and bf16 caches. */
|
||||
* Resolves for either cache. */
|
||||
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store"))
|
||||
op_fused_kv = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
|
||||
@@ -410,9 +468,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
|
||||
|
||||
/* The fold for a streamed group: also writes the mirror and consults the residency map, whose
|
||||
* operands are added at issue. Gated on the same layouts. */
|
||||
if (op_fused && kv_store_streamed_dtype(g.kv_dtype) &&
|
||||
rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
|
||||
* operands are added at issue. */
|
||||
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
|
||||
op_fused_stream = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
|
||||
@@ -463,7 +520,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
if (rad_op_declared(b, gq))
|
||||
op_gq = rw(b, RAD_OP(b, gq,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("n", g.head_dim), RAD_INT("group", w.attn.cg()),
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
|
||||
@@ -488,10 +545,12 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
* row is one (token, head) at q_len 1, and the merge already holds the head_dim values the gate
|
||||
* and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the
|
||||
* pair). Declared only with a selection: the dense path also uses the prefill kernel, which
|
||||
* has no merge. */
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && !w.attn.q8_rot &&
|
||||
rad_op_declared(b, "attn_paged_gate_quant")) {
|
||||
op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
|
||||
* has no merge. Rotated int8 codes (ActFP8::q8_rot) take attn_paged_gate_had_quant, the merge
|
||||
* with gate_had_quant_i8g's quantiser. */
|
||||
const char* attn_gq = w.attn.q8_rot ? "attn_paged_gate_had_quant" : "attn_paged_gate_quant";
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && w.attn.cg() == RAD_FP8_BLOCK &&
|
||||
rad_op_declared(b, attn_gq)) {
|
||||
op_attn_gq = RAD_OP(b, attn_gq,
|
||||
RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
@@ -591,7 +650,7 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
ArPieces* pieces) const {
|
||||
ArPieces* pieces, const SideOps* side) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
@@ -636,7 +695,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
RAD_ISSUE_N(c, op_gq, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, hd, hd, n), brow_slice(w.attn.x, r0, n, qw),
|
||||
brow_slice(w.attn.cq(), r0, n, qw),
|
||||
brow_slice(w.attn.cs(), r0, n, fp8_blocks(qw)),
|
||||
brow_slice(w.attn.cs(), r0, n, qw / w.attn.cg()),
|
||||
brow_slice(w.attn.x, r0, n, qw));
|
||||
o.step(c, w.attn, w.h.x, T, r0, n);
|
||||
if (p == 0) pieces->hand(r0, n);
|
||||
@@ -653,9 +712,23 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
return;
|
||||
}
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
/* The three projections read the same input and none reads another's output, so a recorded
|
||||
* pass starts them together (Ctx::haz_mark) whatever their order; the order decides which
|
||||
* the card launches first. On a decode step of up to `kv_first_rows` rows the two small ones
|
||||
* go first: behind the wide q|gate projection their launches wait until its blocks are all
|
||||
* on the card, and the prologue then waits for them. Qwen3.8-Flash-Next at tp 2, chain 3
|
||||
* with coupling (twelve trunk layers and the head's): -0.66% a step. */
|
||||
if (T <= kv_first_rows && batch->phase == RAD_PHASE_DECODE) {
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
} else {
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
}
|
||||
/* The out projection's weight, read beside the prologue and the attention (op_pf_o). */
|
||||
prefetch_beside(c, op_pf_o_v && T >= pf_o_v_rows ? op_pf_o_v : op_pf_o, o.w, T);
|
||||
|
||||
/* Fused or unfused prologue. The fused kernel takes the whole [q|gate] projection and splits it
|
||||
* itself, and rotates k in place like the unfused ops. It reads one rotary component per
|
||||
@@ -700,6 +773,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
}
|
||||
|
||||
if (!fused_kv && !folded_stream) store_cache(c, kvb, slot, T);
|
||||
if (side) side->at(0);
|
||||
|
||||
/* Sparse attention issues one row per query. `attn_paged` indexes its block table and length
|
||||
* by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with
|
||||
@@ -712,7 +786,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* Launches are chunked because the split-KV scratch is sized at declare from `max_seqs` and
|
||||
* `q_len` (rows = max_seqs * q_len_max * heads); more rows are refused as RAD_E_SCRATCH at
|
||||
* issue. Rows of q_len 1 up to the declared max_seqs always fit. */
|
||||
const int64_t reach = (int64_t)batch->max_ctx_len + batch->max_q_len;
|
||||
const int64_t reach = qsa_reach(batch);
|
||||
/* A pass on a streamed group's ring (a ring smaller than the id space, and not staged) must
|
||||
* take the sparse path: on the ring a block id is not a pool address, so the dense path would
|
||||
* read ring slots as pages. `T == n_seq` alone misses a verify pass, whose T is
|
||||
@@ -726,6 +800,19 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const bool sparse = qsa_sel && qsa_sequ &&
|
||||
(ring_bound || T == batch->n_seq || qsa_exact_to <= 0 ||
|
||||
reach > qsa_exact_to);
|
||||
/* At or below the bound a step of one row a sequence has no selection (qsa_use): the sparse
|
||||
* row reads the sequence's own block table and length, which is what qsa_select would have
|
||||
* written for it (the field says why), so the launch, its kernel and its bytes are the sparse
|
||||
* row's. */
|
||||
const bool by_table = sparse && T == batch->n_seq && qsa_use(batch) == kQsaUnread;
|
||||
const int64_t tpitch = kvb ? kvb->block_table_pitch : 0;
|
||||
auto sel_rows = [&](int64_t off, int64_t rows) {
|
||||
return by_table ? praw2(table + off * tpitch, RAD_I32, rows, tpitch)
|
||||
: brow_slice(qsa_sel, off, rows, qsa_topk + 1);
|
||||
};
|
||||
auto sequ_rows = [&](int64_t off, int64_t rows) {
|
||||
return by_table ? praw(used + off, RAD_I32, rows) : brow_slice(qsa_sequ, off, rows, 1);
|
||||
};
|
||||
const bool gated = sparse && op_attn_gq;
|
||||
/* A streamed group's selection, per launch: make the rows' blocks resident and rewrite `sel`
|
||||
* as ring slots, after this layer's store (a block copied in from the mirror must carry this
|
||||
@@ -733,6 +820,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* and never resolves, so a prefill cannot overflow the ring. */
|
||||
const KVStreamLayer res_l = op_resolve ? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
|
||||
auto resolve_sel = [&](int64_t off, int64_t rows) {
|
||||
if (by_table) return; /* never a streamed group (qsa_use) */
|
||||
if (kv_stage_layer(c, kv, kvb, layer)) return;
|
||||
if (!res_l.host || res_l.blocks <= 0 || res_l.slots <= 0 || rows <= 0) return;
|
||||
kv_resolve_issue(c, op_resolve, res_l, brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
@@ -754,13 +842,12 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
RAD_ISSUE_N(c, op_attn_gq, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_sequ, off, rows, 1),
|
||||
sel_rows(off, rows), sequ_rows(off, rows),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw),
|
||||
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
|
||||
brow_slice(w.attn.cq(), off, rows, qw),
|
||||
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
|
||||
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
|
||||
}
|
||||
o.step(c, w.attn, w.h.x, T, p0, pn);
|
||||
if (p0 + pn < T) pieces->hand(p0, pn);
|
||||
@@ -778,13 +865,12 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
RAD_ISSUE_N(c, op_attn_gq, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_sequ, off, rows, 1),
|
||||
sel_rows(off, rows), sequ_rows(off, rows),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw),
|
||||
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
|
||||
brow_slice(w.attn.cq(), off, rows, qw),
|
||||
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
|
||||
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
|
||||
}
|
||||
} else if (sparse) {
|
||||
const int64_t chunk = qsa_rows();
|
||||
@@ -795,8 +881,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
RAD_ISSUE_N(c, op_attn, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_sequ, off, rows, 1),
|
||||
sel_rows(off, rows), sequ_rows(off, rows),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw));
|
||||
}
|
||||
@@ -857,6 +942,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
/* Every attention launch of this layer is issued: start the next layer's stage copy, which
|
||||
* crosses the link under the out projection and the next layer's projections. */
|
||||
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
|
||||
if (side) side->at(1);
|
||||
if (gated) {
|
||||
/* the sparse attention gated and quantised in its merge */
|
||||
} else if (op_sig) {
|
||||
@@ -870,6 +956,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.attn.x, T),
|
||||
brows(w.attn.cq(), T), brows(w.attn.cs(), T), brows(w.attn.x, T));
|
||||
}
|
||||
if (side && !gated) side->at(2);
|
||||
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
|
||||
|
||||
+130
-42
@@ -147,6 +147,9 @@ struct Dflash2 {
|
||||
/* The target's embedding scale, applied to the query block as the drafter was trained
|
||||
* (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */
|
||||
double escale = 1.0;
|
||||
/* Optional DFlash2 logit transform shipped by Muse Glimmer. */
|
||||
double omul = 1.0;
|
||||
double scap = 0.0;
|
||||
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
|
||||
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
|
||||
int64_t prefetch = 0;
|
||||
@@ -161,6 +164,14 @@ struct Dflash2 {
|
||||
* acceptance, sum min(P, Q). */
|
||||
double q_temp = 1.0;
|
||||
int64_t short_rows = 0;
|
||||
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
|
||||
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
|
||||
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
|
||||
* by had_quant_act_i8g. Every linear must agree. `fc_mapped`: probe_i8 made
|
||||
* `dflash.fc.weight`'s name map. */
|
||||
bool act_i8 = false;
|
||||
int64_t act_g8 = RAD_FP8_BLOCK;
|
||||
bool fc_mapped = false;
|
||||
/* LiLiCorr's backbone (the LILICORR section above): sinks, and the head left to the
|
||||
* plugin. sel_rank and sel_topk are then unused. */
|
||||
int lili = 0;
|
||||
@@ -198,7 +209,9 @@ struct Dflash2 {
|
||||
rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
|
||||
rad_buf ffn = 0; /* [qrows, n_ff] */
|
||||
/* FP8 codes and scales of the activations the linears read, written by `quant_act_fp8`
|
||||
* and read only by the `gemm_nt_q` linears. One pair per activation, not per linear: q, k
|
||||
* and read only by the `gemm_nt_q` linears (int8 codes with a scale per Config::act_g8,
|
||||
* written by `had_quant_act_i8g`, when the drafter's linears are rotated int8:
|
||||
* Config::act_i8). One pair per activation, not per linear: q, k
|
||||
* and v all read h2. h2 is still quantised twice a layer, because the convolution
|
||||
* rewrites it between the attention and feed-forward halves. */
|
||||
rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] e4m3 | [.., /128] f32 */
|
||||
@@ -260,6 +273,9 @@ struct Dflash2 {
|
||||
* 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and
|
||||
* the 2-bit grid otherwise. Set by declare from the copy's encoding. */
|
||||
bool head_i8 = false;
|
||||
/* Muse Glimmer's 202048-token vocab is not divisible by the int8/w2a8 head kernels' 128-row
|
||||
* tile; its copied draft head stays BF16 and uses gemm_nt. */
|
||||
bool head_bf16 = false;
|
||||
|
||||
/* per-layer weights */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
@@ -324,7 +340,7 @@ struct Dflash2 {
|
||||
rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {};
|
||||
|
||||
/* head and selector */
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dcap = 0, op_dtopk = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_drerank = 0; /* the candidates rescored against the target's head */
|
||||
/* The target's lm_head, set by the plugin before declare when logit_rerank can read it (fp8 or
|
||||
@@ -342,6 +358,18 @@ struct Dflash2 {
|
||||
* the drafter's own block is longer (rad_drafter_short_block). */
|
||||
static constexpr int64_t kShortBlock = 4;
|
||||
|
||||
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
|
||||
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
|
||||
* declared, since it decides their dtype and scale grid. */
|
||||
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
|
||||
const char* fwn = nm.f("dflash.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
RadEncoding fe{};
|
||||
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
|
||||
const char* ck_lm, const Wire& wire);
|
||||
@@ -381,11 +409,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
|
||||
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
|
||||
w_fc.w8h_ok = cfg.act_i8;
|
||||
for (int i = 0; i < MAX_LAYERS; ++i)
|
||||
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
|
||||
w_dn[i].w8h_ok = cfg.act_i8;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
{
|
||||
const int64_t K = cfg.n_taps * g.n_embd;
|
||||
const char* fwn = nm.f("dflash.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
if (!cfg.fc_mapped) RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
/* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole
|
||||
* 16-byte words (the gather's unit). */
|
||||
RadEncoding fe{};
|
||||
@@ -453,12 +488,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
|
||||
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which
|
||||
* gemm_nt_q reads at w8a8 against the same quant_act_i8 activation (without its asum). */
|
||||
RadEncoding dhe{};
|
||||
const bool head_known = weight_enc(b, dhn, &dhe);
|
||||
{
|
||||
RadEncoding e{};
|
||||
const RadEncPlane* sc = nullptr;
|
||||
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 &&
|
||||
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 &&
|
||||
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 &&
|
||||
head_i8 = head_known && rad_enc_is(&dhe, "affine") && dhe.n_planes == 2 &&
|
||||
!dhe.transform[0] && dhe.plane[0].dtype == RAD_I8 && dhe.plane[0].block[1] == 1 &&
|
||||
(sc = rad_enc_plane(&dhe, "scale")) && sc->dtype == RAD_F16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
|
||||
}
|
||||
if (head_i8) {
|
||||
@@ -467,6 +503,11 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
|
||||
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN,
|
||||
dh_split, grp_model());
|
||||
} else if (head_known && rad_enc_is(&dhe, "plain") && dhe.n_planes == 1 &&
|
||||
dhe.plane[0].dtype == RAD_BF16) {
|
||||
head_bf16 = true;
|
||||
w_dh = decl_w(b, dhn, RAD_BF16, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
} else {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
@@ -474,7 +515,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split,
|
||||
grp_model());
|
||||
}
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
if (!w_dh || (!head_bf16 && !w_dhs)) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights */
|
||||
@@ -602,9 +643,29 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* Nothing is row-sliced: the fp8a8 pair covers every M, and libr4d's bf16 GEMM row (used by
|
||||
* the conv coefficient projections and the selector's hidden projection, K = n_embd) is
|
||||
* C_LE("M", 65536). */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
/* A rotated int8 drafter (cfg.act_i8): the same five quantisers as had_quant_act_i8g at its
|
||||
* scale group, and no fp8a8 fold. Its linears read one activation pair, so they are all
|
||||
* i8a8h forms at one group or none is. */
|
||||
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
{
|
||||
auto fits = [&](const DenseFP8& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l)
|
||||
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
|
||||
fits(w_gu[l]) && fits(w_dn[l]);
|
||||
if (!same) {
|
||||
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
|
||||
"group or all block fp8 / MXFP4; they read one activation pair, so the "
|
||||
"recipe must give them one format\n");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
op_qsrc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
if (fc_rows) {
|
||||
@@ -634,9 +695,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* One quantise for all layers: every layer's k and v read the same `c`. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
@@ -700,19 +761,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{w.x}, {w.x});
|
||||
/* The query pass's quantisers, issued per layer: h2 twice (the convolution rewrites it between
|
||||
* the halves), attn and ffn once each. */
|
||||
op_qh2 = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qh2 = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h2}, {w.h2q, w.h2s});
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qat = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn}, {w.atq, w.ats});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qff = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn}, {w.ffq, w.ffs});
|
||||
|
||||
@@ -759,7 +820,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
|
||||
/* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
|
||||
* fp8a8 tile, so an MXFP4 or M2XFP4 gate_up takes the pair. */
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x)
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h2q, w.h2s}, {w.ffq, w.ffs}, &gated_rows);
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
|
||||
@@ -832,12 +893,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* Only for a shape a library serves: an op declared for one that resolves to no device
|
||||
* kernel is a hole that refuses startup (Program::device_holes), whether or not it is
|
||||
* issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in
|
||||
* steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim
|
||||
* 128) keeps the chain. */
|
||||
* steps of 256, bf16 rows, either cache). Qwen3.8's DFlash2 drafter (head_dim 128) keeps
|
||||
* the chain. */
|
||||
const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 &&
|
||||
!std::strcmp(g.dtype, "bf16") &&
|
||||
(!std::strcmp(g.kv_dtype, "fp8_e4m3") ||
|
||||
!std::strcmp(g.kv_dtype, "bf16"));
|
||||
!std::strcmp(g.dtype, "bf16");
|
||||
if (fold_shape && g.yarn.factor == 0.0f &&
|
||||
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
|
||||
const int64_t bsz = rad_kv_block_size(b, kv);
|
||||
@@ -898,12 +957,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h2}, {w.x});
|
||||
op_final = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
op_final = cfg.omul != 1.0
|
||||
? rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_F64("mult", cfg.omul), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h})
|
||||
: rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
/* Each residual add and the norm after it as one launch where a library serves add_rmsnorm
|
||||
* (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only
|
||||
* where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run
|
||||
@@ -927,6 +993,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
op_afinal = all ? an(w_norm) : 0;
|
||||
if (!op_afinal)
|
||||
for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0;
|
||||
/* add_rmsnorm has no `mult`; keep Muse's output_multiplier on the final norm. */
|
||||
if (cfg.omul != 1.0) op_afinal = 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the head and the selector
|
||||
@@ -944,12 +1012,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{w.h}, {w.sel_h});
|
||||
/* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */
|
||||
if (cfg.lili) return RAD_OK;
|
||||
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.sel_h}, {w.dq, w.ds, w.dsum});
|
||||
op_dlogits = head_i8
|
||||
if (!head_bf16)
|
||||
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.sel_h}, {w.dq, w.ds, w.dsum});
|
||||
op_dlogits = head_bf16
|
||||
? rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_dh)),
|
||||
{w.sel_h}, {w.dlog})
|
||||
: head_i8
|
||||
? rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
|
||||
@@ -962,6 +1037,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_STR("dtype", "w2a8")),
|
||||
RAD_WEIGHTS(w_dh, w_dhs)),
|
||||
{w.dq, w.ds, w.dsum}, {w.dlog});
|
||||
if (cfg.scap > 0.0) {
|
||||
op_dcap = rw(b, RAD_OP(b, "logit_softcap",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", head_rows(g)),
|
||||
RAD_F64("cap", cfg.scap), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.dlog});
|
||||
if (!op_dcap) return RAD_E_INVAL;
|
||||
}
|
||||
/* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
|
||||
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
|
||||
* with value 0 is a different declaration from an absent one. */
|
||||
@@ -1312,12 +1395,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
|
||||
* whole. */
|
||||
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
|
||||
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
|
||||
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric and
|
||||
* takes no asum. */
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
|
||||
if (head_bf16) {
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.sel_h, S), RAD_W(w_dh), brows(w.dlog, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
|
||||
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
|
||||
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric
|
||||
* and takes no asum. */
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
|
||||
}
|
||||
if (op_dcap) RAD_ISSUE_N(c, op_dcap, S, brows(w.dlog, S), brows(w.dlog, S));
|
||||
/* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
|
||||
* the merge overwrites `cand`/`unary`. */
|
||||
if (op_dmerge) {
|
||||
|
||||
@@ -93,12 +93,15 @@
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* E4M3 + a bf16 [N/128][K/128] plane fc, q/k/v/o, gate_up, down -- every linear
|
||||
* what the recipe made them fc, q/k/v/o, gate_up, down -- every linear
|
||||
* bf16, no plane every norm, and both Markov codebooks
|
||||
*
|
||||
* The checkpoint is dense bf16; the linears are rad_fp8.h's DenseFP8 over weights the recipe
|
||||
* quantises, because the drafter is read whole every decode step (324M parameters: 648 MB at
|
||||
* bf16, 324 MB at fp8). This can only change acceptance.
|
||||
* bf16, 324 MB at eight bits). DenseFP8 reads block fp8 or MXFP4 against E4M3 activations, or a
|
||||
* rotated int8 form (IQ8R and the narrower grids under the same rotation) against int8 ones
|
||||
* (Config::act_i8); one format for all of them, since they share the activation pairs. This can
|
||||
* only change acceptance.
|
||||
*
|
||||
* The codebooks are bf16 and replicated: they are gathered by global token id from a merged
|
||||
* candidate set. 66.8 MiB each; only K rows are read per position, so the cost is residency.
|
||||
@@ -135,6 +138,14 @@ struct Dspark {
|
||||
int64_t top_k = 0; /* candidates the Markov walk re-ranks */
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 0;
|
||||
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
|
||||
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
|
||||
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
|
||||
* by had_quant_act_i8g and the rotating norm. Every linear must agree. `fc_mapped`:
|
||||
* probe_i8 made `dspark.fc.weight`'s name map. */
|
||||
bool act_i8 = false;
|
||||
int64_t act_g8 = RAD_FP8_BLOCK;
|
||||
bool fc_mapped = false;
|
||||
/* Every row predicts, so `block`, not `block - 1` (see ROW ALIGNMENT). */
|
||||
int64_t steps() const { return block; }
|
||||
};
|
||||
@@ -149,7 +160,10 @@ struct Dspark {
|
||||
* rows_pitch). */
|
||||
rad_buf ck = 0; /* [max_tok, kv_dim] one layer's K, reused across layers */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] one layer's V, reused across layers */
|
||||
rad_buf srcq = 0, srcs = 0; /* fp8 codes and scales: e4m3 | f32 [.., /128] */
|
||||
/* The codes and scales the linears read: e4m3 | f32 [.., /128], or with Config::act_i8
|
||||
* i8 | f32 [.., /act_g8]. The same holds for the three ActFP8 pairs below, whose `q` and
|
||||
* `s` are then the int8 pair. */
|
||||
rad_buf srcq = 0, srcs = 0;
|
||||
rad_buf cq = 0, cs = 0;
|
||||
|
||||
/* ---- the query pass, `block` rows per sequence */
|
||||
@@ -235,6 +249,18 @@ struct Dspark {
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_sel = 0;
|
||||
|
||||
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
|
||||
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
|
||||
* declared, since it decides their dtype and scale grid. */
|
||||
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
|
||||
const char* fwn = nm.f("dspark.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
RadEncoding fe{};
|
||||
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
|
||||
const char* ck_lm, const char* ck_lm_alt, const Wire& wire);
|
||||
@@ -274,10 +300,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
|
||||
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
|
||||
w_fc.w8h_ok = cfg.act_i8;
|
||||
for (int i = 0; i < MAX_LAYERS; ++i)
|
||||
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
|
||||
w_dn[i].w8h_ok = cfg.act_i8;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), g.n_embd, cfg.n_taps * g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
|
||||
{ nm.ckpt("%s.fc.weight", ck) }));
|
||||
{ nm.ckpt("%s.fc.weight", ck) }, {}, cfg.fc_mapped));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
|
||||
nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
@@ -379,19 +412,34 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass
|
||||
*
|
||||
* Every linear is `fp8a8`, fed by a `quant_act_fp8`. There is no `fp8a16` band: that kernel is
|
||||
* M <= 1, and neither pass runs at one row. */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
* Every linear is a DenseFP8 GEMM over the pair its quantiser writes: `quant_act_fp8` codes
|
||||
* for block fp8 or MXFP4, had_quant_act_i8g's at the weights' scale group for a rotated int8
|
||||
* drafter (cfg.act_i8). The linears read one activation pair, so they are all i8a8h forms at
|
||||
* one group or none is. There is no `fp8a16` band: that kernel is M <= 1, and neither pass
|
||||
* runs at one row. */
|
||||
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
{
|
||||
auto fits = [&](const DenseFP8& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l)
|
||||
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
|
||||
fits(w_gu[l]) && fits(w_dn[l]);
|
||||
if (!same) {
|
||||
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
|
||||
"group or all block fp8 / MXFP4; they read one activation pair, so the "
|
||||
"recipe must give them one format\n");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
op_qsrc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_fc.w, w_fc.s)),
|
||||
{w.srcq, w.srcs}, {w.c});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
|
||||
* written. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -401,27 +449,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* One quantise for all layers: every layer's k and v read the same `c`. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
|
||||
* and residency class. */
|
||||
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.cq, w.cs}, {w.cv});
|
||||
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
@@ -468,7 +506,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
{w.x}, {w.x});
|
||||
|
||||
/* Norm, residual add and quantise are one op, `rmsnorm_quant_fp8` (what rad_fp8.h's
|
||||
* NormQuantFP8 wraps). Layer 0 has no delta to fold, each later norm folds the previous
|
||||
* NormQuantFP8 wraps), or its rotating int8 twin `rmsnorm_had_quant_i8g` for a rotated int8
|
||||
* drafter, which takes the same operands. Layer 0 has no delta to fold, each later norm folds the previous
|
||||
* block's delta, and op_outnorm folds the last into the final norm, so there is no `add` op.
|
||||
* The final norm's fp8 output is unused (the head runs its own i8 quantiser), a few KiB of
|
||||
* waste that saves a launch: libr4d has no plain `rmsnorm_add` row.
|
||||
@@ -478,9 +517,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* stream as `x` and no residual. `residual` is INOUT, so it is in both the read and write sets;
|
||||
* otherwise the planner could reorder a reader in front of it. */
|
||||
auto decl_norm = [&](rad_weight gain, bool fold) -> rad_op {
|
||||
rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
rad_op h = RAD_OP(b, cfg.act_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", qgr),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(gain));
|
||||
if (!h) return 0;
|
||||
@@ -490,9 +529,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
rad_op_writes(b, h, wr, fold ? 4 : 3);
|
||||
return h;
|
||||
};
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qat = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.x}, {w.attn.q, w.attn.s});
|
||||
if (!op_qat) return RAD_E_INVAL;
|
||||
@@ -508,24 +547,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = decl_norm(w_anorm[i], i != 0);
|
||||
if (!op_anorm[i]) return RAD_E_INVAL;
|
||||
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
|
||||
{w.h.q, w.h.s}, {w.q});
|
||||
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.h.q, w.h.s}, {w.k});
|
||||
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.h.q, w.h.s}, {w.v});
|
||||
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h.q, w.h.s}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
@@ -538,28 +562,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
|
||||
{w.attn.q, w.attn.s}, {w.h.x});
|
||||
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.attn.q, w.attn.s}, {w.h.x});
|
||||
op_fnorm[i] = decl_norm(w_fnorm[i], true);
|
||||
if (!op_fnorm[i]) return RAD_E_INVAL;
|
||||
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h.q, w.h.s}, {w.gate_up});
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
|
||||
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
|
||||
{w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h.q, w.h.s}, {w.gate_up});
|
||||
/* The fold is an fp8a8 tile, so any other gate_up takes the pair. */
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
}
|
||||
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
@@ -588,9 +599,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ffn.x});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qff = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn.x}, {w.ffn.q, w.ffn.s});
|
||||
/* One collective, issued after both the out and the down projection (same shape, same buffer).
|
||||
@@ -687,16 +698,16 @@ inline void Dspark::context(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, RAD_NONE);
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
|
||||
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
@@ -735,11 +746,11 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* quantises; at layer 0 it norms the embedding. */
|
||||
issue_norm(op_anorm[i], i != 0, w_anorm[i], T);
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
|
||||
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
|
||||
@@ -757,7 +768,7 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
brows(w.attn.x, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn.x, T), brows(w.attn.q, T), brows(w.attn.s, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.attn.q, T), brows(w.attn.s, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, w_o[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
|
||||
/* ---- the feed-forward, behind the same fused norm-add-quantise */
|
||||
@@ -769,12 +780,12 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
RAD_NONE);
|
||||
w_gu[i].bref());
|
||||
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn.x, T));
|
||||
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn.x, T), brows(w.ffn.q, T), brows(w.ffn.s, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffn.q, T), brows(w.ffn.s, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, w_dn[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
}
|
||||
|
||||
|
||||
@@ -129,12 +129,19 @@ struct GdnFP8 {
|
||||
/* Geom::plain_norm with an out projection that reads no codes (a 4-bit one): the recurrent
|
||||
* epilogue and the prefill quantiser leave the code pair unwritten. */
|
||||
bool o_plain = false;
|
||||
/* Whether op_cr writes the out projection's codes; otherwise q_o follows it. */
|
||||
bool cr_codes = false;
|
||||
int64_t cr_rows = 0;
|
||||
/* Set by the architecture after declare: a `prefetch` of the out-projection's leading bytes
|
||||
* (decl_prefetch, rad_arch.h), issued on the second lane beside the decode recurrent update on
|
||||
* steps of up to pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
|
||||
* (decl_prefetch, rad_arch.h), issued beside the decode recurrent update on steps of up to
|
||||
* pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
|
||||
rad_op op_pf_out = 0;
|
||||
int64_t pf_out_rows = 0, pf_out_seqs = 0;
|
||||
/* The same read as a second op for steps of at least pf_out_v_rows rows, where the
|
||||
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
|
||||
* every step takes op_pf_out. */
|
||||
rad_op op_pf_out_v = 0;
|
||||
int64_t pf_out_v_rows = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */
|
||||
bool ar_out = false;
|
||||
@@ -351,17 +358,25 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
|
||||
{
|
||||
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
|
||||
op_cr = rw(b, RAD_OP(b, w.o.q8_rot ? "gdn_conv_recurrent_update_had" : "gdn_conv_recurrent_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width),
|
||||
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
|
||||
RAD_STR("state_form",
|
||||
g.max_spec > 0 ? "anchor" : "per_candidate")),
|
||||
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias, w_out_norm)),
|
||||
/* The fold's rotated epilogue writes one scale per (row, 128), or per 256 for an IQ8R
|
||||
* trunk's codes (ActFP8::g8; `group`, stated to that form alone: last, and cut off
|
||||
* otherwise), where this rank's value heads pair up. */
|
||||
const bool cr_wide = w.o.q8_rot && w.o.g8 == RAD_I8_GROUP_WIDE && cfg.n_head_v % 2 == 0;
|
||||
cr_codes = w.o.cq() && !o_plain && (!w.o.q8_rot || w.o.g8 == RAD_FP8_BLOCK || cr_wide);
|
||||
const RadParam cp[] = { RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width),
|
||||
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
|
||||
RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate"),
|
||||
RAD_INT("group", RAD_I8_GROUP_WIDE) };
|
||||
const rad_weight cw[] = { w_conv, w_a_log, w_dt_bias, w_out_norm };
|
||||
op_cr = rw(b, rad_decl_op(b, w.o.q8_rot && cr_codes ? "gdn_conv_recurrent_update_had"
|
||||
: "gdn_conv_recurrent_update",
|
||||
cp, (int)(sizeof cp / sizeof *cp) - (cr_wide && cr_codes ? 0 : 1),
|
||||
cw, 4),
|
||||
{w.in.x, w.ab}, {w.o.x});
|
||||
if (op_cr && w.o.cq() && !o_plain) {
|
||||
if (op_cr && cr_codes) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_cr, oq, 2));
|
||||
}
|
||||
@@ -467,8 +482,12 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
/* At decode and verify sizes the a|b projection is nearly all launch cost and reads only the
|
||||
* norm's output, as the in-projection does, so it runs beside it on lane 1 and is joined before
|
||||
* the convolution reads `ab`. A prefill chunk keeps one lane, where the two would share
|
||||
* bandwidth. */
|
||||
if (ab_lane && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) {
|
||||
* bandwidth. Where launches chain it stays on lane 0: its chained form starts beside the
|
||||
* in-projection without the two lane joins, each of which holds a launch back until the host
|
||||
* has seen the other lane finish (Qwen3.8-27B on two cards: the projection started 55 us late
|
||||
* and the update behind it another 20 to 40 us). */
|
||||
if (ab_lane && !rad_chain_on() && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK &&
|
||||
rad_lane(c, 1) == RAD_OK) {
|
||||
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
|
||||
rad_lane(c, 0);
|
||||
in.step(c, w.h, w.in.x, T);
|
||||
@@ -502,11 +521,18 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
|
||||
/* The recurrent update at decode heights runs one workgroup per (sequence, head) and leaves the
|
||||
* card's memory mostly idle, so the out-projection's weight is read into the on-die cache
|
||||
* beside it, on the second lane behind a join from lane 0 (as prefetch_beside). */
|
||||
* beside it: in front of the update on lane 0 where launches chain (the read's chained form
|
||||
* holds nothing behind it), else on the second lane behind a join from lane 0 (as
|
||||
* prefetch_beside). */
|
||||
if (op_pf_out && D > 0 && D <= pf_out_seqs && P == 0 && T <= pf_out_rows) {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
|
||||
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
|
||||
rad_lane(c, 0);
|
||||
const rad_op pf = op_pf_out_v && T >= pf_out_v_rows ? op_pf_out_v : op_pf_out;
|
||||
if (prefetch_lane0()) {
|
||||
RAD_ISSUE(c, pf, RAD_W(out.w));
|
||||
} else {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
|
||||
RAD_ISSUE(c, pf, RAD_W(out.w));
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
}
|
||||
if (D > 0 && op_cr && qd <= cr_rows) {
|
||||
RAD_ISSUE_N(c, op_cr, qd,
|
||||
@@ -517,8 +543,9 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
|
||||
w.o.cq() && !o_plain ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() && !o_plain ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
cr_codes ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
cr_codes ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
if (w.o.cq() && !o_plain && !cr_codes) q_o.step(c, T, 0, DT);
|
||||
} else if (D > 0) {
|
||||
RAD_ISSUE_N(c, op_conv_update, qd,
|
||||
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
|
||||
|
||||
+39
-11
@@ -77,12 +77,13 @@ struct HyperConn {
|
||||
* skips its own on every step takes_ar() accepts. The block's partial sum is the write's
|
||||
* input buffer, so this saves a launch. */
|
||||
int reduce = 0;
|
||||
/* Whether the read also emits Hadamard-rotated fp8 codes of the block input, for a
|
||||
* consumer whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in
|
||||
* the plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
|
||||
/* Whether the read also emits Hadamard-rotated codes of the block input, for a consumer
|
||||
* whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in the
|
||||
* plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
|
||||
int rotate = 0;
|
||||
/* Whether the plain codes are int8 (q8/s8) rather than E4M3 (q/s), for int8 trunk linears
|
||||
* (LinearFP8::i8). The rotated codes stay E4M3, the routed experts' operand. */
|
||||
* (LinearFP8::i8). The rotated codes take the same dtype (had_quant_act_i8g's beside int8,
|
||||
* had_quant_act_fp8's beside E4M3), so `Wire::rq` is declared to match. */
|
||||
int codes_i8 = 0;
|
||||
/* The most rows one read is declared for, 0 for max_tok; a wider step reads in pieces
|
||||
* (read_pieces). The read's scratch is sized for its band (some 22 KiB a row at
|
||||
@@ -115,6 +116,11 @@ struct HyperConn {
|
||||
* `mix`), read from their encoding at declare. */
|
||||
bool mix_e4m3 = false;
|
||||
rad_op op_read = 0, op_write = 0;
|
||||
/* The block input's own int8 pair is the rotated one (ActFP8::q8_rot, a trunk stored rotated):
|
||||
* the read writes its rotated codes there and its plain ones into `pq` / `ps`, a pair of this
|
||||
* connection's that nothing reads. */
|
||||
bool xrot = false;
|
||||
rad_buf pq = 0, ps = 0;
|
||||
/* The write with the all-reduce folded in; 0 when not requested or not served.
|
||||
* `op_ar_write6` is the same on the rotated 6-bit wire, declared only when a lossy payload is
|
||||
* accepted and issued on the steps ar_wire_is_exact rejects (every trunk all-reduce at a
|
||||
@@ -193,6 +199,17 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.quant && (c.codes_i8 ? (!w.x.q8 || !w.x.s8) : (!w.x.q || !w.x.s))) return RAD_E_INVAL;
|
||||
/* A trunk whose int8 linears are stored rotated reads the rotated codes alone: `x`'s int8 pair
|
||||
* is then that pair (ActFP8::q8_rot), and every reader of the block input -- the trunk's
|
||||
* projections and the rotated experts -- takes it. The read derives the rotated codes in its
|
||||
* plain codes' finisher, so the plain ones still have somewhere to go: a pair of this
|
||||
* connection's own that nothing reads. */
|
||||
xrot = c.quant && c.codes_i8 && w.x.q8_rot;
|
||||
if (xrot && c.rotate) {
|
||||
fprintf(stderr, "radiance: %s: the block input's own codes are the rotated ones "
|
||||
"(ActFP8::q8_rot), so there is no second rotated pair to ask for\n", name);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.rotate && (!c.quant || !w.rq || !w.rs)) {
|
||||
fprintf(stderr, "radiance: %s: the rotated codes need the plain ones (quant) and the "
|
||||
"rq/rs pair on the wire\n", name);
|
||||
@@ -248,8 +265,16 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
|
||||
int n_wr = 1;
|
||||
if (c.inject) wr[n_wr++] = w.inj;
|
||||
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
|
||||
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
|
||||
if (xrot) {
|
||||
pq = decl_b(b, nm.f("%s.plain.q8", name), RAD_I8, { g.max_tok, g.n_embd });
|
||||
ps = decl_b(b, nm.f("%s.plain.s8", name), RAD_F32, { g.max_tok, fp8_blocks(g.n_embd) });
|
||||
if (!pq || !ps || w.x.g8 != RAD_FP8_BLOCK) return RAD_E_INVAL;
|
||||
wr[n_wr++] = pq; wr[n_wr++] = ps;
|
||||
wr[n_wr++] = w.x.q8; wr[n_wr++] = w.x.s8;
|
||||
} else {
|
||||
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
|
||||
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
|
||||
}
|
||||
|
||||
op_read = RAD_OP(b, "hc_read",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.read_rows > 0 && c.read_rows < g.max_tok
|
||||
@@ -259,7 +284,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd), RAD_INT("inject", c.inject ? 1 : 0),
|
||||
RAD_INT("group", c.quant ? RAD_FP8_BLOCK : 0),
|
||||
RAD_INT("rotate", c.rotate ? 1 : 0),
|
||||
RAD_INT("rotate", (c.rotate || xrot) ? 1 : 0),
|
||||
RAD_STR("mix", mix_e4m3 ? "e4m3" : "bf16")),
|
||||
wts, n_wts);
|
||||
if (!op_read) return RAD_E_INVAL;
|
||||
@@ -358,11 +383,14 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
|
||||
c.inject ? RAD_W(w_inj) : RAD_NONE,
|
||||
brow_slice(w.x.x, r0, rows, g.n_embd),
|
||||
c.inject ? brow_slice(w.inj, r0, rows, c.hc) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.q8 : w.x.q, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
|
||||
c.quant ? brow_slice(xrot ? pq : c.codes_i8 ? w.x.q8 : w.x.q, r0, rows,
|
||||
g.n_embd) : RAD_NONE,
|
||||
c.quant ? brow_slice(xrot ? ps : c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rq, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
(c.rotate || xrot) ? brow_slice(xrot ? w.x.q8 : w.rq, r0, rows, g.n_embd)
|
||||
: RAD_NONE,
|
||||
(c.rotate || xrot) ? brow_slice(xrot ? w.x.s8 : w.rs, r0, rows,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* ================================================================== the control-vector projection
|
||||
|
||||
+332
-133
@@ -259,6 +259,17 @@ struct MoeFP8 {
|
||||
* layer's; the 64-group codebook forms may differ by layer and projection, and declare()
|
||||
* resolves each layer's (MoeFP8::fmt). */
|
||||
int expert_w5 = 0;
|
||||
int expert_w6 = 0; /* six-bit codebook, E4M3 scale per 64 */
|
||||
/* Int8 experts (`i8*bf16[1x128]/fwht128`): codes -127..127 with a bf16 scale per (row, 128
|
||||
* of K), each 128 of K rotated as `expert_rot` describes, read against int8 activations
|
||||
* (dtype `i8a8h`). The eight-bit expert of an int8 model, where block fp8 is that of an
|
||||
* E4M3 one. Set with `expert_rot`. */
|
||||
int expert_i8 = 0;
|
||||
/* Experts as IQR weights: the rotated computed trellis (libquant's tcq_code=mad) under one
|
||||
* f32 scale a row, two to six bits a code, each expert decoded where the grouped GEMM
|
||||
* reads it against the rotated int8 activations (dtype `i8a8h`, libr4d's moe_gemm_iqr).
|
||||
* Set with `expert_rot`. */
|
||||
int expert_iqr = 0;
|
||||
/* Plain bf16 experts (no quantising recipe). Both GEMMs are `moe_gemm` over one table of
|
||||
* whole experts with `silu_mul` between, and the shared arm follows the trunk
|
||||
* (Geom::w_bf16). Not sliced by parity: each expert is served whole on its rank, which
|
||||
@@ -302,6 +313,11 @@ struct MoeFP8 {
|
||||
rad_buf ew = 0; /* [max_tok, top_k] F32 for sigmoid_router, BF16 otherwise */
|
||||
rad_buf eoff = 0; /* [n_expert + 1] i32 */
|
||||
rad_buf ecnt = 0; /* [n_expert] i32 */
|
||||
/* Above 0, `ecnt` is the model's routing table (rad_route_table), [layers, ecnt_pitch],
|
||||
* and this block's counts are its row `layer`: the report then costs no copy and every
|
||||
* layer keeps its own counts. 0: `ecnt` is one row, which the layers sharing the wire
|
||||
* overwrite in turn. */
|
||||
int64_t ecnt_pitch = 0;
|
||||
/* the expert planes, one row per (token, slot), a pass tall */
|
||||
rad_buf sorted = 0; /* [rows * top_k] i32, pass-relative slot indices */
|
||||
/* Each slot's row in `sorted`, -1 when dropped; with it the sort writes the gather's slot
|
||||
@@ -364,6 +380,18 @@ struct MoeFP8 {
|
||||
|
||||
NormQuantFP8 nq_h{};
|
||||
GateQuantFP8 gq_exp{}, gq_sh{};
|
||||
/* The shared arm's gate_up and its quantiser as one launch (decl_gated_fold_iqr), and the rows
|
||||
* it serves; 0 where the pair runs. */
|
||||
rad_op op_sh_gated = 0;
|
||||
int64_t sh_gated_rows = 0;
|
||||
/* Whether the routed gate_up is a trellis weight (moe_gemm_iqr), and the routed rows from
|
||||
* which the shared arm's first stage then runs beside the router instead (pass()). */
|
||||
bool gu_trellis = false;
|
||||
static constexpr int64_t kSharedFirstRows = 100;
|
||||
/* The steps, by their rows [lo, hi], whose shared down projection is issued in front of the
|
||||
* routed down GEMM instead of behind it (pass()); hi 0, the default, keeps it behind on
|
||||
* every step. */
|
||||
int64_t sh_down_first_lo = 0, sh_down_first_hi = 0;
|
||||
LinearFP8 sh_gate_up{}, sh_down{};
|
||||
rad_op op_router = 0, op_topk = 0, op_scatter = 0;
|
||||
/* `op_scatter` is moe_scatter_inv and `op_gather` moe_gather_inv: the sort writes `w.inv` and
|
||||
@@ -392,6 +420,16 @@ struct MoeFP8 {
|
||||
* no quantiser for it. Set before declare. */
|
||||
bool hr_in = false;
|
||||
rad_op op_gu = 0, op_dn = 0, op_gather = 0;
|
||||
/* The routed arm's activations are int8: rotated codes with an f32 scale per (row, group),
|
||||
* which the grouped GEMMs meet with the iu8 WMMA (the `a8i8` and `i8a8h` dtypes). The
|
||||
* architecture asks for it by feeding `Wire::eff` int8 (ActFP8::q8_fed with q8_rot); int8
|
||||
* experts take nothing else, and the rotated four-bit forms take either. Resolved by
|
||||
* declare(). */
|
||||
bool a8 = false;
|
||||
/* The codes gate_up reads and the K one of their scales covers: `h`'s own pair where the
|
||||
* trunk feeds rotated int8 (at its group, 128 or IQ8R's 256), else `hr`'s. */
|
||||
rad_buf gin_q = 0, gin_s = 0;
|
||||
int64_t gin_g = RAD_FP8_BLOCK;
|
||||
/* Protected experts: local experts a quantised layer keeps bf16, the few whose output dwarfs
|
||||
* the rest (docs/MOE-W4.md). The scatter sorts them last (`protect`, `prot_list`), the
|
||||
* quantised GEMMs serve the other `n_reg`, and a bf16 grouped GEMM pair serves these over the
|
||||
@@ -413,9 +451,13 @@ struct MoeFP8 {
|
||||
* number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */
|
||||
int ncls = 2;
|
||||
/* This layer's gate_up and down formats (format_of's numbers), resolved by declare(): the
|
||||
* probed layer's, except that among the codebook forms at E4M3 scales (w4nl64a8h, w4nl32a8h,
|
||||
* w5nl64a8h) each projection of each layer takes its own experts'. */
|
||||
* probed layer's, except that among the forms reading one input (declare()'s `family`: the
|
||||
* codebook forms at E4M3 scales, or under an int8 routed arm every form with an int8 row) each
|
||||
* projection of each layer takes its own experts'. */
|
||||
int fmt[2] = { 0, 0 };
|
||||
/* The encoding of the layer's first quantised expert, per projection: a trellis's code width
|
||||
* is the views' dtype. */
|
||||
RadEncoding fenc[2]{};
|
||||
std::vector<rad_weight> w_pgu, w_pdn;
|
||||
rad_buf b_pgu = 0;
|
||||
ActFP8 pff{};
|
||||
@@ -469,11 +511,18 @@ struct MoeFP8 {
|
||||
static int probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg);
|
||||
/* The format `e` names: 0 block fp8, 1 four-bit, 2 four-bit rotated, 3 plain bf16, 4 the
|
||||
* rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales per 64 and 32 of K, 7 its
|
||||
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales; RAD_E_DTYPE otherwise. */
|
||||
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales, 10 rotated int8, 11 the rotated
|
||||
* computed trellis under one f32 scale a row (an IQR weight an expert); RAD_E_DTYPE
|
||||
* otherwise. */
|
||||
static int format_of(const RadEncoding& e);
|
||||
/* format_of's numbers as the grouped GEMMs' dtype strings. */
|
||||
static constexpr const char* kServed[10] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
|
||||
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8", "fp8a8f32" };
|
||||
/* format_of's numbers as the grouped GEMMs' dtype strings against an E4M3 activation, and
|
||||
* against an int8 one (null: the format has no such row). Int8 experts read int8 only. */
|
||||
static constexpr const char* kServed[13] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
|
||||
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8",
|
||||
"fp8a8f32", nullptr, nullptr, "w6nl64a8h" };
|
||||
static constexpr const char* kServed8[13] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr,
|
||||
"w4nl64a8i8h", "w4nl32a8i8h", nullptr, nullptr,
|
||||
nullptr, "i8a8h", "i8a8h", nullptr };
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
|
||||
@@ -505,6 +554,10 @@ struct MoeFP8 {
|
||||
inline int MoeFP8::format_of(const RadEncoding& e) {
|
||||
if (linear_is_mxfp4(e)) return 8;
|
||||
if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3;
|
||||
/* The computed trellis under one f32 scale a row, rotated (IQR-V4's feed-forward form). */
|
||||
if (rad_enc_is(&e, "trellis"))
|
||||
return std::strcmp(e.transform, "fwht128") == 0 && linear_w8h_mad(e) &&
|
||||
linear_w8h_rowf(e) ? 11 : RAD_E_DTYPE;
|
||||
if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE;
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
/* The codebook at E4M3 scales per 64 or 32 of K under one fixed f32 (w4nl64a8h, w4nl32a8h),
|
||||
@@ -521,6 +574,8 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
|
||||
return sc->block[1] == RAD_FP8_BLOCK / 2 ? 5 : 6;
|
||||
if (t->extent[1] == 32 && e.plane[0].dtype == RAD_U5 && sc->block[1] == RAD_FP8_BLOCK / 2)
|
||||
return 7;
|
||||
if (t->extent[1] == 64 && e.plane[0].dtype == RAD_U6 && sc->block[1] == RAD_FP8_BLOCK / 2)
|
||||
return 12;
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (!sc) return RAD_E_DTYPE;
|
||||
@@ -544,6 +599,9 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
|
||||
if (!e.transform[0]) return 1;
|
||||
if (std::strcmp(e.transform, "fwht128") == 0) return 2;
|
||||
}
|
||||
if (e.plane[0].dtype == RAD_I8 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
|
||||
std::strcmp(e.transform, "fwht128") == 0)
|
||||
return 10;
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
@@ -616,7 +674,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
|
||||
cfg->probed_count = ge - g0 + 1;
|
||||
RadEncoding e{};
|
||||
f = 0;
|
||||
if (weight_enc(b, guw, &e) && (f = format_of(e)) < 0) {
|
||||
const bool known = weight_enc(b, guw, &e);
|
||||
if (known && (f = format_of(e)) < 0) {
|
||||
char en[256];
|
||||
rad_enc_format(&e, en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, and the routed experts are served as block fp8 "
|
||||
@@ -624,17 +683,23 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
|
||||
"/fwht128; or u4 codes into a 16-entry f32 table, /fwht128) or plain "
|
||||
"bf16; or the codebook at E4M3 scales a 64 or 32 of K under a fixed "
|
||||
"f32, or its 32-entry five-bit form at a 64, or OCP MXFP4 "
|
||||
"(fp4_e2m1*e8m0[1x32]). "
|
||||
"Convert it with a recipe that makes one of them.\n", guw, en);
|
||||
"(fp4_e2m1*e8m0[1x32]), or rotated int8 (i8*bf16[1x128]/fwht128), or "
|
||||
"the rotated computed trellis under one f32 scale a row. Convert it "
|
||||
"with a recipe that makes one of them.\n", guw, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (known && (f == 0 || f == 8 || f == 9))
|
||||
return linear_refuse_retired(guw, f == 8 ? "MXFP4" : "block fp8");
|
||||
if (f != 3) break;
|
||||
}
|
||||
cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
|
||||
cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
|
||||
cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
|
||||
cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0;
|
||||
cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 12) ? 1 : 0;
|
||||
cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 10 || f == 11 || f == 12) ? 1 : 0;
|
||||
cfg->expert_i8 = f == 10 ? 1 : 0;
|
||||
cfg->expert_iqr = f == 11 ? 1 : 0;
|
||||
cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7 || f == 12) ? 1 : 0;
|
||||
cfg->expert_g64 = (f == 5 || f == 7 || f == 12) ? 2 : f == 6 ? 4 : 0;
|
||||
cfg->expert_w5 = f == 7 ? 1 : 0;
|
||||
cfg->expert_w6 = f == 12 ? 1 : 0;
|
||||
cfg->expert_bf16 = f == 3 ? 1 : 0;
|
||||
cfg->expert_mx = f == 8 ? 1 : 0;
|
||||
cfg->expert_f32_scale = f == 9 ? 1 : 0;
|
||||
@@ -693,7 +758,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* refused, since the fused all-reduce lives inside the norm. See rad_block_attn_gated_fp8.h. */
|
||||
ext_in = (src.norm == nullptr);
|
||||
if (ext_in) {
|
||||
if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
|
||||
if (!w.h.x || (!g.w_bf16 && (!w.h.cq() || !w.h.cs())) || ar_in != kArNone)
|
||||
return RAD_E_INVAL;
|
||||
} else {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l), src.norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
@@ -714,9 +780,12 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_ARCH_TRY(moe_map_expert(b, nm, src, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge),
|
||||
nm.f("blk.%d.ffn_down_exps.%lld.weight", l, ge), ge, !probed));
|
||||
}
|
||||
/* The routed arm's activations (see `a8`), known before the layer's formats are resolved:
|
||||
* which forms may share a model depends on the codes they read. */
|
||||
a8 = w.eff.q8_fed && !c.expert_bf16;
|
||||
prot.clear();
|
||||
{
|
||||
const int want = c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
|
||||
const int want = c.expert_iqr ? 11 : c.expert_i8 ? 10 : c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w6 ? 12 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
|
||||
: c.expert_g64 ? 5 : c.expert_nl ? 4
|
||||
: c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0;
|
||||
auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) {
|
||||
@@ -728,36 +797,54 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (weight_enc(b, nmv[i], &enc[i])) fe[i] = format_of(enc[i]);
|
||||
}
|
||||
};
|
||||
/* The codebook forms at E4M3 scales differ only in the GEMM's dtype (same rotated input,
|
||||
* scale views, fixed second level, accumulators), so each layer and projection may use any
|
||||
* of them. The layer's first non-bf16 expert decides both; every other must match. Outside
|
||||
* that family a layer uses the probed layer's form. */
|
||||
auto family = [](int f) { return f == 5 || f == 6 || f == 7; };
|
||||
/* The forms that read one input may differ by layer and projection: against E4M3 codes the
|
||||
* codebook forms at E4M3 scales (same rotated input, scale views, fixed second level,
|
||||
* accumulators; only the GEMM's dtype differs), and against the rotated int8 pair every
|
||||
* form with a row for it (four-bit, the codebook at a 64 or 32 of K, int8), whose views
|
||||
* efmt_of states per projection. The layer's first non-bf16 expert decides both
|
||||
* projections; every other must match. Outside its family a layer uses the probed
|
||||
* layer's form. */
|
||||
const bool a8f = a8;
|
||||
auto family = [a8f](int f) {
|
||||
return a8f ? (f == 2 || f == 5 || f == 6 || f == 10 || f == 11)
|
||||
: (f == 5 || f == 6 || f == 7 || f == 12);
|
||||
};
|
||||
fmt[0] = fmt[1] = want;
|
||||
if (family(want))
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
RadEncoding enc[2]{};
|
||||
int fe[2];
|
||||
const char* nmv[2];
|
||||
fmt_of(e, enc, fe, nmv);
|
||||
if (fe[0] == 3 && fe[1] == 3) continue;
|
||||
for (int i = 0; i < 2; ++i)
|
||||
if (family(fe[i])) fmt[i] = fe[i];
|
||||
break;
|
||||
fenc[0] = fenc[1] = RadEncoding{};
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
RadEncoding enc[2]{};
|
||||
int fe[2];
|
||||
const char* nmv[2];
|
||||
fmt_of(e, enc, fe, nmv);
|
||||
if (fe[0] == 3 && fe[1] == 3) continue;
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
/* A trellis gate_up reads rotated int8, but the down projection can use the
|
||||
* W5NL E4M3 kernel: its gated intermediate is quantised independently below. */
|
||||
const bool mixed_codebook_down = a8f && want == 11 && i == 1 &&
|
||||
(fe[i] == 7 || fe[i] == 12);
|
||||
if (family(want) && (family(fe[i]) || mixed_codebook_down)) fmt[i] = fe[i];
|
||||
fenc[i] = enc[i];
|
||||
}
|
||||
break;
|
||||
}
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
RadEncoding enc[2]{};
|
||||
int fe[2];
|
||||
const char* names[2];
|
||||
fmt_of(e, enc, fe, names);
|
||||
if (fe[0] == fmt[0] && fe[1] == fmt[1]) continue;
|
||||
/* A trellis layer is one code width a projection: the views are declared at it. */
|
||||
const bool same = fe[0] == fmt[0] && fe[1] == fmt[1] &&
|
||||
(fmt[0] != 11 || enc[0].plane[0].dtype == fenc[0].plane[0].dtype) &&
|
||||
(fmt[1] != 11 || enc[1].plane[0].dtype == fenc[1].plane[0].dtype);
|
||||
if (same) continue;
|
||||
if (want != 3 && fe[0] == 3 && fe[1] == 3) { prot.push_back(e); continue; }
|
||||
const int i = fe[0] != fmt[0] ? 0 : 1;
|
||||
char en[256];
|
||||
rad_enc_format(&enc[i], en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, and this layer's experts are served as %s -- one "
|
||||
"table of experts takes one encoding, and only a whole expert kept "
|
||||
"plain bf16 is served beside it.\n", names[i], en, kServed[fmt[i]]);
|
||||
"plain bf16 is served beside it.\n", names[i], en,
|
||||
kServed[fmt[i]] ? kServed[fmt[i]] : kServed8[fmt[i]]);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
@@ -950,14 +1037,33 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
(long long)wq[q], (long long)g.n_embd, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The codes view's dtype and planes; a codebook's table is selected with its codes so the
|
||||
* relayout sees it. */
|
||||
auto edt_of = [&](int f) {
|
||||
return f == 8 ? (uint32_t)RAD_FP4E2M1 : f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
|
||||
: c.expert_w4 ? (uint32_t)RAD_I4 : (uint32_t)RAD_F8E4M3;
|
||||
/* A format's views: the codes view's dtype and planes (a codebook's table is selected with its
|
||||
* codes so the relayout sees it), and the scale view's -- bf16 per
|
||||
* (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group forms E4M3 per (row, 64 of
|
||||
* K) selected with the fixed second level; f32 per 128x128 tile (format 9) or E8M0 per (row, 32
|
||||
* of K) for MXFP4. `sgk` is the K one declared scale column covers: a view of two planes is a
|
||||
* view of the logical weight, like the codes view (rad_builder.cpp), declared at the weight's
|
||||
* extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
|
||||
* hook. */
|
||||
struct EFmt { uint32_t cdt; const char* cplanes; uint32_t sdt; int64_t sgk; const char* splanes; };
|
||||
auto efmt_of = [](int f, const RadEncoding& fe) -> EFmt {
|
||||
switch (f) {
|
||||
/* An IQR weight: the codes at their stored width with the code's planes, and the row and
|
||||
* block scales as one view at the weight's extents (LinearFP8's views of the same form). */
|
||||
case 12: return { RAD_U6, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
|
||||
case 11: return { fe.plane[0].dtype, "codes,trellis,trellis.mad", RAD_F32, 1,
|
||||
"scale,scale.col" };
|
||||
case 10: return { RAD_I8, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
|
||||
case 9: return { RAD_F8E4M3, "codes", RAD_F32, RAD_FP8_BLOCK, "scale" };
|
||||
case 8: return { RAD_FP4E2M1, "codes", RAD_E8M0, RAD_MX_GROUP, "scale" };
|
||||
case 7: return { RAD_U5, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
|
||||
case 5: case 6: return { RAD_U4, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
|
||||
case 4: return { RAD_U4, "codes,table", RAD_BF16, RAD_FP8_BLOCK, "scale" };
|
||||
case 1: case 2: return { RAD_I4, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
|
||||
default: return { RAD_F8E4M3, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
|
||||
}
|
||||
};
|
||||
const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) };
|
||||
const char* const ecodes = c.expert_nl ? "codes,table" : "codes";
|
||||
const EFmt ef[2] = { efmt_of(fmt[0], fenc[0]), efmt_of(fmt[1], fenc[1]) };
|
||||
/* Under expert parallelism each owned expert is whole, so its weights are not sharded;
|
||||
* RAD_SHARD_ROW would make the loader slice it again (and refuse). */
|
||||
const bool ep = c.n_expert != c.n_expert_all;
|
||||
@@ -972,33 +1078,57 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
*
|
||||
* Rotation exists only for the 4-bit plane (the fp8 layout hook has no rotated form), and the
|
||||
* codebook only with rotation; other combinations are refused. */
|
||||
if ((c.expert_rot && !c.expert_w4) || (c.expert_nl && !c.expert_rot)) {
|
||||
fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit expert format, "
|
||||
"and a codebook (expert_nl) the rotated one; there is no rotated E4M3 "
|
||||
"expert plane and no unrotated codebook\n");
|
||||
if ((c.expert_rot && !c.expert_w4 && !c.expert_i8 && !c.expert_iqr) ||
|
||||
(c.expert_nl && !c.expert_rot) || ((c.expert_i8 || c.expert_iqr) && !c.expert_rot)) {
|
||||
fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit or the int8 "
|
||||
"expert format, and a codebook (expert_nl) or int8 experts the rotated "
|
||||
"one; there is no rotated E4M3 expert plane, no unrotated codebook and no "
|
||||
"unrotated int8 expert\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* ---- The routed arm's activations (see `a8`). */
|
||||
if ((c.expert_i8 || c.expert_iqr || fmt[0] == 10 || fmt[0] == 11 ||
|
||||
fmt[1] == 10 || fmt[1] == 11) && !a8) {
|
||||
fprintf(stderr, "radiance: layer %d's experts read int8 activations (int8, or an IQR weight); the "
|
||||
"architecture declared the routed arm's codes E4M3\n", l);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const bool down_codebook_fp8 = a8 && fmt[0] == 11 && (fmt[1] == 7 || fmt[1] == 12);
|
||||
if (a8) {
|
||||
const bool pair = w.eff.q8 && w.eff.s8 && w.eff.q8_rot && w.eff.g8 == RAD_FP8_BLOCK;
|
||||
const bool down_supported = down_codebook_fp8 ? (w.eff.q && w.eff.s && kServed[fmt[1]])
|
||||
: kServed8[fmt[1]] != nullptr;
|
||||
/* A clamped layer is served too: GateQuantFP8 clamps into the bf16 plane, then
|
||||
* quantises it into the rotated codes. Not before a codebook (W5NL, W6NL) down
|
||||
* projection, which reads rotated E4M3: no clamp writes those codes. */
|
||||
const bool clamp_codebook = down_codebook_fp8 && c.swiglu_limit > 0;
|
||||
if (!pair || !c.expert_rot || !kServed8[fmt[0]] || !down_supported || c.calib ||
|
||||
clamp_codebook) {
|
||||
fprintf(stderr, "radiance: layer %d: int8 activations meet rotated experts (int8, "
|
||||
"four-bit, or the codebook at E4M3 scales a 64 or 32 of K) through "
|
||||
"rotated codes at one scale a 128 of K, outside calibration; these "
|
||||
"are %s / %s%s%s\n", l,
|
||||
kServed[fmt[0]] ? kServed[fmt[0]] : kServed8[fmt[0]],
|
||||
kServed[fmt[1]] ? kServed[fmt[1]] : kServed8[fmt[1]],
|
||||
pair ? "" : ", and the gated product's int8 pair is not that",
|
||||
clamp_codebook ? ", and a W5NL or W6NL down projection is served unclamped only"
|
||||
: "");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
const int sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW;
|
||||
const int sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL;
|
||||
const int n_parts = ep ? 0 : (int)gu;
|
||||
/* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit (per 32
|
||||
* for MXFP4). `sdiv` is how many weight rows or columns one scale covers along the split
|
||||
* dimension. */
|
||||
const int64_t sdiv = (c.expert_w4 || c.expert_mx) ? 1 : RAD_FP8_BLOCK;
|
||||
const bool rowscale = c.expert_w4 || c.expert_mx || c.expert_i8 || c.expert_iqr;
|
||||
const int64_t sdiv = rowscale ? 1 : RAD_FP8_BLOCK;
|
||||
/* The dtype string per projection selects the grouped GEMM; its layout hook then accepts the
|
||||
* experts' encoding or the kernel is not a candidate. */
|
||||
const char* const edtype[2] = { kServed[fmt[0]], kServed[fmt[1]] };
|
||||
/* The scale views: bf16 per (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group
|
||||
* forms E4M3 per (row, 64 of K) selected with the fixed second level; f32 per 128x128 tile
|
||||
* (expert_f32_scale) or E8M0 per (row, 32 of K) for MXFP4. With two planes it is a
|
||||
* view of the logical weight, like the codes view (rad_builder.cpp): declared at the weight's
|
||||
* extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
|
||||
* hook. `sgk` is the K one declared scale column covers. */
|
||||
const uint32_t sdt = c.expert_f32_scale ? (uint32_t)RAD_F32
|
||||
: c.expert_mx ? (uint32_t)RAD_E8M0
|
||||
: c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
|
||||
const int64_t sgk = c.expert_mx ? RAD_MX_GROUP : c.expert_g64 ? 1 : RAD_FP8_BLOCK;
|
||||
const char* escale = c.expert_g64 ? "scale,scale.1" : "scale";
|
||||
gu_trellis = fmt[0] == 11;
|
||||
const char* const edtype[2] = { a8 ? kServed8[fmt[0]] : kServed[fmt[0]],
|
||||
a8 && !down_codebook_fp8 ? kServed8[fmt[1]] : kServed[fmt[1]] };
|
||||
/* This class's slice of each expert: gate and up rows [lo, hi), down columns [lo, hi), scale
|
||||
* planes the same in their own units. */
|
||||
auto span = [&](rad_weight h, int q, int64_t unit) -> int {
|
||||
@@ -1064,7 +1194,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_weight& h = w_gu[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
nullptr, ecodes, edt[0], {gu * wq[q], g.n_embd},
|
||||
nullptr, ef[0].cplanes, ef[0].cdt, {gu * wq[q], g.n_embd},
|
||||
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
|
||||
parts, n_parts);
|
||||
if (!h) return RAD_E_INVAL;
|
||||
@@ -1079,9 +1209,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
(long long)(c.expert_base + e)),
|
||||
nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
escale, sdt,
|
||||
{(c.expert_w4 || c.expert_mx) ? gu * wq[q] : fp8_blocks(gu * wq[q]),
|
||||
(c.expert_w4 || c.expert_mx) ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
|
||||
ef[0].splanes, ef[0].sdt,
|
||||
{rowscale ? gu * wq[q] : fp8_blocks(gu * wq[q]),
|
||||
rowscale ? g.n_embd / ef[0].sgk : fp8_blocks(g.n_embd)},
|
||||
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
|
||||
parts, n_parts);
|
||||
if (!h) return RAD_E_INVAL;
|
||||
@@ -1093,7 +1223,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_weight& h = w_dn[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
nullptr, ecodes, edt[1], {g.n_embd, wq[q]},
|
||||
nullptr, ef[1].cplanes, ef[1].cdt, {g.n_embd, wq[q]},
|
||||
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
|
||||
if (!h) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(span(h, q, 1));
|
||||
@@ -1106,11 +1236,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
(long long)(c.expert_base + e)),
|
||||
nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
escale, sdt,
|
||||
{(c.expert_w4 || c.expert_mx) ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
|
||||
ef[1].splanes, ef[1].sdt,
|
||||
{rowscale ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / ef[1].sgk},
|
||||
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
|
||||
if (!h) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(span(h, q, sgk));
|
||||
RAD_ARCH_TRY(span(h, q, ef[1].sgk));
|
||||
}
|
||||
|
||||
/* ---- the two grouped GEMMs. `M` is a pass's token count, not the sorted row count: kernels
|
||||
@@ -1125,19 +1255,32 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
/* The routed arm's rotated copy of the input. Not in place: the shared expert also reads
|
||||
* `w.h.q` with an unrotated weight (see Config::expert_rot). Declared just before its one
|
||||
* consumer so graph and issue order agree. */
|
||||
if (rot) {
|
||||
if (!w.hr.q || !w.hr.s) {
|
||||
fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire; "
|
||||
"the architecture declares the buffers\n");
|
||||
gin_q = w.h.q;
|
||||
gin_s = w.h.s;
|
||||
gin_g = RAD_FP8_BLOCK;
|
||||
if (a8 && w.h.q8_fed && w.h.q8_rot) {
|
||||
/* The trunk's own rotated int8 codes, at its group: no second quantiser. */
|
||||
gin_q = w.h.q8;
|
||||
gin_s = w.h.s8;
|
||||
gin_g = w.h.g8;
|
||||
} else if (rot) {
|
||||
if (a8 ? !(w.hr.q8 && w.hr.s8 && w.hr.q8_fed && w.hr.q8_rot) : !(w.hr.q && w.hr.s)) {
|
||||
fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire%s; "
|
||||
"the architecture declares the buffers\n",
|
||||
a8 ? ", int8 and fed" : "");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
gin_q = w.hr.cq();
|
||||
gin_s = w.hr.cs();
|
||||
gin_g = w.hr.cg();
|
||||
if (!hr_in)
|
||||
op_hq = rw(b, RAD_OP(b, "had_quant_act_fp8",
|
||||
op_hq = rw(b, RAD_OP(b, a8 ? "had_quant_act_i8g" : "had_quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", gin_g), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.hr.q, w.hr.s});
|
||||
{w.h.x}, {gin_q, gin_s});
|
||||
}
|
||||
if (!gin_q || !gin_s || g.n_embd % gin_g) return RAD_E_INVAL;
|
||||
/* A table op's weights in operand order: even experts' codes and scales, then odd experts'
|
||||
* (`w`, `w_scale`, `w_odd`, `w_odd_scale`), or at four classes classes 0 to 3. */
|
||||
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
|
||||
@@ -1154,55 +1297,64 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* and the zeros past the width are never read by that class's down projection. */
|
||||
{
|
||||
const std::vector<rad_weight> tab = tables(w_gu, w_gus);
|
||||
/* `a_group` is stated to the int8 rows alone: last, and cut off otherwise, so an E4M3
|
||||
* graph is the one it was. */
|
||||
const RadParam p4[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_1", gu * wq[1]), RAD_INT("K_1", g.n_embd),
|
||||
RAD_INT("N_2", gu * wq[2]), RAD_INT("K_2", g.n_embd),
|
||||
RAD_INT("N_3", gu * wq[3]), RAD_INT("K_3", g.n_embd),
|
||||
RAD_INT("parts", gu), RAD_INT("a_group", gin_g) };
|
||||
const RadParam p2[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
|
||||
RAD_INT("parts", gu), RAD_INT("a_group", gin_g) };
|
||||
const int cut = a8 ? 0 : 1;
|
||||
rad_op h = ncls == 4
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_1", gu * wq[1]), RAD_INT("K_1", g.n_embd),
|
||||
RAD_INT("N_2", gu * wq[2]), RAD_INT("K_2", g.n_embd),
|
||||
RAD_INT("N_3", gu * wq[3]), RAD_INT("K_3", g.n_embd),
|
||||
RAD_INT("parts", gu)),
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
|
||||
RAD_INT("parts", gu)),
|
||||
tab.data(), (int)tab.size());
|
||||
op_gu = rw(b, h, {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, w.sorted, w.eoff}, {w.egu});
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q", p2, (int)(sizeof p2 / sizeof *p2) - cut,
|
||||
tab.data(), (int)tab.size());
|
||||
op_gu = rw(b, h, {gin_q, gin_s, w.sorted, w.eoff}, {w.egu});
|
||||
}
|
||||
/* The down projection's input can be rotated in place: `w.eff` is read only by the down GEMM,
|
||||
* which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to
|
||||
* the rotated op at no extra launch. */
|
||||
gq_exp.fuse_clamped = c.swiglu_quant != 0;
|
||||
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
|
||||
false, rot, c.swiglu_limit, c.swiglu_step != 0));
|
||||
/* Gate_up and down are separate GEMMs. A trellis gate uses int8 input while W5NL down
|
||||
* reads rotated E4M3: select the latter pair only for the gated intermediate. */
|
||||
ActFP8 down_eff = w.eff;
|
||||
if (down_codebook_fp8) down_eff.q8_fed = down_eff.q8_rot = false;
|
||||
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, down_eff, c.n_ff_exp, gact, c.rows * c.top_k,
|
||||
false, rot && (!a8 || down_codebook_fp8), c.swiglu_limit,
|
||||
c.swiglu_step != 0));
|
||||
{
|
||||
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
|
||||
const RadParam p4[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
|
||||
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
|
||||
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
|
||||
RAD_INT("parts", 1), RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
const RadParam p2[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]),
|
||||
RAD_INT("parts", 1), RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
const int cut = a8 && !down_codebook_fp8 ? 0 : 1;
|
||||
rad_op h = ncls == 4
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
|
||||
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
|
||||
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
|
||||
RAD_INT("parts", 1)),
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]),
|
||||
RAD_INT("parts", 1)),
|
||||
tab.data(), (int)tab.size());
|
||||
op_dn = rw(b, h, {w.eff.q, w.eff.s, w.sorted, w.eoff}, {w.edn});
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q", p2, (int)(sizeof p2 / sizeof *p2) - cut,
|
||||
tab.data(), (int)tab.size());
|
||||
op_dn = rw(b, h, {down_eff.cq(), down_eff.cs(), w.sorted, w.eoff}, {w.edn});
|
||||
}
|
||||
/* ---- The protected experts' own GEMM pair. Their weights belong to the layer group, not to
|
||||
* expert slots: each container expert unit has a fixed size and these are four times larger, so
|
||||
@@ -1339,7 +1491,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_NOWEIGHTS),
|
||||
{rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, b_gram_gu}, {b_gram_gu});
|
||||
{gin_q, gin_s, b_gram_gu}, {b_gram_gu});
|
||||
/* The down tap's M is the sorted height `rows * top_k` (one row per (token, slot)).
|
||||
* gate_up's is the token height: every token goes to exactly top_k experts, so the gathered
|
||||
* distribution is the token distribution scaled by top_k, and H is used only up to scale. */
|
||||
@@ -1412,7 +1564,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const char* shared_up = src.shared_mlp_up
|
||||
? src.shared_mlp_up
|
||||
: nm.ckpt("%s.up_proj.weight", src.shared);
|
||||
RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, { shared_down }));
|
||||
/* An architecture that sized the gate's code pair from this weight has probed it. */
|
||||
if (!sh_down.mapped) RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, { shared_down }));
|
||||
/* The code pair the gate writes, E4M3 or int8 (ActFP8::q8_fed); an int8 down projection
|
||||
* that quantises for itself also writes the int8 pair on this lane. */
|
||||
if (w.sff.cq()) {
|
||||
@@ -1441,6 +1594,17 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows,
|
||||
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false,
|
||||
sh_limit, c.swiglu_step != 0));
|
||||
/* An IQR gate_up between the rotated int8 trunk's fed pairs folds SwiGLU and the rotating
|
||||
* quantiser into its epilogue, to 16 rows: one launch a layer less than the pair, which
|
||||
* stays declared for longer steps, other encodings and a clamped product. */
|
||||
if (sh_limit <= 0 && sh_gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.sff.q8_fed &&
|
||||
w.sff.q8_rot)
|
||||
op_sh_gated = decl_gated_fold_iqr(
|
||||
b, c.rows, sh_gate_up.N, sh_gate_up.K, sh_gate_up.w, sh_gate_up.ws,
|
||||
{ w.h.q8, w.h.s8 },
|
||||
gq_sh.want_x ? std::initializer_list<rad_buf>{ w.sff.q8, w.sff.s8, w.sff.x }
|
||||
: std::initializer_list<rad_buf>{ w.sff.q8, w.sff.s8 },
|
||||
&sh_gated_rows);
|
||||
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
|
||||
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
|
||||
{ shared_down },
|
||||
@@ -1641,7 +1805,14 @@ inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
|
||||
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
|
||||
brow_slice(w.sgate, r0, rows, 1));
|
||||
}
|
||||
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
|
||||
if (op_sh_gated && rows <= sh_gated_rows)
|
||||
RAD_ISSUE_N(c_, op_sh_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
|
||||
brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(sh_gate_up.w),
|
||||
RAD_W(sh_gate_up.ws), brow_slice(w.sff.cq(), r0, rows, c.n_ff_shared),
|
||||
brow_slice(w.sff.cs(), r0, rows, c.n_ff_shared / RAD_FP8_BLOCK),
|
||||
gq_sh.want_x ? brow_slice(w.sff.x, r0, rows, c.n_ff_shared) : RAD_NONE);
|
||||
else
|
||||
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
|
||||
}
|
||||
|
||||
/* One pass of at most `c.rows` tokens. Every op is per row (norm and quantiser within a row,
|
||||
@@ -1660,9 +1831,10 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
|
||||
/* The shared arm is interleaved with the routed arm on the same queue. It reads the same
|
||||
* input and writes nothing the routed arm touches before the gather, so each of its stages
|
||||
* (gate + gate_up, quantiser, down) is issued right behind the matching routed stage. A
|
||||
* recorded pass leaves each such pair unordered (Ctx::haz_mark), so they overlap without a
|
||||
* second queue's fork/join cost. The arm's buffers are excluded from sharing (see declare), so
|
||||
* (gate + gate_up, quantiser, down) is issued right behind the matching routed stage (its
|
||||
* first stage behind the router instead where `sh_first` below says so). A recorded pass
|
||||
* leaves each such pair unordered (Ctx::haz_mark), so they overlap without a second queue's
|
||||
* fork/join cost. The arm's buffers are excluded from sharing (see declare), so
|
||||
* issuing them ahead of their declared position is safe. */
|
||||
|
||||
/* The routed arm. */
|
||||
@@ -1675,8 +1847,11 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
* the histogram the kernel writes there never lands, and a consumer reading the reported
|
||||
* counts -- the file stager, at the layer's trigger -- sees zeros and skips every expert's
|
||||
* weights. The declared buffer is stable across record and replay, and route_report hands
|
||||
* the same buffer on, so the stager's stream-ordered read sees this pass's counts. */
|
||||
const RadOperand ecnt = brows(w.ecnt, ne);
|
||||
* the same buffer on, so the stager's stream-ordered read sees this pass's counts. With a
|
||||
* routing table (Wire::ecnt_pitch) the buffer is the core's rows too, and this is the
|
||||
* layer's. */
|
||||
const RadOperand ecnt = w.ecnt_pitch > 0 ? brow_slice(w.ecnt, layer, 1, w.ecnt_pitch)
|
||||
: brows(w.ecnt, ne);
|
||||
/* The fused router when it resolved and the pass fits: router, topk + scatter and (with
|
||||
* `router_fused_gate`) the shared gate in one launch. Otherwise the separate ops. */
|
||||
const bool rfused = op_router_fused && rows <= router_fused_rows;
|
||||
@@ -1726,13 +1901,22 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
const bool rot = c.expert_rot != 0;
|
||||
if (op_hq)
|
||||
RAD_ISSUE_N(c_, op_hq, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.hr.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.hr.s, r0, rows, g.n_embd / RAD_FP8_BLOCK));
|
||||
brow_slice(gin_q, r0, rows, g.n_embd),
|
||||
brow_slice(gin_s, r0, rows, g.n_embd / gin_g));
|
||||
|
||||
/* The grouped GEMMs. Each table is the first handle of its run and its length; runs are
|
||||
* contiguous (see declare), so `w_gu[q] + i` is expert 2 * i + q, or 4 * i + q at four
|
||||
* classes, where class q holds ceil((n_reg - q) / 4). */
|
||||
const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 };
|
||||
/* Behind a trellis gate_up from kSharedFirstRows routed rows, the shared arm's first stage is
|
||||
* issued here, so it overlaps the router and the routed gate_up runs alone: that GEMM is
|
||||
* compute-bound at such heights, and with the arm beside it the pair ends later than the two
|
||||
* in turn. Flash-Next's 16- and 32-row verify passes on two R9700: 22.1 -> 21.9 ms and
|
||||
* 31.6 -> 30.95 ms. Below, the arm fits inside the routed GEMM's time and stays beside it. */
|
||||
const bool sh_first = shared && gu_trellis && rows * k >= kSharedFirstRows;
|
||||
if (sh_first)
|
||||
shared_up(c_, T, r0, rows,
|
||||
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
|
||||
/* Apply the previous layer's prefetch prediction: substitute the copied experts into the
|
||||
* tables. */
|
||||
(void)rad_expert_prefetch_step(c_, layer);
|
||||
@@ -1742,8 +1926,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
brows(w.egu, rows * k));
|
||||
else if (ncls == 4)
|
||||
RAD_ISSUE_N(c_, op_gu, rows,
|
||||
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
|
||||
brow_slice(gin_q, r0, rows, g.n_embd),
|
||||
brow_slice(gin_s, r0, rows, g.n_embd / gin_g),
|
||||
RAD_WTAB(w_gu[0], n4[0]), RAD_WTAB(w_gus[0], n4[0]),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_gu[1], n4[1]), RAD_WTAB(w_gus[1], n4[1]),
|
||||
@@ -1752,22 +1936,36 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
brows(w.egu, rows * k));
|
||||
else
|
||||
RAD_ISSUE_N(c_, op_gu, rows,
|
||||
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
|
||||
brow_slice(gin_q, r0, rows, g.n_embd),
|
||||
brow_slice(gin_s, r0, rows, g.n_embd / gin_g),
|
||||
RAD_WTAB(w_gu[0], n_reg / 2), RAD_WTAB(w_gus[0], n_reg / 2),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2),
|
||||
brows(w.egu, rows * k));
|
||||
if (shared) shared_up(c_, T, r0, rows,
|
||||
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
|
||||
if (shared && !sh_first)
|
||||
shared_up(c_, T, r0, rows,
|
||||
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
|
||||
gq_exp.step(c_, w.egu, rows * k, 0, rows * k);
|
||||
if (shared) gq_sh.step(c_, w.sgu, T, r0, rows);
|
||||
if (shared && !(op_sh_gated && rows <= sh_gated_rows)) gq_sh.step(c_, w.sgu, T, r0, rows);
|
||||
/* The shared arm's down projection in front of the routed down GEMM on a step of
|
||||
* [sh_down_first_lo, sh_down_first_hi] rows. Behind it (below) the two still run together,
|
||||
* but the card launches the arm only once every block of the routed GEMM is on it; at a
|
||||
* verify step's forty routed rows that is a few microseconds before that GEMM ends, and the
|
||||
* gather then waits for the arm. In front, the arm is the ordered launch behind the two
|
||||
* quantisers and the routed GEMM starts beside it (it reads nothing the arm writes): the same
|
||||
* start for the routed GEMM, and the arm is done long before it. At one row the routed GEMM
|
||||
* is a quarter of the blocks, the arm behind it is launched in time, and in front it only
|
||||
* delays that GEMM's launch (+0.38% a step), hence the lower bound. The arm's buffers are
|
||||
* excluded from sharing (declare), so the order is free. Qwen3.8-Flash-Next at tp 2 with
|
||||
* coupling, chain 1 / 2 / 3 (two / three / four rows): -0.28% / -0.21% / -0.25% a step. */
|
||||
const bool sh_dn_first = shared && T >= sh_down_first_lo && T <= sh_down_first_hi;
|
||||
if (sh_dn_first) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
|
||||
if (c.expert_bf16)
|
||||
RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k));
|
||||
else if (ncls == 4)
|
||||
RAD_ISSUE_N(c_, op_dn, rows,
|
||||
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
|
||||
brows(gq_exp.a.cq(), rows * k), brows(gq_exp.a.cs(), rows * k),
|
||||
RAD_WTAB(w_dn[0], n4[0]), RAD_WTAB(w_dns[0], n4[0]),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_dn[1], n4[1]), RAD_WTAB(w_dns[1], n4[1]),
|
||||
@@ -1776,7 +1974,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
brows(w.edn, rows * k));
|
||||
else
|
||||
RAD_ISSUE_N(c_, op_dn, rows,
|
||||
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
|
||||
brows(gq_exp.a.cq(), rows * k), brows(gq_exp.a.cs(), rows * k),
|
||||
RAD_WTAB(w_dn[0], n_reg / 2), RAD_WTAB(w_dns[0], n_reg / 2),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_dn[1], n_reg / 2), RAD_WTAB(w_dns[1], n_reg / 2),
|
||||
@@ -1796,7 +1994,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
RAD_ISSUE_N(c_, op_pdn, rows, brows(pff.x, rows * k), RAD_WTAB(w_pdn[0], np),
|
||||
brows(w.sorted, rows * k), poff, brows(w.edn, rows * k));
|
||||
}
|
||||
if (shared) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
|
||||
if (shared && !sh_dn_first) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
|
||||
/* The calibration tap reads the GEMMs' operands and writes nothing they touch, so it does not
|
||||
* change the model's output. */
|
||||
if (op_gram_gu && !calib_done) {
|
||||
@@ -1946,12 +2144,13 @@ inline void MoeFP8::route_report(RadCtx* c_) const {
|
||||
* destination row, the copy here is skipped, and the row stays zero -- which the file stager
|
||||
* read as "no expert routed" and skipped every layer's weights (NaN logits, empty text).
|
||||
* Copying w.ecnt into the row (the pointers now differ) also feeds the heat engine real
|
||||
* histograms instead of the zeros it saw before. */
|
||||
* histograms instead of the zeros it saw before. With a routing table (Wire::ecnt_pitch) the
|
||||
* router did write the core's row, as a declared operand, and the report copies nothing. */
|
||||
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0);
|
||||
RadRouting r{};
|
||||
r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids);
|
||||
r.expert_w = nullptr;
|
||||
r.expert_count = (const int32_t*)rad_buf_ptr(c_, w.ecnt);
|
||||
r.expert_count = (const int32_t*)rad_buf_ptr(c_, w.ecnt) + (int64_t)layer * w.ecnt_pitch;
|
||||
r.sorted_tok = (const int32_t*)rad_buf_ptr(c_, w.sorted);
|
||||
r.expert_offset = (const int32_t*)rad_buf_ptr(c_, w.eoff);
|
||||
r.top_k = c.top_k;
|
||||
|
||||
@@ -152,6 +152,13 @@ struct MtpHcBlock {
|
||||
MoeFP8 mlp{};
|
||||
|
||||
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
|
||||
/* The selected draft calibration also records the bf16 attention input shared by
|
||||
* qg/k/v, independently of the expert gate's later input. */
|
||||
rad_buf b_attn_gram = 0;
|
||||
rad_op op_attn_gram = 0;
|
||||
const char* attn_gram_stem = nullptr;
|
||||
mutable int64_t attn_gram_rows = 0;
|
||||
mutable bool attn_gram_done = false;
|
||||
|
||||
/* Media rows over the head's embedding (see MtpBlockFP8::media). Set before declare when the
|
||||
* program has an encoder. */
|
||||
@@ -258,6 +265,20 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
* order. */
|
||||
RAD_ARCH_TRY(hc_attn.declare(b, nm, g, nm.f("mtp.attn_hc"), hc, HyperConn::Wire{w.hw, w.x, w.inj},
|
||||
src.hc_attn));
|
||||
if (src.mlp.cfg.calib) {
|
||||
/* Only a BF16 source supplies domain-0 inputs for this calibration. The input
|
||||
* is replicated, so each TP rank records the same width and GPTQ sums them. */
|
||||
if (!src.mlp.cfg.expert_bf16 || !w.attn.h.x) return RAD_E_UNSUPPORTED;
|
||||
attn_gram_stem = nm.f("blk.%d.attn_qg", l);
|
||||
b_attn_gram = decl_b(b, nm.f("blk.%d.mtp_attn_gram", l), RAD_F32,
|
||||
{g.n_embd, g.n_embd}, RAD_BUF_PERSIST);
|
||||
op_attn_gram = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.h.x, b_attn_gram}, {b_attn_gram});
|
||||
if (!b_attn_gram || !op_attn_gram) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
|
||||
attn.ar_out_take = hc_attn.ar_take();
|
||||
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn,
|
||||
@@ -282,7 +303,11 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
/* The connection's read also writes the rotated expert input, as on the trunk. */
|
||||
HyperConn::Config mcfg = hc;
|
||||
HyperConn::Wire mwire{w.hw, w.x, w.inj};
|
||||
if (src.mlp.cfg.expert_rot) { mcfg.rotate = 1; mwire.rq = w.mlp.hr.q; mwire.rs = w.mlp.hr.s; }
|
||||
if (src.mlp.cfg.expert_rot && !w.x.q8_rot) {
|
||||
mcfg.rotate = 1;
|
||||
mwire.rq = w.mlp.hr.cq();
|
||||
mwire.rs = w.mlp.hr.cs();
|
||||
}
|
||||
RAD_ARCH_TRY(hc_mlp.declare(b, nm, g, nm.f("mtp.ffn_hc"), mcfg, mwire, src.hc_mlp));
|
||||
mlp.ar_out_take = hc_mlp.ar_take();
|
||||
mlp.hr_in = mcfg.rotate != 0;
|
||||
@@ -467,6 +492,17 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int r = batch->draft_pass;
|
||||
/* Expert calibration needs real draft-layer inputs, not the trunk's Hessian. In a
|
||||
* selected calibration layer, run the history's teacher-forced rows through the full
|
||||
* draft block before selecting the rows needed by the drafter. Normal inference and
|
||||
* a tap that has reached its target retain the ordinary history-only fast path. */
|
||||
const bool tap_history = r < 0 && mlp.c.calib && !mlp.calib_done;
|
||||
/* serial_batch names one trunk hidden row per history token. Refuse an incomplete
|
||||
* gather instead of silently calibrating stale hin rows if that contract changes. */
|
||||
if (tap_history && (batch->n_out != T || !batch->out_ids)) {
|
||||
rad_step_fail(c, "MTP calibration needs one trunk hidden row per history token");
|
||||
return;
|
||||
}
|
||||
|
||||
/* The history pass continues from the trunk's wide stream; later rounds from the head's,
|
||||
* which the carry left in the same buffer. */
|
||||
@@ -489,11 +525,26 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
|
||||
|
||||
hc_attn.read_pieces(c, T);
|
||||
if (tap_history && op_attn_gram && !attn_gram_done) {
|
||||
if (attn_gram_rows == 0)
|
||||
rad_memset_async(rad_buf_ptr(c, b_attn_gram), 0,
|
||||
g.n_embd * g.n_embd * 4, rad_stream(c));
|
||||
RAD_ISSUE_N(c, op_attn_gram, T, brows(w.attn.h.x, T), RAD_NONE,
|
||||
brows(b_attn_gram, g.n_embd));
|
||||
attn_gram_rows += T;
|
||||
if (attn_gram_rows >= calib_target()) {
|
||||
if (!calib_write(c, b_attn_gram, g.n_embd, attn_gram_rows, attn_gram_stem, 0)) {
|
||||
rad_step_fail(c, "MTP calibration could not write its attention input Gram");
|
||||
return;
|
||||
}
|
||||
attn_gram_done = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only stores
|
||||
* the head's state: K and V, and the indexer's block keys and tail. `n_draft_out` is the same
|
||||
* on every rank, so skipped collectives match. */
|
||||
if (r < 0 && batch->n_draft_out <= 0) {
|
||||
if (r < 0 && batch->n_draft_out <= 0 && !tap_history) {
|
||||
qsa.store(c, attn.w.h, batch);
|
||||
attn.store_kv(c, batch);
|
||||
return;
|
||||
@@ -501,7 +552,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
/* The indexer runs first because the attention reads its selection; `w.h` is already final,
|
||||
* written by the connection above. */
|
||||
qsa.step(c, attn.w.h, batch, qsa_win_cu);
|
||||
qsa.step(c, attn.w.h, batch, qsa_win_cu, attn.qsa_use(batch));
|
||||
attn.step(c, batch);
|
||||
|
||||
hc_attn.write(c, T, 0, T);
|
||||
@@ -509,7 +560,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
/* A history pass with drafting rows continues on those rows alone (round 1): they are moved
|
||||
* to the front of `hw` and the rest of the head runs over them. */
|
||||
int64_t L = T; /* the rows the stream goes on with */
|
||||
if (r < 0) {
|
||||
if (r < 0 && !tap_history) {
|
||||
L = batch->n_draft_out;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.hin, L));
|
||||
@@ -520,6 +571,16 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
mlp.step_rows(c, L);
|
||||
hc_mlp.write(c, L, 0, L);
|
||||
|
||||
if (tap_history) {
|
||||
/* History-only chunks have no proposal. For the last chunk, select the same
|
||||
* round-1 rows the ordinary path would have selected before its feed-forward. */
|
||||
L = batch->n_draft_out;
|
||||
if (L <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.hin, L));
|
||||
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
|
||||
}
|
||||
|
||||
/* The carry, only if a later round reads it: a history pass is round 1, followed by round 2
|
||||
* when depth > 1; the last round is followed by a trunk step. */
|
||||
if (r < 0 ? depth > 1 : r < depth)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,584 @@
|
||||
/* rad_block_museglimmer_vision.h -- Muse Glimmer's vision tower (transformers'
|
||||
* MuseGlimmerVisionModel, an InternVit-shaped stack), its adapter and the perception norm, served
|
||||
* by museglimmer.
|
||||
*
|
||||
* What it computes, per encoder pass (RadBatch::enc), in the reference's order:
|
||||
*
|
||||
* x = patches @ Wp^T the patch embedding as a linear layer, bias-less;
|
||||
* a patch row is (temporal, channel, y, x)
|
||||
* x += position table resampled to the grid `grid_embed_pad`, bilinear at half-pixel
|
||||
* centres, align_corners=False, out-of-range taps
|
||||
* zero-weighted (grid_sample padding zeros)
|
||||
* x = LN_pre(x) LayerNorm, eps `layer_norm_eps`
|
||||
* x = x[window order] `window_order`: the 32x32-patch window permutation
|
||||
* (per frame, ragged edges smaller windows), its
|
||||
* inverse, per-slot rotary positions and the
|
||||
* per-window cumulative boundaries
|
||||
* depth times:
|
||||
* h = LN1(x) LayerNorm, eps 1e-5 (the blocks hard-code it)
|
||||
* q|k|v = qkv(h) the reference's three biased projections, joined
|
||||
* q first into one GEMM as the reference's fused
|
||||
* tensors would read
|
||||
* rope(q, k) `rope` axial, the whole head, sections
|
||||
* head_dim/4 a side on theta^(-j/(head_dim/4)),
|
||||
* positions (column + 1, row + 1) -- HF's
|
||||
* position_ids.flip(-1) + 1
|
||||
* x += proj(attn(q, k, v)) non-causal, scale 1/sqrt(head_dim). A
|
||||
* window_attention layer attends within one window
|
||||
* (cu = the per-window boundaries in permuted
|
||||
* order); a full_attention layer attends within
|
||||
* its frame (cu = the frame boundaries). The
|
||||
* window permutation never moves a patch across
|
||||
* frames, so the frame boundaries among permuted
|
||||
* rows are the boundaries among natural rows:
|
||||
* `enc_cu` is passed unchanged, exactly what the
|
||||
* reference passes (modeling_muse_glimmer.py maps
|
||||
* full_attention to the frame cu_seqlens while the
|
||||
* rows stay permuted).
|
||||
* x += fc2(gelu(fc1(LN2(x)))) both biased; `gelu` the exact erf form the
|
||||
* config's hidden_act names, in gemm_nt_bias's
|
||||
* epilogue
|
||||
* x = x[inv] the window order undone (gather_rows)
|
||||
* x = LN_post(x) LayerNorm, eps `layer_norm_eps`
|
||||
* y = pixel_shuffle(x) the merge (`pixtral_merge`): each 2x2 block's
|
||||
* four patches fold into one row of merge^2 *
|
||||
* width, channels interleaved -- the reference's
|
||||
* [block, merge^2, dim].permute(0, 2, 1)
|
||||
* y = gelu(fc2(gelu(fc1(y)))) the adapter: both linears bias-less, TWO
|
||||
* activations (projector_hidden_act)
|
||||
* y = y @ Wproj^T the projection, bias-less, the model's width
|
||||
* out = rms(y) `perception_emb_norm`, a weightless RMS norm at
|
||||
* the TEXT model's rms_norm_eps
|
||||
*
|
||||
* The reference permutes AFTER ln_pre, so the tower works in window order and un-permutes before
|
||||
* ln_post, exactly as above. The processor stages patches in the reference's raster order; the
|
||||
* merge is a real fold (not a view: the reference interleaves the four patches' channels, which
|
||||
* four consecutive rows do not spell), and its output is what the adapter reads.
|
||||
*
|
||||
* Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the
|
||||
* weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx::
|
||||
* max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's
|
||||
* step; the attention's longest segment stays at the real pass so the kernel rows do not move.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MUSEGLIMMER_VISION_H
|
||||
#define RAD_BLOCK_MUSEGLIMMER_VISION_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct MuseTower {
|
||||
/* Geometry, from the container's vision_config (never aliased: only the full prefix). The
|
||||
* adapter's widths are top-level keys of the family config. */
|
||||
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0;
|
||||
int64_t merge = 0, side = 0, npos = 0, proj_ff = 0, out_hidden = 0, n_embd = 0;
|
||||
int64_t patch_dim = 0, P = 0;
|
||||
double eps = 1e-5; /* ln_pre / ln_post; the blocks hard-code 1e-5 */
|
||||
float theta = 10000.0f;
|
||||
bool on = false;
|
||||
|
||||
struct Layer {
|
||||
bool full = false; /* full_attention: frame-wide attention, NoPE-free (rotary runs
|
||||
* on every layer of this tower, full or window) */
|
||||
rad_weight n1w = 0, n1b = 0, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
|
||||
rad_weight n2w = 0, n2b = 0, up_w = 0, up_b = 0, down_w = 0, down_b = 0;
|
||||
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
|
||||
int64_t max_seg = 0; /* the kernel band's longest segment */
|
||||
};
|
||||
std::vector<Layer> L;
|
||||
rad_weight w_patch = 0, w_pos = 0, lw_pre = 0, lb_pre = 0, lw_post = 0, lb_post = 0;
|
||||
rad_weight w_a1 = 0, w_a2 = 0, w_proj = 0;
|
||||
rad_op op_patch = 0, op_pos = 0, op_lpre = 0, op_wo = 0, op_gidx = 0, op_ginv = 0;
|
||||
rad_op op_lpost = 0, op_merge = 0, op_m1 = 0, op_g1 = 0, op_m2 = 0, op_g2 = 0, op_proj = 0,
|
||||
op_perc = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_p = 0, b_qkv = 0, b_att = 0, b_ff = 0;
|
||||
rad_buf b_idx = 0, b_inv = 0, b_pos = 0, b_cuw = 0;
|
||||
rad_buf b_mh = 0, b_m1 = 0, b_m2 = 0, b_out = 0;
|
||||
char sec[48] = {};
|
||||
|
||||
/* Whether the container carries this family's tower. */
|
||||
static bool present(const RadModelMeta* m) {
|
||||
return rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
|
||||
Names& nm, int64_t model_embd, int first_group) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
|
||||
depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
|
||||
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
|
||||
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
|
||||
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
|
||||
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
|
||||
temporal = rad_meta_geti(m, "vision_config.patch_temporal", 2);
|
||||
merge = rad_meta_geti(m, "vision_config.merge_size", 2);
|
||||
side = rad_meta_geti(m, "vision_config.pos_emb_height", 0);
|
||||
npos = rad_meta_geti(m, "vision_config.pos_emb_height", 0) *
|
||||
rad_meta_geti(m, "vision_config.pos_emb_width", 0);
|
||||
eps = rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-5);
|
||||
theta = (float)rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0);
|
||||
proj_ff = rad_meta_geti(m, "projector_hidden_size", 4096);
|
||||
out_hidden = rad_meta_geti(m, "out_hidden_size", 6144);
|
||||
n_embd = model_embd;
|
||||
/* Bounds the walk and the host allocations below take at face value, set against published
|
||||
* maxima rather than round numbers: the deepest vision encoder ever shipped is 48 layers
|
||||
* (ViT-22B, InternViT-6B; this family's towers are SigLIP-class, tens), and the largest
|
||||
* stored position table a side of 92 (SigLIP at 1292 px over patch 14; CLIP 16, SAM 64 --
|
||||
* native-resolution towers store no side x side table at all). The caps sit ~2.6x and
|
||||
* ~5.5x past those maxima, so they never bite an honest container, and at the cap the
|
||||
* guarded shapes are harmless: the depth vectors cost KiB and the grid products reach 2^18
|
||||
* at most. Past the caps the container is not describing a model but a vector size
|
||||
* (full.assign(depth) and L.assign(depth) would throw past max_size, and the grid products
|
||||
* below overflow signed 64 before any comparison could notice). Refuse like every other
|
||||
* bad config: say so and RAD_E_INVAL. */
|
||||
if (depth <= 0 || depth > 128 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 ||
|
||||
temporal <= 0 || merge <= 0 || side <= 0 || side > 512 || proj_ff <= 0 ||
|
||||
out_hidden <= 0 || width % heads ||
|
||||
rad_meta_geti(m, "vision_config.pos_emb_width", 0) != side) {
|
||||
fprintf(stderr, "radiance: museglimmer: the container's vision_config is incomplete, "
|
||||
"inconsistent, or past what this tower walks (depth %lld, hidden %lld, "
|
||||
"heads %lld, ff %lld, patch %lld, "
|
||||
"temporal %lld, merge %lld, position grid %lld x %lld, projector %lld, "
|
||||
"merged %lld)\n", (long long)depth, (long long)width, (long long)heads,
|
||||
(long long)ff, (long long)patch, (long long)temporal, (long long)merge,
|
||||
(long long)side, (long long)rad_meta_geti(m, "vision_config.pos_emb_width", 0),
|
||||
(long long)proj_ff, (long long)out_hidden);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The merge is `pixtral_merge`, whose kernels fold a 2x2 block: the only factor Muse Glimmer
|
||||
* ships and the only one the op serves. */
|
||||
if (merge != 2) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower states merge_size %lld; the "
|
||||
"merge op folds a 2x2 block\n", (long long)merge);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The exact-erf GELU is what this tower and its adapter state; another activation is another
|
||||
* tower (the reference would compute a different function). */
|
||||
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu");
|
||||
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
|
||||
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial");
|
||||
if (std::strcmp(act, "gelu") || std::strcmp(pact, "gelu")) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower has hidden_act '%s' and "
|
||||
"projector_hidden_act '%s'; it serves the exact gelu both call for\n",
|
||||
act, pact);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* `axial` is Meta's spelling and `default` NVIDIA's ModelOpt export of the same tower: the
|
||||
* reference's vision embedder has one rotary (axial), so both name it. Anything else is
|
||||
* another tower. */
|
||||
if (std::strcmp(rt, "axial") && std::strcmp(rt, "default")) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower states rope_type '%s'; it "
|
||||
"serves the axial 2-D rotary the tower's rotary embedder raises on "
|
||||
"leaving\n", rt);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The tower's full layers: every fourth, counted from the start, plus the last (the config's
|
||||
* own rule, MuseGlimmerVisionConfig.__post_init__). The shipped array must say the same
|
||||
* thing; a window layer where the rule puts a full one changes what the model saw. */
|
||||
std::vector<int> full;
|
||||
const char* kinds = rad_meta_gets(m, "vision_config.layer_types", "");
|
||||
if (kinds && *kinds) {
|
||||
RAD_ARCH_TRY(parse_layer_kinds("museglimmer vision", kinds, {"full_attention"},
|
||||
"window_attention", &full));
|
||||
if ((int64_t)full.size() != depth) {
|
||||
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types names %zu layers "
|
||||
"and the tower has %lld\n", full.size(), (long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int64_t l = 0; l < depth; ++l) {
|
||||
const bool rule = is_full_attention(l, 4) || l == depth - 1;
|
||||
if ((full[(size_t)l] != 0) != rule) {
|
||||
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types makes tower "
|
||||
"layer %lld %s and the family rule (every fourth from the first, "
|
||||
"plus the last) makes it %s\n", (long long)l,
|
||||
full[(size_t)l] ? "full" : "window", rule ? "full" : "window");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
full.assign((size_t)depth, 0);
|
||||
for (int64_t l = 0; l < depth; ++l)
|
||||
full[(size_t)l] = is_full_attention(l, 4) || l == depth - 1;
|
||||
}
|
||||
|
||||
head_dim = width / heads;
|
||||
patch_dim = 3 * temporal * patch * patch;
|
||||
/* The 2-D rotary: half the head a side, each on its own ladder (arange(0, head_dim/2, 2)
|
||||
* frequencies, sections head_dim/4 a side). */
|
||||
if (head_dim % 4) return RAD_E_SHAPE;
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4),
|
||||
(long long)(head_dim / 4));
|
||||
/* The merger's rows replace token embeddings, so they must be the model's width. */
|
||||
if (out_hidden != merge * merge * width) {
|
||||
fprintf(stderr, "radiance: museglimmer: out_hidden_size %lld is not merge %lld squared "
|
||||
"times the tower's width %lld, whose view the adapter's first layer "
|
||||
"reads\n", (long long)out_hidden, (long long)merge, (long long)width);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The tower emits merged rows the width of the model's tokens: the caller passes the model's
|
||||
* width and the projection is declared at it, so no separate check exists. */
|
||||
|
||||
const int64_t mm = merge * merge;
|
||||
P = ctx->max_enc_patches;
|
||||
if (ctx->shape_probe) {
|
||||
/* A sizing declare: rows follow the probe's step (rounded to whole merged rows), keeping
|
||||
* the activations out of the levels a decode step runs at. The kernel bands stay at the
|
||||
* real pass: the engine runs the real declare's kernels at every level. */
|
||||
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
|
||||
P = std::max<int64_t>(mm, r / mm * mm);
|
||||
}
|
||||
if (P % mm) return RAD_E_SHAPE;
|
||||
const int64_t R = P / mm;
|
||||
const int64_t ACC = RAD_ACCESS_PER_REQUEST;
|
||||
/* The window side in patches (the reference states it in pixels and divides by patch_size).
|
||||
* A window_attention layer's longest segment is one window. */
|
||||
const int64_t win_seg = side * side;
|
||||
|
||||
/* ---- weights, replicated. Model-level groups for the stem and the adapter; one group per
|
||||
* block from `first_group` on, so a tower block is its own movement unit. */
|
||||
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
w_patch = bw(nm.f("v.patch.weight"),
|
||||
nm.ckpt("model.vision_tower.patch_embedder.patch_embedding.weight"),
|
||||
{ width, patch_dim }, grp_model());
|
||||
w_pos = bw(nm.f("v.pos.weight"),
|
||||
nm.ckpt("model.vision_tower.patch_embedder.position_embedding_table.weight"),
|
||||
{ npos, width }, grp_model());
|
||||
lw_pre = bw(nm.f("v.lnpre.weight"), nm.ckpt("model.vision_tower.ln_pre.weight"), { width },
|
||||
grp_model());
|
||||
lb_pre = bw(nm.f("v.lnpre.bias"), nm.ckpt("model.vision_tower.ln_pre.bias"), { width },
|
||||
grp_model());
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
const int li = (int)i;
|
||||
auto src = [&](const char* s) { return nm.ckpt("model.vision_tower.layers.%d.%s", li, s); };
|
||||
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
|
||||
l.n1w = bw(dn("norm1.weight"), src("norm1.weight"), { width }, g);
|
||||
l.n1b = bw(dn("norm1.bias"), src("norm1.bias"), { width }, g);
|
||||
/* The reference's three biased projections, joined q | k | v into one GEMM. */
|
||||
if (map_concat(b, dn("qkv.weight"),
|
||||
{ src("attn.q_proj.weight"), src("attn.k_proj.weight"),
|
||||
src("attn.v_proj.weight") }) < 0)
|
||||
return RAD_E_INVAL;
|
||||
l.qkv_w = decl_w(b, dn("qkv.weight"), RAD_BF16, { 3 * width, width }, ACC,
|
||||
RAD_SHARD_NONE, g, 0, { width, width, width });
|
||||
if (map_concat(b, dn("qkv.bias"),
|
||||
{ src("attn.q_proj.bias"), src("attn.k_proj.bias"),
|
||||
src("attn.v_proj.bias") }) < 0)
|
||||
return RAD_E_INVAL;
|
||||
l.qkv_b = decl_w(b, dn("qkv.bias"), RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g, 0,
|
||||
{ width, width, width });
|
||||
l.out_w = bw(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g);
|
||||
l.out_b = bw(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
|
||||
l.n2w = bw(dn("norm2.weight"), src("norm2.weight"), { width }, g);
|
||||
l.n2b = bw(dn("norm2.bias"), src("norm2.bias"), { width }, g);
|
||||
l.up_w = bw(dn("fc1.weight"), src("mlp.fc1.weight"), { ff, width }, g);
|
||||
l.up_b = bw(dn("fc1.bias"), src("mlp.fc1.bias"), { ff }, g);
|
||||
l.down_w= bw(dn("fc2.weight"), src("mlp.fc2.weight"), { width, ff }, g);
|
||||
l.down_b= bw(dn("fc2.bias"), src("mlp.fc2.bias"), { width }, g);
|
||||
if (!l.n1w || !l.n1b || !l.qkv_w || !l.qkv_b || !l.out_w || !l.out_b || !l.n2w || !l.n2b ||
|
||||
!l.up_w || !l.up_b || !l.down_w || !l.down_b)
|
||||
return RAD_E_INVAL;
|
||||
l.full = full[(size_t)i] != 0;
|
||||
l.max_seg = l.full ? ctx->max_enc_patches : win_seg;
|
||||
}
|
||||
lw_post = bw(nm.f("v.lnpost.weight"), nm.ckpt("model.vision_tower.ln_post.weight"), { width },
|
||||
grp_model());
|
||||
lb_post = bw(nm.f("v.lnpost.bias"), nm.ckpt("model.vision_tower.ln_post.bias"), { width },
|
||||
grp_model());
|
||||
w_a1 = bw(nm.f("v.mlp.fc1.weight"), nm.ckpt("model.vision_adapter.fc1.weight"),
|
||||
{ proj_ff, out_hidden }, grp_model());
|
||||
w_a2 = bw(nm.f("v.mlp.fc2.weight"), nm.ckpt("model.vision_adapter.fc2.weight"),
|
||||
{ proj_ff, proj_ff }, grp_model());
|
||||
w_proj = bw(nm.f("v.proj.weight"), nm.ckpt("model.vision_projection.weight"),
|
||||
{ n_embd, proj_ff }, grp_model());
|
||||
if (!w_patch || !w_pos || !lw_pre || !lb_pre || !lw_post || !lb_post || !w_a1 || !w_a2 ||
|
||||
!w_proj)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- activations. `mh` holds the merged rows: `pixtral_merge` folds each 2x2 block's four
|
||||
* patch rows into one row of mm * width in the reference's pixel_shuffle layout, and the
|
||||
* adapter's first layer reads it. */
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
|
||||
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
|
||||
b_p = decl_b(b, nm.f("v.p"), RAD_BF16, { P, width });
|
||||
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
|
||||
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
|
||||
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
|
||||
b_idx = decl_b(b, nm.f("v.idx"), RAD_I32, { P });
|
||||
b_inv = decl_b(b, nm.f("v.inv"), RAD_I32, { P });
|
||||
b_pos = decl_b(b, nm.f("v.pos"), RAD_I32, { 2, P });
|
||||
b_cuw = decl_b(b, nm.f("v.cuw"), RAD_I32, { P + 1 });
|
||||
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mm * width });
|
||||
b_m1 = decl_b(b, nm.f("v.m1"), RAD_BF16, { R, proj_ff });
|
||||
b_m2 = decl_b(b, nm.f("v.m2"), RAD_BF16, { R, proj_ff });
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
|
||||
if (!b_x || !b_h || !b_p || !b_qkv || !b_att || !b_ff || !b_idx || !b_inv || !b_pos || !b_cuw ||
|
||||
!b_mh || !b_m1 || !b_m2 || !b_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
|
||||
rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto lnorm = [&](int64_t rows, int64_t n, double e, rad_weight w, rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", e),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto attn_op = [&](int64_t max_seg) -> rad_op {
|
||||
return RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
|
||||
RAD_INT("max_seqlen", max_seg)),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
|
||||
/* The stem is bias-less (the reference's patch_embedding states no bias). */
|
||||
op_patch = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
|
||||
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_patch)),
|
||||
{}, { b_x });
|
||||
op_pos = rw(b, RAD_OP(b, "grid_embed_pad",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_pos)),
|
||||
{ b_x }, { b_x });
|
||||
op_lpre = rw(b, lnorm(P, width, eps, lw_pre, lb_pre), { b_x }, { b_h });
|
||||
op_wo = rw(b, RAD_OP(b, "window_order",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("window", side)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_idx, b_inv, b_pos, b_cuw });
|
||||
op_gidx = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_h, b_idx }, { b_p });
|
||||
for (Layer& l : L) {
|
||||
l.ln1 = rw(b, lnorm(P, width, 1e-5, l.n1w, l.n1b), { b_p }, { b_h });
|
||||
l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
|
||||
l.rope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
|
||||
RAD_F64("theta", theta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", "axial"),
|
||||
RAD_INT("rotary_dim", head_dim),
|
||||
RAD_STR("sections", sec)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_qkv, b_pos }, { b_qkv });
|
||||
/* A window layer's segment bounds are the order op's per-window cu; a full layer's are
|
||||
* the pass's frame bounds, raw (the permutation is within frames, so they read the same
|
||||
* values in permuted order). */
|
||||
l.attn = rw(b, attn_op(l.max_seg),
|
||||
l.full ? std::initializer_list<rad_buf>{ b_qkv }
|
||||
: std::initializer_list<rad_buf>{ b_qkv, b_cuw },
|
||||
{ b_att });
|
||||
l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_p }, { b_p });
|
||||
l.ln2 = rw(b, lnorm(P, width, 1e-5, l.n2w, l.n2b), { b_p }, { b_h });
|
||||
l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff });
|
||||
l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_p }, { b_p });
|
||||
}
|
||||
op_ginv = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_p, b_inv }, { b_x });
|
||||
op_lpost = rw(b, lnorm(P, width, eps, lw_post, lb_post), { b_x }, { b_x });
|
||||
/* The reference's pixel_shuffle: each 2x2 block's four patches fold into one row with the
|
||||
* channels interleaved (block, channel, sub-patch), which is `pixtral_merge`'s layout. A view
|
||||
* over four consecutive rows cannot produce it: the concatenated form is a different tensor. */
|
||||
op_merge = rw(b, RAD_OP(b, "pixtral_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("merge", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_x }, { b_mh });
|
||||
/* The adapter: both linears bias-less, gelu between and after (the reference's
|
||||
* act(fc2(act(fc1(x))))). */
|
||||
op_m1 = rw(b, gemm(R, proj_ff, mm * width, w_a1), { b_mh }, { b_m1 });
|
||||
op_g1 = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_m1 }, { b_m2 });
|
||||
op_m2 = rw(b, gemm(R, proj_ff, proj_ff, w_a2), { b_m2 }, { b_m1 });
|
||||
op_g2 = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_m1 }, { b_m2 });
|
||||
op_proj = rw(b, gemm(R, n_embd, proj_ff, w_proj), { b_m2 }, { b_out });
|
||||
/* perception_emb_norm: MuseGlimmerRMSNorm(eps = the TEXT model's rms_norm_eps, with_scale
|
||||
* False) -- no gain operand, no centered 1+. */
|
||||
op_perc = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
|
||||
RAD_F64("eps", m->rms_eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_out }, { b_out });
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = mm;
|
||||
e.max_patches = ctx->max_enc_patches;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
int64_t nfull = 0;
|
||||
for (int64_t l = 0; l < depth; ++l) nfull += full[(size_t)l];
|
||||
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x "
|
||||
"%lld x %lld, merge %lld, windows of %lld patches (%lld full attention); "
|
||||
"%lld patches a pass -> %lld rows of %lld",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
|
||||
(long long)ff, (long long)temporal, (long long)patch, (long long)patch,
|
||||
(long long)merge, (long long)side, (long long)nfull, (long long)P, (long long)R,
|
||||
(long long)n_embd);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Stage taps, the same protocol as rad_block_sam.h's: RADIANCE_DEBUG_MM_BUFFERS names stages
|
||||
* (comma separated, matched as substrings) and RADIANCE_DEBUG_MM_DUMP's directory receives
|
||||
* tap.<tag>.bf16 -- raw bf16 rows, one file a stage. The copy is issued on the pass's stream
|
||||
* behind the producing op and synced, so it reads that op's output rather than whatever writes
|
||||
* the buffer later (the after-pass dump in core/engine_mm.cpp cannot see intermediates). */
|
||||
inline void muse_tap(RadCtx* c, const char* tag, rad_buf b, int64_t rows, int64_t cols) {
|
||||
static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP");
|
||||
static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
|
||||
if (!dir || !*dir || !env || !*env || rows <= 0 || cols <= 0 || rad_rank(c) != 0) return;
|
||||
bool want = false;
|
||||
const size_t tl = std::strlen(tag);
|
||||
for (const char* s = env; *s && !want;) {
|
||||
const char* e = s;
|
||||
while (*e && *e != ',') ++e;
|
||||
const size_t l = (size_t)(e - s);
|
||||
for (size_t i = 0; l && i + l <= tl && !want; ++i)
|
||||
want = std::strncmp(tag + i, s, l) == 0;
|
||||
s = *e ? e + 1 : e;
|
||||
}
|
||||
if (!want) return;
|
||||
void* p = rad_buf_ptr(c, b);
|
||||
if (!p) return;
|
||||
std::vector<uint16_t> h((size_t)(rows * cols));
|
||||
if (rad_memcpy_async(h.data(), p, (size_t)(rows * cols * 2), rad_stream(c)) < 0) return;
|
||||
rad_stream_sync(rad_stream(c));
|
||||
char path[512];
|
||||
std::snprintf(path, sizeof path, "%s/tap.%s.bf16", dir, tag);
|
||||
if (FILE* f = std::fopen(path, "wb")) {
|
||||
std::fwrite(h.data(), sizeof(uint16_t), h.size(), f);
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
inline void MuseTower::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
const int64_t mm = merge * merge, Rn = Pn / mm;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0 || !batch->enc_coord || !batch->enc_cu ||
|
||||
!batch->enc_seg_h || !batch->enc_seg_w || !batch->enc_pixels) {
|
||||
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or "
|
||||
"more patches than it was declared for, or not whole merged rows");
|
||||
return;
|
||||
}
|
||||
/* Windows per frame, from the pass's host grids: the window layers' cu is the per-window
|
||||
* boundaries among permuted rows, `n_win + 1` entries of the order op's output. */
|
||||
int64_t n_win = 0;
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
n_win += (batch->enc_seg_h[s] + side - 1) / side * ((batch->enc_seg_w[s] + side - 1) / side);
|
||||
if (n_win > P) {
|
||||
rad_step_fail(c, "an encoder pass whose window count exceeds the tower's declared rows");
|
||||
return;
|
||||
}
|
||||
/* Patches, coordinates (planes 0-3: row, column, segment height, segment width, in patches)
|
||||
* and the frame boundaries, staged by the core. The full layers read the frame boundaries
|
||||
* unchanged: the window permutation is within frames, so the boundaries among permuted rows
|
||||
* are these values (the reference passes its cu_seqlens the same way). */
|
||||
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
|
||||
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
RadOperand cuw = RAD_B(b_cuw);
|
||||
cuw.rows = n_win + 1;
|
||||
RadOperand pos = RAD_B(b_pos);
|
||||
pos.rows = 2;
|
||||
pos.cols = Pn;
|
||||
|
||||
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
|
||||
muse_tap(c, "v.patchpos", b_x, Pn, width);
|
||||
RAD_ISSUE_N(c, op_lpre, Pn, brows(b_x, Pn), RAD_W(lw_pre), RAD_W(lb_pre), brows(b_h, Pn));
|
||||
muse_tap(c, "v.lnpre", b_h, Pn, width);
|
||||
RAD_ISSUE_N(c, op_wo, Pn, crd, cu, brows(b_idx, Pn), brows(b_inv, Pn), pos, cuw);
|
||||
RAD_ISSUE_N(c, op_gidx, Pn, brows(b_h, Pn), brows(b_idx, Pn), brows(b_p, Pn));
|
||||
for (size_t li = 0; li < L.size(); ++li) {
|
||||
const Layer& l = L[li];
|
||||
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_p, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
|
||||
brows(b_qkv, Pn));
|
||||
RAD_ISSUE_N(c, l.rope, Pn, brows(b_qkv, Pn), pos);
|
||||
RAD_ISSUE_N(c, l.attn, Pn,
|
||||
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn),
|
||||
l.full ? cu : cuw, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
|
||||
brows(b_p, Pn), brows(b_p, Pn));
|
||||
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_p, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
|
||||
brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
|
||||
brows(b_p, Pn), brows(b_p, Pn));
|
||||
if (li == 0) muse_tap(c, "v.blk0", b_p, Pn, width);
|
||||
if (li + 1 == L.size()) muse_tap(c, "v.blkL", b_p, Pn, width);
|
||||
}
|
||||
RAD_ISSUE_N(c, op_ginv, Pn, brows(b_p, Pn), brows(b_inv, Pn), brows(b_x, Pn));
|
||||
muse_tap(c, "v.ginv", b_x, Pn, width);
|
||||
/* ln_post over the P patches, then the reference's pixel_shuffle into merged rows. */
|
||||
RAD_ISSUE_N(c, op_lpost, Pn, brows(b_x, Pn), RAD_W(lw_post), RAD_W(lb_post), brows(b_x, Pn));
|
||||
muse_tap(c, "v.lnpost", b_x, Pn, width);
|
||||
RAD_ISSUE_N(c, op_merge, Pn, brows(b_x, Pn), crd, brows(b_mh, Rn));
|
||||
muse_tap(c, "v.merge", b_mh, Rn, mm * width);
|
||||
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(w_a1), brows(b_m1, Rn));
|
||||
muse_tap(c, "v.fc1", b_m1, Rn, proj_ff);
|
||||
RAD_ISSUE_N(c, op_g1, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
|
||||
RAD_ISSUE_N(c, op_m2, Rn, brows(b_m2, Rn), RAD_W(w_a2), brows(b_m1, Rn));
|
||||
RAD_ISSUE_N(c, op_g2, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
|
||||
RAD_ISSUE_N(c, op_proj, Rn, brows(b_m2, Rn), RAD_W(w_proj), brows(b_out, Rn));
|
||||
muse_tap(c, "v.proj", b_out, Rn, n_embd);
|
||||
RAD_ISSUE_N(c, op_perc, Rn, brows(b_out, Rn), RAD_NONE, brows(b_out, Rn));
|
||||
muse_tap(c, "v.out", b_out, Rn, n_embd);
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MUSEGLIMMER_VISION_H */
|
||||
+129
-22
@@ -98,12 +98,24 @@ struct PleLayer {
|
||||
rad_weight w_table = 0, w_scale = 0, w_mult = 0, w_vsz = 0, w_off = 0;
|
||||
/* The table is plain bf16 as shipped (no scale weight) rather than E4M3. */
|
||||
bool table_bf16 = false;
|
||||
rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
|
||||
rad_weight w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
|
||||
/* The two projections of the gathered embedding, each in the encoding its container stores:
|
||||
* plain bf16 as the checkpoint ships them, or rotated int8 (or a narrower rotated form), which
|
||||
* halves the bytes a pass waits for once the rows are on the card. `a_embd` is their input and
|
||||
* `a_fed` the same planes for the second projection, whose codes the first one's quantiser
|
||||
* wrote. */
|
||||
LinearFP8 key{}, value{};
|
||||
ActFP8 a_embd{}, a_fed{};
|
||||
|
||||
rad_kvgroup kv_tok = 0, kv_conv = 0;
|
||||
rad_buf b_ids = 0, b_emb = 0, b_embd = 0, b_k = 0, b_v = 0, b_gv = 0, b_gvn = 0, b_out = 0;
|
||||
rad_op op_ids = 0, op_gather = 0, op_embd = 0, op_key = 0, op_value = 0;
|
||||
rad_op op_ids = 0, op_gather = 0, op_embd = 0;
|
||||
rad_op op_gate = 0, op_conv = 0, op_add = 0;
|
||||
/* The draft passes' hint (hint_ids, hint_fetch), where a drafter and `ngram_hint` exist: the
|
||||
* per-slot tails the hash continues from, the hinted ids (host domain, as `ple_ids`) and the
|
||||
* rows fetched for them, which nothing reads. */
|
||||
rad_buf b_tail = 0, b_hint_ids = 0, b_hint_emb = 0;
|
||||
rad_op op_hint_hist = 0, op_hint_round = 0, op_hint_gather = 0;
|
||||
|
||||
int64_t hn() const { return c.hc * g.n_embd; }
|
||||
/* The read-ahead queue's depth in steps: batch.cpp's k_ahead_chunks steps of the following
|
||||
@@ -123,6 +135,14 @@ struct PleLayer {
|
||||
/* The hash, issued at the top of the step; the rest at the layer (see ids()). */
|
||||
void ids(RadCtx* c_, const RadBatch* batch) const;
|
||||
void step(RadCtx* c_, const RadBatch* batch) const;
|
||||
/* On a draft head's pass: the ids of each sequence's newest token, first in the pass, and
|
||||
* the fetch of their rows, last in it (see hint_ids()). */
|
||||
void hint_ids(RadCtx* c_, const RadBatch* batch) const;
|
||||
void hint_fetch(RadCtx* c_, const RadBatch* batch) const;
|
||||
bool hints(const RadBatch* batch) const {
|
||||
return op_hint_gather != 0 &&
|
||||
(batch->draft_pass > 1 || (batch->draft_pass < 0 && batch->n_draft_out > 0));
|
||||
}
|
||||
};
|
||||
|
||||
inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg,
|
||||
@@ -178,7 +198,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
/* E4M3 with one scale for all 320 million rows (Qwen3.8-Flash-Next-FP8's choice; E4M3 has its
|
||||
* own exponent, a row's dynamic range is 2.3x, and the scale sits on a three-octave plateau).
|
||||
* One stored weight, `fp8_e4m3*bf16[*x*]`: codes plus a one-element scale plane, made by the
|
||||
* recipe (data/recipes/qwen4exp-w4.recipe) or read as that release ships it (its shards under
|
||||
* recipe (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe) or read as that release ships it (its shards under
|
||||
* one `weight_scale`); the gather takes them as two operands. The name map
|
||||
* joins the shards along rows and is declared first, since the encoding is looked up through
|
||||
* it. RAD_ACCESS_VOCAB: it is a vocabulary table, just not the token one. */
|
||||
@@ -212,13 +232,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* ---- the projections and the three gains ------------------------------------------------ */
|
||||
/* bf16: the FP8 checkpoint's `modules_to_not_convert` names both projections. */
|
||||
/* bf16 as shipped (the FP8 checkpoint's `modules_to_not_convert` names both projections); a
|
||||
* recipe may store them rotated int8. The name maps come first: the encodings, looked up
|
||||
* through them, say whether the input needs its int8 pair. They are declared below, with the
|
||||
* buffers they read and write. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_key.weight", layer), src.key_proj));
|
||||
w_key = decl_w(b, nm.f("blk.%d.ple_key.weight", layer), RAD_BF16, {HN, c.embed_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_value.weight", layer), src.value_proj));
|
||||
w_value = decl_w(b, nm.f("blk.%d.ple_value.weight", layer), RAD_BF16,
|
||||
{g.n_embd, c.embed_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_key.weight", layer), src.norm_key));
|
||||
w_nk = decl_w(b, nm.f("blk.%d.ple_norm_key.weight", layer), RAD_F32, {HN},
|
||||
@@ -236,7 +255,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
w_conv = decl_w(b, nm.f("blk.%d.ple_conv.weight", layer), RAD_BF16, {HN, c.conv_width},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off || !w_key || !w_value ||
|
||||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off ||
|
||||
!w_nk || !w_nq || !w_nc || !w_conv) return RAD_E_INVAL;
|
||||
|
||||
/* ---- the two rolling windows ------------------------------------------------------------ */
|
||||
@@ -337,22 +356,83 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
{b_ids}, {b_emb});
|
||||
}
|
||||
|
||||
/* ---- the draft passes' hint. A verify step's rows are the token the last verify chose and
|
||||
* the drafter's proposals, each known a draft pass or more before the verify hashes it,
|
||||
* except the last. Each draft pass hashes its sequences' newest token (`ngram_hint`) and
|
||||
* gathers those rows through the same row source, which for a table on a drive reads them
|
||||
* into its row cache; the verify step's gather then waits for the last proposal's rows
|
||||
* only. All three ops or none: without a drafter, or where no library hashes the hint,
|
||||
* nothing is declared and the verify step reads every row itself, as before. */
|
||||
if (g.max_spec > 0 && rad_op_declared(b, "ngram_hint")) {
|
||||
const int64_t ctx = c.ngram - 1;
|
||||
b_tail = decl_b(b, nm.f("ple_hint_tail"), RAD_I32, {g.max_seqs, 2 * ctx}, RAD_BUF_PERSIST);
|
||||
RadBufDecl hi{};
|
||||
hi.dtype = RAD_I32; hi.rank = 2;
|
||||
hi.shape[0] = g.max_seqs; hi.shape[1] = c.heads;
|
||||
hi.kind = RAD_BUF_PERSIST; hi.domain = RAD_DOMAIN_HOST;
|
||||
b_hint_ids = rad_decl_buffer(b, nm.f("ple_hint_ids"), &hi);
|
||||
/* PERSIST although nothing reads it: a transient's bytes are shared by declared op
|
||||
* order, and the fetch runs on the host while the draft pass's other buffers are live. */
|
||||
RadBufDecl he{};
|
||||
he.dtype = g.act_dtype; he.rank = 2;
|
||||
he.shape[0] = g.max_seqs; he.shape[1] = c.embed_dim;
|
||||
he.kind = RAD_BUF_PERSIST; he.domain = RAD_DOMAIN_HOST;
|
||||
b_hint_emb = rad_decl_buffer(b, nm.f("ple_hint_emb"), &he);
|
||||
if (!b_tail || !b_hint_ids || !b_hint_emb) return RAD_E_INVAL;
|
||||
for (const int hist : { 1, 0 })
|
||||
(hist ? op_hint_hist : op_hint_round) =
|
||||
rw(b, RAD_OP(b, "ngram_hint",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("heads", c.heads),
|
||||
RAD_INT("ngram", c.ngram), RAD_INT("eos", c.eos),
|
||||
RAD_INT("hist", hist)),
|
||||
RAD_WEIGHTS(w_mult, w_vsz, w_off)),
|
||||
{b_tail}, {b_tail, b_hint_ids});
|
||||
const rad_weight wt[2] = { w_table, w_scale };
|
||||
op_hint_gather = rw(b, RAD_OP(b, "embed_lookup_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs * c.heads),
|
||||
RAD_INT("n_embd", HD), RAD_INT("n_vocab", c.rows),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
wt, table_bf16 ? 1 : 2),
|
||||
{b_hint_ids}, {b_hint_emb});
|
||||
if (!op_hint_hist || !op_hint_round || !op_hint_gather)
|
||||
op_hint_hist = op_hint_round = op_hint_gather = 0;
|
||||
}
|
||||
|
||||
op_embd = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_emb}, {b_embd});
|
||||
|
||||
op_key = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", HN),
|
||||
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_key)),
|
||||
{b_embd}, {b_k});
|
||||
op_value = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_value)),
|
||||
{b_embd}, {b_v});
|
||||
/* The projections. An int8 one reads the embedding's int8 codes at its own scale group; the
|
||||
* first such quantises the bf16 plane and a second reads those codes, so two int8 projections
|
||||
* must agree in rotation and group (LinearFP8 refuses the pair otherwise). */
|
||||
{
|
||||
const char* kb = nm.f("blk.%d.ple_key", layer);
|
||||
const char* vb = nm.f("blk.%d.ple_value", layer);
|
||||
RadEncoding ke{}, ve{};
|
||||
const bool kk = weight_enc(b, nm.f("%s.weight", kb), &ke);
|
||||
const bool vk = weight_enc(b, nm.f("%s.weight", vb), &ve);
|
||||
const bool k8 = !g.w_bf16 && kk && (linear_is_w8(ke) || linear_is_w8h(ke));
|
||||
const bool v8 = !g.w_bf16 && vk && (linear_is_w8(ve) || linear_is_w8h(ve));
|
||||
a_embd.x = b_embd;
|
||||
if (k8 || v8)
|
||||
RAD_ARCH_TRY(a_embd.declare_qs(b, nm, g, "ple_emb_dev", c.embed_dim, 0, true, false,
|
||||
linear_w8h_group(k8 ? ke : ve)));
|
||||
a_fed = a_embd;
|
||||
if (k8 && v8) {
|
||||
a_fed.q8_fed = true;
|
||||
a_fed.q8_rot = linear_is_w8h(ke);
|
||||
}
|
||||
key.mapped = value.mapped = true;
|
||||
/* Anything but an int8 form is the plain bf16 GEMM, in a quantised model too. */
|
||||
Geom gb = g;
|
||||
gb.w_bf16 = true;
|
||||
RAD_ARCH_TRY(key.declare(b, nm, k8 ? g : gb, kb, HN, c.embed_dim, RAD_SHARD_NONE,
|
||||
grp_model(), { src.key_proj }, a_embd, b_k));
|
||||
RAD_ARCH_TRY(value.declare(b, nm, v8 ? g : gb, vb, g.n_embd, c.embed_dim, RAD_SHARD_NONE,
|
||||
grp_model(), { src.value_proj }, a_fed, b_v));
|
||||
}
|
||||
|
||||
/* `q` is the incoming stream, un-normed; the op applies all three norms because the third is
|
||||
* over bytes it writes. */
|
||||
@@ -378,7 +458,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h, b_out}, {w.h});
|
||||
|
||||
if (!op_ids || !op_gather || !op_embd || !op_key || !op_value || !op_gate || !op_conv ||
|
||||
if (!op_ids || !op_gather || !op_embd || !key.op || !value.op || !op_gate || !op_conv ||
|
||||
!op_add)
|
||||
return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
@@ -433,6 +513,33 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* The hint of a draft head's pass. The history pass ends at the token the verify chose and each
|
||||
* later round reads the proposal before it (RadBatch::draft_pass), so the pass's newest token per
|
||||
* sequence is one the next verify step runs. hint_ids() hashes it first in the pass, so the ids
|
||||
* are in host memory as the pass starts; hint_fetch() goes last, where the host has issued the
|
||||
* whole pass and only waits for that one kernel, and the rows it reads arrive while the card
|
||||
* drafts. A history pass that drafts nothing gets neither. */
|
||||
inline void PleLayer::hint_ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
if (!hints(batch)) return;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadKVGroupBatch* tk = kv_batch(batch, kv_tok);
|
||||
const int32_t* tk_idx = tk ? tk->state_index : nullptr;
|
||||
RAD_ISSUE_N(c_, batch->draft_pass < 0 ? op_hint_hist : op_hint_round, S,
|
||||
praw(batch->token_ids, RAD_I32, T), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
|
||||
tk_idx ? praw(tk_idx, RAD_I32, S) : RAD_NONE,
|
||||
RAD_B(b_tail), brows(b_hint_ids, S));
|
||||
}
|
||||
|
||||
inline void PleLayer::hint_fetch(RadCtx* c_, const RadBatch* batch) const {
|
||||
if (!hints(batch)) return;
|
||||
const int64_t S = batch->n_seq;
|
||||
RAD_ISSUE_N(c_, op_hint_gather, S * c.heads,
|
||||
brows(b_hint_ids, S), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
|
||||
brows(b_hint_emb, S), RAD_NONE);
|
||||
}
|
||||
|
||||
inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
@@ -454,8 +561,8 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
|
||||
RAD_ISSUE_N(c_, op_embd, T, brows(b_emb, T), brows(b_embd, T));
|
||||
RAD_ISSUE_N(c_, op_key, T, brows(b_embd, T), RAD_W(w_key), brows(b_k, T));
|
||||
RAD_ISSUE_N(c_, op_value, T, brows(b_embd, T), RAD_W(w_value), brows(b_v, T));
|
||||
key.step(c_, a_embd, b_k, T, 0, T);
|
||||
value.step(c_, a_fed, b_v, T, 0, T);
|
||||
|
||||
RAD_ISSUE_N(c_, op_gate, T,
|
||||
brows(b_k, T), brows(w.h, T), brows(b_v, T),
|
||||
|
||||
+214
-39
@@ -48,6 +48,9 @@ namespace arch {
|
||||
/* The scale block in both dimensions, fixed by the checkpoint (`weight_block_size`). libr4d
|
||||
* compiles it in and its rows carry C_EQ("group", 128), so other widths resolve to no kernel. */
|
||||
enum { RAD_FP8_BLOCK = 128 };
|
||||
/* IQ8R's scale group: an int8 weight rotated 128 wide with one bf16 scale per row per 256 of K,
|
||||
* met by an int8 activation with one f32 scale per (token, 256). */
|
||||
enum { RAD_I8_GROUP_WIDE = 256 };
|
||||
|
||||
/* Rows of the scale plane for an N-row weight, and columns for a K-wide one. */
|
||||
inline int64_t fp8_blocks(int64_t n) { return (n + RAD_FP8_BLOCK - 1) / RAD_FP8_BLOCK; }
|
||||
@@ -63,6 +66,9 @@ struct ActFP8 {
|
||||
* by the linear's own quant_act_i8g from `x`, or by the producer when `q8_fed`. */
|
||||
rad_buf q8 = 0;
|
||||
rad_buf s8 = 0;
|
||||
/* The int8 pair's scale group: RAD_FP8_BLOCK, or RAD_I8_GROUP_WIDE for an IQ8R trunk, whose
|
||||
* producers and quantisers write one scale per (row, 256). s8 has ceil(n / g8) columns. */
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
/* The producer writes q8/s8 instead of the E4M3 pair (a connection read with
|
||||
* HyperConn::Config::codes_i8, a gated quantiser, the attention gate or delta-net output
|
||||
* epilogue), so an int8 linear reading it declares no quantiser. Set by the model when it
|
||||
@@ -76,6 +82,8 @@ struct ActFP8 {
|
||||
/* The code pair the producer writes: int8 when the model fed it, E4M3 otherwise. */
|
||||
rad_buf cq() const { return q8_fed ? q8 : q; }
|
||||
rad_buf cs() const { return q8_fed ? s8 : s; }
|
||||
/* The scale group of cs(). */
|
||||
int64_t cg() const { return q8_fed ? g8 : (int64_t)RAD_FP8_BLOCK; }
|
||||
|
||||
/* Declares the codes: the E4M3 pair with `fp8_pair`, the int8 pair with `i8` (an int8 model's
|
||||
* activations need no E4M3 plane taking arena); `x` is set by the caller.
|
||||
@@ -84,7 +92,9 @@ struct ActFP8 {
|
||||
* (a MoE expert plane is `rows * top_k`, an encoder tower's its patch count); too small a value
|
||||
* overruns the arena (core/runtime/issue.cpp refuses such an issue). */
|
||||
int declare_qs(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
|
||||
int64_t rows = 0, bool i8 = false, bool fp8_pair = true) {
|
||||
int64_t rows = 0, bool i8 = false, bool fp8_pair = true,
|
||||
int64_t i8_group = RAD_FP8_BLOCK) {
|
||||
g8 = i8_group;
|
||||
/* bf16 linears read only `x` (Geom::w_bf16), so declare no codes; an unused plane would
|
||||
* still take arena space. */
|
||||
if (g.w_bf16) { q = s = q8 = s8 = 0; return RAD_OK; }
|
||||
@@ -96,11 +106,30 @@ struct ActFP8 {
|
||||
}
|
||||
if (i8) {
|
||||
q8 = decl_b(b, nm.f("%s.q8", name), RAD_I8, { m, n });
|
||||
s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, fp8_blocks(n) });
|
||||
s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, (n + g8 - 1) / g8 });
|
||||
if (!q8 || !s8) return RAD_E_INVAL;
|
||||
}
|
||||
return (fp8_pair || i8) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The code pair of a model that learned from a probe whether its linears are rotated int8
|
||||
* (`i8`, at `i8_group` columns a scale): declare_qs's E4M3 pair for a block-fp8 model, and for
|
||||
* an int8 one int8 codes. Those are written by the producer's own rotating quantiser `fed_op`
|
||||
* (had_quant_act_i8g, or gated_had_quant_i8g behind a gated product) where the kernels serve
|
||||
* it, and the linears reading them declare none; where they do not (the CPU kernels) the
|
||||
* producer keeps its E4M3 pair and each linear quantises its own input from the bf16 plane.
|
||||
* `x` is set by the caller. */
|
||||
int declare_pair(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
|
||||
int64_t rows, bool i8, int64_t i8_group, const char* fed_op) {
|
||||
if (i8 && (i8_group <= 0 || n % i8_group)) {
|
||||
fprintf(stderr, "radiance: the int8 linears keep one scale a %lld of K, which does not "
|
||||
"divide this rank's %lld-wide '%s'\n",
|
||||
(long long)i8_group, (long long)n, name);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (i8 && rad_op_declared(b, fed_op)) q8_fed = q8_rot = true;
|
||||
return declare_qs(b, nm, g, name, n, rows, i8, !q8_fed, i8 ? i8_group : RAD_FP8_BLOCK);
|
||||
}
|
||||
};
|
||||
|
||||
/* The fused attention prologue's row band, shared by the block issuing it, the rope table fill,
|
||||
@@ -145,7 +174,7 @@ inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, in
|
||||
* are rotated (ActFP8::q8_rot). */
|
||||
op = rw(b, RAD_OP(b, a.q8_fed ? (a.q8_rot ? "had_quant_act_i8g" : "quant_act_i8g") : "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a.x }, { a.cq(), a.cs() });
|
||||
return RAD_OK;
|
||||
@@ -155,7 +184,7 @@ inline void QuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const
|
||||
if (!op) return;
|
||||
if (rows <= 0) rows = T - r0;
|
||||
RAD_ISSUE(c, op, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n),
|
||||
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()));
|
||||
}
|
||||
|
||||
/* ================================== the quantiser folded into the op that produces the row
|
||||
@@ -466,7 +495,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
|
||||
op = RAD_OP(b, hi8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
|
||||
RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(w));
|
||||
if (!op) return RAD_E_INVAL;
|
||||
@@ -489,7 +518,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
|
||||
op_arn = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
|
||||
RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("group", a.cg()),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(w));
|
||||
@@ -504,7 +533,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
|
||||
op_arn6 = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
|
||||
RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("group", a.cg()),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd),
|
||||
RAD_INT("wire", 6)),
|
||||
@@ -549,7 +578,7 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
|
||||
RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n),
|
||||
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
|
||||
brow_slice(hi8 ? a.q8 : a.q, r0, rows, n),
|
||||
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / RAD_FP8_BLOCK),
|
||||
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / (hi8 ? a.g8 : (int64_t)RAD_FP8_BLOCK)),
|
||||
brow_slice(a.x, r0, rows, n));
|
||||
}
|
||||
|
||||
@@ -637,11 +666,14 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
|
||||
return op_q ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (clipped) {
|
||||
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated; and no clamp
|
||||
* with `silu_only`. */
|
||||
if (!gate_up || !a.x || n <= 0 || rot || silu_only || (a.q8_fed && a.q8_rot) ||
|
||||
std::strcmp(act_name, "silu"))
|
||||
/* The clamp writes the bf16 plane and a quantiser reads it: E4M3, plain int8, or the
|
||||
* rotated int8 codes an i8a8h consumer reads (had_quant_act_i8g at that consumer's
|
||||
* group, the quantiser the rotated trunk's other inputs use). Against the unclamped
|
||||
* gated_had_quant_i8g that is one launch more, in the clamped layers only. No clamp
|
||||
* with `silu_only`, and none into a rotated E4M3 consumer (`rot`). */
|
||||
if (!gate_up || !a.x || n <= 0 || rot || silu_only || std::strcmp(act_name, "silu"))
|
||||
return RAD_E_INVAL;
|
||||
const bool hi8 = a.q8_fed && a.q8_rot;
|
||||
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
|
||||
if (fuse_clamped && !step && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
|
||||
rad_op_declared(b, "swiglu_clamped_quant_fp8")) {
|
||||
@@ -667,11 +699,13 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
|
||||
{ gate_up }, { a.x });
|
||||
if (!bf16) {
|
||||
if (!a.cq() || !a.cs()) return RAD_E_INVAL;
|
||||
const char* qn = hi8 ? "had_quant_act_i8g" : a.q8_fed ? "quant_act_i8g"
|
||||
: "quant_act_fp8";
|
||||
op_quant =
|
||||
rw(b,
|
||||
RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
|
||||
RAD_OP(b, qn,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a.x }, { a.cq(), a.cs() });
|
||||
if (!op_quant) return RAD_E_INVAL;
|
||||
@@ -703,7 +737,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
|
||||
if (!rot || rad_op_declared(b, "gated_had_quant_fp8"))
|
||||
op = RAD_OP(b, gq,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype),
|
||||
RAD_STR("act", act_name)),
|
||||
RAD_NOWEIGHTS);
|
||||
/* The rotated op's chain, which writes the bf16 plane whether or not a consumer asked. */
|
||||
@@ -742,7 +776,7 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
|
||||
if (clamped_fused) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
|
||||
brow_slice(a.cq(), r0, rows, n),
|
||||
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK),
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()),
|
||||
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
|
||||
return;
|
||||
}
|
||||
@@ -752,7 +786,7 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
|
||||
if (op_quant)
|
||||
RAD_ISSUE_N(c, op_quant, rows, brow_slice(a.x, r0, rows, n),
|
||||
brow_slice(a.cq(), r0, rows, n),
|
||||
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()));
|
||||
return;
|
||||
}
|
||||
if (bf16 || op_q) {
|
||||
@@ -760,12 +794,12 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
|
||||
if (op_q)
|
||||
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, n),
|
||||
brow_slice(a.cq(), r0, rows, n),
|
||||
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
|
||||
brow_slice(a.cq(), r0, rows, n),
|
||||
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK),
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()),
|
||||
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
|
||||
}
|
||||
|
||||
@@ -865,6 +899,9 @@ struct LinearFP8 {
|
||||
/* probe() found an int8 weight; lets a model learn its trunk's format from one linear before
|
||||
* declaring activation buffers (ActFP8::declare_qs's `i8`). */
|
||||
bool probed_i8 = false;
|
||||
/* With probed_i8: the weight's scale group along K (linear_w8h_group), which the model's int8
|
||||
* activation pairs must share (ActFP8::g8). */
|
||||
int64_t probed_g8 = RAD_FP8_BLOCK;
|
||||
/* Whether this linear's block-fp8 GEMM takes the short-prompt split rule
|
||||
* (`gemm_nt_q_short`, narrow_ksplit's `short_unsplit`): at N <= 512, K <= 5120 and 41..64 rows
|
||||
* the split's per-slice floors dominate, so the row runs unsplit. Opt-in, so every other
|
||||
@@ -1022,7 +1059,26 @@ inline bool linear_w8h_scale2(const RadEncoding& e) {
|
||||
s2->kind == RAD_PLANE_TILED && (s2->dtype == RAD_F32 || s2->dtype == RAD_BF16) &&
|
||||
(s2->block[0] == 0 || s2->block[0] == 1) && s2->block[1] == 0;
|
||||
}
|
||||
/* IQ8R: int8 codes rotated 128 wide with a u8 scale per [1 x 256] under one bf16 scale a row
|
||||
* (libquant `codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128`), served as the
|
||||
* I8 form at twice the scale group. */
|
||||
inline bool linear_is_iq8r(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "affine") || e.n_planes != 3 ||
|
||||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
|
||||
return false;
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
const RadEncPlane* s2 = rad_enc_plane(&e, "scale.1");
|
||||
return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_U8 &&
|
||||
sc->kind == RAD_PLANE_TILED && sc->block[0] == 1 && sc->block[1] == RAD_I8_GROUP_WIDE &&
|
||||
s2 && s2->dtype == RAD_BF16 && s2->kind == RAD_PLANE_TILED && s2->block[0] == 1 &&
|
||||
s2->block[1] == 0;
|
||||
}
|
||||
/* The scale group along K of a weight served at i8a8 / i8a8h. */
|
||||
inline int64_t linear_w8h_group(const RadEncoding& e) {
|
||||
return linear_is_iq8r(e) ? (int64_t)RAD_I8_GROUP_WIDE : (int64_t)RAD_FP8_BLOCK;
|
||||
}
|
||||
inline W8hForm linear_w8h_form(const RadEncoding& e) {
|
||||
if (linear_is_iq8r(e)) return W8hForm::I8;
|
||||
const bool trellis = rad_enc_is(&e, "trellis");
|
||||
if ((!rad_enc_is(&e, "affine") && !trellis) ||
|
||||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
|
||||
@@ -1087,6 +1143,17 @@ inline bool linear_is_wnh(const RadEncoding& e) {
|
||||
zp->block[1] == RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
/* Whether a trunk whose first linear probed as `e` is rotated int8 -- w8h or wnh -- and if so
|
||||
* how wide its activation codes' scale group is: 256 for IQ8R, 128 for the other rotated forms
|
||||
* (linear_w8h_group spells the rule). An arch learns this by probing layer 0's q projection
|
||||
* before declaring activations; the probe and the fields are the arch's, the question belongs
|
||||
* beside the predicates it is made of. */
|
||||
inline bool trunk_rotation(const RadEncoding& e, int64_t* g8) {
|
||||
if (!linear_is_w8h(e) && !linear_is_wnh(e)) return false;
|
||||
*g8 = linear_w8h_group(e);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes and an E8M0 exponent per [1 x 32],
|
||||
* no transform (libr4d's MXFP4 layout hook). */
|
||||
enum { RAD_MX_GROUP = 32 };
|
||||
@@ -1145,6 +1212,32 @@ inline bool linear_is_paro_m2xfp4(const RadEncoding& e) {
|
||||
mt->block[1] == RAD_MX_GROUP;
|
||||
}
|
||||
|
||||
/* The weight formats rad-convert reads and the engine does not serve: block fp8 (E4M3
|
||||
* codes under a scale per 128 x 128), OCP MXFP4, M2XFP4 and the ParoQuant-rotated forms of the
|
||||
* last two. The format's name, or nullptr for one that is served. */
|
||||
inline const char* linear_retired(const RadEncoding& e) {
|
||||
if (linear_is_paro_m2xfp4(e)) return "ParoQuant M2XFP4";
|
||||
if (linear_is_paro_mxfp4(e)) return "ParoQuant MXFP4";
|
||||
if (linear_is_givens(e)) return "ParoQuant";
|
||||
if (linear_is_m2xfp4(e)) return "M2XFP4";
|
||||
if (linear_is_mxfp4(e)) return "MXFP4";
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
if (rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
|
||||
e.plane[0].dtype == RAD_F8E4M3 && sc && (sc->dtype == RAD_BF16 || sc->dtype == RAD_F32) &&
|
||||
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK)
|
||||
return "block fp8";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* The refusal of a weight stored in one of them, by name, with what serves the model instead. */
|
||||
inline int linear_refuse_retired(const char* weight, const char* format) {
|
||||
fprintf(stderr, "radiance: '%s' is stored as %s, which this build does not serve. Convert "
|
||||
"the checkpoint again with an int8 recipe (the IQ8R ones in data/recipes); if "
|
||||
"the weight belongs to the container's drafter, `num-speculative-tokens: 0` "
|
||||
"serves the model without it\n", weight, format);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* A 4-bit weight with a zero point and no transform: u4 codes, an f16 scale and a u4 or u8 zero
|
||||
* point per 128 of K (libquant `codes=u4 zero=u4 group=128 scale=f16`, or rad-convert's import rule
|
||||
* over an int4 release). At decode w4a16_asym narrows the BF16 input to F16 on load; larger
|
||||
@@ -1179,6 +1272,7 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
|
||||
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16;
|
||||
probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
probed_g8 = known ? linear_w8h_group(enc) : (int64_t)RAD_FP8_BLOCK;
|
||||
/* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or
|
||||
* quantises it. */
|
||||
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc) ||
|
||||
@@ -1302,6 +1396,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
const bool known = weight_enc(b, sw, &enc);
|
||||
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16;
|
||||
if (known && !plain)
|
||||
if (const char* gone = linear_retired(enc)) return linear_refuse_retired(sw, gone);
|
||||
|
||||
/* ---- bf16 weight, `gemm_nt` over `a.x`: every linear of a bf16 model, or one a quantised
|
||||
* container keeps at checkpoint precision (e.g. the QSA indexer's projection, whose top-k is a
|
||||
@@ -1375,10 +1471,18 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
"int8)\n", wn, a.q8_fed ? "" : " or the bf16 plane it quantises");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
/* The scale group: 128, or 256 for IQ8R, which the input's int8 pair must share. */
|
||||
const int64_t wg = linear_w8h_group(enc);
|
||||
if (wg != a.g8) {
|
||||
fprintf(stderr, "radiance: '%s' has a scale per %lld columns and its input's int8 codes "
|
||||
"one per %lld; a trunk mixes IQ8R and 128-group int8 weights\n",
|
||||
wn, (long long)wg, (long long)a.g8);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % 16 || K % wg) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an int8 weight takes rows in "
|
||||
"16s and K in whole %d-column scale groups\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
"16s and K in whole %lld-column scale groups\n",
|
||||
base, (long long)N, (long long)K, (long long)wg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RowParts rp;
|
||||
@@ -1402,42 +1506,42 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
rp.w, rp.n);
|
||||
/* A view of two planes is declared at the weight's logical extents and sliced in its
|
||||
* columns, the stored planes left to the layout hook. */
|
||||
const bool two = linear_w8h_scale2(enc) || linear_w8h_rowf(enc);
|
||||
const bool iq8r = linear_is_iq8r(enc);
|
||||
const bool two = linear_w8h_scale2(enc) || linear_w8h_rowf(enc) || iq8r;
|
||||
ws = asym ? decl_view(b, sn, wn, "scale,zero", RAD_F16, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n)
|
||||
: linear_w8h_rowf(enc) ? decl_view(b, sn, wn, "scale,scale.col", RAD_F32, { N, K },
|
||||
access, shard, grp, rp.w, rp.n)
|
||||
: two ? decl_view(b, sn, wn, "scale,scale.1", RAD_F8E4M3, { N, K }, access, shard,
|
||||
grp, rp.w, rp.n)
|
||||
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, access,
|
||||
: two ? decl_view(b, sn, wn, "scale,scale.1", iq8r ? RAD_U8 : RAD_F8E4M3, { N, K },
|
||||
access, shard, grp, rp.w, rp.n)
|
||||
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / wg }, access,
|
||||
shard, grp, rp.w, rp.n);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
if (span_hi > 0) {
|
||||
/* The (scale, zero) and (scale, scale.1) views are at the logical extents, sliced as
|
||||
* the codes are. */
|
||||
const bool col = shard == RAD_SHARD_COL && !asym && !two;
|
||||
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
|
||||
if (col && (span_lo % wg || span_hi % wg)) {
|
||||
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
|
||||
"%d-column scale group\n", base, (long long)span_lo,
|
||||
(long long)span_hi, RAD_FP8_BLOCK);
|
||||
"%lld-column scale group\n", base, (long long)span_lo,
|
||||
(long long)span_hi, (long long)wg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
|
||||
if ((asym || two) && shard == RAD_SHARD_COL &&
|
||||
(span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
|
||||
if ((asym || two) && shard == RAD_SHARD_COL && (span_lo % wg || span_hi % wg)) {
|
||||
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
|
||||
"%d-column scale group\n", base, (long long)span_lo,
|
||||
(long long)span_hi, RAD_FP8_BLOCK);
|
||||
"%lld-column scale group\n", base, (long long)span_lo,
|
||||
(long long)span_hi, (long long)wg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / RAD_FP8_BLOCK : span_lo,
|
||||
col ? span_hi / RAD_FP8_BLOCK : span_hi));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / wg : span_lo,
|
||||
col ? span_hi / wg : span_hi));
|
||||
}
|
||||
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
|
||||
if (!a.q8_fed)
|
||||
op_q = rw(b, RAD_OP(b, rot8 ? "had_quant_act_i8g" : "quant_act_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("n", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
RAD_INT("group", wg), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a.x }, { a.q8, a.s8 });
|
||||
const char* qdt = asym ? (enc.plane[0].dtype == RAD_U5 ? "w5a8i8" : "w4a8i8_asym")
|
||||
@@ -1452,7 +1556,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
{ a.q8, a.s8 }, { y })
|
||||
: rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", qdt)),
|
||||
RAD_INT("group", wg), RAD_STR("dtype", qdt)),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ a.q8, a.s8 }, { y });
|
||||
return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL;
|
||||
@@ -1770,9 +1874,9 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
if (i8) {
|
||||
if (op_q)
|
||||
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, K), brow_slice(a.q8, r0, rows, K),
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK));
|
||||
brow_slice(a.s8, r0, rows, K / a.g8));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K),
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK),
|
||||
brow_slice(a.s8, r0, rows, K / a.g8),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
@@ -1846,6 +1950,17 @@ struct DenseFP8 {
|
||||
bool mx = false;
|
||||
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand. */
|
||||
bool m2x = false;
|
||||
/* Or a weight served at i8a8h (linear_w8h_form): IQ8R, the rotated int8 grid at 128, or a
|
||||
* narrower form on it (signed codes, a zero point, a codebook, a trellis), its views as
|
||||
* LinearFP8 declares them. It reads an INT8 activation pair with one scale per (row, `g8`) under
|
||||
* the same rotation (had_quant_act_i8g at that group); the block declares that pair where it
|
||||
* would the E4M3 one. `w_rb`: a trellis on a grid of several rows a scale says how many. */
|
||||
bool w8h = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
int64_t w_rb = 0;
|
||||
/* Set before declare by a block that declares the int8 activation pair such a weight reads;
|
||||
* any other block's activations are E4M3, so declare refuses the weight there. */
|
||||
bool w8h_ok = false;
|
||||
|
||||
/* `mapped`: the caller made the name map already, to ask the encoding before choosing this
|
||||
* struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */
|
||||
@@ -1900,6 +2015,19 @@ struct DenseFP8 {
|
||||
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
|
||||
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes,
|
||||
int64_t split_n = 0) const {
|
||||
if (w8h && w_rb > 0)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", g8), RAD_STR("dtype", "i8a8h"),
|
||||
RAD_INT("w_rb", w_rb)),
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
if (w8h)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", g8), RAD_STR("dtype", "i8a8h")),
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
if (mx || m2x)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
@@ -1941,6 +2069,53 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
mx = known && linear_is_mxfp4(enc);
|
||||
m2x = known && linear_is_m2xfp4(enc);
|
||||
/* Plain MXFP4 is still read here: the published IQR-V4 containers carry their DFlash2
|
||||
* drafter in it. */
|
||||
if (known && !mx)
|
||||
if (const char* gone = linear_retired(enc)) return linear_refuse_retired(wn, gone);
|
||||
const W8hForm form = known ? linear_w8h_form(enc) : W8hForm::None;
|
||||
w8h = form != W8hForm::None;
|
||||
if (w8h && !w8h_ok) {
|
||||
fprintf(stderr, "radiance: '%s' is a rotated int8 weight, which reads an int8 "
|
||||
"activation; this block quantises its activations to E4M3 and takes "
|
||||
"block fp8 or MXFP4 weights\n", base);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (w8h) {
|
||||
g8 = linear_w8h_group(enc);
|
||||
if (N % 16 || K % g8) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a rotated int8 weight takes "
|
||||
"rows in 16s and K in whole %lld-column scale groups\n",
|
||||
base, (long long)N, (long long)K, (long long)g8);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RowParts rp;
|
||||
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "int8 tiles"));
|
||||
/* The views LinearFP8's i8a8h branch declares: a narrower form's codes take the plane
|
||||
* that decodes them, and a scale of two planes is one view at the weight's logical
|
||||
* extents, which the kernel's layout combines. */
|
||||
const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis");
|
||||
w_rb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1 ? tpl->block[1] : 0;
|
||||
const char* cv = form == W8hForm::Zero ? "codes,zero"
|
||||
: form == W8hForm::Table ? "codes,table"
|
||||
: form == W8hForm::Grid ? "codes,grid"
|
||||
: form == W8hForm::Trellis ? (linear_w8h_mad(enc) ? "codes,trellis,trellis.mad"
|
||||
: "codes,trellis")
|
||||
: "codes";
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
const bool iq8r = linear_is_iq8r(enc);
|
||||
w = decl_view(b, wn, nullptr, cv, enc.plane[0].dtype, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n);
|
||||
s = linear_w8h_rowf(enc)
|
||||
? decl_view(b, sn, wn, "scale,scale.col", RAD_F32, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n)
|
||||
: (linear_w8h_scale2(enc) || iq8r)
|
||||
? decl_view(b, sn, wn, "scale,scale.1", iq8r ? RAD_U8 : RAD_F8E4M3, { N, K },
|
||||
access, shard, grp, rp.w, rp.n)
|
||||
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / g8 }, access, shard, grp,
|
||||
rp.w, rp.n);
|
||||
return w && s ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (mx || m2x) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s weight takes rows "
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/* Muse Glimmer's reply format: the ATEM channel protocol its chat template renders.
|
||||
*
|
||||
* The template's generation prompt ends at `<|start|>assistant`, so the model opens its own
|
||||
* channels: `<to=self>` reasoning first, then the answer:
|
||||
*
|
||||
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=user<|message|> ...answer...
|
||||
*
|
||||
* `reasoning_close` carries the whole channel transition, so the answer's own header is consumed
|
||||
* with the reasoning block's close and the content begins at the answer's first byte. A reply
|
||||
* that skips the reasoning opens on the answer's channel directly (`to=user<|message|> ...`);
|
||||
* `content_open` names that header so it is dropped there too.
|
||||
*
|
||||
* Tool calls are the template's ATEM dialect, emitted as their own assistant turn whose channel
|
||||
* names the tool (chat_template.jinja, render_atem):
|
||||
*
|
||||
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=NAME<|message|>
|
||||
* <atem:function_calls>
|
||||
* <atem:invoke name="NAME">
|
||||
* <atem:parameter name="k">value</atem:parameter>
|
||||
* </atem:invoke>
|
||||
* </atem:function_calls>
|
||||
*
|
||||
* String parameters are written raw, everything else as JSON (the template's `tojson`); the
|
||||
* section opener is the constrained-decoding trigger, and it is also the reasoning break: a call
|
||||
* turn's channel header names the tool rather than `user`, so the answer's `reasoning_close`
|
||||
* does not match there and the reasoning block runs to the section, swallowing the `<|eom|>` and
|
||||
* the header.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace museglimmer {
|
||||
|
||||
inline const RadChatFormat* muse_chat_format() {
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat x{};
|
||||
x.struct_size = sizeof(x);
|
||||
x.name = "plugin:museglimmer";
|
||||
x.reasoning_open = "to=self<|message|>";
|
||||
x.reasoning_close = "<|eom|><|start|>assistant to=user<|message|>";
|
||||
static const char* const kBreaks[] = {"<atem:function_calls>"};
|
||||
x.reasoning_breaks = kBreaks;
|
||||
x.n_reasoning_breaks = 1;
|
||||
/* The model opens its own channel; the prompt carries none. */
|
||||
x.reasoning_in_prompt = RAD_CHAT_THINK_NEVER;
|
||||
x.content_open = "to=user<|message|>";
|
||||
x.section_open = "<atem:function_calls>";
|
||||
x.section_close = "</atem:function_calls>";
|
||||
x.call_open = "<atem:invoke ";
|
||||
x.name_prefix = "name=\"";
|
||||
x.name_suffix = "\">";
|
||||
x.call_end = "</atem:invoke>";
|
||||
x.arg_prefix = "<atem:parameter name=\"";
|
||||
x.arg_name_suffix = "\">";
|
||||
x.arg_value_suffix = "</atem:parameter>";
|
||||
x.string_value = RAD_CHAT_VALUE_RAW; /* the template writes string arguments raw */
|
||||
x.other_value = RAD_CHAT_VALUE_JSON; /* booleans, numbers, arrays, objects as tojson */
|
||||
x.value_newlines = 1;
|
||||
/* No grammar triggers: the reference deployment (vLLM's --tool-call-parser muse) runs
|
||||
* unconstrained and parses whatever the model writes. A trigger arms the lazy tool-call
|
||||
* grammar, and with the DFlash drafter the trigger fires mid-verify -- inside drafted
|
||||
* text -- at the reasoning-to-call boundary, which spins the sampler and loops the
|
||||
* channel header (measured: drafter on = the header repeats 3-4x and the reply stalls;
|
||||
* drafter off = one header, clean call). The streaming parser reads natural ATEM as
|
||||
* it is. */
|
||||
return x;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace museglimmer */
|
||||
+80
-21
@@ -9,7 +9,8 @@
|
||||
* Contents: the projection and query path, the block-key path with its two states, and the score
|
||||
* and selection. Below `budget + ratio - 1` tokens of context every visible block is selected, so
|
||||
* the sparse path must reproduce the dense path's text byte for byte; that is the test for any
|
||||
* change here.
|
||||
* change here. A step entirely at or below that bound therefore needs no selection at all, and
|
||||
* step() issues only the block-key path for it (its `use`; docs/QSA.md, "Below the bound").
|
||||
*/
|
||||
#ifndef RAD_QSA_H
|
||||
#define RAD_QSA_H
|
||||
@@ -121,13 +122,43 @@ struct QsaIndexer {
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
|
||||
const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
|
||||
/* `win_cu`, device: {0, plane_rows}, the one sequence of a window of a step wider than the
|
||||
* score plane (Config::plane_rows); null where no step is. */
|
||||
* score plane (Config::plane_rows); null where no step is.
|
||||
*
|
||||
* `use` is what the layer's attention reads of the selection this step (QsaUse, rad_arch.h;
|
||||
* AttnGatedFP8::qsa_use): the default issues the query, the scores and the selection as every
|
||||
* step did before. `first` is whether this is the first full-attention layer the pass issues:
|
||||
* at or below the bound the selection is made there once and read by every layer after it (the
|
||||
* buffers are the model's, live across its layers, and nothing else writes them). The default
|
||||
* makes it at every layer. */
|
||||
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch,
|
||||
const int32_t* win_cu = nullptr) const;
|
||||
const int32_t* win_cu = nullptr, int use = kQsaSelect, bool first = true) const;
|
||||
/* Stores the pass's block keys and tail exactly as step() does, with no query, score or
|
||||
* selection (see AttnGatedFP8::store_kv). */
|
||||
void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
|
||||
bool store_keys(RadCtx* c, const RadBatch* batch) const;
|
||||
/* `part` 0 issues all of it; 1, 2 and 3 its three stages apart and in that order (the work
|
||||
* list, the block keys, the tail store), for a caller that issues them behind another block's
|
||||
* launches (deferrable, below). */
|
||||
bool store_keys(RadCtx* c, const RadBatch* batch, int part = 0) const;
|
||||
/* Whether this step's keys and tail may be issued behind the attention block's launches
|
||||
* instead of in front of them (SideOps, rad_arch.h): nothing reads a selection of this
|
||||
* layer's (`use` as step() resolves it), so the attention reads nothing the three ops write.
|
||||
* The caller answers for the buffers (Wire: qk, stage, page, bpos, nc excluded from
|
||||
* sharing). */
|
||||
bool deferrable(const RadBatch* batch, int use, bool first) const {
|
||||
if (!on() || qsa_eager()) return false;
|
||||
/* step() stores no keys for a batch without the attention's group; leave that to it. */
|
||||
if (!kv_batch(batch, c.kv_attn)) return false;
|
||||
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
|
||||
return use == kQsaUnread;
|
||||
}
|
||||
/* What step() issues on a deferrable step, a piece at a time: the projection, then
|
||||
* store_keys's stages 1..3. */
|
||||
void step_proj(RadCtx* c, const ActFP8& in, const RadBatch* batch) const {
|
||||
proj.step(c, in, w.qk, batch->n_tok);
|
||||
}
|
||||
void step_part(RadCtx* c, const RadBatch* batch, int part) const {
|
||||
(void)store_keys(c, batch, part);
|
||||
}
|
||||
};
|
||||
|
||||
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
@@ -267,7 +298,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
/* Stores the block keys of the blocks the pass completes and the tail of raw keys after them,
|
||||
* from the projection's raw-key head. False when the step has no batch for the indexer's
|
||||
* groups. */
|
||||
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
|
||||
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch, int part) const {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t nw = (c.heads + 1) * c.head_dim;
|
||||
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
|
||||
@@ -289,20 +320,24 @@ inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
|
||||
const bool mc = g.rope_mc && batch->rope_pos;
|
||||
RadOperand bpos = g.rope_mc ? RAD_B_COL(w.bpos, 0, mc ? 3 : 1) : brows(w.bpos, work);
|
||||
if (g.rope_mc) bpos.rows = work;
|
||||
RAD_ISSUE_N(c_, op_work, T,
|
||||
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
kv_cache(c.kv_tail, layer),
|
||||
praw2(tlb->state_index, RAD_I32, S, tw),
|
||||
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
|
||||
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
|
||||
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
|
||||
brows(w.nc, S));
|
||||
RAD_ISSUE_N(c_, op_bkey, work,
|
||||
brows(w.stage, work * c.ratio), RAD_W(w_kn),
|
||||
brows(w.page, work), bpos,
|
||||
kv_cache(kv_bk, layer));
|
||||
if (part <= 1)
|
||||
RAD_ISSUE_N(c_, op_work, T,
|
||||
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
kv_cache(c.kv_tail, layer),
|
||||
praw2(tlb->state_index, RAD_I32, S, tw),
|
||||
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
|
||||
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
|
||||
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
|
||||
brows(w.nc, S));
|
||||
if (part == 1) return true;
|
||||
if (part == 0 || part == 2)
|
||||
RAD_ISSUE_N(c_, op_bkey, work,
|
||||
brows(w.stage, work * c.ratio), RAD_W(w_kn),
|
||||
brows(w.page, work), bpos,
|
||||
kv_cache(kv_bk, layer));
|
||||
if (part == 2) return true;
|
||||
RAD_ISSUE_N(c_, op_tail, T,
|
||||
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
@@ -319,13 +354,31 @@ inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batc
|
||||
}
|
||||
|
||||
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch,
|
||||
const int32_t* win_cu) const {
|
||||
const int32_t* win_cu, int use, bool first) const {
|
||||
if (!on()) return;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t qw = c.heads * c.head_dim;
|
||||
const int64_t nw = (c.heads + 1) * c.head_dim;
|
||||
|
||||
/* What the attention reads this step (QsaUse); anything asked of a step that cannot give it is
|
||||
* the full issue, which every reader accepts.
|
||||
*
|
||||
* kQsaOnce: the attention reads a selection on a step entirely at or below the exactness
|
||||
* bound. A row there has at most `topk` complete blocks, so qsa_select takes every one whose
|
||||
* key is not 0 -- every block with a page and a score that is a number, whatever the number --
|
||||
* and what it writes (the pages in block order, the partial page, their count, seqused) is a
|
||||
* function of the positions and the block table: the same bytes from every layer's scores. So
|
||||
* the pass's first full-attention layer issues the selection exactly as it always did, and
|
||||
* every later layer reads that one and issues none of its own: no query, no score. */
|
||||
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
|
||||
if (use != kQsaUnread) use = kQsaSelect;
|
||||
/* RADIANCE_DEBUG_QSA_EAGER: the issue sequence as it was, every layer its own. */
|
||||
if (qsa_eager()) use = kQsaSelect;
|
||||
|
||||
/* The projection always: its raw-key head is the block keys' and the tail's. */
|
||||
proj.step(c_, in, w.qk, T);
|
||||
/* The query heads are read by the score alone. */
|
||||
if (use == kQsaSelect) {
|
||||
/* One fused launch or `heads` + 1 unfused. The fused form takes the whole projection at its
|
||||
* row pitch and writes the query heads contiguous and rotated. `n_head` 0 is the k-only form:
|
||||
* no q_gate, q_w or q_out, and `gate_out` absent. `T <= qprep_rows` is a correctness bound
|
||||
@@ -342,8 +395,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
|
||||
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
|
||||
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
}
|
||||
|
||||
/* The keys first: the selection below reads the blocks they complete. */
|
||||
/* The keys first: the selection below reads the blocks they complete. The stateful half runs
|
||||
* whatever the attention reads: later steps score the block keys and build on the tail. */
|
||||
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
|
||||
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
|
||||
if (!atb || !store_keys(c_, batch)) return;
|
||||
@@ -352,6 +407,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
|
||||
* is a query row, so each query of a prefill chunk selects from the shared history, as the
|
||||
* checkpoint does. */
|
||||
if (!c.emit_sel) return;
|
||||
/* Nothing reads a selection of this layer's: the step is at or below the exactness bound and
|
||||
* its attention reads the block table, or the selection the pass's first full-attention layer
|
||||
* made (AttnGatedFP8::qsa_use). */
|
||||
if (use == kQsaUnread) return;
|
||||
|
||||
/* Narrow the score columns to the live history. Both kernels size their grid from the
|
||||
* operand's width (the live count is device data), so the full `max_ctx` width would make a
|
||||
|
||||
@@ -86,7 +86,7 @@ struct Model {
|
||||
Gemma4Audio aud;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The layer schedule, read rather than derived: layer_types states which layers attend to the
|
||||
* whole input, and an assumed pattern would silently be wrong for a sibling checkpoint that
|
||||
@@ -123,7 +123,8 @@ static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector<
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
/* A 270M encoder fits easily on one card; tensor parallelism would only add an all-reduce per
|
||||
* layer, so it is not offered. */
|
||||
if (ctx->world_size > 1) {
|
||||
@@ -132,7 +133,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
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));
|
||||
@@ -417,7 +418,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
|
||||
if (batch->enc) {
|
||||
@@ -480,6 +481,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace embgemma2 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(embgemma2, "embeddinggemma2", "", "0.1.0",
|
||||
"EmbeddingGemma 2: a bidirectional Gemma encoder with per-layer embeddings, "
|
||||
"mean-pooled to one vector an input; bf16")
|
||||
|
||||
@@ -322,7 +322,7 @@ struct Model {
|
||||
* row's label). */
|
||||
constexpr int64_t kPcW = kMaxPrompt + 1;
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, double wadd,
|
||||
@@ -1701,8 +1701,9 @@ static int declare_encoder(RadBuilder* b, Model& m) {
|
||||
/* ================================================================== declare */
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
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(check_format(meta));
|
||||
@@ -2184,7 +2185,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->agen_b) {
|
||||
rad_step_fail(c, "fishomni is an audio generator and runs generator passes only");
|
||||
return;
|
||||
@@ -2352,6 +2353,8 @@ RAD_ARCH_PROBE(fishomni)
|
||||
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
return fishomni::text_prepare(field, in, out, cap);
|
||||
}
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(fishomni, "fishomni", "bsgemm-moe", "0.1.0",
|
||||
"Fish Audio drama-3: the Qwen3.5-35B-A3B backbone (block-scaled fp8 experts), a "
|
||||
"13-layer codebook tower over its full-attention cache, and Fish S2's modified "
|
||||
|
||||
@@ -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,542 @@
|
||||
/* 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;
|
||||
/* Whether layer 0's probe found a rotated-int8 trunk, and its activation scale group: see
|
||||
* rad_fp8.h's trunk_rotation. */
|
||||
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, probed from layer 0's q projection: rad_fp8.h's trunk_rotation
|
||||
* answers whether it is rotated int8 and how wide the activation codes' scale group is. */
|
||||
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) &&
|
||||
trunk_rotation(enc, &m.trunk_g8);
|
||||
}
|
||||
|
||||
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 */
|
||||
+54
-20
@@ -39,7 +39,11 @@
|
||||
*
|
||||
* Every linear of the language model and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16
|
||||
* throughout when the first joint block's projection is plain; the embedders, the timestep MLPs,
|
||||
* the modulations, the output layer and the VAE stay bf16.
|
||||
* the modulations, the output layer and the VAE stay bf16. That projection also says whether the
|
||||
* linears are rotated int8 (IQ8R): the activations they read then carry int8 codes in place of the
|
||||
* E4M3 pair, which a block's modulated norm writes in its own pass where a library serves the
|
||||
* rotating twin (rms_mod_had_quant_i8g) and the rotating quantiser behind the plain norm
|
||||
* elsewhere.
|
||||
*
|
||||
* ============================== TENSOR PARALLEL ==============================
|
||||
*
|
||||
@@ -113,6 +117,9 @@ struct Block {
|
||||
LinearFP8 qkv{}, o{}, ff_in{}, ff_out{};
|
||||
GateQuantFP8 gq{};
|
||||
QuantFP8 q_attn{};
|
||||
/* The normed rows' quantiser for a rotated int8 model whose norm is the unquantised one
|
||||
* (Model::norm_i8 false). */
|
||||
QuantFP8 q_n{};
|
||||
rad_op op_n = 0, op_qkr = 0, op_attn = 0, op_sum = 0, op_ar = 0;
|
||||
};
|
||||
|
||||
@@ -172,6 +179,14 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
std::vector<Block> mode[3], single;
|
||||
LinearFP8 qkv0{};
|
||||
/* The linears of both networks are rotated int8 (IQ8R, or the 128-group int8 before it), read
|
||||
* off qkv0's probe: the activations then carry int8 code pairs with one scale per (token, `g8`
|
||||
* columns) in place of the E4M3 pair. */
|
||||
bool i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
/* A block's modulated norm writes those int8 codes in its own pass (rms_mod_had_quant_i8g),
|
||||
* where a library serves it. */
|
||||
bool norm_i8 = false;
|
||||
rad_weight w_pout = 0;
|
||||
|
||||
/* ---- per-image state and conditioning store (PERSIST) */
|
||||
@@ -184,7 +199,7 @@ struct Model {
|
||||
rad_buf b_dl = 0, b_decin = 0, b_cu4 = 0, b_img = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
std::vector<double> v;
|
||||
@@ -276,14 +291,16 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, E });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, E });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", E, T));
|
||||
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", E, T, m.i8, m.g8, "had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T));
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, E });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T));
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, T, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { T, kNTaps * E });
|
||||
m.b_tidx = decl_b(b, nm.f("te.rows"), RAD_I32, { T });
|
||||
|
||||
@@ -530,11 +547,16 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), RAD_F32,
|
||||
{ hd }, RAD_ACCESS_PER_TOKEN, grp);
|
||||
if (!B.w_qn || !B.w_kn) return RAD_E_INVAL;
|
||||
const bool q = !g.w_bf16;
|
||||
/* The norm with the quantiser in it: E4M3 for block-fp8 linears, the rotating int8 twin for
|
||||
* rotated int8 ones where a library serves it. bf16 linears read its bf16 rows, and rotated
|
||||
* int8 ones without the twin quantise those with the rotating quantiser (q_n). */
|
||||
m.norm_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "rms_mod_had_quant_i8g") != 0;
|
||||
const bool q = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
auto norm = [&](bool gt) {
|
||||
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
|
||||
rad_op op = q ? RAD_OP(b, m.norm_i8 ? "rms_mod_had_quant_i8g" : "rms_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D),
|
||||
RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_F64("eps", eps),
|
||||
RAD_INT("group", m.norm_i8 ? m.g8 : RAD_FP8_BLOCK),
|
||||
RAD_INT("gated", gt ? 1 : 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("norm", "layer")),
|
||||
RAD_NOWEIGHTS)
|
||||
@@ -546,7 +568,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
if (!op) return op;
|
||||
/* The residual, the modulation table and, gated, the branch sum. */
|
||||
rad_buf rd[4] = { m.b_xc, m.b_h, mod, m.b_sum };
|
||||
rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h };
|
||||
rad_buf wq[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h };
|
||||
rad_buf wb[2] = { m.a_hm.x, m.b_h };
|
||||
rad_op_reads(b, op, rd, gt ? 4 : 3);
|
||||
if (q) rad_op_writes(b, op, wq, 3);
|
||||
@@ -554,6 +576,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
return op;
|
||||
};
|
||||
B.op_n = norm(gated);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n.declare(b, g, m.a_hm, D));
|
||||
RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW,
|
||||
grp_layer(grp),
|
||||
{ nm.ckpt("%s.attn.to_q.weight", pre),
|
||||
@@ -728,14 +751,16 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
/* ---- the blocks' buffers */
|
||||
const int64_t qd = g.q_dim();
|
||||
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
|
||||
RAD_ARCH_TRY(m.a_hm.declare_pair(b, nm, g, "dit.hm", D, 0, m.i8, m.g8, "had_quant_act_i8g"));
|
||||
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd });
|
||||
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_pair(b, nm, g, "dit.attn", qd, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_o = decl_b(b, nm.f("dit.o"), RAD_BF16, { T, D });
|
||||
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_pair(b, nm, g, "dit.ffn", g.n_ff, 0, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_f = decl_b(b, nm.f("dit.f"), RAD_BF16, { T, D });
|
||||
m.b_sum = decl_b(b, nm.f("dit.sum"), RAD_BF16, { T, D });
|
||||
|
||||
@@ -895,8 +920,9 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
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(check_format(meta));
|
||||
@@ -941,9 +967,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.single_transformer_blocks.0.attn.to_k.weight",
|
||||
"transformer.single_transformer_blocks.0.attn.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
const bool known = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e);
|
||||
const bool plain = known && rad_enc_is(&e, "plain");
|
||||
gd.w_bf16 = m.gt.w_bf16 = plain;
|
||||
/* Or rotated int8 (IQ8R): the activations then carry int8 codes at the weights' scale
|
||||
* group in place of the E4M3 pair (ActFP8::declare_pair). */
|
||||
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
|
||||
if (m.i8) m.g8 = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
const int64_t lane_rows = m.lanes * m.max_img;
|
||||
@@ -1030,7 +1060,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"+ %zu joint blocks (%lld heads a rank, ff %lld), %s linears",
|
||||
m.gt.rank, m.gt.world, m.flow_map ? " (flow map)" : " base", kTaps[kNTaps - 1],
|
||||
(long long)m.gt.n_layer, m.mode[0].size(), m.single.size(), (long long)gd.n_head,
|
||||
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : "block-fp8");
|
||||
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1125,17 +1155,19 @@ static void step_blocks(RadCtx* c, const Model& m, const std::vector<Block>& sta
|
||||
const RadOperand& s, const RadOperand& gt, const RadOperand& pos) {
|
||||
const Geom& g = m.gd;
|
||||
const int64_t D = g.n_embd, qd = g.q_dim(), nD = D / RAD_FP8_BLOCK;
|
||||
const bool q8 = !g.w_bf16;
|
||||
const bool q8 = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
const RadOperand xv = brow_slice(x, r0, R, D);
|
||||
for (size_t i = 0; i < stack.size(); ++i) {
|
||||
const Block& B = stack[i];
|
||||
const bool gated = i > 0;
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.q, R), brows(m.a_hm.s, R), RAD_NONE);
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.cq(), R), brows(m.a_hm.cs(), R),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.x, R));
|
||||
B.q_n.step(c, R);
|
||||
B.qkv.step(c, m.a_hm, m.b_qkv, R);
|
||||
RAD_ISSUE_N(c, B.op_qkr, R, brows(m.b_qkv, R), pos, RAD_W(B.w_qn), RAD_W(B.w_kn));
|
||||
RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R),
|
||||
@@ -1254,7 +1286,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "flux3 is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1283,6 +1315,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
/* One more level of expansion so `#NS` sees the expanded namespace. */
|
||||
#define FLUX3_PROBE_X(NS) RAD_ARCH_PROBE(NS)
|
||||
#define FLUX3_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
FLUX3_PROBE_X(FLUX3_NS)
|
||||
FLUX3_PLUGIN_X(FLUX3_NS, FLUX3_ID, "", "0.1.0",
|
||||
"FLUX.3 [klein] and its base: Qwen3-VL-4B's stacked layers, a 5.6B three-mode "
|
||||
|
||||
+30
-15
@@ -85,7 +85,8 @@ struct ClassGeom {
|
||||
* - `mx`: OCP-MXFP4 (e2m1 codes, an E8M0 exponent per [1 x 32]), gemm_nt_q at mxfp4a8 over
|
||||
* quant_act_fp8's E4M3 codes, an f32 scale per (row, 128); the exponent plane is passed twice,
|
||||
* as b_scale and as b_ref (arch/common/rad_fp8.h LinearFP8 says why).
|
||||
* Neither has a fused norm/quantiser here, so the junctions stay off for them. */
|
||||
* The i8g grid takes the `_i8g` twins of the fused junction and of the GELU quantiser, as
|
||||
* gemma4_bf16's does; MXFP4 has its own junction (G3JunctionFP8). */
|
||||
struct G3Linear {
|
||||
rad_weight w = 0, ws = 0, wref = 0;
|
||||
rad_op op = 0, op_q = 0;
|
||||
@@ -192,6 +193,7 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
|
||||
i8g = known && linear_is_w8(enc);
|
||||
mx = known && linear_is_mxfp4(enc);
|
||||
if (mx) return linear_refuse_retired(wn, "MXFP4");
|
||||
/* Asymmetric int4 (libquant `codes=u4 zero=u8 group=128 scale=f16`), unrotated: gemm_nt_q at
|
||||
* w4a8i8_asym over the same per-(row, 128) int8 activation as i8g. LinearFP8 serves this grid
|
||||
* only under ParoQuant's rotation, which a tensor-parallel shard cannot cut; unrotated it shards
|
||||
@@ -698,8 +700,9 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gu}, {w.ffn});
|
||||
// Not under calibration: the tap reads the bf16 activation this fusion never writes.
|
||||
if (ln_down.quant && !ln_down.shared_in && !calib_dir() && rad_op_declared(b, "gelu_mul_quant_i8"))
|
||||
op_gq = rw(b, RAD_OP(b, "gelu_mul_quant_i8",
|
||||
const char* gq = ln_down.quant ? "gelu_mul_quant_i8" : ln_down.i8g ? "gelu_mul_quant_i8g" : nullptr;
|
||||
if (gq && !ln_down.shared_in && !calib_dir() && rad_op_declared(b, gq))
|
||||
op_gq = rw(b, RAD_OP(b, gq,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gu}, {ln_down.q8, ln_down.s8});
|
||||
@@ -782,7 +785,8 @@ void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
/* ---- one residual junction as one op (libr4d `rmsnorm_quant_i8`): [post-norm of the branch,
|
||||
/* ---- one residual junction as one op (libr4d `rmsnorm_quant_i8`, on quant_act_i8g's grid
|
||||
* `rmsnorm_quant_i8g`): [post-norm of the branch,
|
||||
* the add into the stream,] the next block's norm and its int8 quantiser. gemma4_bf16's
|
||||
* G4Junction without the layer scalar. */
|
||||
struct G3Junction {
|
||||
@@ -794,25 +798,27 @@ struct G3Junction {
|
||||
int declare(RadBuilder* b, const Geom& g, rad_buf x_, rad_buf res_, rad_weight w_,
|
||||
rad_weight wp_, const G3Linear& into) {
|
||||
x = x_; res = res_; w = w_; wp = wp_; q8 = into.q8; s8 = into.s8;
|
||||
if (!into.quant || into.shared_in || !q8 || !s8 || !w || (wp && !res))
|
||||
if (!(into.quant || into.i8g) || into.shared_in || !q8 || !s8 || !w || (wp && !res))
|
||||
return RAD_E_INVAL;
|
||||
const char* rq = into.i8g ? "rmsnorm_quant_i8g" : "rmsnorm_quant_i8";
|
||||
const char* arq = into.i8g ? "ar_rmsnorm_quant_i8g" : "ar_rmsnorm_quant_i8";
|
||||
const RadParam p[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd) };
|
||||
const rad_weight ws[2] = { w, wp };
|
||||
const int nw = wp ? 2 : 1;
|
||||
if (rad_op_declared(b, "rmsnorm_quant_i8"))
|
||||
op = rad_decl_op(b, "rmsnorm_quant_i8", p, (int)(sizeof p / sizeof p[0]), ws, nw);
|
||||
if (rad_op_declared(b, rq))
|
||||
op = rad_decl_op(b, rq, p, (int)(sizeof p / sizeof p[0]), ws, nw);
|
||||
if (!op) return RAD_OK;
|
||||
const rad_buf rd[2] = { x, res };
|
||||
const rad_buf wr[3] = { q8, s8, res };
|
||||
rad_op_reads (b, op, rd, res ? 2 : 1);
|
||||
rad_op_writes(b, op, wr, res ? 3 : 2);
|
||||
if (res && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
if (res && g.world == 2 && rad_op_declared(b, arq)) {
|
||||
const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) };
|
||||
op_ar = rad_decl_op(b, "ar_rmsnorm_quant_i8", pa, (int)(sizeof pa / sizeof pa[0]), ws, nw);
|
||||
op_ar = rad_decl_op(b, arq, pa, (int)(sizeof pa / sizeof pa[0]), ws, nw);
|
||||
if (op_ar) {
|
||||
const rad_buf wa[4] = { x, q8, s8, res };
|
||||
rad_op_reads (b, op_ar, rd, 2);
|
||||
@@ -1002,7 +1008,7 @@ struct Model {
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
* to 64 rows (qwen35_fp8 says why). */
|
||||
@@ -1149,9 +1155,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
@@ -1322,8 +1329,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (g.n_layer > 0 && !calib_dir()) {
|
||||
bool ok = true;
|
||||
for (const Layer& lay : m.layers)
|
||||
ok = ok && lay.attn.ln_q.quant && lay.attn.ln_k.shared_in && lay.attn.ln_v.shared_in &&
|
||||
lay.mlp.ln_gu.quant;
|
||||
ok = ok && (lay.attn.ln_q.quant || lay.attn.ln_q.i8g) && lay.attn.ln_k.shared_in &&
|
||||
lay.attn.ln_v.shared_in && (lay.mlp.ln_gu.quant || lay.mlp.ln_gu.i8g);
|
||||
if (ok) {
|
||||
RAD_ARCH_TRY(m.j0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, 0, m.layers[0].attn.ln_q));
|
||||
ok = m.j0.op != 0;
|
||||
@@ -1665,7 +1672,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
if (batch->enc) {
|
||||
rad_step_fail(c, "gemma3 serves text only");
|
||||
return;
|
||||
@@ -1800,11 +1807,19 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
out->draft_depth = bs > 1 ? (int)(bs - 1) : 7;
|
||||
out->draft_depth_fixed = 1; /* as qwen35_fp8: the trained block */
|
||||
}
|
||||
/* Chained launches pay with a drafter and without one: the decode kernels of the int8 trunk
|
||||
* have chained forms (libr4d's rad_kernel_chain), and the weight reads beside the reductions
|
||||
* then stay on lane 0 instead of a second queue. TranslateGemma 27B int8 on two R9700, ms a
|
||||
* decode step unchained / chained: 31.9 / 24.1 at one sequence, 32.2 / 24.8 at four (with
|
||||
* the junctions unfused, 40.9 / 26.4 and 41.2 / 27.0). */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(gemma3)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(gemma3, "gemma3", "", "0.1.0",
|
||||
"Gemma 3 dense text trunk (TranslateGemma), bf16 or w4a8 at convert: sliding-window "
|
||||
"and linearly-scaled global attention over a (1 + w) RMSNorm stream with GELU "
|
||||
|
||||
+172
-91
@@ -1,6 +1,6 @@
|
||||
/* gemma4 -- Gemma 4 text decoders (26B-A4B MoE, and the dense members of the family): a bf16
|
||||
* trunk, routed experts bf16 or block fp8 (see FP8 EXPERTS), and the DFlash block-diffusion
|
||||
* drafter.
|
||||
* trunk, routed experts bf16, block fp8 or rotated int8 (see FP8 EXPERTS), and the DFlash
|
||||
* block-diffusion drafter.
|
||||
*
|
||||
* ============================== THE SHAPE (gemma-4-26B-A4B-it) ==============================
|
||||
*
|
||||
@@ -77,7 +77,17 @@
|
||||
* blocks, which 704 is not. It stays bf16 -- unless the checkpoint is padded to 768
|
||||
* first, outside the engine: zero rows of gate and up give gelu(0) * 0 = 0 in the
|
||||
* padded columns, which meet zero columns of down, so the function is unchanged, and
|
||||
* then both projections are fp8 (data/recipes/gemma4-26b-a4b-df-pad768.recipe).
|
||||
* then both projections are fp8.
|
||||
*
|
||||
* Rotated int8 experts (`rtn codes=i8 group=128 scale=bf16 transform=fwht128`) take the same
|
||||
* tables and the same widths through `moe_gemm_q` at i8a8h, over int8 codes of the experts' input
|
||||
* that the attention join's fused route writes (`norm_add_norm_route_i8g`), or the rotating norm
|
||||
* (`rmsnorm_had_quant_i8g`) where that is not served. A model's quantised experts are all one or
|
||||
* all the other.
|
||||
*
|
||||
* The cache is bf16 or int8 with an f16 scale of K and of V per token and head
|
||||
* (--kv-cache-dtype i8, libr4d's windowed kernels' int8 rows and kv_store_i8), the drafter's
|
||||
* with it.
|
||||
*
|
||||
* ============================== NOT DECLARED ==============================
|
||||
*
|
||||
@@ -157,7 +167,9 @@ struct Layer {
|
||||
* w_egus/w_edns, so each parity is one run (see declare). */
|
||||
rad_weight w_rscale = 0, w_router = 0, w_escale = 0, w_enorm = 0, w_fpost2 = 0;
|
||||
std::vector<rad_weight> w_egu, w_edn, w_egus, w_edns;
|
||||
bool gu_fp8 = false, dn_fp8 = false;
|
||||
/* A projection's experts are quantised (block fp8 or rotated int8: the table GEMM over a code
|
||||
* pair), else plain bf16. */
|
||||
bool gu_q = false, dn_q = false;
|
||||
rad_op op_rnorm = 0, op_router = 0, op_topk = 0, op_escale = 0, op_emul = 0, op_enorm = 0;
|
||||
rad_op op_scatter = 0, op_egu = 0, op_eact = 0, op_eq = 0, op_edn = 0, op_gather = 0;
|
||||
/* libr4d's fused forms of the router, its top-k and the sort, where they resolve: the pair
|
||||
@@ -177,8 +189,9 @@ struct Layer {
|
||||
* then declared and issued instead. */
|
||||
rad_op op_join_a = 0, op_join_f = 0;
|
||||
/* op_join_r: op_join_a writing the routed arm's two inputs as well -- the router's norm into
|
||||
* b_rn and the experts' fp8 codes into b_hq / b_hqs (norm_add_norm_route) -- where the
|
||||
* layer's gate_up is block fp8. op_rnorm and op_enorm are then declared and not issued. */
|
||||
* b_rn and the experts' codes into b_hq / b_hqs (norm_add_norm_route's E4M3, or
|
||||
* norm_add_norm_route_i8g's rotated int8) -- where the layer's gate_up is quantised. op_rnorm
|
||||
* and op_enorm are then declared and not issued. */
|
||||
rad_op op_join_r = 0;
|
||||
/* op_join_f also writes the next norm (the following layer's input norm, or the final norm
|
||||
* after the last layer) into `h`, with that norm's gain `w_next`; the replaced norm is then
|
||||
@@ -220,7 +233,10 @@ struct Model {
|
||||
/* the experts' E4M3 inputs, declared only where some layer's projection is fp8: gate_up's
|
||||
* (the normed block input, a row a token) and down's (the gated product, a row a slot) */
|
||||
rad_buf b_hq = 0, b_hqs = 0, b_eq = 0, b_eqs = 0;
|
||||
int n_gu_fp8 = 0, n_dn_fp8 = 0; /* layers whose projection is fp8 */
|
||||
int n_gu_q = 0, n_dn_q = 0; /* layers whose projection is quantised */
|
||||
/* The quantised experts are rotated int8 against int8 activations (EXP_I8), every layer's:
|
||||
* the code pairs are one buffer each for the whole model. */
|
||||
bool exp_i8 = false, exp_seen = false;
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_onorm = 0;
|
||||
@@ -245,7 +261,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ============================================================== geometry */
|
||||
|
||||
@@ -331,7 +347,7 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
* plan, rad_weight_encoding), which picks the GEMM: plain bf16 is `moe_gemm`, block fp8 (fp8_e4m3
|
||||
* codes, a bf16 scale per 128x128 block) is `moe_gemm_q` at fp8a8. Anything else is refused by
|
||||
* name. A builder with no model behind it answers nothing, and the declared dtype bf16 is read. */
|
||||
enum { EXP_BF16 = 0, EXP_FP8 = 1 };
|
||||
enum { EXP_BF16 = 0, EXP_FP8 = 1, EXP_I8 = 2 };
|
||||
static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
|
||||
RadEncoding e{};
|
||||
*fmt = EXP_BF16;
|
||||
@@ -341,11 +357,22 @@ static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
|
||||
*fmt = EXP_FP8;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Rotated int8: codes with a bf16 scale per (row, 128 of K), each 128 of K rotated by the
|
||||
* Hadamard (libquant's `codes=i8 group=128 scale=bf16 transform=fwht128`). */
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
if (rad_enc_is(&e, "affine") && e.n_planes == 2 && e.plane[0].dtype == RAD_I8 && sc &&
|
||||
sc->dtype == RAD_BF16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
|
||||
std::strcmp(e.transform, "fwht128") == 0) {
|
||||
*fmt = EXP_I8;
|
||||
return RAD_OK;
|
||||
}
|
||||
char en[256];
|
||||
rad_enc_format(&e, en, sizeof en);
|
||||
fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16 or "
|
||||
"block fp8 (fp8_e4m3*bf16[128x128]). Convert with no rule for them, or with "
|
||||
"`rtn codes=fp8_e4m3 block=128x128 scale=bf16`.\n", wn, en);
|
||||
fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16, "
|
||||
"block fp8 (fp8_e4m3*bf16[128x128]) or rotated int8 "
|
||||
"(i8*bf16[1x128]/fwht128). Convert with no rule for them, or with `rtn "
|
||||
"codes=fp8_e4m3 block=128x128 scale=bf16` or `rtn codes=i8 group=128 "
|
||||
"scale=bf16 transform=fwht128 clamp=sym rule=search`.\n", wn, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
@@ -360,11 +387,11 @@ static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base
|
||||
RAD_ARCH_TRY(expert_format(b, wn, &f));
|
||||
if (e == 0) { *fmt = f; continue; }
|
||||
if (f != *fmt) {
|
||||
static const char* const kName[3] = { "bf16", "block fp8", "rotated int8" };
|
||||
fprintf(stderr, "radiance: gemma4: '%s' is %s and expert %lld of the same layer is %s; "
|
||||
"one layer's %s experts take one encoding (a recipe rule for them "
|
||||
"matches all of a layer's or none)\n", wn,
|
||||
f == EXP_FP8 ? "block fp8" : "bf16", (long long)base,
|
||||
*fmt == EXP_FP8 ? "block fp8" : "bf16", what);
|
||||
"matches all of a layer's or none)\n", wn, kName[f], (long long)base,
|
||||
kName[*fmt], what);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
@@ -375,7 +402,8 @@ static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->is_draft) {
|
||||
fprintf(stderr, "radiance: gemma4: this plugin has no draft scope\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -388,7 +416,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -541,24 +569,45 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* ---- the KV groups, one per geometry: the sliding layers' (256-wide heads) and the full
|
||||
* layers' (512).
|
||||
*
|
||||
* The sliding layers' group is RAD_KV_FULL, not RAD_KV_WINDOW; the window lives on the
|
||||
* attention op (`window` 1024), which reads only keys inside it. A window group is not
|
||||
* prefix-cached (core/mem/prefix.cpp), so a prefix hit on a model with one reuses nothing and
|
||||
* re-prefills (core/sched). As FULL the group is cached with the others and the drafter's KV
|
||||
* has no hole. The only loss is recycling below the window, which gains nothing here: the
|
||||
* planner gives every paged group the same block count, so the full group bounds the tokens a
|
||||
* card holds anyway. */
|
||||
* The sliding layers' group is RAD_KV_WINDOW, sized to the attention window, which is what
|
||||
* the kernel reads anyway: attn_paged takes `window` 1024 on those layers and never looks at
|
||||
* a key older than it. As a window group the pool is capped at the window plus one block per
|
||||
* sequence (core/mem/kv.cpp), so 25 sliding layers cost ~1k tokens of cache each instead of
|
||||
* the whole context -- at 32k and fp8 KV, 0.4 GiB a sequence where FULL costs 3.5. The full
|
||||
* layers' group stays RAD_KV_FULL: it is the only one whose keys outlive a window.
|
||||
*
|
||||
|
||||
* A windowed group is not prefix-cached (core/mem/prefix.cpp): its rows below the window are
|
||||
* recycled, and adopt() would overfill a table capped at window_blocks. What that costs on
|
||||
* a prefix hit is only the windowed rows; the full layers' rows still come back from the
|
||||
* store. The window itself resumes from the deepest retained checkpoint at or below the
|
||||
* matched end — that checkpoint's slot carries the window behind it — and only the gap between
|
||||
* that checkpoint and the match end is recomputed. Only where no retained checkpoint sits at
|
||||
* or below the match do the windowed layers start their cache where the hit ended
|
||||
* (the re-prefill case); that is the regime gemma3 runs with a DFlash drafter on the
|
||||
* same core, and it declares its sliding group exactly this way.
|
||||
*
|
||||
|
||||
* The drafter does not read the trunk's cache. DFlash keeps its own windowed draft KV (2048),
|
||||
* rebuilt each context pass from the trunk's residual taps; its rows live inside that window
|
||||
* like every other draft query's, and it has no stake in the trunk's windowed rows outliving
|
||||
* the window. A windowed trunk group therefore costs the drafter nothing. */
|
||||
|
||||
{
|
||||
const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
d.kind = RAD_KV_WINDOW;
|
||||
d.window = m.ks.window; /* the same 1024 the attention op reads */
|
||||
d.dtype = kvdt;
|
||||
d.n_head_kv = m.ks.nkv;
|
||||
d.head_dim = m.ks.hd;
|
||||
m.ks.kv = rad_decl_kv_group(b, nm.f("kv_swa"), &d);
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.window = 0;
|
||||
d.n_head_kv = m.kf.nkv;
|
||||
d.head_dim = m.kf.hd;
|
||||
m.kf.kv = rad_decl_kv_group(b, nm.f("kv_full"), &d);
|
||||
g.kv_dtype = rad_dtype_name(d.dtype);
|
||||
g.kv_dtype = rad_dtype_name(kvdt);
|
||||
}
|
||||
|
||||
/* Gemma4ForConditionalGeneration keeps the text model under model.language_model;
|
||||
@@ -587,26 +636,40 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
int fgu = EXP_BF16, fdn = EXP_BF16;
|
||||
RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "gate_up", &fgu));
|
||||
RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "down", &fdn));
|
||||
y.gu_fp8 = fgu == EXP_FP8;
|
||||
y.dn_fp8 = fdn == EXP_FP8;
|
||||
y.gu_q = fgu != EXP_BF16;
|
||||
y.dn_q = fdn != EXP_BF16;
|
||||
/* One quantised format for the model: the experts' code pairs are shared buffers. */
|
||||
for (const int f : { fgu, fdn }) {
|
||||
if (f == EXP_BF16) continue;
|
||||
const bool i8 = f == EXP_I8;
|
||||
if (m.exp_seen && i8 != m.exp_i8) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's experts are %s and an earlier "
|
||||
"projection's %s; a model's quantised experts are all block "
|
||||
"fp8 or all rotated int8\n", ll,
|
||||
i8 ? "rotated int8" : "block fp8", i8 ? "block fp8" : "rotated int8");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
m.exp_seen = true;
|
||||
m.exp_i8 = i8;
|
||||
}
|
||||
/* moe_gemm_q's geometry, refused here by name rather than as a kernel miss. It takes
|
||||
* experts as two tables by parity, so a rank must hold an even count. */
|
||||
if ((y.gu_fp8 || y.dn_fp8) && NL % 2) {
|
||||
fprintf(stderr, "radiance: gemma4: block fp8 experts come in pairs on a rank (the "
|
||||
"fp8 grouped GEMM takes them as two tables by parity); this rank "
|
||||
if ((y.gu_q || y.dn_q) && NL % 2) {
|
||||
fprintf(stderr, "radiance: gemma4: quantised experts come in pairs on a rank (the "
|
||||
"grouped GEMM takes them as two tables by parity); this rank "
|
||||
"holds %lld\n", (long long)NL);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (y.gu_fp8 && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are block fp8 at "
|
||||
"%lld x %lld; the fp8 grouped GEMM takes N in 64s and K in whole "
|
||||
if (y.gu_q && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are quantised at "
|
||||
"%lld x %lld; the grouped GEMM takes N in 64s and K in whole "
|
||||
"%d-column blocks\n", ll, (long long)(2 * m.n_ffe), (long long)E,
|
||||
RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (y.dn_fp8 && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's down experts are block fp8, and "
|
||||
"the experts are %lld wide: the fp8 grouped GEMM reads K in whole "
|
||||
if (y.dn_q && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's down experts are quantised, and "
|
||||
"the experts are %lld wide: the grouped GEMM reads K in whole "
|
||||
"%d-column scale blocks. Keep `ffn_down_exps` bf16 (no recipe "
|
||||
"rule for it), or pad the experts to a multiple of %d (zero rows "
|
||||
"of gate and up, zero columns of down) and convert the padded "
|
||||
@@ -614,8 +677,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
(long long)m.n_ffe, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
m.n_gu_fp8 += y.gu_fp8;
|
||||
m.n_dn_fp8 += y.dn_fp8;
|
||||
m.n_gu_q += y.gu_q;
|
||||
m.n_dn_q += y.dn_q;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -640,10 +703,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {T, K});
|
||||
m.b_ew = decl_b(b, nm.f("moe_w"), RAD_BF16, {T, K});
|
||||
m.b_es = decl_b(b, nm.f("moe_es"), RAD_BF16, {T, K});
|
||||
if (m.n_gu_fp8 < m.n_layer)
|
||||
if (m.n_gu_q < m.n_layer)
|
||||
m.b_hx = decl_b(b, nm.f("moe_h"), RAD_BF16, {T, E});
|
||||
if (m.n_gu_fp8 > 0) {
|
||||
m.b_hq = decl_b(b, nm.f("moe_hq"), RAD_F8E4M3, {T, E});
|
||||
if (m.n_gu_q > 0) {
|
||||
m.b_hq = decl_b(b, nm.f("moe_hq"), m.exp_i8 ? RAD_I8 : RAD_F8E4M3, {T, E});
|
||||
m.b_hqs = decl_b(b, nm.f("moe_hqs"), RAD_F32, {T, fp8_blocks(E)});
|
||||
}
|
||||
m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {P * K});
|
||||
@@ -651,8 +714,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.n_local});
|
||||
m.b_egu = decl_b(b, nm.f("moe_egu"), RAD_BF16, {P * K, 2 * m.n_ffe});
|
||||
m.b_eact = decl_b(b, nm.f("moe_eact"), RAD_BF16, {P * K, m.n_ffe});
|
||||
if (m.n_dn_fp8 > 0) {
|
||||
m.b_eq = decl_b(b, nm.f("moe_eq"), RAD_F8E4M3, {P * K, m.n_ffe});
|
||||
if (m.n_dn_q > 0) {
|
||||
m.b_eq = decl_b(b, nm.f("moe_eq"), m.exp_i8 ? RAD_I8 : RAD_F8E4M3, {P * K, m.n_ffe});
|
||||
m.b_eqs = decl_b(b, nm.f("moe_eqs"), RAD_F32, {P * K, fp8_blocks(m.n_ffe)});
|
||||
}
|
||||
m.b_edn = decl_b(b, nm.f("moe_edn"), RAD_BF16, {P * K, E});
|
||||
@@ -769,7 +832,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* (libr4d/r4d_norm_join_bf16.hip); on a card they differ from libr4d's chain only in reduction
|
||||
* order. libref deliberately has no row for them, so the chain path stays tested. */
|
||||
const bool has_join_a = rad_op_declared(b, "norm_add_norm") != 0;
|
||||
const bool has_join_r = rad_op_declared(b, "norm_add_norm_route") != 0;
|
||||
const char* const join_r = m.exp_i8 ? "norm_add_norm_route_i8g" : "norm_add_norm_route";
|
||||
const bool has_join_r = rad_op_declared(b, join_r) != 0;
|
||||
const bool has_join_f = rad_op_declared(b, "join_add_scale") != 0;
|
||||
const bool has_escale = rad_op_declared(b, "expert_scale") != 0;
|
||||
const bool has_qrow = rad_op_declared(b, "attn_paged_qrow") != 0;
|
||||
@@ -924,12 +988,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl);
|
||||
}
|
||||
|
||||
/* The attention join. On a layer whose gate_up is block fp8 it also writes the routed
|
||||
/* The attention join. On a layer whose gate_up is quantised it also writes the routed
|
||||
* arm's two inputs: the router's norm (rmsnorm with mult hidden^-0.5) and the experts'
|
||||
* E4M3 codes (as rmsnorm_quant_fp8), saving two launches and two reads of x per layer.
|
||||
* Otherwise norm_add_norm, else the chain. */
|
||||
if (has_join_r && m.moe && y.gu_fp8)
|
||||
y.op_join_r = rw(b, RAD_OP(b, "norm_add_norm_route",
|
||||
* codes (as rmsnorm_quant_fp8, or for rotated int8 experts rmsnorm_had_quant_i8g),
|
||||
* saving two launches and two reads of x per layer. Otherwise norm_add_norm, else the
|
||||
* chain. */
|
||||
if (has_join_r && m.moe && y.gu_q)
|
||||
y.op_join_r = rw(b, RAD_OP(b, join_r,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("mult", 1.0 / std::sqrt((double)E)),
|
||||
@@ -972,10 +1037,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The experts: this rank's run of whole experts (name maps and encodings were settled
|
||||
* before the buffers). Each projection's handles are declared in its GEMM's table
|
||||
* order, since a table is a run of consecutively declared handles: bf16 is one run in
|
||||
* expert order; block fp8 is the even local experts' codes, then the odd ones', then
|
||||
* the scale views in the same two runs (`moe_gemm_q` takes two tables by parity). Codes
|
||||
* expert order; block fp8 or int8 is the even local experts' codes, then the odd ones',
|
||||
* then the scale views in the same two runs (`moe_gemm_q` takes two tables by parity;
|
||||
* an int8 expert's scale is per row, block fp8's per 128 rows). Codes
|
||||
* and scale plane are two views of one stored weight and one movement unit (slot 0
|
||||
* gate_up, 1 down). */
|
||||
const uint32_t cdt = m.exp_i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
|
||||
auto experts = [&](bool fp8, const char* what, int slot, int64_t rows, int64_t cols,
|
||||
std::vector<rad_weight>& wc, std::vector<rad_weight>& ws) {
|
||||
wc.assign((size_t)NL, 0);
|
||||
@@ -1001,18 +1068,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_weight& h = (pass ? ws : wc)[(size_t)(par * half + i)];
|
||||
h = pass ? decl_view(b, nm.f("blk.%lld.ffn_%s_exps.%lld.scale", ll, what, ge),
|
||||
wn, "scale", RAD_BF16,
|
||||
{fp8_blocks(rows), fp8_blocks(cols)},
|
||||
{m.exp_i8 ? rows : fp8_blocks(rows),
|
||||
fp8_blocks(cols)},
|
||||
RAD_ACCESS_CONDITIONAL, N,
|
||||
grp_expert_slot(li, (int)e, slot))
|
||||
: decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, {rows, cols},
|
||||
: decl_view(b, wn, nullptr, "codes", cdt, {rows, cols},
|
||||
RAD_ACCESS_CONDITIONAL, N,
|
||||
grp_expert_slot(li, (int)e, slot));
|
||||
if (!h) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
RAD_ARCH_TRY(experts(y.gu_fp8, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus));
|
||||
RAD_ARCH_TRY(experts(y.dn_fp8, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns));
|
||||
RAD_ARCH_TRY(experts(y.gu_q, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus));
|
||||
RAD_ARCH_TRY(experts(y.dn_q, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns));
|
||||
/* An fp8 projection's op takes its weights in its table operands' order: even codes,
|
||||
* even scales, odd codes, odd scales. */
|
||||
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
|
||||
@@ -1051,11 +1119,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{m.b_ids}, {m.b_es});
|
||||
y.op_emul = binop("mul", P, K, m.b_ew, m.b_es, m.b_ew);
|
||||
}
|
||||
/* The experts' input, pre_feedforward_layernorm_2 of the stream. For an fp8 gate_up it
|
||||
* is normed and quantised in one pass (`rmsnorm_quant_fp8`) with no bf16 copy, since
|
||||
* the fp8 GEMM reads only codes and scales. */
|
||||
if (y.gu_fp8) {
|
||||
y.op_enorm = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
/* The experts' input, pre_feedforward_layernorm_2 of the stream. For a quantised
|
||||
* gate_up it is normed and quantised in one pass (`rmsnorm_quant_fp8`, or for int8
|
||||
* experts the rotating `rmsnorm_had_quant_i8g`) with no bf16 copy, since the table
|
||||
* GEMM reads only codes and scales. */
|
||||
if (y.gu_q) {
|
||||
y.op_enorm = RAD_OP(b, m.exp_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", E),
|
||||
RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("wadd", 0.0)),
|
||||
@@ -1108,13 +1177,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The two grouped GEMMs use different a_order: gate_up reads the block input, one row
|
||||
* per token, gathered through sorted_tok; down reads gate_up's product, already one row
|
||||
* per (token, slot) in scatter order (rad_block_moe_fp8.h). */
|
||||
if (y.gu_fp8) {
|
||||
if (y.gu_q) {
|
||||
const std::vector<rad_weight> tab = tables(y.w_egu, y.w_egus);
|
||||
y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe),
|
||||
RAD_INT("K", E), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", "fp8a8")),
|
||||
/* `a_group` is stated to the int8 rows alone, last and cut off otherwise. */
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe),
|
||||
RAD_INT("K", E), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"),
|
||||
RAD_STR("dtype", m.exp_i8 ? "i8a8h" : "fp8a8"),
|
||||
RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q", ps,
|
||||
(int)(sizeof ps / sizeof *ps) - (m.exp_i8 ? 0 : 1),
|
||||
tab.data(), (int)tab.size()),
|
||||
{m.b_hq, m.b_hqs, m.b_sorted, m.b_eoff}, {m.b_egu});
|
||||
} else {
|
||||
@@ -1129,19 +1202,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* gelu_tanh(gate) * up over the two column halves. An fp8 down then quantises the
|
||||
* product on its own launch: libr4d's fused gated quantiser is compiled for silu. */
|
||||
y.op_eact = act_mul(P * K, m.n_ffe, m.b_egu, m.b_eact);
|
||||
if (y.dn_fp8) {
|
||||
y.op_eq = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
if (y.dn_q) {
|
||||
y.op_eq = rw(b, RAD_OP(b, m.exp_i8 ? "had_quant_act_i8g" : "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n", m.n_ffe),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_eact}, {m.b_eq, m.b_eqs});
|
||||
const std::vector<rad_weight> tab = tables(y.w_edn, y.w_edns);
|
||||
y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", E),
|
||||
RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", "fp8a8")),
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, P), RAD_INT("N", E),
|
||||
RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"),
|
||||
RAD_STR("dtype", m.exp_i8 ? "i8a8h" : "fp8a8"),
|
||||
RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q", ps,
|
||||
(int)(sizeof ps / sizeof *ps) - (m.exp_i8 ? 0 : 1),
|
||||
tab.data(), (int)tab.size()),
|
||||
{m.b_eq, m.b_eqs, m.b_sorted, m.b_eoff}, {m.b_edn});
|
||||
} else {
|
||||
@@ -1165,7 +1241,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_op_reads(b, y.op_gather, rd, 3);
|
||||
rad_op_writes(b, y.op_gather, wr, 1);
|
||||
}
|
||||
if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_fp8 && !y.op_eq)) return RAD_E_INVAL;
|
||||
if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_q && !y.op_eq)) return RAD_E_INVAL;
|
||||
if (W > 1) y.op_ar_f = allreduce(2 * T * E, m.b_ff2);
|
||||
if (has_join_f)
|
||||
{
|
||||
@@ -1309,24 +1385,27 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_note(b, "sandwich joins: %d of %lld fused (norm_add_norm / join_add_scale)%s",
|
||||
n_joins, (long long)(m.moe ? 2 * m.n_layer : m.n_layer),
|
||||
n_joins == 0 ? " -- not served, the rmsnorm / add / mul_weight chain" : "");
|
||||
if (m.moe && m.n_gu_fp8 > 0)
|
||||
rad_note(b, "routed inputs: %d of %d fp8 layers take the router's norm and the experts' "
|
||||
"codes from the attention join (norm_add_norm_route)%s",
|
||||
n_route, m.n_gu_fp8,
|
||||
n_route ? "" : " -- the rmsnorm and rmsnorm_quant_fp8 launches instead");
|
||||
if (m.moe && m.n_gu_q > 0)
|
||||
rad_note(b, "routed inputs: %d of %d quantised layers take the router's norm and the "
|
||||
"experts' codes from the attention join (%s)%s",
|
||||
n_route, m.n_gu_q, join_r,
|
||||
n_route ? "" : m.exp_i8 ? " -- the rmsnorm and rmsnorm_had_quant_i8g launches instead"
|
||||
: " -- the rmsnorm and rmsnorm_quant_fp8 launches instead");
|
||||
if (m.ks.nh > 0)
|
||||
rad_note(b, "sliding attention: q %s", m.qrow == 1
|
||||
? "read in the fused qkv row (attn_paged_qrow)"
|
||||
: "lifted into a dense block for attn_paged (attn_paged_qrow not served)");
|
||||
if (m.moe) {
|
||||
auto how = [&](int n_fp8) {
|
||||
return n_fp8 == m.n_layer ? "block fp8" : n_fp8 == 0 ? "bf16" : "mixed";
|
||||
return n_fp8 == 0 ? "bf16" : n_fp8 < m.n_layer ? "mixed"
|
||||
: m.exp_i8 ? "rotated int8" : "block fp8";
|
||||
};
|
||||
rad_note(b, "routed arm: %lld local experts from %lld of %lld, top %lld, %lld wide; "
|
||||
"gate_up %s (%d of %lld layers fp8), down %s (%d fp8); passes of %lld tokens",
|
||||
"gate_up %s (%d of %lld layers quantised), down %s (%d quantised); passes of "
|
||||
"%lld tokens",
|
||||
(long long)m.n_local, (long long)m.expert_base, (long long)m.n_expert,
|
||||
(long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_fp8), m.n_gu_fp8,
|
||||
(long long)m.n_layer, how(m.n_dn_fp8), m.n_dn_fp8, (long long)m.moe_rows);
|
||||
(long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_q), m.n_gu_q,
|
||||
(long long)m.n_layer, how(m.n_dn_q), m.n_dn_q, (long long)m.moe_rows);
|
||||
if (W > 1)
|
||||
rad_note(b, "prefill overlap: %s", m.overlap
|
||||
? "a chunk of two routed passes or more runs as two slices, each slice's "
|
||||
@@ -1394,11 +1473,11 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
|
||||
}
|
||||
/* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent);
|
||||
* issued only where the attention join did not already write the codes. */
|
||||
if (y.gu_fp8 && !y.op_join_r)
|
||||
if (y.gu_q && !y.op_join_r)
|
||||
RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm),
|
||||
brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK),
|
||||
RAD_NONE);
|
||||
else if (!y.gu_fp8)
|
||||
else if (!y.gu_q)
|
||||
RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_enorm),
|
||||
brow_slice(m.b_hx, r0, n, E));
|
||||
if (!rfused && !pair)
|
||||
@@ -1407,7 +1486,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
|
||||
/* An fp8 projection's tables: the first handle of each parity's run and its length --
|
||||
* even codes, even scales, odd codes, odd scales (declare). */
|
||||
const int64_t H = NL / 2;
|
||||
if (y.gu_fp8)
|
||||
if (y.gu_q)
|
||||
RAD_ISSUE_N(c, y.op_egu, n, brow_slice(m.b_hq, r0, n, E),
|
||||
brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK),
|
||||
RAD_WTAB(y.w_egu[0], H), RAD_WTAB(y.w_egus[0], H),
|
||||
@@ -1419,7 +1498,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
|
||||
brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), brows(m.b_egu, n * K));
|
||||
RAD_ISSUE_N(c, y.op_eact, n * K, bcol(m.b_egu, 0, m.n_ffe, n * K),
|
||||
bcol(m.b_egu, m.n_ffe, m.n_ffe, n * K), brows(m.b_eact, n * K));
|
||||
if (y.dn_fp8) {
|
||||
if (y.dn_q) {
|
||||
RAD_ISSUE_N(c, y.op_eq, n * K, brows(m.b_eact, n * K), brows(m.b_eq, n * K),
|
||||
brows(m.b_eqs, n * K));
|
||||
RAD_ISSUE_N(c, y.op_edn, n, brows(m.b_eq, n * K), brows(m.b_eqs, n * K),
|
||||
@@ -1737,7 +1816,7 @@ static void calib_count(RadCtx* c, Model& m, int64_t T) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (batch->draft_pass != 0) {
|
||||
if (!m.have_df) {
|
||||
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
|
||||
@@ -1763,7 +1842,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const int64_t cut = split_at(m, T);
|
||||
if (cut > 0) trunk_overlap(c, m, batch, cut);
|
||||
else trunk(c, m, batch);
|
||||
if (m.calib && m.tap_live) calib_count(c, g_model[rad_rank(c)], T);
|
||||
if (m.calib && m.tap_live) calib_count(c, g_model[rad_slot(c)], T);
|
||||
|
||||
if (m.op_onorm) RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T));
|
||||
if (batch->n_out > 0) {
|
||||
@@ -1796,6 +1875,8 @@ static const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_cha
|
||||
} /* namespace gemma4 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(gemma4, "gemma4", "", "0.1.0",
|
||||
"Gemma 4 text decoders (26B-A4B MoE, dense 31B), bf16: sliding and full attention "
|
||||
"with proportional rope and K = V, a dense and a routed feed-forward side by side, "
|
||||
|
||||
@@ -2013,7 +2013,7 @@ struct Model {
|
||||
bool slice_attn = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A DFlash2 drafter's config key, from vLLM's speculators layout (the speculator's keys at the
|
||||
* top of `draft.`) or z-lab's (under `draft.dflash_config.`), whichever the checkpoint has. */
|
||||
@@ -2162,17 +2162,31 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
|
||||
dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
|
||||
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
|
||||
dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32,
|
||||
{dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
|
||||
dw.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
|
||||
dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd});
|
||||
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)});
|
||||
dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff});
|
||||
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
|
||||
/* The codes the drafter's linears read: int8 with one f32 scale per (row, group) for linears
|
||||
* stored rotated int8 (the -df2 recipe's), which the drafter's `fc` tells; E4M3 with a scale
|
||||
* per 128 for an MXFP4 drafter (rad_fp8.h's DenseFP8). */
|
||||
RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
|
||||
dc.fc_mapped = true;
|
||||
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
|
||||
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
if (dc.act_i8 && ((dc.n_taps * dg.n_embd) % dqg || dg.n_embd % dqg || qd % dqg ||
|
||||
dg.n_ff % dqg)) {
|
||||
fprintf(stderr, "radiance: a rotated int8 drafter takes widths in whole %lld-column scale "
|
||||
"groups; this one is n_embd %lld, q %lld, n_ff %lld\n", (long long)dqg,
|
||||
(long long)dg.n_embd, (long long)qd, (long long)dg.n_ff);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto dqs = [&](int64_t n) { return (n + dqg - 1) / dqg; };
|
||||
dw.srcq = decl_b(b, nm.f("df_srcq"), dqt, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, dqs(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("df_cq"), dqt, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, dqs(dg.n_embd)});
|
||||
dw.h2q = decl_b(b, nm.f("df_h2q"), dqt, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, dqs(dg.n_embd)});
|
||||
dw.atq = decl_b(b, nm.f("df_atq"), dqt, {qr, qd});
|
||||
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, dqs(qd)});
|
||||
dw.ffq = decl_b(b, nm.f("df_ffq"), dqt, {qr, dg.n_ff});
|
||||
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, dqs(dg.n_ff)});
|
||||
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
|
||||
dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank});
|
||||
dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd});
|
||||
@@ -2261,9 +2275,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
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));
|
||||
@@ -3155,7 +3170,7 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
|
||||
/* An encoder pass runs only its encoder. */
|
||||
if (batch->enc) {
|
||||
@@ -3301,6 +3316,14 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
* DFlash2 one too (rad_block_dflash2.h). */
|
||||
(void)gemma4::dflash_probe(meta, out);
|
||||
(void)gemma4::dflash2_probe(meta, out);
|
||||
/* Chained launches pay on the dense trunk under any drafter and without one: its decode
|
||||
* kernels have chained forms (libr4d's rad_kernel_chain), the two-rank junctions among them,
|
||||
* and the weight reads beside the reductions then stay on lane 0 instead of a second queue.
|
||||
* Gemma 4 31B on two R9700, ms a decode step unchained / chained: grouped int8 35.81 / 27.60
|
||||
* without a drafter and 42.14 / 31.23 with the assistant head (44.93 / 34.17 at four
|
||||
* sequences); w4a8 26.14 / 15.78 and 32.30 / 20.36 (35.93 / 25.01). The 12B with its head:
|
||||
* bf16 38.65 / 28.84, grouped int8 24.35 / 14.74. */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
/* The tower's pooling window, so a pass size the core picks itself is whole windows. */
|
||||
if (Gemma4Vision::present(meta)) {
|
||||
const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0);
|
||||
@@ -3314,6 +3337,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0",
|
||||
"Gemma 4 dense (text, images, E2B/E4B/12B audio), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) "
|
||||
"release: sliding-window and proportional-RoPE global attention over a plain "
|
||||
|
||||
@@ -79,7 +79,7 @@ struct Model {
|
||||
GlmVision vit{};
|
||||
MediaRows mrows{};
|
||||
};
|
||||
static std::unique_ptr<Model> models[MAX_RANKS];
|
||||
static std::unique_ptr<Model> models[MAX_SLOTS];
|
||||
static thread_local std::unique_ptr<Model> probe_model;
|
||||
|
||||
/* Whether every routed expert is MXFP4, asked before any buffer is sized and of the same experts on
|
||||
@@ -473,7 +473,8 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i
|
||||
return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK;
|
||||
}
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
if (!GlmTp::world_ok(world)) {
|
||||
@@ -514,7 +515,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[rad_build_slot(ctx)];
|
||||
slot = std::make_unique<Model>();
|
||||
auto& m = *slot;
|
||||
auto& g = m.g;
|
||||
@@ -625,7 +626,7 @@ static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
|
||||
m.mtp.step_head(c, batch);
|
||||
}
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
auto& m = *models[rad_rank(c)];
|
||||
auto& m = *models[rad_slot(c)];
|
||||
const int64_t T = batch->n_tok;
|
||||
// An encoder pass runs only the vision tower (RadBatch::enc).
|
||||
if (batch->enc) {
|
||||
@@ -675,11 +676,15 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
out->shape_probe_ok = 1;
|
||||
out->tp_attn_rows_ok = 1;
|
||||
/* --kv-cache-dtype fp8: the latent attention cache as E4M3 (declare, kv_groups). */
|
||||
out->kv_fp8_ok = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
} // namespace glm5next
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(glm5next)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(glm5next, "glm5next", "", "0.1.0",
|
||||
"GLM-5.3-Flash mixed MXFP4/FP8, mHC/KDA/MLA and native serial MTP")
|
||||
#endif
|
||||
@@ -180,7 +180,8 @@ struct Model {
|
||||
b_qlogit = 0, b_field = 0;
|
||||
};
|
||||
|
||||
static Model g_model;
|
||||
/* One per engine instance in the process, by slot (rad_builder.h, rad_build_slot). */
|
||||
static Model g_model[RAD_MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype,
|
||||
@@ -890,7 +891,9 @@ static int declare_query(RadBuilder* b, Model& m) {
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
Model& m = g_model;
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || rad_build_slot(ctx) >= RAD_MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -1197,7 +1200,7 @@ static void step_query(RadCtx* c, const RadShapeGenBatch* S, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model;
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const RadShapeGenBatch* S = batch->sgen_b;
|
||||
if (!batch->gen || !S) {
|
||||
rad_step_fail(c, "hunyuan3d2 is a shape generator and runs generator passes only");
|
||||
@@ -1225,6 +1228,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
} /* namespace hunyuan3d2 */
|
||||
|
||||
RAD_ARCH_PROBE(hunyuan3d2)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(hunyuan3d2, "hunyuan3d2", "", "0.1.0",
|
||||
"Hunyuan3D-2's shape model: DINOv2-giant over the picture, a flow-matching DiT of "
|
||||
"16 double and 32 single blocks over 3072 latents, and the shape VAE's geometry "
|
||||
|
||||
@@ -38,7 +38,6 @@ struct AttnQKFP8 {
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
const char* o = nullptr;
|
||||
double k_scale = 1.0, v_scale = 1.0; /* static FP8-cache descales; 1 for BF16 cache */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
@@ -48,11 +47,9 @@ struct AttnQKFP8 {
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
LinearFP8 q{}, k{}, v{}, o{};
|
||||
rad_buf k_descale = 0, v_descale = 0;
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
rad_op op_q_norm = 0, op_k_norm = 0;
|
||||
rad_op op_k_descale = 0, op_v_descale = 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 and BF16 cache store, decode band */
|
||||
int64_t qkr_rows = 0;
|
||||
@@ -78,14 +75,6 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const bool fp8_cache = std::strcmp(g.kv_dtype, "fp8_e4m3") == 0;
|
||||
if (fp8_cache && (!std::isfinite(src.k_scale) || src.k_scale <= 0.0 ||
|
||||
!std::isfinite(src.v_scale) || src.v_scale <= 0.0)) {
|
||||
fprintf(stderr, "radiance: HYV3 layer %d needs positive finite static K/V descales for "
|
||||
"its FP8 KV cache\n", l);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
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));
|
||||
@@ -122,23 +111,7 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, "neox"),
|
||||
{w.k}, {w.k});
|
||||
|
||||
if (fp8_cache) {
|
||||
k_descale = decl_b(b, nm.f("blk.%d.attn_k_descale", l), RAD_F32,
|
||||
{g.max_seqs, g.n_head_kv});
|
||||
v_descale = decl_b(b, nm.f("blk.%d.attn_v_descale", l), RAD_F32,
|
||||
{g.max_seqs, g.n_head_kv});
|
||||
op_k_descale = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", g.n_head_kv),
|
||||
RAD_STR("dtype", "f32"), RAD_F64("value", src.k_scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {k_descale});
|
||||
op_v_descale = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", g.n_head_kv),
|
||||
RAD_STR("dtype", "f32"), RAD_F64("value", src.v_scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {v_descale});
|
||||
}
|
||||
const rad_op attn = decl_attn(b, g, "attn_paged",
|
||||
const rad_op attn = rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
@@ -146,19 +119,17 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
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);
|
||||
op_attn = fp8_cache ? rw(b, attn, {w.q, k_descale, v_descale}, {w.attn.x})
|
||||
: rw(b, attn, {w.q}, {w.attn.x});
|
||||
op_attn = rw(b, attn, {w.q}, {w.attn.x});
|
||||
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_F64("k_scale", src.k_scale), RAD_F64("v_scale", src.v_scale)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* The standalone chain stays available for prefill, scaled/multicomponent rotary, FP8 KV,
|
||||
* and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five tiny
|
||||
/* The standalone chain stays available for prefill, scaled/multicomponent rotary, the int8
|
||||
* cache and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five tiny
|
||||
* launches; the fused kernel preserves the BF16 norm rounding before the rotary. */
|
||||
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
|
||||
!std::strcmp(g.kv_dtype, "bf16") &&
|
||||
@@ -195,9 +166,7 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
return op_attn && op_kv_store && (!add_out || op_add) &&
|
||||
(!fp8_cache || (k_descale && v_descale && op_k_descale && op_v_descale))
|
||||
? RAD_OK : RAD_E_INVAL;
|
||||
return op_attn && op_kv_store && (!add_out || op_add) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
@@ -223,21 +192,10 @@ inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE(c, op_kv_store, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, layer));
|
||||
}
|
||||
if (op_k_descale) {
|
||||
RAD_ISSUE_N(c, op_k_descale, batch->n_seq, brows(k_descale, batch->n_seq));
|
||||
RAD_ISSUE_N(c, op_v_descale, batch->n_seq, brows(v_descale, batch->n_seq));
|
||||
}
|
||||
if (k_descale && v_descale)
|
||||
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), brows(k_descale, batch->n_seq),
|
||||
brows(v_descale, batch->n_seq),
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), 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));
|
||||
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 (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
|
||||
@@ -56,7 +56,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model models[MAX_RANKS];
|
||||
static Model models[MAX_SLOTS];
|
||||
|
||||
static int check_format(const RadModelMeta* meta) {
|
||||
const char* q = meta && meta->quant ? meta->quant : "";
|
||||
@@ -153,8 +153,10 @@ static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = models[ctx->rank];
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = models[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
int status = check_format(meta);
|
||||
@@ -173,19 +175,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
status = check_model_config(meta, g, m);
|
||||
if (status < 0) return status;
|
||||
#if HYV3_FP8_SOURCE
|
||||
if ((ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 &&
|
||||
ctx->kv_dtype != RAD_F8E4M3) || ctx->kv_quant != RAD_KVQ_NONE) {
|
||||
fprintf(stderr, "radiance: HYV3 FP8 supports BF16 or plain E4M3 KV cache, not this layout\n");
|
||||
if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) {
|
||||
fprintf(stderr, "radiance: HYV3 serves a bf16 or an int8 KV cache, not %s\n",
|
||||
rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#else
|
||||
if ((ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16) ||
|
||||
ctx->kv_quant != RAD_KVQ_NONE) {
|
||||
fprintf(stderr, "radiance: HYV3 BF16 supports a BF16 KV cache only\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#endif
|
||||
status = yarn_from(g, meta, "", g.head_dim);
|
||||
if (status < 0) return status;
|
||||
|
||||
@@ -340,21 +334,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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);
|
||||
#endif
|
||||
#if HYV3_FP8_SOURCE
|
||||
if (kd.dtype == RAD_F8E4M3) {
|
||||
const std::string sk = "hyv3.kv_cache." + std::to_string(l) + ".k_scale";
|
||||
const std::string sv = "hyv3.kv_cache." + std::to_string(l) + ".v_scale";
|
||||
as.k_scale = meta_text_getf(meta, sk.c_str(), NAN);
|
||||
as.v_scale = meta_text_getf(meta, sv.c_str(), NAN);
|
||||
if (!std::isfinite(as.k_scale) || as.k_scale <= 0.0 ||
|
||||
!std::isfinite(as.v_scale) || as.v_scale <= 0.0) {
|
||||
fprintf(stderr, "radiance: hyv3_fp8: FP8 KV cache needs positive finite scales "
|
||||
"for layer %lld (metadata keys %s and %s)\n",
|
||||
(long long)l, sk.c_str(), sv.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
|
||||
// Each norm folds its predecessor's residual add. The first attention reads the
|
||||
@@ -462,7 +441,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[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));
|
||||
@@ -529,6 +508,8 @@ extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
|
||||
return &kHyv3ChatFormat;
|
||||
}
|
||||
extern "C" const char* rad_arch_id(void) { return "hyv3"; }
|
||||
/* 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 HYV3_QUANT; }
|
||||
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
|
||||
return HYV3_NS::declare(b, m, c);
|
||||
|
||||
+115
-41
@@ -33,10 +33,15 @@
|
||||
*
|
||||
* ============================== WHAT IS QUANTISED ==============================
|
||||
*
|
||||
* One plugin serves bf16 and block-fp8 containers: every linear of the language model, of the
|
||||
* text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16 throughout when the first
|
||||
* DiT projection is plain. txt_in, img_in, the timestep MLP and modulation, the final layer and
|
||||
* the VAE stay bf16.
|
||||
* One plugin serves bf16, block-fp8 and rotated int8 (IQ8R) containers: every linear of the
|
||||
* language model, of the text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16
|
||||
* throughout when the first DiT projection is plain. That projection also says whether the
|
||||
* linears are rotated int8: the activations they read then carry int8 codes in place of the E4M3
|
||||
* pair, written by the rotating twins of the fused ops where a library serves them
|
||||
* (rms_mod_had_quant_i8g for a modulated norm, gate_had_quant_i8g for an attention's output
|
||||
* gate); elsewhere the norm, or the sigmoid and multiply pair, is followed by the rotating
|
||||
* quantiser. txt_in, img_in, the timestep MLP and modulation, the final layer and the VAE stay
|
||||
* bf16.
|
||||
*
|
||||
* ============================== TENSOR PARALLEL ==============================
|
||||
*
|
||||
@@ -132,6 +137,9 @@ struct DitLayer {
|
||||
rad_op op_tab = 0; /* the shared modulation plus this block's table, into its columns */
|
||||
LinearFP8 qkv{}, gate{}, o{}, gate_up{}, down{};
|
||||
QuantFP8 q_attn{};
|
||||
/* The two modulated norms' quantisers for a rotated int8 model whose norms are the
|
||||
* unquantised form (Model::norm_i8 false). */
|
||||
QuantFP8 q_n1{}, q_n2{};
|
||||
GateQuantFP8 gq{};
|
||||
rad_op op_n1 = 0, op_n2 = 0, op_qkr = 0, op_attn = 0, op_gq = 0, op_sig = 0;
|
||||
rad_op op_ar1 = 0, op_ar2 = 0;
|
||||
@@ -189,6 +197,15 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
std::vector<DitLayer> dit;
|
||||
LinearFP8 qkv0{};
|
||||
/* The linears of every network are rotated int8 (IQ8R, or the 128-group int8 before it), read
|
||||
* off qkv0's probe: the activations then carry int8 code pairs with one scale per (token, `g8`
|
||||
* columns) in place of the E4M3 pair. */
|
||||
bool i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
/* Where a library serves the rotating twins, a DiT block's modulated norms write those int8
|
||||
* codes in their own pass (rms_mod_had_quant_i8g: norm_i8) and an attention's output gate
|
||||
* writes the out projection's (gate_had_quant_i8g: gate_i8, and fgate_i8 for the fusion blocks'). */
|
||||
bool norm_i8 = false, gate_i8 = false, fgate_i8 = false;
|
||||
rad_weight w_fn = 0, w_pout = 0, b_pout = 0;
|
||||
rad_op op_fn = 0, op_pout = 0, op_euler = 0;
|
||||
rad_buf b_fz = 0, b_v = 0;
|
||||
@@ -205,7 +222,7 @@ struct Model {
|
||||
std::string inv_std, mean, ones, zeros;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A space-separated list off the container (rad-convert flattens arrays that way). */
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
@@ -281,14 +298,27 @@ static rad_op zc_norm(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_we
|
||||
}
|
||||
|
||||
/* The attention's sigmoid output gate: `gate_quant_fp8` (gate, multiply and the out projection's
|
||||
* quantiser in one pass) over fp8 linears, or `sigmoid` then `mul` over bf16 ones and wherever no
|
||||
* loaded library declares the fused op (the out projection's quantiser then runs on its own).
|
||||
* Rows are (token, head) pairs of `head_dim` columns. Returns the gate op; `sig` is the pair's
|
||||
* sigmoid, written into `g` itself. */
|
||||
* quantiser in one pass) over fp8 linears, rows (token, head) pairs of `head_dim` columns; over
|
||||
* rotated int8 ones (`pair`) its rotating twin `gate_had_quant_i8g`, a token a row, since one
|
||||
* scale covers the codes' group across heads (`fused_i8` says so); or `sigmoid` then `mul` over
|
||||
* bf16 ones and wherever no loaded library declares the fused op (the out projection's quantiser
|
||||
* then runs on its own). Returns the gate op; `sig` is the pair's sigmoid, written into `g`
|
||||
* itself. */
|
||||
static rad_op out_gate(RadBuilder* b, const Geom& g, int64_t rows, int64_t width, rad_buf gate,
|
||||
const ActFP8& attn, rad_op* sig) {
|
||||
const ActFP8& attn, rad_op* sig, bool pair, bool* fused_i8) {
|
||||
const int64_t hd = g.head_dim;
|
||||
if (g.w_bf16 || !rad_op_declared(b, "gate_quant_fp8")) {
|
||||
*fused_i8 = false;
|
||||
if (pair && !g.w_bf16 && attn.q8_fed && attn.q8_rot && rad_op_declared(b, "gate_had_quant_i8g")) {
|
||||
*sig = 0;
|
||||
*fused_i8 = true;
|
||||
return rw(b, RAD_OP(b, "gate_had_quant_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_INT("group", attn.cg()), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ gate, attn.x }, { attn.cq(), attn.cs(), attn.x });
|
||||
}
|
||||
if (g.w_bf16 || pair || !rad_op_declared(b, "gate_quant_fp8")) {
|
||||
*sig = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
@@ -369,14 +399,17 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd, T));
|
||||
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", g.n_embd, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T));
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T));
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, T, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { (int64_t)kTeRows * kNTaps, g.n_embd });
|
||||
m.b_tidx = decl_b(b, nm.f("te.tap_idx"), RAD_I32, { T });
|
||||
|
||||
@@ -579,7 +612,7 @@ static int declare_fuse_block(RadBuilder* b, Model& m, FuseBlock& F, const char*
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_fqkv }, { m.a_fattn.x });
|
||||
F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig);
|
||||
F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig, m.i8, &m.fgate_i8);
|
||||
if (F.op_sig) RAD_ARCH_TRY(F.q_attn.declare(b, g, m.a_fattn, qd));
|
||||
RAD_ARCH_TRY(F.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL,
|
||||
grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) },
|
||||
@@ -610,15 +643,35 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const int64_t D = g.n_embd, qd = g.q_dim();
|
||||
const int64_t RL = (int64_t)kCondRows * kNTaps; /* the layer-wise blocks' rows */
|
||||
m.a_fh.x = decl_b(b, nm.f("fuse.h"), RAD_BF16, { RL, D });
|
||||
RAD_ARCH_TRY(m.a_fh.declare_qs(b, nm, g, "fuse.h", D, RL));
|
||||
RAD_ARCH_TRY(m.a_fh.declare_pair(b, nm, g, "fuse.h", D, RL, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_fqkv = decl_b(b, nm.f("fuse.qkv"), RAD_BF16, { RL, 3 * qd });
|
||||
m.b_fg = decl_b(b, nm.f("fuse.gate"), RAD_BF16, { RL, qd });
|
||||
m.a_fattn.x = decl_b(b, nm.f("fuse.attn"), RAD_BF16, { RL, qd });
|
||||
RAD_ARCH_TRY(m.a_fattn.declare_qs(b, nm, g, "fuse.attn", qd, RL));
|
||||
RAD_ARCH_TRY(m.a_fattn.declare_pair(b, nm, g, "fuse.attn", qd, RL, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_fo = decl_b(b, nm.f("fuse.o"), RAD_BF16, { RL, D });
|
||||
m.b_fgu = decl_b(b, nm.f("fuse.gate_up"), RAD_BF16, { RL, 2 * g.n_ff });
|
||||
m.a_fffn.x = decl_b(b, nm.f("fuse.ffn"), RAD_BF16, { RL, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_fffn.declare_qs(b, nm, g, "fuse.ffn", g.n_ff, RL));
|
||||
/* The feed-forward product's scale group is its reader's, the first block's down projection,
|
||||
* which a recipe may keep narrower than the other linears: the fusion's 6912-wide product is
|
||||
* 3456 a rank at two, which whole 128s tile and whole 256s do not (krea-2-iq8r.recipe). The
|
||||
* probe maps the weight through the block's own LinearFP8, which then does not map it again;
|
||||
* the resizes here keep the blocks the loops below declare. */
|
||||
const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2);
|
||||
const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2);
|
||||
m.lw.resize((size_t)nlw);
|
||||
m.rf.resize((size_t)nrf);
|
||||
int64_t ffn_g8 = m.g8;
|
||||
if (m.i8 && nlw + nrf > 0) {
|
||||
LinearFP8& d0 = nlw > 0 ? m.lw[0].down : m.rf[0].down;
|
||||
RAD_ARCH_TRY(d0.probe(b, nm, g, nm.f("fuse.0.ffn_down"),
|
||||
{ nm.ckpt("transformer.text_fusion.%s.0.ff.down.weight",
|
||||
nlw > 0 ? "layerwise_blocks" : "refiner_blocks") }));
|
||||
ffn_g8 = d0.probed_g8;
|
||||
}
|
||||
RAD_ARCH_TRY(m.a_fffn.declare_pair(b, nm, g, "fuse.ffn", g.n_ff, RL, m.i8, ffn_g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_fcu = decl_b(b, nm.f("fuse.cu"), RAD_I32, { kCondRows + 1 });
|
||||
m.b_ft = decl_b(b, nm.f("fuse.out"), RAD_BF16, { kCondRows, D });
|
||||
|
||||
@@ -628,10 +681,6 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_INT("step", kNTaps)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { m.b_fcu });
|
||||
const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2);
|
||||
const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2);
|
||||
m.lw.resize((size_t)nlw);
|
||||
m.rf.resize((size_t)nrf);
|
||||
for (int i = 0; i < nlw; ++i) {
|
||||
RAD_ARCH_TRY(declare_fuse_block(b, m, m.lw[(size_t)i],
|
||||
nm.f("transformer.text_fusion.layerwise_blocks.%d", i),
|
||||
@@ -645,7 +694,7 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
* served bf16 as diffusers runs them: a recipe casts them. */
|
||||
if (weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16) != RAD_BF16) {
|
||||
fprintf(stderr, "radiance: krea2: 'fuse.mix.weight' is stored %s; convert with "
|
||||
"data/recipes/krea-2-bf16.recipe or krea-2-fp8.recipe, which cast the "
|
||||
"data/recipes/krea-2-bf16.recipe or krea-2-iq8r.recipe, which cast the "
|
||||
"release's f32 tensors\n",
|
||||
rad_dtype_name(weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16)));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -789,15 +838,18 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
/* ---- the blocks */
|
||||
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
|
||||
RAD_ARCH_TRY(m.a_hm.declare_pair(b, nm, g, "dit.hm", D, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, qd + 2 * kvd });
|
||||
m.b_g = decl_b(b, nm.f("dit.gate"), RAD_BF16, { T, qd });
|
||||
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_pair(b, nm, g, "dit.attn", qd, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D });
|
||||
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_pair(b, nm, g, "dit.ffn", g.n_ff, 0, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
|
||||
const std::vector<double> ax = meta_list(meta, "transformer.axes_dims_rope");
|
||||
const int64_t a0 = ax.size() == 3 ? (int64_t)ax[0] : 32, a1 = ax.size() == 3 ? (int64_t)ax[1] : 48,
|
||||
@@ -811,12 +863,15 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const double theta = rad_meta_getf(meta, "transformer.rope_theta", 1000.0);
|
||||
|
||||
/* The modulated norm, gated by the branch before it when `gated`, into the next linear's
|
||||
* input (codes for fp8, the bf16 plane for bf16). */
|
||||
* input: codes for fp8 and, where the rotating twin is served, for rotated int8; the bf16
|
||||
* plane for bf16 and for rotated int8 without the twin, whose codes the rotating quantiser
|
||||
* then takes from it (DitLayer::q_n1 / q_n2). */
|
||||
m.norm_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "rms_mod_had_quant_i8g") != 0;
|
||||
auto mod_norm = [&](rad_weight w, bool gated) {
|
||||
const bool q = !g.w_bf16;
|
||||
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
|
||||
const bool q = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
rad_op op = q ? RAD_OP(b, m.norm_i8 ? "rms_mod_had_quant_i8g" : "rms_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("group", m.norm_i8 ? m.g8 : RAD_FP8_BLOCK),
|
||||
RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)),
|
||||
RAD_WEIGHTS(w))
|
||||
@@ -827,7 +882,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_WEIGHTS(w));
|
||||
if (!op) return op;
|
||||
rad_buf rd[3] = { m.b_mods, m.b_h, m.b_ao };
|
||||
rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h };
|
||||
rad_buf wq[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h };
|
||||
rad_buf wb[2] = { m.a_hm.x, m.b_h };
|
||||
rad_op_reads(b, op, rd, gated ? 3 : 2);
|
||||
if (q) rad_op_writes(b, op, wq, 3);
|
||||
@@ -866,6 +921,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
if (!B.w_tab || !B.op_tab) return RAD_E_INVAL;
|
||||
}
|
||||
B.op_n1 = mod_norm(B.w_n1, l > 0);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n1.declare(b, g, m.a_hm, D));
|
||||
if (l == 0) B.qkv = m.qkv0;
|
||||
RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), qd + 2 * kvd, D,
|
||||
RAD_SHARD_ROW, grp_layer(grp),
|
||||
@@ -893,13 +949,14 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_qkv }, { m.a_attn.x });
|
||||
B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig);
|
||||
B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig, m.i8, &m.gate_i8);
|
||||
if (B.op_sig) RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd));
|
||||
RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL,
|
||||
grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) },
|
||||
m.a_attn, m.b_ao));
|
||||
B.op_ar1 = all_reduce(b, g, m.b_ao, T);
|
||||
B.op_n2 = mod_norm(B.w_n2, true);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n2.declare(b, g, m.a_hm, D));
|
||||
RAD_ARCH_TRY(B.gate_up.declare(b, nm, g, nm.f("%s.ffn_gate_up", dn), 2 * g.n_ff, D,
|
||||
RAD_SHARD_ROW, grp_layer(grp),
|
||||
{ nm.ckpt("%s.ff.gate.weight", pre),
|
||||
@@ -1090,8 +1147,9 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
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(check_format(meta));
|
||||
@@ -1150,9 +1208,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.transformer_blocks.0.attn.to_k.weight",
|
||||
"transformer.transformer_blocks.0.attn.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
const bool known = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e);
|
||||
const bool plain = known && rad_enc_is(&e, "plain");
|
||||
gd.w_bf16 = gf.w_bf16 = m.gt.w_bf16 = plain;
|
||||
/* Or rotated int8 (IQ8R): the activations then carry int8 codes at the weights' scale
|
||||
* group in place of the E4M3 pair (ActFP8::declare_pair). */
|
||||
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
|
||||
if (m.i8) m.g8 = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
/* ---- the per-image state, the conditioning store, and in issue order the language model,
|
||||
@@ -1220,7 +1282,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.gt.rank, m.gt.world, m.turbo ? " Turbo" : "", kTaps[kNTaps - 1],
|
||||
(long long)m.gt.n_layer, m.lw.size(), m.rf.size(), (long long)gd.n_layer,
|
||||
(long long)gd.n_head, (long long)gd.n_head_kv, (long long)gd.n_ff,
|
||||
gd.w_bf16 ? "bf16" : "block-fp8");
|
||||
gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1284,6 +1346,9 @@ static void step_fuse(RadCtx* c, const Model& m, const FuseBlock& F, int64_t r0,
|
||||
RAD_ISSUE_N(c, F.op_sig, R, brows(m.b_fg, R), brows(m.b_fg, R));
|
||||
RAD_ISSUE_N(c, F.op_gq, R, brows(m.a_fattn.x, R), brows(m.b_fg, R), brows(m.a_fattn.x, R));
|
||||
F.q_attn.step(c, R);
|
||||
} else if (m.fgate_i8) {
|
||||
RAD_ISSUE_N(c, F.op_gq, R, brows(m.b_fg, R), brows(m.a_fattn.x, R),
|
||||
brows(m.a_fattn.cq(), R), brows(m.a_fattn.cs(), R), brows(m.a_fattn.x, R));
|
||||
} else {
|
||||
const int64_t rh = R * (qd / hd), nb = hd / RAD_FP8_BLOCK;
|
||||
RAD_ISSUE_N(c, F.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_fg), RAD_BF16, rh, hd),
|
||||
@@ -1368,7 +1433,7 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadOperand pos = praw2(G->rope_f, RAD_F32, 4, N);
|
||||
auto mod = [&](int64_t l, int k, int width) { return bcol_at(m.b_mods, 0, W, (6 * l + k) * D,
|
||||
width * D, S); };
|
||||
const bool q8 = !g.w_bf16;
|
||||
const bool q8 = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
const DitLayer& B = m.dit[(size_t)l];
|
||||
/* The block's modulation: the shared projection plus its own table, into its columns. */
|
||||
@@ -1377,11 +1442,13 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE,
|
||||
l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu,
|
||||
brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE);
|
||||
brows(m.b_h, N), brows(m.a_hm.cq(), N), brows(m.a_hm.cs(), N),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE,
|
||||
l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu,
|
||||
brows(m.b_h, N), brows(m.a_hm.x, N));
|
||||
B.q_n1.step(c, N);
|
||||
B.qkv.step(c, m.a_hm, m.b_qkv, N);
|
||||
B.gate.step(c, m.a_hm, m.b_g, N);
|
||||
RAD_ISSUE_N(c, B.op_qkr, N, brows(m.b_qkv, N), pos, RAD_W(B.w_qn), RAD_W(B.w_kn));
|
||||
@@ -1391,6 +1458,9 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
RAD_ISSUE_N(c, B.op_sig, N, brows(m.b_g, N), brows(m.b_g, N));
|
||||
RAD_ISSUE_N(c, B.op_gq, N, brows(m.a_attn.x, N), brows(m.b_g, N), brows(m.a_attn.x, N));
|
||||
B.q_attn.step(c, N);
|
||||
} else if (m.gate_i8) {
|
||||
RAD_ISSUE_N(c, B.op_gq, N, brows(m.b_g, N), brows(m.a_attn.x, N),
|
||||
brows(m.a_attn.cq(), N), brows(m.a_attn.cs(), N), brows(m.a_attn.x, N));
|
||||
} else {
|
||||
const int64_t rh = N * (qd / hd), nb = hd / RAD_FP8_BLOCK;
|
||||
RAD_ISSUE_N(c, B.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_g), RAD_BF16, rh, hd),
|
||||
@@ -1403,10 +1473,12 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
if (B.op_ar1) RAD_ISSUE_N(c, B.op_ar1, N * D, brows(m.b_ao, N), RAD_NONE);
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2),
|
||||
cu, brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE);
|
||||
cu, brows(m.b_h, N), brows(m.a_hm.cq(), N), brows(m.a_hm.cs(), N),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2),
|
||||
cu, brows(m.b_h, N), brows(m.a_hm.x, N));
|
||||
B.q_n2.step(c, N);
|
||||
B.gate_up.step(c, m.a_hm, m.b_gu, N);
|
||||
B.gq.step(c, m.b_gu, N);
|
||||
B.down.step(c, m.a_ffn, m.b_ao, N);
|
||||
@@ -1467,7 +1539,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "krea2 is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1493,6 +1565,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(krea2)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(krea2, "krea2", "", "0.1.0",
|
||||
"Krea 2 / Krea 2 Turbo: Qwen3-VL-4B taps through a text-fusion transformer, a 12.9B "
|
||||
"single-stream diffusion transformer over the joint text and image, and Wan 2.1's "
|
||||
|
||||
+7
-4
@@ -74,7 +74,7 @@ struct Model {
|
||||
std::vector<HeadLayer> head;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
@@ -115,7 +115,8 @@ static int sliding_layers(const RadModelMeta* meta, int64_t n_layer, std::vector
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: laya runs on one card (--tp 1); the largest checkpoint is "
|
||||
"0.4B parameters\n");
|
||||
@@ -124,7 +125,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RadArchProbe pr{};
|
||||
RAD_ARCH_TRY(probe(meta, &pr));
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
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));
|
||||
@@ -409,7 +410,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd, F = m.F;
|
||||
const int64_t P = RAD_LAYA_POOLED;
|
||||
@@ -523,6 +524,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
|
||||
} /* namespace laya */
|
||||
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(laya, "laya", "", "0.1.0",
|
||||
"Convai Innovations' Laya (laya, laya-typed-decisions, laya-multilingual): a "
|
||||
"ModernBERT encoder and a decision head scoring each option at its [MASK], one "
|
||||
|
||||
@@ -28,8 +28,9 @@
|
||||
* block E4M3 (`codes=fp8_e4m3 block=128x128 scale=bf16`) is `gemm_nt_q` at fp8a8 over the
|
||||
* activation quantised per 128 columns (one quant_act_fp8 per activation, shared by the linears
|
||||
* that read it); int8 (`codes=i8 group=128 scale=bf16`) is `gemm_nt_q` at i8a8, each linear
|
||||
* quantising its input. The trunk's format is read off layer 0's down projection and every linear
|
||||
* must match it. The convolution, the norms and attention stay bf16; the lm_head is read at its
|
||||
* quantising its input, and IQ8R (rotated int8 with a scale per 256 of K,
|
||||
* data/recipes/d1-3b-iq8r.recipe) the same at i8a8h with the activation pairs at the weights'
|
||||
* group. The trunk's format is read off layer 0's first linear and every linear must match it. The convolution, the norms and attention stay bf16; the lm_head is read at its
|
||||
* stored codes (bf16, or E4M3 / int8 where a recipe made it so; logits_gemm_fp8 / _i8). At d1-3B
|
||||
* the linears are 5.8 of the 6.3 GB a token reads, so 8-bit codes nearly halve decode and short
|
||||
* prefill, both bound by that read.
|
||||
@@ -106,6 +107,8 @@ struct Model {
|
||||
/* The trunk's format, read off layer 0's first linear. `fused`: the fp8 trunk's fused
|
||||
* producers (see the head of the file). */
|
||||
bool q_fp8 = false, q_i8 = false, fused = false;
|
||||
/* An int8 trunk's scale group along K, which its activation pairs share (ActFP8::g8). */
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
|
||||
@@ -118,7 +121,7 @@ struct Model {
|
||||
MediaRows mrows{};
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A text_config key first, then the top level: a VL checkpoint nests the text model's settings
|
||||
* and a text checkpoint does not. */
|
||||
@@ -166,7 +169,9 @@ static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Lay
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: lfm2_bf16 serves one rank; run it with --tp 1\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -178,7 +183,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -290,14 +295,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
enc.plane[0].dtype == RAD_BF16);
|
||||
g.w_bf16 = plain;
|
||||
m.q_i8 = !plain && L0.in.probed_i8;
|
||||
if (m.q_i8) m.g8 = L0.in.probed_g8;
|
||||
m.q_fp8 = !plain && !m.q_i8;
|
||||
m.fused = m.q_fp8;
|
||||
}
|
||||
if (m.q_i8 && (g.n_embd % m.g8 || g.q_dim() % m.g8 || g.n_ff % m.g8)) {
|
||||
fprintf(stderr, "radiance: lfm2: the int8 trunk keeps one scale a %lld of K, which does not "
|
||||
"divide this model's widths (hidden %lld, attention %lld, feed-forward "
|
||||
"%lld)\n",
|
||||
(long long)m.g8, (long long)g.n_embd, (long long)g.q_dim(), (long long)g.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.a_h.x = m.b_h; m.a_attn.x = m.b_attn; m.a_conv.x = m.b_conv_out; m.a_ffn.x = m.b_ffn;
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8));
|
||||
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8));
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8, true, m.g8));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8, true, m.g8));
|
||||
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8, true, m.g8));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8, true, m.g8));
|
||||
/* An E4M3 activation is quantised once by the model and read by every linear on it; an int8
|
||||
* linear quantises its own input (LinearFP8::op_q), and a bf16 one reads the bf16 plane. */
|
||||
auto quant = [&](QuantFP8& q, const ActFP8& a, int64_t n) {
|
||||
@@ -471,7 +484,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ms.up = nm.ckpt(ffn_fmt, pre, l, "w3.weight");
|
||||
ms.down = nm.ckpt(ffn_fmt, pre, l, "w2.weight");
|
||||
const bool last = l + 1 == (int)m.layers.size();
|
||||
/* The whole prompt in the fold: gemm_nt_q_gated_wide serves every M, so a prefill
|
||||
/* The whole prompt in the fold (`wide_fold`): its row serves every M, so a prefill
|
||||
* chunk does not fall back to the pair past 64 rows. */
|
||||
RAD_ARCH_TRY(L.mlp8.declare(b, nm, g, l, mw, ms, /*fold=*/true, /*add_out=*/last,
|
||||
0, false, 0, /*wide_fold=*/true));
|
||||
@@ -572,7 +585,7 @@ static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch*
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
if (batch->draft_pass || batch->spec_parent ||
|
||||
(!m.media && (batch->enc || batch->n_mm_rows > 0))) {
|
||||
@@ -663,9 +676,23 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Chained launches pay on the plain-bf16 trunk: its GEMMs, norms and elementwise kernels have
|
||||
* chained forms (libr4d's rad_kernel_chain); the head norms, the rotary and the convolution keep
|
||||
* their plain rows, with which the long GEMMs between them run faster. The 3B text model on one
|
||||
* R9700, ms a decode step unchained / chained: 12.14 / 11.31 at one sequence and 12.54 / 11.60 at
|
||||
* four. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace lfm2_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PROBE(lfm2_bf16)
|
||||
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.2.0",
|
||||
"LiquidAI LFM2 / LFM2-VL, bf16, or with block-fp8 or int8 linears from a recipe: "
|
||||
"short gated convolutions and GQA attention in the checkpoint's own schedule, one "
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/lfm3_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(lfm3_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(lfm3_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/lfm3_bf16.cpp)
|
||||
@@ -0,0 +1,779 @@
|
||||
/* lfm3_bf16 -- LiquidAI's LFM3, bf16 activations over bf16 or int8 (IQ8R) linears, one rank.
|
||||
*
|
||||
* ============================== THE SHAPE ==============================
|
||||
*
|
||||
* LFM2's hybrid with a third layer kind, in the order the checkpoint's `layer_types` lists them
|
||||
* (read, not derived):
|
||||
*
|
||||
* conv in_proj -> [B | C | x], y = out_proj(C * conv(B * x)), where conv is a
|
||||
* depthwise causal convolution of width `conv_L_cache` with no activation
|
||||
* full_attention GQA with per-head RMS norms on q and k, a partial NeoX rotary on the "head"
|
||||
* ladder (the first `partial_rotary_factor * head_dim` channels rotate, at the
|
||||
* frequencies of the whole head; the rest do not), and a gate per query head
|
||||
* sliding_attention the same attention over the last `sliding_window` tokens, its rotary over
|
||||
* the whole head at its own theta
|
||||
*
|
||||
* each followed by a SwiGLU feed-forward (w1 the gate, w3 the up, w2 the down). The norms are a
|
||||
* sandwich: `operator_norm` before the mixer and `post_operator_norm` on its output, before the
|
||||
* residual add; `ffn_norm` and `post_ffn_norm` likewise. Every norm is a plain RMSNorm
|
||||
* (`x_hat * w`), and the final one is `embedding_norm`. A post norm, its add and the norm that
|
||||
* reads the sum are one `norm_add_norm` where a library serves it (Gemma's sandwich join; see
|
||||
* declare). At 1.7B: 24 layers (13 conv, 6 full, 5
|
||||
* sliding with a window of 256), hidden 2048, 16 heads over 4 at head_dim 128, ffn 7680,
|
||||
* vocabulary 128000 with the lm_head tied to the embedding, conv width 7; theta 1e6 over half the
|
||||
* head on the full layers, 1e4 on the sliding ones.
|
||||
*
|
||||
* ============================== THE GATE ==============================
|
||||
*
|
||||
* The attention output of each query head is multiplied by sigmoid(gate_proj(h)), one scalar a
|
||||
* (token, head), before the out projection. `mul` multiplies planes of equal width, so the gate
|
||||
* is computed at the output's width: the name map repeats each of gate_proj's n_head rows head_dim
|
||||
* times (RAD_MAP_ROWS), and `gemm_nt` + `sigmoid` + `mul` then give every channel of a head that
|
||||
* head's gate, with the reference's rounding (the gate and the product are each a bf16 tensor
|
||||
* there). It costs n_embd * (q_dim - n_head) stored weights an attention layer, 2.6% of the
|
||||
* container at 1.7B.
|
||||
*
|
||||
* ============================== 8-BIT LINEARS ==============================
|
||||
*
|
||||
* Every linear but the gate is a LinearFP8 (rad_fp8.h), as lfm2_bf16's are, so the container's
|
||||
* encoding of each weight decides the GEMM: plain bf16 is `gemm_nt` over the bf16 activation,
|
||||
* exactly as a bf16 model runs; int8 (`codes=i8 group=128 scale=bf16`) is `gemm_nt_q` at i8a8, and
|
||||
* the rotated form (those codes under the 128-wide Hadamard, data/recipes/lfm3-1.7b-iq8r.recipe,
|
||||
* or IQ8R's scale per 256 of K) the same at i8a8h, each linear quantising its input from
|
||||
* the bf16 plane. The trunk's format is read off layer 0's first linear and every linear must
|
||||
* match it. The gate stays bf16 in every container (n_head distinct rows; its product is a hard
|
||||
* multiplier on a whole head), as do the convolution, the norms, the joins and attention. The
|
||||
* lm_head is read at its stored codes.
|
||||
*
|
||||
* ============================== WHAT IT DOES NOT SERVE ==============================
|
||||
*
|
||||
* Tensor parallelism (the model needs one card), block-fp8 or narrower linears, a trunk that mixes
|
||||
* formats, a quantised gate, a drafter, media, conv bias, a checkpoint without the sandwich norms,
|
||||
* or a rotary other than the default type: each is refused by name.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace lfm3_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
enum Kind { kConv = 0, kFull = 1, kSliding = 2 };
|
||||
|
||||
/* One plain bf16 linear: its weight and the gemm_nt over it. The attention gate is the one linear
|
||||
* declared this way: its weight is gate_proj's rows repeated, which the shared LinearFP8 that
|
||||
* serves every other linear does not map. */
|
||||
struct Linear {
|
||||
rad_weight w = 0;
|
||||
rad_op op = 0;
|
||||
};
|
||||
|
||||
/* What differs between the two attention classes. */
|
||||
struct AttnClass {
|
||||
double theta = 0.0;
|
||||
int64_t rot = 0; /* rotary_dim */
|
||||
int64_t window = 0; /* 0: full */
|
||||
rad_kvgroup kv = 0;
|
||||
};
|
||||
|
||||
struct Layer {
|
||||
Kind kind = kConv;
|
||||
rad_weight w_norm = 0, w_post_norm = 0, w_ffn_norm = 0, w_ffn_post_norm = 0;
|
||||
rad_op op_norm = 0, op_post_norm = 0, op_add = 0;
|
||||
/* conv */
|
||||
LinearFP8 conv_in, conv_out;
|
||||
rad_weight w_conv = 0;
|
||||
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
|
||||
/* attention */
|
||||
LinearFP8 q, k, v, out;
|
||||
Linear gate;
|
||||
rad_weight w_q_norm = 0, w_k_norm = 0;
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_store = 0, op_attn = 0, op_sigmoid = 0, op_gate_mul = 0;
|
||||
/* the feed-forward: norm, gate|up (w1 | w3), SiLU(gate) * up, down (w2), norm, residual add */
|
||||
LinearFP8 gate_up, down;
|
||||
rad_op op_ffn_norm = 0, op_act = 0, op_ffn_post_norm = 0, op_ffn_add = 0;
|
||||
/* The sandwich joins, fused: op_join is post_norm + add + ffn_norm, and op_ffn_join is
|
||||
* ffn_post_norm + ffn_add + the next layer's norm, which that layer then does not declare. */
|
||||
rad_op op_join = 0, op_ffn_join = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
int64_t width = 0; /* conv_L_cache: the convolution's taps */
|
||||
AttnClass full{}, sliding{};
|
||||
rad_kvgroup kv_conv = 0;
|
||||
|
||||
rad_buf b_x = 0, b_h = 0, b_arm = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
|
||||
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate = 0, b_gate_up = 0, b_ffn = 0;
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
/* The four activations a linear reads, as LinearFP8 takes them: the bf16 plane is the buffer
|
||||
* above. */
|
||||
ActFP8 a_h{}, a_attn{}, a_conv{}, a_ffn{};
|
||||
/* An int8 trunk (i8a8, or IQ8R at i8a8h), and its scale group along K, which the activations'
|
||||
* int8 pairs share (ActFP8::g8). */
|
||||
bool q_i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
const AttnClass& cls(const Layer& L) const { return L.kind == kSliding ? sliding : full; }
|
||||
};
|
||||
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int64_t meta_int(const RadModelMeta* m, const char* key, int64_t dflt) {
|
||||
const char* v = rad_meta_gets(m, key, nullptr);
|
||||
return v ? std::strtoll(v, nullptr, 10) : dflt;
|
||||
}
|
||||
static double meta_f64(const RadModelMeta* m, const char* key, double dflt) {
|
||||
const char* v = rad_meta_gets(m, key, nullptr);
|
||||
return v ? std::strtod(v, nullptr) : dflt;
|
||||
}
|
||||
static bool meta_bool(const RadModelMeta* m, const char* key, bool dflt) {
|
||||
const char* v = rad_meta_gets(m, key, nullptr);
|
||||
if (!v) return dflt;
|
||||
return std::strcmp(v, "true") == 0 || std::strcmp(v, "1") == 0;
|
||||
}
|
||||
|
||||
/* `layer_types`, one word per layer, space-separated in the container. */
|
||||
static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Layer>* out) {
|
||||
const char* s = rad_meta_gets(m, "layer_types", nullptr);
|
||||
if (!s || !*s) {
|
||||
fprintf(stderr, "radiance: lfm3: the container has no layer_types; this family's schedule "
|
||||
"is read, not derived\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
std::istringstream in(s);
|
||||
std::string kind;
|
||||
while (in >> kind) {
|
||||
Layer l;
|
||||
if (kind == "conv") l.kind = kConv;
|
||||
else if (kind == "full_attention") l.kind = kFull;
|
||||
else if (kind == "sliding_attention") l.kind = kSliding;
|
||||
else {
|
||||
fprintf(stderr, "radiance: lfm3: layer_types[%zu] is '%s'; this plugin knows 'conv', "
|
||||
"'full_attention' and 'sliding_attention'\n", out->size(), kind.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
out->push_back(l);
|
||||
}
|
||||
if ((int64_t)out->size() != n_layer) {
|
||||
fprintf(stderr, "radiance: lfm3: layer_types names %zu layers and the model has %lld\n",
|
||||
out->size(), (long long)n_layer);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One class's rotary from `rope_parameters.<type>`: theta is required (the typed rope_theta is a
|
||||
* top-level key this family does not write), the type must be the default, and the partial factor
|
||||
* gives an even rotary width inside the head. */
|
||||
static int read_rotary(const RadModelMeta* m, const char* type, int64_t head_dim, AttnClass* c) {
|
||||
const std::string pre = std::string("rope_parameters.") + type + ".";
|
||||
const char* rt = rad_meta_gets(m, (pre + "rope_type").c_str(), "default");
|
||||
if (std::strcmp(rt, "default") != 0) {
|
||||
fprintf(stderr, "radiance: lfm3: rope_parameters.%s.rope_type '%s' is not 'default'\n",
|
||||
type, rt);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
c->theta = meta_f64(m, (pre + "rope_theta").c_str(), 0.0);
|
||||
if (!(c->theta > 0.0)) {
|
||||
fprintf(stderr, "radiance: lfm3: rope_parameters.%s.rope_theta is required\n", type);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const double prf = meta_f64(m, (pre + "partial_rotary_factor").c_str(), 1.0);
|
||||
/* the reference's int(prf * head_dim) // 2 angles */
|
||||
c->rot = 2 * ((int64_t)(prf * (double)head_dim) / 2);
|
||||
if (!(prf > 0.0) || c->rot < 2 || c->rot > head_dim) {
|
||||
fprintf(stderr, "radiance: lfm3: rope_parameters.%s.partial_rotary_factor %g gives a "
|
||||
"rotary width %lld outside 2..head_dim\n", type, prf, (long long)c->rot);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
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;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: lfm3_bf16 serves one rank; run it with --tp 1\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (meta->n_expert > 0 || meta_bool(meta, "conv_bias", false) ||
|
||||
!meta_bool(meta, "use_sandwich_norm", true)) {
|
||||
fprintf(stderr, "radiance: lfm3_bf16 serves the dense SwiGLU model with sandwich norms, "
|
||||
"gated attention and bias-free convolutions; this checkpoint is not that\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &m.layers));
|
||||
m.width = meta_int(meta, "conv_L_cache", 0);
|
||||
if (m.width < 2 || m.width > 8) {
|
||||
fprintf(stderr, "radiance: lfm3: conv_L_cache %lld is outside the 2..8 the convolution "
|
||||
"kernels serve\n", (long long)m.width);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
bool has_full = false, has_sliding = false, has_conv = false;
|
||||
for (const Layer& L : m.layers) {
|
||||
has_full |= L.kind == kFull;
|
||||
has_sliding |= L.kind == kSliding;
|
||||
has_conv |= L.kind == kConv;
|
||||
}
|
||||
if (has_full) RAD_ARCH_TRY(read_rotary(meta, "full_attention", g.head_dim, &m.full));
|
||||
if (has_sliding) {
|
||||
RAD_ARCH_TRY(read_rotary(meta, "sliding_attention", g.head_dim, &m.sliding));
|
||||
m.sliding.window = meta_int(meta, "sliding_window", 0);
|
||||
if (m.sliding.window < 1) {
|
||||
fprintf(stderr, "radiance: lfm3: the sliding_attention layers need a sliding_window, "
|
||||
"and the container has %lld\n", (long long)m.sliding.window);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
const char* pre = "model";
|
||||
|
||||
/* ---- the state groups: paged KV for the full layers, the same bounded by the window for the
|
||||
* sliding ones, and a rolling window of the convolution's last width-1 inputs (plus the
|
||||
* speculative slack the manager adds) for the conv layers. The conv group's channels are
|
||||
* n_head_kv * head_dim: one "head" of n_embd. */
|
||||
const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
g.kv_dtype = rad_dtype_name(kvdt);
|
||||
if (has_full) {
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = RAD_KV_FULL;
|
||||
fd.dtype = kvdt;
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
m.full.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
if (!m.full.kv) return RAD_E_INVAL;
|
||||
}
|
||||
if (has_sliding) {
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_WINDOW;
|
||||
sd.dtype = kvdt;
|
||||
sd.window = m.sliding.window;
|
||||
sd.n_head_kv = g.n_head_kv;
|
||||
sd.head_dim = g.head_dim;
|
||||
m.sliding.kv = rad_decl_kv_group(b, nm.f("kv_sliding"), &sd);
|
||||
if (!m.sliding.kv) return RAD_E_INVAL;
|
||||
}
|
||||
if (has_conv) {
|
||||
RadKVGroupDecl cd{};
|
||||
cd.kind = RAD_KV_CONV;
|
||||
cd.dtype = RAD_BF16;
|
||||
cd.n_head_kv = 1;
|
||||
cd.head_dim = g.n_embd;
|
||||
cd.conv_width = m.width;
|
||||
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_conv"), &cd);
|
||||
if (!m.kv_conv) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
/* a mixer's or a feed-forward's output, before its post norm: a join reads it beside x and
|
||||
* writes h, so it is not h */
|
||||
m.b_arm = decl_b(b, nm.f("arm"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_bcx = decl_b(b, nm.f("conv_bcx"), RAD_BF16, {g.max_tok, 3 * g.n_embd});
|
||||
m.b_conv_in = decl_b(b, nm.f("conv_in"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_conv_out = decl_b(b, nm.f("conv_out"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_q = decl_b(b, nm.f("attn_q"), RAD_BF16, {g.max_tok, g.q_dim()});
|
||||
m.b_k = decl_b(b, nm.f("attn_k"), RAD_BF16, {g.max_tok, g.kv_dim()});
|
||||
m.b_v = decl_b(b, nm.f("attn_v"), RAD_BF16, {g.max_tok, g.kv_dim()});
|
||||
m.b_attn = decl_b(b, nm.f("attn_out"), RAD_BF16, {g.max_tok, g.q_dim()});
|
||||
m.b_gate = decl_b(b, nm.f("attn_gate"), RAD_BF16, {g.max_tok, g.q_dim()});
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), RAD_BF16, {g.max_tok, 2 * g.n_ff});
|
||||
m.b_ffn = decl_b(b, nm.f("ffn"), RAD_BF16, {g.max_tok, g.n_ff});
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {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 trunk's format, read off layer 0's first linear before any activation is declared
|
||||
* (probe() makes its name map and reads its encoding). Plain bf16, or no encoding yet, is a
|
||||
* bf16 trunk: every linear is `gemm_nt` over its input's bf16 plane. An int8 weight makes the
|
||||
* activations carry int8 codes beside it. */
|
||||
{
|
||||
Layer& L0 = m.layers[0];
|
||||
const bool at = L0.kind != kConv;
|
||||
LinearFP8& first = at ? L0.q : L0.conv_in;
|
||||
const char* base0 = nm.f(at ? "blk.%d.attn_q" : "blk.%d.conv_in", 0);
|
||||
RAD_ARCH_TRY(first.probe(b, nm, g, base0,
|
||||
{ nm.ckpt(at ? "%s.layers.%d.self_attn.%s" : "%s.layers.%d.conv.%s",
|
||||
pre, 0, at ? "q_proj.weight" : "in_proj.weight") }));
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, nm.f("%s.weight", base0), &enc);
|
||||
const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16);
|
||||
g.w_bf16 = plain;
|
||||
m.q_i8 = !plain && first.probed_i8;
|
||||
if (m.q_i8) m.g8 = first.probed_g8;
|
||||
if (!plain && !m.q_i8) {
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
fprintf(stderr, "radiance: lfm3: '%s.weight' is %s; this plugin serves a bf16 trunk or "
|
||||
"an int8 one (codes=i8 group=128, or IQ8R)\n", base0, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
if (m.q_i8 && (g.n_embd % m.g8 || g.q_dim() % m.g8 || g.n_ff % m.g8)) {
|
||||
fprintf(stderr, "radiance: lfm3: the int8 trunk keeps one scale a %lld of K, which does not "
|
||||
"divide this model's widths (hidden %lld, attention %lld, feed-forward "
|
||||
"%lld)\n",
|
||||
(long long)m.g8, (long long)g.n_embd, (long long)g.q_dim(), (long long)g.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.a_h.x = m.b_h; m.a_attn.x = m.b_attn; m.a_conv.x = m.b_conv_out; m.a_ffn.x = m.b_ffn;
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8, false, m.g8));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8, false, m.g8));
|
||||
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8, false, m.g8));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8, false, m.g8));
|
||||
|
||||
/* ---- the vocabulary edges. The lm_head is tied but declared as its own weight: the
|
||||
* embedding may live in host memory (--embedding-placement) and the head on the card. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.embedding_norm.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("%s.embed_tokens.weight", pre)));
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
/* The head at its codes' dtype: bf16, or int8 where a recipe made it so. */
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
|
||||
/* `op`: "rmsnorm", or "rmsnorm_rows" for the head norms, whose short-row form a prefill's
|
||||
* thousands of head_dim-wide rows take. */
|
||||
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out,
|
||||
const char* op = "rmsnorm") {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w)),
|
||||
{in}, {out});
|
||||
};
|
||||
auto add = [&](rad_buf x, rad_buf h) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{x, h}, {x});
|
||||
};
|
||||
auto mul = [&](std::initializer_list<rad_buf> rd, rad_buf out, int64_t n) {
|
||||
return rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
rd, {out});
|
||||
};
|
||||
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
|
||||
uint32_t dtype) {
|
||||
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
};
|
||||
/* A norm's gain: mapped, and declared f32. */
|
||||
auto norm_w = [&](rad_weight* w, const char* name, int l, const char* src, int64_t n) -> int {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f(name, l), src));
|
||||
*w = layer_w(name, l, {n}, RAD_F32);
|
||||
return *w ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
/* The gate: one plain bf16 linear over an already mapped weight, in every container. */
|
||||
auto plain_linear = [&](Linear& lin, int l, const char* name, int64_t N, int64_t K, rad_buf in,
|
||||
rad_buf out) -> int {
|
||||
RadEncoding enc{};
|
||||
if (weight_enc(b, nm.f(name, l), &enc) &&
|
||||
!(rad_enc_is(&enc, "plain") && enc.n_planes == 1 && enc.plane[0].dtype == RAD_BF16)) {
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
fprintf(stderr, "radiance: lfm3: '%s' is %s; the attention gate stays bf16 (leave "
|
||||
"gate_proj out of the recipe)\n", nm.f(name, l), en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
lin.w = decl_w(b, nm.f(name, l), RAD_BF16, {N, K}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
if (!lin.w) return RAD_E_INVAL;
|
||||
lin.op = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lin.w)),
|
||||
{in}, {out});
|
||||
return lin.op ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
/* One linear: `base` is the declared name without `.weight`, `src` its checkpoint tensor (or
|
||||
* the tensors stacked along its rows, `parts` their row counts), `a` the activation it reads. */
|
||||
auto linear = [&](LinearFP8& lin, int l, const char* base_fmt, int64_t N, int64_t K,
|
||||
std::initializer_list<const char*> src, const ActFP8& a, rad_buf y,
|
||||
std::initializer_list<int64_t> parts) -> int {
|
||||
const char* base = nm.f(base_fmt, l);
|
||||
RAD_ARCH_TRY(lin.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(l), src, a, y, 0,
|
||||
parts));
|
||||
/* Every linear has the trunk's format. LinearFP8 refuses a quantised weight in a bf16
|
||||
* trunk; this refuses a bf16 or narrower one in an int8 trunk. */
|
||||
if (g.w_bf16 ? !lin.bf16 : !(lin.i8 && !lin.iqr)) {
|
||||
fprintf(stderr, "radiance: lfm3: '%s.weight' is not in the trunk's format (%s); "
|
||||
"quantise every linear of the trunk alike\n",
|
||||
base, g.w_bf16 ? "bf16" : "int8");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
/* q names its query heads; k is rotated as a q-only row of the kv heads (its own buffer).
|
||||
* The partial rotary is on the "head" ladder; over the whole head the ladders coincide and
|
||||
* the parameter is left out. */
|
||||
auto rope = [&](const AttnClass& c, int64_t heads, rad_buf buf) {
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", c.theta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", "neox"), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_STR("ladder", "head") };
|
||||
const int n = (int)(sizeof ps / sizeof ps[0]) - (c.rot < g.head_dim ? 0 : 1);
|
||||
return rw(b, rad_decl_op(b, "rope_rows", ps, n, nullptr, 0), {buf}, {buf});
|
||||
};
|
||||
|
||||
|
||||
/* ---- the sandwich joins. `norm_add_norm` is a post norm, the residual add and the norm that
|
||||
* reads the sum in one launch: post_norm + add + ffn_norm inside a layer, and ffn_post_norm +
|
||||
* add + the next layer's norm between two. It rounds where the chain rounds. The device
|
||||
* libraries serve it and libref and libavx do not, and declaring an op no loaded library
|
||||
* declares is an error, so it is asked for first; without it, or where it does not resolve,
|
||||
* the rmsnorm / add / rmsnorm chain runs. The last layer's feed-forward keeps the chain: the
|
||||
* final norm is on the gathered rows. */
|
||||
const bool has_join = rad_op_declared(b, "norm_add_norm") != 0;
|
||||
auto join = [&](rad_weight w_a, rad_weight w_y) {
|
||||
return rw(b, RAD_OP(b, "norm_add_norm",
|
||||
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_WEIGHTS(w_a, w_y)),
|
||||
{m.b_arm, m.b_x}, {m.b_x, m.b_h});
|
||||
};
|
||||
int n_joins = 0;
|
||||
|
||||
/* Every layer's input norm gain, ahead of the layers: a feed-forward join names the next
|
||||
* layer's, and an op can only name weights already declared. */
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l)
|
||||
RAD_ARCH_TRY(norm_w(&m.layers[(size_t)l].w_norm, "blk.%d.attn_norm.weight", l,
|
||||
nm.ckpt("%s.layers.%d.%s", pre, l, "operator_norm.weight"), g.n_embd));
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
Layer& L = m.layers[(size_t)l];
|
||||
const char* lay = "%s.layers.%d.%s";
|
||||
RAD_ARCH_TRY(norm_w(&L.w_post_norm, "blk.%d.attn_post_norm.weight", l,
|
||||
nm.ckpt(lay, pre, l, "post_operator_norm.weight"), g.n_embd));
|
||||
RAD_ARCH_TRY(norm_w(&L.w_ffn_norm, "blk.%d.ffn_norm.weight", l,
|
||||
nm.ckpt(lay, pre, l, "ffn_norm.weight"), g.n_embd));
|
||||
RAD_ARCH_TRY(norm_w(&L.w_ffn_post_norm, "blk.%d.ffn_post_norm.weight", l,
|
||||
nm.ckpt(lay, pre, l, "post_ffn_norm.weight"), g.n_embd));
|
||||
/* written by the layer before, where its feed-forward join is fused */
|
||||
if (!(l > 0 && m.layers[(size_t)l - 1].op_ffn_join))
|
||||
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
|
||||
|
||||
if (L.kind != kConv) {
|
||||
const AttnClass& c = m.cls(L);
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, c.kv));
|
||||
const char* a = "%s.layers.%d.self_attn.%s";
|
||||
/* The gate at the output's width: row h of gate_proj, head_dim times, for each head
|
||||
* in turn (see the head of the file). Successive ROWS maps extend the weight. */
|
||||
{
|
||||
const std::string dst = nm.f("blk.%d.attn_gate.weight", l);
|
||||
const std::string src = nm.ckpt(a, pre, l, "gate_proj.weight");
|
||||
for (int64_t h = 0; h < g.n_head; ++h)
|
||||
for (int64_t d = 0; d < g.head_dim; d += 8) {
|
||||
RadNameMap mp = map_base(dst.c_str(), RAD_MAP_ROWS);
|
||||
for (int64_t i = d; i < g.head_dim && i < d + 8; ++i) {
|
||||
mp.src[mp.n_src] = src.c_str();
|
||||
mp.src_index[mp.n_src] = (int)h;
|
||||
mp.src_rows[mp.n_src] = 1;
|
||||
++mp.n_src;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_decl_name_map(b, &mp));
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(linear(L.q, l, "blk.%d.attn_q", g.q_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "q_proj.weight") }, m.a_h, m.b_q, {}));
|
||||
RAD_ARCH_TRY(linear(L.k, l, "blk.%d.attn_k", g.kv_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "k_proj.weight") }, m.a_h, m.b_k, {}));
|
||||
RAD_ARCH_TRY(linear(L.v, l, "blk.%d.attn_v", g.kv_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "v_proj.weight") }, m.a_h, m.b_v, {}));
|
||||
RAD_ARCH_TRY(plain_linear(L.gate, l, "blk.%d.attn_gate.weight", g.q_dim(), g.n_embd,
|
||||
m.b_h, m.b_gate));
|
||||
RAD_ARCH_TRY(norm_w(&L.w_q_norm, "blk.%d.attn_q_norm.weight", l,
|
||||
nm.ckpt(a, pre, l, "q_norm.weight"), g.head_dim));
|
||||
RAD_ARCH_TRY(norm_w(&L.w_k_norm, "blk.%d.attn_k_norm.weight", l,
|
||||
nm.ckpt(a, pre, l, "k_norm.weight"), g.head_dim));
|
||||
|
||||
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
|
||||
* T * heads rows. */
|
||||
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q,
|
||||
"rmsnorm_rows");
|
||||
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k,
|
||||
"rmsnorm_rows");
|
||||
L.op_rope_q = rope(c, g.n_head, m.b_q);
|
||||
L.op_rope_k = rope(c, g.n_head_kv, m.b_k);
|
||||
/* attn_paged before kv_store: the cache's block size is read from the resolved
|
||||
* attention kernel. */
|
||||
L.op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
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", c.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});
|
||||
L.op_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, c.kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_k, m.b_v}, {});
|
||||
L.op_sigmoid = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.q_dim()),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_gate}, {m.b_gate});
|
||||
L.op_gate_mul = mul({m.b_gate, m.b_attn}, m.b_attn, g.q_dim());
|
||||
RAD_ARCH_TRY(linear(L.out, l, "blk.%d.attn_output", g.n_embd, g.q_dim(),
|
||||
{ nm.ckpt(a, pre, l, "o_proj.weight") }, m.a_attn, m.b_arm, {}));
|
||||
} else {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
|
||||
const char* c = "%s.layers.%d.conv.%s";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
|
||||
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
|
||||
RAD_ARCH_TRY(linear(L.conv_in, l, "blk.%d.conv_in", 3 * g.n_embd, g.n_embd,
|
||||
{ nm.ckpt(c, pre, l, "in_proj.weight") }, m.a_h, m.b_bcx, {}));
|
||||
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
|
||||
* convert, as LFM2's is. */
|
||||
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
|
||||
L.op_gate_in = mul({m.b_bcx}, m.b_conv_in, g.n_embd);
|
||||
L.op_conv = rw(b, RAD_OP(b, "causal_conv1d",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(L.w_conv)),
|
||||
{m.b_conv_in}, {m.b_conv_out});
|
||||
L.op_gate_out = mul({m.b_bcx, m.b_conv_out}, m.b_conv_out, g.n_embd);
|
||||
RAD_ARCH_TRY(linear(L.conv_out, l, "blk.%d.conv_out", g.n_embd, g.n_embd,
|
||||
{ nm.ckpt(c, pre, l, "out_proj.weight") }, m.a_conv, m.b_arm, {}));
|
||||
}
|
||||
/* the sandwich: the mixer's output is normed before it joins the stream, and the
|
||||
* feed-forward reads the norm of the sum */
|
||||
if (has_join) L.op_join = join(L.w_post_norm, L.w_ffn_norm);
|
||||
if (!L.op_join) {
|
||||
L.op_post_norm = rmsnorm(g.max_tok, g.n_embd, L.w_post_norm, m.b_arm, m.b_arm);
|
||||
L.op_add = add(m.b_x, m.b_arm);
|
||||
L.op_ffn_norm = rmsnorm(g.max_tok, g.n_embd, L.w_ffn_norm, m.b_x, m.b_h);
|
||||
}
|
||||
|
||||
/* ---- the feed-forward */
|
||||
const char* ffn = "%s.layers.%d.feed_forward.%s";
|
||||
RAD_ARCH_TRY(linear(L.gate_up, l, "blk.%d.ffn_gate_up", 2 * g.n_ff, g.n_embd,
|
||||
{ nm.ckpt(ffn, pre, l, "w1.weight"), nm.ckpt(ffn, pre, l, "w3.weight") },
|
||||
m.a_h, m.b_gate_up, { g.n_ff, g.n_ff }));
|
||||
L.op_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_gate_up}, {m.b_ffn});
|
||||
RAD_ARCH_TRY(linear(L.down, l, "blk.%d.ffn_down", g.n_embd, g.n_ff,
|
||||
{ nm.ckpt(ffn, pre, l, "w2.weight") }, m.a_ffn, m.b_arm, {}));
|
||||
if (has_join && l + 1 < (int)m.layers.size())
|
||||
L.op_ffn_join = join(L.w_ffn_post_norm, m.layers[(size_t)l + 1].w_norm);
|
||||
if (!L.op_ffn_join) {
|
||||
L.op_ffn_post_norm = rmsnorm(g.max_tok, g.n_embd, L.w_ffn_post_norm, m.b_arm, m.b_arm);
|
||||
L.op_ffn_add = add(m.b_x, m.b_arm);
|
||||
}
|
||||
n_joins += (L.op_join ? 1 : 0) + (L.op_ffn_join ? 1 : 0);
|
||||
}
|
||||
|
||||
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
|
||||
* lm_head reads. */
|
||||
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_x}, {m.b_hout});
|
||||
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, m.b_hout);
|
||||
/* A tied head is the bf16 embedding table: a scored step leaves the final-normed rows in
|
||||
* h_out and the core takes the candidates' logits from the table on the host. */
|
||||
if (meta_bool(meta, "tie_word_embeddings", false))
|
||||
RAD_ARCH_TRY(rad_declare_scores(b, m.b_hout, m.w_tok));
|
||||
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_lm_head)),
|
||||
{m.b_hout}, {m.b_logits});
|
||||
|
||||
int64_t n_full = 0, n_sliding = 0;
|
||||
for (const Layer& L : m.layers) {
|
||||
n_full += L.kind == kFull ? 1 : 0;
|
||||
n_sliding += L.kind == kSliding ? 1 : 0;
|
||||
}
|
||||
rad_note(b, "lfm3: %lld layers, %lld full attention + %lld sliding (window %lld) + %lld short "
|
||||
"convolution of width %lld; %lld heads over %lld at head_dim %lld, ffn %lld, "
|
||||
"vocab %lld",
|
||||
(long long)g.n_layer, (long long)n_full, (long long)n_sliding,
|
||||
(long long)m.sliding.window, (long long)(g.n_layer - n_full - n_sliding),
|
||||
(long long)m.width, (long long)g.n_head, (long long)g.n_head_kv,
|
||||
(long long)g.head_dim, (long long)g.n_ff, (long long)g.n_vocab);
|
||||
rad_note(b, "sandwich joins: %d of %lld fused (norm_add_norm)%s", n_joins,
|
||||
(long long)(2 * g.n_layer - 1),
|
||||
n_joins == 0 ? " -- not served, the rmsnorm / add / rmsnorm chain" : "");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void lin_step(RadCtx* c, const Linear& lin, rad_buf in, rad_buf out, int64_t T) {
|
||||
RAD_ISSUE(c, lin.op, brows(in, T), RAD_W(lin.w), brows(out, T));
|
||||
}
|
||||
|
||||
/* The convolution is issued once per half of the step, as LFM2's is: the decode rows [0, D) with
|
||||
* `num_accepted`, leaving the window in the layout a partly rejected verify reads back from, and
|
||||
* the prefill chunks [D, S) without it, each leaving its tail at offset zero. `has_init` is
|
||||
* `ctx_lens` (a sequence with earlier tokens has a history). The prefill half's per-sequence
|
||||
* arrays start at `+ D`; the token operands stay at their base, since the kernel reads rows at the
|
||||
* absolute offsets in `cu`. */
|
||||
static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch* batch, int l) {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadKVGroupBatch* cv = kv_batch(batch, m.kv_conv);
|
||||
const int32_t* idx = cv ? cv->state_index : nullptr;
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
const int64_t P = S - D;
|
||||
if (D > 0)
|
||||
RAD_ISSUE_N(c, L.op_conv, DT,
|
||||
brows(m.b_conv_in, DT), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1), praw(idx, RAD_I32, D),
|
||||
praw(batch->ctx_lens, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
|
||||
brows(m.b_conv_out, DT));
|
||||
if (P > 0)
|
||||
RAD_ISSUE_N(c, L.op_conv, T,
|
||||
brows(m.b_conv_in, T), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
|
||||
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
praw(idx ? idx + D : nullptr, RAD_I32, P),
|
||||
praw(batch->ctx_lens + D, RAD_I32, P), RAD_NONE,
|
||||
brows(m.b_conv_out, T));
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
if (batch->draft_pass || batch->spec_parent || batch->enc || batch->n_mm_rows > 0) {
|
||||
rad_step_fail(c, "lfm3_bf16: this step asks for an encoder, a draft pass or media rows, "
|
||||
"and the program declares none of them");
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok, n = g.n_embd;
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
const Layer& L = m.layers[(size_t)l];
|
||||
if (!(l > 0 && m.layers[(size_t)l - 1].op_ffn_join))
|
||||
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
|
||||
if (L.kind != kConv) {
|
||||
const rad_kvgroup grp = m.cls(L).kv;
|
||||
const RadKVGroupBatch* kv = kv_batch(batch, grp);
|
||||
L.q.step(c, m.a_h, m.b_q, T);
|
||||
L.k.step(c, m.a_h, m.b_k, T);
|
||||
L.v.step(c, m.a_h, m.b_v, T);
|
||||
lin_step(c, L.gate, m.b_h, m.b_gate, T);
|
||||
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
|
||||
brows(m.b_q, T));
|
||||
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
|
||||
brows(m.b_k, T));
|
||||
RAD_ISSUE(c, L.op_rope_q, brows(m.b_q, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE(c, L.op_rope_k, brows(m.b_k, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE(c, L.op_store, brows(m.b_k, T), brows(m.b_v, T),
|
||||
praw(kv ? kv->slot_mapping : nullptr, RAD_I32, T), kv_cache(grp, l));
|
||||
RAD_ISSUE_N(c, L.op_attn, batch->max_q_len,
|
||||
brows(m.b_q, T), kv_cache(grp, l),
|
||||
praw2(kv ? kv->block_table : nullptr, RAD_I32, batch->n_seq,
|
||||
kv ? kv->block_table_pitch : 0),
|
||||
praw(kv ? kv->seqused : nullptr, 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(c, L.op_sigmoid, brows(m.b_gate, T), brows(m.b_gate, T));
|
||||
RAD_ISSUE(c, L.op_gate_mul, brows(m.b_gate, T), brows(m.b_attn, T), brows(m.b_attn, T));
|
||||
L.out.step(c, m.a_attn, m.b_arm, T);
|
||||
} else {
|
||||
L.conv_in.step(c, m.a_h, m.b_bcx, T);
|
||||
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
|
||||
brows(m.b_conv_in, T));
|
||||
conv_step(m, L, c, batch, l);
|
||||
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
|
||||
brows(m.b_conv_out, T));
|
||||
L.conv_out.step(c, m.a_conv, m.b_arm, T);
|
||||
}
|
||||
if (L.op_join) {
|
||||
RAD_ISSUE(c, L.op_join, brows(m.b_arm, T), RAD_W(L.w_post_norm), brows(m.b_x, T),
|
||||
RAD_W(L.w_ffn_norm), brows(m.b_h, T));
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_post_norm, brows(m.b_arm, T), RAD_W(L.w_post_norm),
|
||||
brows(m.b_arm, T));
|
||||
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_arm, T), brows(m.b_x, T));
|
||||
RAD_ISSUE(c, L.op_ffn_norm, brows(m.b_x, T), RAD_W(L.w_ffn_norm), brows(m.b_h, T));
|
||||
}
|
||||
L.gate_up.step(c, m.a_h, m.b_gate_up, T);
|
||||
RAD_ISSUE(c, L.op_act, brows(m.b_gate_up, T), brows(m.b_ffn, T));
|
||||
L.down.step(c, m.a_ffn, m.b_arm, T);
|
||||
if (L.op_ffn_join) {
|
||||
/* y is the next layer's input norm */
|
||||
RAD_ISSUE(c, L.op_ffn_join, brows(m.b_arm, T), RAD_W(L.w_ffn_post_norm),
|
||||
brows(m.b_x, T), RAD_W(m.layers[(size_t)l + 1].w_norm), brows(m.b_h, T));
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_ffn_post_norm, brows(m.b_arm, T), RAD_W(L.w_ffn_post_norm),
|
||||
brows(m.b_arm, T));
|
||||
RAD_ISSUE(c, L.op_ffn_add, brows(m.b_x, T), brows(m.b_arm, T), brows(m.b_x, T));
|
||||
}
|
||||
}
|
||||
|
||||
/* The lm_head runs only on the rows the sampler asked for; a prefill chunk that finishes no
|
||||
* sequence skips it. */
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_x, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_out_norm), brows(m.b_hout, batch->n_out));
|
||||
if (!batch->score_only)
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace lfm3_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(lfm3_bf16, "lfm3", "", "0.1.0",
|
||||
"LiquidAI LFM3, bf16 or IQ8R: short gated convolutions, full and sliding-window GQA "
|
||||
"attention with a partial rotary and a gate per head, sandwich norms, in the "
|
||||
"checkpoint's own schedule, one rank")
|
||||
#endif
|
||||
@@ -1,9 +1,9 @@
|
||||
/* llama_dense_fp8 -- arch/llama_fp8 over a bf16 checkpoint quantised by rad-convert.
|
||||
*
|
||||
* For MiniCPM5-2B, which OpenBMB publishes only in bf16. The recipe
|
||||
* data/recipes/minicpm5-2b-dspark.recipe takes one amax per 128x128 block with scale = amax/448
|
||||
* rounded to bf16, so the container matches what a checkpoint shipped in fp8 would hold and every
|
||||
* kernel, layout and placement decision downstream is the same.
|
||||
* data/recipes/minicpm5-2b-iq8r.recipe stores every linear as rotated int8 with a scale per
|
||||
* (row, 256 of K); data/recipes/minicpm5-2b-bf16-dspark.recipe keeps the model's own linears bf16
|
||||
* and quantises only the merged drafter.
|
||||
*
|
||||
* A separate .so because the selection key is the (architecture, quantisation) pair (spec §2.4),
|
||||
* and a dense checkpoint's descriptor is empty. Everything else is arch/llama_fp8/llama_fp8.cpp;
|
||||
|
||||
+112
-28
@@ -14,10 +14,10 @@
|
||||
*
|
||||
* llama_fp8 quant "fp8_e4m3" the checkpoint holds E4M3 codes and a `weight_scale_inv`
|
||||
* plane per linear, as the engine reads them.
|
||||
* llama_dense_fp8 quant "" the checkpoint is dense bf16, and a recipe quantises each
|
||||
* linear to those two planes at convert time
|
||||
* (data/recipes/minicpm5-2b-dspark.recipe: amax per 128x128
|
||||
* block, scale = amax/448 rounded to bf16).
|
||||
* llama_dense_fp8 quant "" the checkpoint is dense bf16, and a recipe quantises its
|
||||
* linears at convert time
|
||||
* (data/recipes/minicpm5-2b-iq8r.recipe: rotated int8, a
|
||||
* scale per (row, 256 of K)) or leaves them bf16.
|
||||
*
|
||||
* MiniCPM5-2B needs the second, since it is published only in bf16. Both builds declare the same
|
||||
* weights and ops, so nothing downstream can tell which one ran.
|
||||
@@ -28,8 +28,17 @@
|
||||
* BF16, no plane every norm and the embedding
|
||||
*
|
||||
* The lm_head is declared at whatever the model holds: bf16 as llama checkpoints ship it, or block
|
||||
* fp8 where a recipe quantised it (the widest GEMM at half the bytes), and the logits kernel for
|
||||
* that encoding is selected. Both vocabulary edges are row-sharded with the vocabulary.
|
||||
* fp8 or int8 where a recipe quantised it (the widest GEMM at half the bytes), and the logits
|
||||
* kernel for that encoding is selected. Both vocabulary edges are row-sharded with the vocabulary.
|
||||
*
|
||||
* ============================== AN INT8 TRUNK ==============================
|
||||
*
|
||||
* The dense build also serves a recipe that makes the linears rotated int8 (IQ8R:
|
||||
* data/recipes/minicpm5-2b-iq8r.recipe). Each is a LinearFP8, which reads what the container holds,
|
||||
* and declare() learns the format from the first layer's q|k|v before it declares the activations:
|
||||
* they then carry int8 codes with one scale per (token, scale group) in place of the E4M3 pair,
|
||||
* written by the norms, the gated product and the attention output's quantiser. The DSpark
|
||||
* drafter's linears follow their own encodings the same way (rad_block_dspark.h).
|
||||
*/
|
||||
#ifndef LLAMA_DENSE_SRC
|
||||
#define LLAMA_DENSE_SRC 0
|
||||
@@ -67,6 +76,12 @@ struct Model {
|
||||
|
||||
rad_kvgroup kv_full = 0;
|
||||
|
||||
/* The trunk's linears are rotated int8 (IQ8R, or the 128-group int8 before it), read from the
|
||||
* first layer's fused q|k|v: the activations then carry int8 code pairs at `trunk_g8` columns
|
||||
* a scale, written by the norms, the gated product and the attention output's quantiser. */
|
||||
bool trunk_i8 = false;
|
||||
int64_t trunk_g8 = RAD_FP8_BLOCK;
|
||||
|
||||
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
|
||||
ActFP8 a_h{};
|
||||
rad_buf b_qkv = 0;
|
||||
@@ -101,7 +116,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The quantisation descriptor is the selection key but is checked anyway: `--arch` can override
|
||||
* the architecture id at convert time, and a plugin handed the wrong checkpoint should say which
|
||||
@@ -205,6 +220,13 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The drafter's own stored format, which decides its activation pairs below. */
|
||||
RAD_ARCH_TRY(Dspark::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
|
||||
dc.fc_mapped = true;
|
||||
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
|
||||
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
auto dqcols = [dqg](int64_t n) { return (n + dqg - 1) / dqg; };
|
||||
|
||||
/* DSpark's published config sets `sliding_window: null`, so this is normally a full cache. */
|
||||
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, &m.kv_draft));
|
||||
|
||||
@@ -223,28 +245,35 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
dw.c = decl_b(b, nm.f("ds_c"), dg.act_dtype, {dg.max_tok, dg.n_embd});
|
||||
dw.ck = decl_b(b, nm.f("ds_ck"), dg.act_dtype, {dg.max_tok, kvd});
|
||||
dw.cv = decl_b(b, nm.f("ds_cv"), dg.act_dtype, {dg.max_tok, kvd});
|
||||
/* FP8 copies for the context pass. `srcq` is the largest (20 MiB at a 2048-token chunk, five
|
||||
* taps, hidden 2048) and halves the bytes of the context pass's dominant GEMM. */
|
||||
dw.srcq = decl_b(b, nm.f("ds_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32,
|
||||
{dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("ds_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("ds_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
|
||||
/* Eight-bit copies for the context pass, at the code type and scale group the drafter's
|
||||
* linears read. `srcq` is the largest (20 MiB at a 2048-token chunk, five taps, hidden 2048)
|
||||
* and halves the bytes of the context pass's dominant GEMM. */
|
||||
if (dc.act_i8 && (qd % dqg || dg.n_embd % dqg || dg.n_ff % dqg)) {
|
||||
fprintf(stderr, "radiance: the DSpark drafter's int8 linears keep one scale a %lld of K, "
|
||||
"which does not divide its widths (hidden %lld, attention %lld, "
|
||||
"feed-forward %lld)\n",
|
||||
(long long)dqg, (long long)dg.n_embd, (long long)qd, (long long)dg.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
dw.srcq = decl_b(b, nm.f("ds_srcq"), dqt, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32, {dg.max_tok, dqcols(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("ds_cq"), dqt, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("ds_cs"), RAD_F32, {dg.max_tok, dqcols(dg.n_embd)});
|
||||
|
||||
dw.x = decl_b(b, nm.f("ds_x"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.h.x = decl_b(b, nm.f("ds_h"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.h.q = decl_b(b, nm.f("ds_h.q"), RAD_F8E4M3, {qr, dg.n_embd});
|
||||
dw.h.s = decl_b(b, nm.f("ds_h.s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
|
||||
dw.h.q = decl_b(b, nm.f("ds_h.q"), dqt, {qr, dg.n_embd});
|
||||
dw.h.s = decl_b(b, nm.f("ds_h.s"), RAD_F32, {qr, dqcols(dg.n_embd)});
|
||||
dw.q = decl_b(b, nm.f("ds_q"), dg.act_dtype, {qr, qd});
|
||||
dw.k = decl_b(b, nm.f("ds_k"), dg.act_dtype, {qr, kvd});
|
||||
dw.v = decl_b(b, nm.f("ds_v"), dg.act_dtype, {qr, kvd});
|
||||
dw.attn.x = decl_b(b, nm.f("ds_attn"), dg.act_dtype, {qr, qd});
|
||||
dw.attn.q = decl_b(b, nm.f("ds_attn.q"), RAD_F8E4M3, {qr, qd});
|
||||
dw.attn.s = decl_b(b, nm.f("ds_attn.s"), RAD_F32, {qr, fp8_blocks(qd)});
|
||||
dw.attn.q = decl_b(b, nm.f("ds_attn.q"), dqt, {qr, qd});
|
||||
dw.attn.s = decl_b(b, nm.f("ds_attn.s"), RAD_F32, {qr, dqcols(qd)});
|
||||
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
|
||||
dw.ffn.x = decl_b(b, nm.f("ds_ffn"), dg.act_dtype, {qr, dg.n_ff});
|
||||
dw.ffn.q = decl_b(b, nm.f("ds_ffn.q"), RAD_F8E4M3, {qr, dg.n_ff});
|
||||
dw.ffn.s = decl_b(b, nm.f("ds_ffn.s"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
|
||||
dw.ffn.q = decl_b(b, nm.f("ds_ffn.q"), dqt, {qr, dg.n_ff});
|
||||
dw.ffn.s = decl_b(b, nm.f("ds_ffn.s"), RAD_F32, {qr, dqcols(dg.n_ff)});
|
||||
|
||||
dw.sel_h = decl_b(b, nm.f("ds_selh"), dg.act_dtype, {sr, dg.n_embd});
|
||||
dw.dq = decl_b(b, nm.f("ds_dq"), RAD_I8, {sr, dg.n_embd});
|
||||
@@ -310,9 +339,10 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -346,18 +376,58 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
/* ---- activations. */
|
||||
/* ---- the trunk's stored format, read from the first layer's fused q|k|v before any
|
||||
* activation is declared: only an int8 trunk's activations carry an int8 code pair. The probe
|
||||
* maps the weight through the layer's own LinearFP8, which then does not map it again; the
|
||||
* resize before the layer loop keeps the layers sized here. */
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
m.layers.resize((size_t)m.n_main);
|
||||
if (m.n_main > 0) {
|
||||
const char* pre = "model.layers";
|
||||
RAD_ARCH_TRY(m.layers[0].attn.qkv.probe(
|
||||
b, nm, g, nm.f("blk.0.attn_qkv"),
|
||||
{ nm.ckpt("%s.0.self_attn.q_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.k_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.v_proj.weight", pre) }));
|
||||
RadEncoding enc{};
|
||||
m.trunk_i8 = weight_enc(b, nm.f("blk.0.attn_qkv.weight"), &enc) &&
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
if (m.trunk_i8) m.trunk_g8 = linear_w8h_group(enc);
|
||||
}
|
||||
if (m.trunk_i8 && (g.n_embd % m.trunk_g8 || q_dim % m.trunk_g8 || g.n_ff % m.trunk_g8)) {
|
||||
fprintf(stderr, "radiance: llama: the int8 trunk keeps one scale a %lld of K, which does "
|
||||
"not divide this rank's widths (hidden %lld, attention %lld, "
|
||||
"feed-forward %lld)\n",
|
||||
(long long)m.trunk_g8, (long long)g.n_embd, (long long)q_dim, (long long)g.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- activations. An int8 trunk's quantisers sit in their producers where the kernels serve
|
||||
* the rotated forms: the norms write had_quant_act_i8g's codes for q|k|v and gate|up, the
|
||||
* gated product for the down projection, and the attention output's own quantiser for the
|
||||
* out-projection, so no projection declares one and the activation carries no E4M3 pair.
|
||||
* Where a form is not declared (the CPU kernels), the producer keeps its E4M3 pair and each
|
||||
* projection quantises its own input from the bf16 plane. */
|
||||
if (m.trunk_i8) {
|
||||
if (rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g")))
|
||||
m.a_h.q8_fed = m.a_h.q8_rot = true;
|
||||
if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
|
||||
if (rad_op_declared(b, "had_quant_act_i8g")) m.a_attn.q8_fed = m.a_attn.q8_rot = true;
|
||||
}
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd));
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8, !m.a_h.q8_fed,
|
||||
m.trunk_g8));
|
||||
m.b_qkv = decl_b(b, nm.f("attn_qkv"), g.act_dtype, {g.max_tok, q_dim + 2 * kv_dim});
|
||||
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim});
|
||||
m.a_attn.x = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim});
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8,
|
||||
!m.a_attn.q8_fed, m.trunk_g8));
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
|
||||
m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8, !m.a_ffn.q8_fed,
|
||||
m.trunk_g8));
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
|
||||
|
||||
/* ---- the drafter's taps, only when the container carries a drafter that reads them and the
|
||||
@@ -431,7 +501,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
MlpFP8::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
|
||||
|
||||
m.layers.resize((size_t)m.n_main);
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
/* Residual fold and collective placement: rad_fp8.h, layer_fold. */
|
||||
@@ -496,6 +565,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
(long long)g.head_dim, (long long)m.n_rot, (long long)g.n_ff,
|
||||
(long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab));
|
||||
#if LLAMA_DENSE_SRC
|
||||
if (m.trunk_i8)
|
||||
rad_note(b, "a dense bf16 checkpoint, every linear quantised by the recipe to rotated "
|
||||
"int8 with one scale a [1 x %lld] of K, read against int8 activations with a "
|
||||
"scale per (token, %lld)", (long long)m.trunk_g8, (long long)m.trunk_g8);
|
||||
else
|
||||
rad_note(b, "a dense bf16 checkpoint, every linear quantised by the recipe to E4M3 with a "
|
||||
"bf16 [N/%d,K/%d] scale plane (scale = block amax / 448, rounded to bf16)",
|
||||
RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
@@ -523,7 +597,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
/* A drafter pass; the sign gives the kind. Positive is the query pass, proposing the whole
|
||||
* block at once; negative is the context pass, turning the tokens the trunk just committed
|
||||
* into the drafter's own K and V. Zero is a trunk step. */
|
||||
@@ -579,6 +653,14 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
#if LLAMA_DENSE_SRC
|
||||
/* Chained launches pay on an IQ8R trunk with and without its drafter: libr4d's
|
||||
* rad_kernel_chain holds the IQ8R decode rows. MiniCPM5-2B on one R9700, ms a decode step
|
||||
* unchained / chained: 5.57 / 5.17 at one sequence and 6.09 / 5.71 at eight without a drafter,
|
||||
* and with DSpark 7.32 / 6.87 at one and 8.15 / 7.92 at four. A block-fp8 trunk gains less
|
||||
* and loses nowhere: 5.45 / 5.40 and 5.92 / 5.89 without, 7.14 / 7.12 and 8.17 / 8.16 with. */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
#endif
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (da && (std::strstr(da, "DSpark") || std::strstr(da, "DFlash"))) {
|
||||
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
@@ -596,6 +678,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
/* One more level of expansion so `#NS` sees the expanded namespace. */
|
||||
#define LLAMA_PROBE_X(NS) RAD_ARCH_PROBE(NS)
|
||||
#define LLAMA_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
LLAMA_PROBE_X(LLAMA_NS)
|
||||
#if LLAMA_DENSE_SRC
|
||||
LLAMA_PLUGIN_X(LLAMA_NS, "llama", LLAMA_QUANT, "0.1.0",
|
||||
|
||||
+45
-28
@@ -58,7 +58,8 @@
|
||||
*
|
||||
* Every network computes in bf16, as the reference loads it; the latents, the guidance and the
|
||||
* sampler are f32. The text encoder's, the connectors' and the DiT's large linears are bf16 or
|
||||
* block fp8 as the container holds them (data/recipes/ltx-2.5-fp8.recipe); the vocoder runs in
|
||||
* rotated int8 as the container holds them (data/recipes/ltx-2.5-bf16.recipe,
|
||||
* ltx-2.5-iq8r.recipe), one kind a container; the vocoder runs in
|
||||
* f32 (its anti-aliased activation's kernels are f32), its log-mel input rounded where the
|
||||
* reference's bf16 one is.
|
||||
*
|
||||
@@ -182,8 +183,11 @@ static int64_t positions(const RadVideoGeom* g, float* pos, int64_t cap) {
|
||||
}
|
||||
|
||||
/* ================================================================== linears */
|
||||
/* An activation a linear reads: its bf16 plane and, for block-fp8 linears, its codes, which a
|
||||
* quantiser makes from the plane (QuantFP8). */
|
||||
/* An activation a linear reads: its bf16 plane and, for block-fp8 or rotated int8 linears, its
|
||||
* codes, which a quantiser makes from the plane (QuantFP8: E4M3, or had_quant_act_i8g's int8 at
|
||||
* the weights' scale group). Rows narrower than that group carry no codes: a bf16 linear reads
|
||||
* them (the latents' projections in). Where no library serves the rotating quantiser, each int8
|
||||
* linear quantises its own input and this declares none. */
|
||||
struct Act {
|
||||
ActFP8 a{};
|
||||
QuantFP8 q{};
|
||||
@@ -196,27 +200,30 @@ struct Act {
|
||||
if (!a.x) return RAD_E_INVAL;
|
||||
Geom gg = g;
|
||||
gg.max_tok = rows;
|
||||
RAD_ARCH_TRY(a.declare_qs(b, nm, gg, name, width, rows));
|
||||
if (g.w_i8h && width % g.w_i8_group) return RAD_OK;
|
||||
RAD_ARCH_TRY(a.declare_pair(b, nm, gg, name, width, rows, g.w_i8h, g.w_i8_group,
|
||||
"had_quant_act_i8g"));
|
||||
if (g.w_i8h && !a.q8_fed) return RAD_OK;
|
||||
return q.declare(b, gg, a, width);
|
||||
}
|
||||
/* The codes of rows [r0, r0 + rows), at those rows' count. */
|
||||
void step(RadCtx* c, int64_t rows, int64_t r0 = 0) const {
|
||||
if (!q.op || rows <= 0) return;
|
||||
RAD_ISSUE_N(c, q.op, rows, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n),
|
||||
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()));
|
||||
}
|
||||
};
|
||||
|
||||
/* A linear, y = x W^T (+ b): `gemm_nt_bias` over the bf16 plane for a bf16 weight (the bias in the
|
||||
* GEMM's one rounding, as torch's), or `gemm_nt_q` over the codes for a block-fp8 one with the
|
||||
* bias added after (`table_add`, one more rounding). `small` keeps a weight bf16 in any container
|
||||
* (a gate's logits: too few rows for 128-row fp8 blocks). The input and output rows may sit at
|
||||
* different offsets of their buffers. */
|
||||
* GEMM's one rounding, as torch's), or `gemm_nt_q` over the codes for a block-fp8 or rotated int8
|
||||
* one with the bias added after (`table_add`, one more rounding). `small` keeps a weight bf16 in
|
||||
* any container (a gate's logits: too few rows for 128-row fp8 blocks). The input and output rows
|
||||
* may sit at different offsets of their buffers. */
|
||||
struct Lin {
|
||||
LinearFP8 l{};
|
||||
rad_weight w = 0, bias = 0;
|
||||
rad_op op = 0, op_b = 0;
|
||||
bool fp8 = false;
|
||||
bool fp8 = false; /* read through its codes: block fp8, or rotated int8 */
|
||||
bool mapped = false; /* the weight's name map was made already (a probe's) */
|
||||
int64_t N = 0, K = 0;
|
||||
|
||||
@@ -257,9 +264,11 @@ struct Lin {
|
||||
l.mapped = mapped;
|
||||
RAD_ARCH_TRY(l.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(group), wsrc, in.a, y,
|
||||
max_rows, parts));
|
||||
if (l.bf16 || l.i8 || l.mx || l.w4 || l.paro || l.paro5) {
|
||||
fprintf(stderr, "radiance: ltx2: '%s' is not block fp8; this plugin reads bf16 or "
|
||||
"block-fp8 linears\n", base);
|
||||
const bool other = l.bf16 || l.mx || l.w4 || l.paro || l.paro5 || l.iqr;
|
||||
if (other || (g.w_i8h ? !(l.i8 && l.i8_rot) : l.i8)) {
|
||||
fprintf(stderr, "radiance: ltx2: '%s' is not %s as the first DiT projection is; this "
|
||||
"plugin reads bf16, block-fp8 or rotated int8 linears, one kind a "
|
||||
"container\n", base, g.w_i8h ? "rotated int8" : "block fp8");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
op = l.op;
|
||||
@@ -285,9 +294,12 @@ struct Lin {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(in.a.x, ri, rows, K), RAD_W(w), out);
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(in.a.q, ri, rows, K),
|
||||
brow_slice(in.a.s, ri, rows, K / RAD_FP8_BLOCK), RAD_W(l.w), RAD_W(l.ws), out,
|
||||
RAD_NONE, RAD_NONE);
|
||||
if (l.i8)
|
||||
l.step(c, in.a, y, ri + rows, ri, rows, ro);
|
||||
else
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(in.a.q, ri, rows, K),
|
||||
brow_slice(in.a.s, ri, rows, K / RAD_FP8_BLOCK), RAD_W(l.w), RAD_W(l.ws),
|
||||
out, RAD_NONE, RAD_NONE);
|
||||
if (op_b) RAD_ISSUE_N(c, op_b, rows, out, RAD_W(bias), out);
|
||||
}
|
||||
};
|
||||
@@ -712,7 +724,7 @@ struct Model {
|
||||
rad_buf b_ddcu = 0, b_dsig = 0, b_dtg = 0, b_dgrid = 0, b_dg5 = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== check_format */
|
||||
static long long tgeti(const RadModelMeta* m, const char* key, long long def) {
|
||||
@@ -2370,7 +2382,7 @@ static int declare_audio(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
for (const char* w : { "voc.conv_in.weight", "bwe.conv_in.weight" }) {
|
||||
if (weight_codes_dtype(b, w, RAD_F32) != RAD_F32) {
|
||||
fprintf(stderr, "radiance: ltx2: '%s' is stored %s; the vocoders run in f32 -- convert "
|
||||
"with data/recipes/ltx-2.5-bf16.recipe or ltx-2.5-fp8.recipe, which "
|
||||
"with one of data/recipes/ltx-2.5-*.recipe, which "
|
||||
"cast them\n", w, rad_dtype_name(weight_codes_dtype(b, w, RAD_F32)));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -3140,7 +3152,8 @@ static const double kStage2[] = { 0.909375, 0.725, 0.421875 };
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->is_draft) {
|
||||
fprintf(stderr, "radiance: ltx2: this plugin has no draft scope\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -3150,7 +3163,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"every head\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -3217,8 +3230,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- bf16 or block fp8: what the container holds for the first DiT projection decides every
|
||||
* large linear (rad_fp8.h, Geom::w_bf16) */
|
||||
/* ---- bf16, block fp8 or rotated int8: what the container holds for the first DiT projection
|
||||
* decides every large linear (rad_arch.h, Geom::w_bf16 and w_i8h) */
|
||||
{
|
||||
LinearFP8 probe{};
|
||||
RAD_ARCH_TRY(probe.probe(b, nm, m.gd, "dit.blk.0.attn1.qkv",
|
||||
@@ -3226,9 +3239,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.transformer_blocks.0.attn1.to_k.weight",
|
||||
"transformer.transformer_blocks.0.attn1.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.blk.0.attn1.qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
m.gd.w_bf16 = m.gt.w_bf16 = plain;
|
||||
const bool known = weight_enc(b, nm.f("dit.blk.0.attn1.qkv.weight"), &e);
|
||||
m.gd.w_bf16 = m.gt.w_bf16 = known && rad_enc_is(&e, "plain");
|
||||
m.gd.w_i8h = m.gt.w_i8h = known && linear_is_w8h(e);
|
||||
if (m.gd.w_i8h) m.gd.w_i8_group = m.gt.w_i8_group = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
/* ---- the scheduler: the base model's shifted linspace, or the distilled release's sigmas */
|
||||
@@ -3371,7 +3385,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"bandwidth extender%s%s",
|
||||
distilled ? " distilled" : "", (long long)m.tL, (long long)m.tC, m.cv.blk.size(),
|
||||
m.ca.blk.size(), (long long)m.nb, (long long)m.D, (long long)m.Da,
|
||||
m.gd.w_bf16 ? "bf16" : "block-fp8", m.venc ? "decoder + encoder" : "decoder",
|
||||
m.gd.w_bf16 ? "bf16" : m.gd.w_i8h ? "rotated int8" : "block-fp8",
|
||||
m.venc ? "decoder + encoder" : "decoder",
|
||||
m.ups ? ", latent upsampler x2" : "", m.dur ? ", duration head" : "");
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -4144,7 +4159,7 @@ static void step_upscale(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->vgen_b) {
|
||||
rad_step_fail(c, "ltx2 is a video generator and runs its generator passes only");
|
||||
return;
|
||||
@@ -4179,12 +4194,14 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(ltx2)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(ltx2, "ltx2", "", "0.1.0",
|
||||
"LTX-2.5 (t2va, i2va): a Gemma 4 text encoder and connectors, the duration head, a "
|
||||
"22B dual-stream audio-video diffusion transformer with four-way guidance, the "
|
||||
"causal 3D video VAE (tiled past the default canvas) and the diffusion decoder, the "
|
||||
"audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; "
|
||||
"bf16 or block-fp8 linears")
|
||||
"bf16, block-fp8 or rotated int8 linears")
|
||||
|
||||
extern "C" int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos,
|
||||
int64_t cap) {
|
||||
|
||||
+135
-35
@@ -288,10 +288,11 @@ struct DitBlock {
|
||||
rad_op op_kq = 0; /* the keys to int8 codes for the attention's scores */
|
||||
rad_op op_vq = 0; /* the values to E4M3 codes for the attention's P.V */
|
||||
/* The three modulation projections, one a modality, this rank's share of their rows; a
|
||||
* curve-form checkpoint's are bf16 (ada_w). */
|
||||
* curve-form checkpoint's are bf16 (ada_w). A rotated int8 one adds its bias after the GEMM
|
||||
* (op_ada_b). */
|
||||
DenseFP8 ada[3];
|
||||
rad_weight ada_w[3] = {}, ada_b[3] = {};
|
||||
rad_op op_ada[3] = {};
|
||||
rad_op op_ada[3] = {}, op_ada_b[3] = {};
|
||||
};
|
||||
|
||||
/* A video decoder block. */
|
||||
@@ -423,6 +424,7 @@ struct Model {
|
||||
/* ---- the lanes (PERSIST) */
|
||||
rad_buf b_text = 0; /* [lanes * kMaxText, D] bf16: the refined prompt */
|
||||
rad_buf b_ada = 0; /* [lanes * S, 150 * Ws] bf16: the modulation table */
|
||||
rad_buf b_adat = 0; /* [S, Ws] bf16: a rotated int8 projection's rows before its bias */
|
||||
rad_buf b_nout = 0; /* [lanes * S, 3 * 2D] bf16: norm_out's, by segment */
|
||||
rad_buf b_vstate = 0; /* [lanes * maxV, 96] f32 */
|
||||
rad_buf b_astate = 0; /* [lanes * maxA, 32] f32 */
|
||||
@@ -450,6 +452,12 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
/* The DiT's linears are int8 (W8A8): their activations are int8 codes as well. */
|
||||
bool dit_i8 = false;
|
||||
/* The text encoder's, the refiner's and the modulation projections' linears are rotated int8
|
||||
* (IQ8R, or the 128-group form where K is not whole 256s), each read off its first weight:
|
||||
* their activations then carry int8 pairs at that weight's scale group in place of the E4M3
|
||||
* ones (ActFP8::declare_pair). */
|
||||
bool te_i8 = false, ref_i8 = false, ada_i8 = false;
|
||||
int64_t te_g8 = RAD_FP8_BLOCK, ref_g8 = RAD_FP8_BLOCK, ada_g8 = RAD_FP8_BLOCK;
|
||||
std::vector<DitBlock> dit;
|
||||
rad_weight w_no_n = 0, w_vout = 0, b_vout = 0, w_aout = 0, b_aout = 0;
|
||||
rad_op op_nout = 0, op_hcast = 0, op_vout = 0, op_aout = 0, op_ev = 0, op_ea = 0;
|
||||
@@ -561,7 +569,7 @@ struct Model {
|
||||
rad_buf b_enca = 0; /* [kEncSlotsA * kEncSlotRowsA, kAudioC] f32 PERSIST */
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A space-separated list off the container (rad-convert flattens arrays that way). */
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
@@ -704,16 +712,35 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd },
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
/* The linears' format, from layer 0's projection, before the activations' codes are declared:
|
||||
* rotated int8 ones read int8 pairs. */
|
||||
m.te.resize((size_t)g.n_layer);
|
||||
{
|
||||
const char* pre = "model.language_model.layers";
|
||||
RAD_ARCH_TRY(m.te[0].qkv.probe(b, nm, g, "te.blk.0.attn_qkv",
|
||||
{ nm.ckpt("%s.0.self_attn.q_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.k_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.v_proj.weight", pre) }));
|
||||
RadEncoding e{};
|
||||
if (weight_enc(b, nm.f("te.blk.0.attn_qkv.weight"), &e) &&
|
||||
(linear_is_w8h(e) || linear_is_wnh(e))) {
|
||||
m.te_i8 = true;
|
||||
m.te_g8 = linear_w8h_group(e);
|
||||
}
|
||||
}
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd));
|
||||
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", g.n_embd, 0, m.te_i8, m.te_g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim));
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, 0, m.te_i8, m.te_g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, 0, m.te_i8, m.te_g8,
|
||||
"gated_had_quant_i8g"));
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd),
|
||||
@@ -887,15 +914,32 @@ static int declare_refiner(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.b_rh = decl_b(b, nm.f("ref.h"), RAD_BF16, { T, D });
|
||||
m.op_ce = dense_bias(b, nm, "ref.ctx", "transformer.context_embedder", RAD_BF16, "bf16", D,
|
||||
tdim, T, m.b_tx, m.b_rh, &m.w_ce, &m.b_ce, acc, gx);
|
||||
/* The refiner's linears' format, from block 0's projection (declare_te's note). */
|
||||
{
|
||||
const char* pre = nm.ckpt("transformer.token_refiner.refiner_blocks.0");
|
||||
RAD_ARCH_TRY(m.rb[0].qkv.probe(b, nm, g, "ref.blk.0.attn_qkv",
|
||||
{ nm.ckpt("%s.attn.to_q.weight", pre),
|
||||
nm.ckpt("%s.attn.to_k.weight", pre),
|
||||
nm.ckpt("%s.attn.to_v.weight", pre) }));
|
||||
RadEncoding e{};
|
||||
if (weight_enc(b, nm.f("ref.blk.0.attn_qkv.weight"), &e) &&
|
||||
(linear_is_w8h(e) || linear_is_wnh(e))) {
|
||||
m.ref_i8 = true;
|
||||
m.ref_g8 = linear_w8h_group(e);
|
||||
}
|
||||
}
|
||||
m.a_rh.x = decl_b(b, nm.f("ref.hn"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_rh.declare_qs(b, nm, g, "ref.hn", D));
|
||||
RAD_ARCH_TRY(m.a_rh.declare_pair(b, nm, g, "ref.hn", D, 0, m.ref_i8, m.ref_g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_rqkv = decl_b(b, nm.f("ref.qkv"), RAD_BF16, { T, 3 * qd });
|
||||
m.a_rattn.x = decl_b(b, nm.f("ref.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_rattn.declare_qs(b, nm, g, "ref.attn", qd));
|
||||
RAD_ARCH_TRY(m.a_rattn.declare_pair(b, nm, g, "ref.attn", qd, 0, m.ref_i8, m.ref_g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_rao = decl_b(b, nm.f("ref.ao"), RAD_BF16, { T, D });
|
||||
m.b_rgu = decl_b(b, nm.f("ref.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_rffn.x = decl_b(b, nm.f("ref.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_rffn.declare_qs(b, nm, g, "ref.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_rffn.declare_pair(b, nm, g, "ref.ffn", g.n_ff, 0, m.ref_i8, m.ref_g8,
|
||||
"gated_had_quant_i8g"));
|
||||
const int64_t ff_all = g.n_ff_all;
|
||||
|
||||
for (int l = 0; l < 2; ++l) {
|
||||
@@ -1063,13 +1107,10 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.op_ts = unary(b, "silu", TT, hd1, "f32", m.b_te1, m.b_te1s);
|
||||
m.op_t2 = dense_bias(b, nm, "tmb.l2", "transformer.time_embedder.linear_2", RAD_F32, "f32",
|
||||
td, hd1, TT, m.b_te1s, m.b_temb, &m.w_t2, &m.b_t2, acc, gx);
|
||||
/* silu(temb) in f32, rounded once to the bf16 the projections take. */
|
||||
Geom gs = g;
|
||||
gs.max_tok = TT;
|
||||
/* silu(temb) in f32, rounded once to the bf16 the projections take. Its codes are
|
||||
* declared below, once the first projection's encoding says which they are. */
|
||||
m.a_temb.x = decl_b(b, nm.f("tmb.act"), RAD_BF16, { TT, td });
|
||||
m.op_ts2 = unary(b, "silu", TT, td, "f32", m.b_temb, m.a_temb.x);
|
||||
RAD_ARCH_TRY(m.a_temb.declare_qs(b, nm, gs, "tmb.act", td, TT));
|
||||
RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td));
|
||||
if (!m.op_temb || !m.op_temb_pv || !m.op_temb_pa || !m.op_t1 || !m.op_ts || !m.op_t2
|
||||
|| !m.op_ts2) return RAD_E_INVAL;
|
||||
}
|
||||
@@ -1106,16 +1147,58 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_WEIGHTS(B.ada_w[md], B.ada_b[md])),
|
||||
{ m.a_temb.x }, { m.b_ada });
|
||||
} else {
|
||||
/* The embedding's codes, from the first projection's encoding: E4M3, or for
|
||||
* rotated int8 projections the int8 pair at their scale group. */
|
||||
if (l == 0 && md == 0) {
|
||||
RadEncoding e{};
|
||||
if (weight_enc(b, wn, &e) && linear_is_w8h(e)) {
|
||||
m.ada_i8 = true;
|
||||
m.ada_g8 = linear_w8h_group(e);
|
||||
}
|
||||
Geom gs = g;
|
||||
gs.max_tok = TT;
|
||||
RAD_ARCH_TRY(m.a_temb.declare_pair(b, nm, gs, "tmb.act", td, TT, m.ada_i8,
|
||||
m.ada_g8, "had_quant_act_i8g"));
|
||||
if (m.ada_i8 && !m.a_temb.q8_fed) {
|
||||
fprintf(stderr, "radiance: minimaxh3: rotated int8 modulation projections "
|
||||
"need had_quant_act_i8g, which no loaded library serves\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td));
|
||||
}
|
||||
/* The row slice is mapped above (DenseFP8 takes that as its argument). */
|
||||
B.ada[md].w8h_ok = m.ada_i8;
|
||||
RAD_ARCH_TRY(B.ada[md].declare(b, nm, base, m.Ws, td, acc, RAD_SHARD_ROW,
|
||||
grp_layer(grp), { src_w }, {}, true));
|
||||
B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws),
|
||||
RAD_INT("K", td),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(B.ada[md].w, B.ada[md].s, B.ada_b[md])),
|
||||
{ m.a_temb.q, m.a_temb.s }, { m.b_ada });
|
||||
if (B.ada[md].w8h != m.ada_i8) {
|
||||
fprintf(stderr, "radiance: minimaxh3: '%s' is not encoded as the first "
|
||||
"modulation projection is\n", wn);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (m.ada_i8) {
|
||||
/* i8a8h has no biased row and writes whole rows: the GEMM goes to its own
|
||||
* rows, and the bias is added on the way into the table's cell. */
|
||||
if (!m.b_adat) m.b_adat = decl_b(b, nm.f("tmb.ada"), RAD_BF16, { S, m.Ws });
|
||||
if (!m.b_adat) return RAD_E_INVAL;
|
||||
B.op_ada[md] = B.ada[md].gemm(b, S, m.Ws, td,
|
||||
{ m.a_temb.cq(), m.a_temb.cs() }, { m.b_adat });
|
||||
B.op_ada_b[md] = rw(b, RAD_OP(b, "table_add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S),
|
||||
RAD_INT("n", m.Ws), RAD_INT("L", 1),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(B.ada_b[md])),
|
||||
{ m.b_adat }, { m.b_ada });
|
||||
if (!B.op_ada_b[md]) return RAD_E_INVAL;
|
||||
} else {
|
||||
B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws),
|
||||
RAD_INT("K", td),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(B.ada[md].w, B.ada[md].s,
|
||||
B.ada_b[md])),
|
||||
{ m.a_temb.q, m.a_temb.s }, { m.b_ada });
|
||||
}
|
||||
}
|
||||
if (!B.op_ada[md]) return RAD_E_INVAL;
|
||||
}
|
||||
@@ -2263,7 +2346,11 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.ve_fold_mul = join_list(fm);
|
||||
m.ve_fold_add = join_list(fa);
|
||||
m.b_epix32 = decl_b(b, nm.f("venc.pix32"), RAD_F32, { Rmax, 3 });
|
||||
m.b_epix = decl_b(b, nm.f("venc.pix"), RAD_BF16, { Rmax, 3 });
|
||||
/* conv_in and the k=1 projections run on the host. Their activation operands must be
|
||||
* pinned host buffers too: joining a device queue does not make its VRAM CPU-readable.
|
||||
* Device convolutions can read/write these boundary buffers over the link in place. */
|
||||
m.b_epix = decl_b(b, nm.f("venc.pix"), RAD_BF16, { Rmax, 3 },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.b_egn = decl_b(b, nm.f("venc.gn"), RAD_F32, { G * (2 + 3 * 1024) });
|
||||
const rad_buf st = m.b_egn;
|
||||
/* The tiled encode's two planes and the quant_conv are declared ahead of the trunk, and the
|
||||
@@ -2271,12 +2358,16 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
* tiled pass reruns the whole trunk once a tile while `b_vtile` holds every tile's pixels and
|
||||
* `b_eqt` the finished tiles' moments, so both lifetimes must span the trunk's ops (from
|
||||
* op_ve_pix's and op_ve_q's use to op_vt_crop and op_vt_join). */
|
||||
m.b_tplan = decl_b(b, nm.f("venc.tplan"), RAD_I32, { m.tiles, 22 }, RAD_BUF_PERSIST);
|
||||
m.b_tplan = decl_b(b, nm.f("venc.tplan"), RAD_I32, { m.tiles, 22 },
|
||||
RAD_BUF_PERSIST, RAD_DOMAIN_HOST);
|
||||
m.b_vtile = decl_b(b, nm.f("venc.vtile"), RAD_F32,
|
||||
{ m.tiles * (int64_t)kEncMaxSide * kEncMaxSide, 3 });
|
||||
m.b_eq48 = decl_b(b, nm.f("venc.q48"), RAD_BF16, { R[5], 48 });
|
||||
m.b_eq2 = decl_b(b, nm.f("venc.q"), RAD_BF16, { R[5], 48 });
|
||||
m.b_eqt = decl_b(b, nm.f("venc.qt"), RAD_BF16, { m.tiles * (int64_t)kTile * kTile, 48 });
|
||||
m.b_eq48 = decl_b(b, nm.f("venc.q48"), RAD_BF16, { R[5], 48 },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.b_eq2 = decl_b(b, nm.f("venc.q"), RAD_BF16, { R[5], 48 },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.b_eqt = decl_b(b, nm.f("venc.qt"), RAD_BF16, { m.tiles * (int64_t)kTile * kTile, 48 },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.ve_qw = wh(nm.f("venc.q.weight"), nm.ckpt("vae.quant_conv.weight"), { 48, 48, 1, 1, 1 });
|
||||
m.ve_qb = wh(nm.f("venc.q.bias"), nm.ckpt("vae.quant_conv.bias"), { 48 });
|
||||
/* The whole-canvas pass writes b_eq2; the tiled pass writes a tile's slice of b_eqt, which
|
||||
@@ -2313,7 +2404,8 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const int64_t cout = (int64_t)dims[L], cin = L == 0 ? cout : (int64_t)dims[L - 1];
|
||||
const bool sc = L > 0 && cout != cin;
|
||||
E.cin = cin, E.cout = cout, E.rows = R[L], E.pf = PF[L], E.frames = tf[L];
|
||||
E.a = decl_b(b, nm.f("venc.l%d.a", L), RAD_BF16, { R[L], cout });
|
||||
E.a = decl_b(b, nm.f("venc.l%d.a", L), RAD_BF16, { R[L], cout },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
E.b = decl_b(b, nm.f("venc.l%d.b", L), RAD_BF16, { R[L], cout });
|
||||
E.c = decl_b(b, nm.f("venc.l%d.c", L), RAD_BF16, { R[L], cout });
|
||||
/* A level that changes the width takes its input in a buffer of that width, which the
|
||||
@@ -2321,7 +2413,8 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
* none. */
|
||||
if (sc) {
|
||||
const bool dn_in = (int64_t)sds[L - 1] == 2 || (int64_t)tds[L - 1] == 2;
|
||||
E.in = dn_in ? decl_b(b, nm.f("venc.l%d.in", L), RAD_BF16, { R[L], cin })
|
||||
E.in = dn_in ? decl_b(b, nm.f("venc.l%d.in", L), RAD_BF16, { R[L], cin },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST)
|
||||
: m.v_lv[(size_t)L - 1].a;
|
||||
const char* sc_src = nm.ckpt("vae.encoder.down_blocks.%d.resnets.0.conv_shortcut", L);
|
||||
E.scw = wh(nm.f("venc.l%d.sc.weight", L), nm.ckpt("%s.weight", sc_src),
|
||||
@@ -2798,8 +2891,9 @@ static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
/* ================================================================== declare */
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
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);
|
||||
Names& nm = m.nm;
|
||||
@@ -2923,8 +3017,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(declare_dit(b, meta, m));
|
||||
if (m.dit[0].qkv.bf16) {
|
||||
fprintf(stderr, "radiance: minimaxh3: the DiT's linears are bf16; this plugin serves the "
|
||||
"block-fp8 container (data/recipes/minimax-h3-fp8.recipe) or the int8 one "
|
||||
"(data/recipes/minimax-h3-w8a8.recipe)\n");
|
||||
"int8 container (data/recipes/minimax-h3-i8.recipe)\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(declare_ups(b, meta, m));
|
||||
@@ -3203,10 +3296,15 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const int64_t r0 = cell[(size_t)e].second;
|
||||
const RadOperand out =
|
||||
bcol_at(m.b_ada, base, L * kMaxSegs * m.Ws, (l * kMaxSegs + e) * m.Ws, m.Ws, S);
|
||||
if (m.curve > 0)
|
||||
if (m.curve > 0) {
|
||||
RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.x, r0, S, td),
|
||||
RAD_W(B.ada_w[md]), RAD_W(B.ada_b[md]), RAD_NONE, out);
|
||||
else
|
||||
} else if (m.ada_i8) {
|
||||
RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q8, r0, S, td),
|
||||
brow_slice(m.a_temb.s8, r0, S, td / m.ada_g8), RAD_W(B.ada[md].w),
|
||||
RAD_W(B.ada[md].s), brows(m.b_adat, S), RAD_NONE, RAD_NONE);
|
||||
RAD_ISSUE_N(c, B.op_ada_b[md], S, brows(m.b_adat, S), RAD_W(B.ada_b[md]), out);
|
||||
} else
|
||||
RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q, r0, S, td),
|
||||
brow_slice(m.a_temb.s, r0, S, td / RAD_FP8_BLOCK), RAD_W(B.ada[md].w),
|
||||
RAD_W(B.ada[md].s), RAD_W(B.ada_b[md]), out);
|
||||
@@ -3934,7 +4032,7 @@ static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->vgen_b) {
|
||||
rad_step_fail(c, "minimaxh3 is a video generator and runs its generator passes only");
|
||||
return;
|
||||
@@ -3987,6 +4085,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(minimaxh3)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(minimaxh3, "minimaxh3", "", "0.1.0",
|
||||
"MiniMax-H3 (t2va, i2va, l2va, fl2va, ref2va): Qwen3-VL-32B conditioning, a 33B "
|
||||
"single-stream diffusion transformer over text, soundtrack and video, a tiled ViT "
|
||||
|
||||
@@ -208,7 +208,7 @@ struct Model {
|
||||
rad_buf b_audio = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x,
|
||||
@@ -1083,8 +1083,9 @@ static int check_format(const RadModelMeta* meta) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
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(check_format(meta));
|
||||
@@ -1381,7 +1382,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->agen_b) {
|
||||
rad_step_fail(c, "minimaxmusic3 is an audio generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1575,6 +1576,8 @@ RAD_ARCH_PROBE(minimaxmusic3)
|
||||
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
return minimaxmusic3::text_prepare(field, in, out, cap);
|
||||
}
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(minimaxmusic3, "minimaxmusic3", "", "0.1.0",
|
||||
"MiniMax-Music3: a Qwen3-8B music language model with a residual-code depth "
|
||||
"decoder, a 2.4B flow-matching transformer over windows of frames, and a DAC "
|
||||
|
||||
@@ -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,198 @@
|
||||
/* dflash2.h -- wire rad_block_dflash2.h onto a Muse Glimmer trunk.
|
||||
*
|
||||
* Meta's assistant is a plain DFlash (rad_block_muse_dflash.h). incoai's Muse-Glimmer-30B-DFlash2
|
||||
* is the DFlash2 block: candidate selector, grouped convolutions, 8 KV heads. The two are
|
||||
* selected by draft.architectures. Muse's DFlash2 ships output_multiplier and
|
||||
* final_logit_softcapping; the block applies those (Config::omul / Config::scap).
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <arch/rad_block_dflash2.h>
|
||||
#include <arch/rad_block_muse_dflash.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
inline bool muse_draft_is_dflash2(const RadModelMeta* meta) {
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
return da && std::strstr(da, "DFlash2");
|
||||
}
|
||||
|
||||
/* Same 12 MiB prefetch qwen35 measured on two R9700s. */
|
||||
constexpr int64_t kMuseDf2Prefetch = (int64_t)12 << 20;
|
||||
|
||||
inline int declare_muse_dflash2(Dflash2* ds, Dflash2::Wire* w, rad_kvgroup* kv,
|
||||
RadBuilder* b, Names& nm, const RadModelMeta* meta,
|
||||
const RadBuildCtx* ctx, const Geom& target,
|
||||
const MuseTaps& taps, int base_layer, rad_weight tok_embd,
|
||||
rad_weight head_w) {
|
||||
if (!ds || !w || !kv || !b) return RAD_E_INVAL;
|
||||
Geom dg{};
|
||||
RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DFlash2", /*kv_repl_ok=*/true));
|
||||
const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size",
|
||||
rad_meta_geti(meta, "draft.dflash_config.hidden_size",
|
||||
dg.n_embd));
|
||||
if (want_embd != dg.n_embd) {
|
||||
fprintf(stderr, "radiance: museglimmer: the DFlash2 drafter reads a %lld-wide trunk and "
|
||||
"this target is %lld wide; they are not the same model\n",
|
||||
(long long)want_embd, (long long)dg.n_embd);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Dflash2::Config dc{};
|
||||
dc.short_block = 1;
|
||||
dc.prefetch = kMuseDf2Prefetch;
|
||||
dc.n_taps = taps.n;
|
||||
dc.block = ctx->max_spec + 1;
|
||||
dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2);
|
||||
dc.group = rad_meta_geti(meta, "draft.dflash_config.conv_group_size", 16);
|
||||
dc.sel_rank = rad_meta_geti(meta, "draft.dflash_config.selector_rank", 0);
|
||||
dc.sel_topk = rad_meta_geti(meta, "draft.dflash_config.selector_top_k", 0);
|
||||
dc.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
|
||||
if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
|
||||
dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size",
|
||||
rad_meta_geti(meta, "draft.sliding_window", 0));
|
||||
if (dc.sel_rank <= 0 || dc.sel_topk <= 0) {
|
||||
fprintf(stderr, "radiance: museglimmer: the DFlash2 drafter states no selector geometry "
|
||||
"(rank %lld, top_k %lld)\n",
|
||||
(long long)dc.sel_rank, (long long)dc.sel_topk);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
const long long trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0);
|
||||
if (dc.block < 2 || (dc.block & (dc.block - 1))) {
|
||||
fprintf(stderr, "radiance: museglimmer: DFlash2's convolution masks the block position "
|
||||
"with block_size - 1, so the query block has to be a power of two. This "
|
||||
"serve asks for %d draft tokens, which makes it %lld; the checkpoint was "
|
||||
"trained at %lld.\n",
|
||||
ctx->max_spec, (long long)dc.block, trained);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (trained > 0 && trained != dc.block)
|
||||
rad_note(b, "DFlash2 was trained at block_size %lld (%lld draft tokens) and runs at "
|
||||
"%lld; it accepts less away from its trained block length",
|
||||
trained, trained - 1, (long long)dc.block);
|
||||
|
||||
dc.escale = rad_meta_getf(meta, "draft.dflash_config.input_embedding_scale", 1.0);
|
||||
dc.omul = rad_meta_getf(meta, "draft.dflash_config.output_multiplier", 1.0);
|
||||
dc.scap = rad_meta_getf(meta, "draft.dflash_config.final_logit_softcapping", 0.0);
|
||||
RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
|
||||
dc.fc_mapped = true;
|
||||
|
||||
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, kv));
|
||||
|
||||
const int64_t qd = dg.n_head * dg.head_dim;
|
||||
const int64_t kvd = dg.n_head_kv * dg.head_dim;
|
||||
const uint32_t act_dtype = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
|
||||
const int64_t act_group = dc.act_i8 ? dc.act_g8 : RAD_FP8_BLOCK;
|
||||
const auto act_groups = [act_group](int64_t n) { return (n + act_group - 1) / act_group; };
|
||||
int64_t qr = dg.max_seqs * dc.block;
|
||||
if (qr > dg.max_tok) qr = dg.max_tok;
|
||||
const int64_t sr = dg.max_seqs * dc.steps();
|
||||
const int64_t spad = ((sr + 15) / 16) * 16;
|
||||
|
||||
Dflash2::Wire& dw = *w;
|
||||
dw.src = taps.src;
|
||||
dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd});
|
||||
dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd});
|
||||
dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd});
|
||||
dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.h2 = decl_b(b, nm.f("df_h2"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.coef = decl_b(b, nm.f("df_coef"), dg.act_dtype, {qr, dc.coef_dim(dg.n_embd)});
|
||||
dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd});
|
||||
dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd});
|
||||
dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd});
|
||||
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
|
||||
dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
|
||||
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
|
||||
dw.srcq = decl_b(b, nm.f("df_srcq"), act_dtype,
|
||||
{dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32,
|
||||
{dg.max_tok, act_groups(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("df_cq"), act_dtype, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, act_groups(dg.n_embd)});
|
||||
dw.h2q = decl_b(b, nm.f("df_h2q"), act_dtype, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, act_groups(dg.n_embd)});
|
||||
dw.atq = decl_b(b, nm.f("df_atq"), act_dtype, {qr, qd});
|
||||
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, act_groups(qd)});
|
||||
dw.ffq = decl_b(b, nm.f("df_ffq"), act_dtype, {qr, dg.n_ff});
|
||||
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, act_groups(dg.n_ff)});
|
||||
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
|
||||
dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank});
|
||||
dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd});
|
||||
dw.ds = decl_b(b, nm.f("df_ds"), RAD_F32, {sr, 1});
|
||||
dw.dsum = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad});
|
||||
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)});
|
||||
{
|
||||
const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16);
|
||||
if (head_w && (hd == RAD_F8E4M3 || hd == RAD_I8) &&
|
||||
(Dflash2::head_sharded(dg) || dg.world <= 1)) {
|
||||
ds->w_lm = head_w;
|
||||
ds->top_w = Dflash2::kRerankR;
|
||||
}
|
||||
}
|
||||
const int64_t tw = ds->w_lm ? ds->top_w : dc.sel_topk;
|
||||
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, tw});
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, tw});
|
||||
if (Dflash2::head_sharded(dg)) {
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
|
||||
}
|
||||
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
|
||||
if (ctx->draft_coupling) {
|
||||
if (dc.steps() > RAD_MTP_COUPLE_MAX_ROUNDS || dc.sel_topk > RAD_DFLASH_COUPLE_MAX_K ||
|
||||
dc.sel_rank % RAD_DFLASH_EDGE_PARTS || dc.sel_rank > RAD_DFLASH_COUPLE_MAX_R) {
|
||||
fprintf(stderr, "radiance: museglimmer: --draft-coupling on DFlash2 needs at most "
|
||||
"%d drafts, %d candidates and a selector rank that is a multiple of "
|
||||
"%d up to %d\n",
|
||||
RAD_MTP_COUPLE_MAX_ROUNDS, RAD_DFLASH_COUPLE_MAX_K, RAD_DFLASH_EDGE_PARTS,
|
||||
RAD_DFLASH_COUPLE_MAX_R);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
dc.q_temp = 0.6;
|
||||
dw.couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
|
||||
{dg.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, RAD_BUF_PERSIST);
|
||||
dw.couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
|
||||
{dc.steps(), dg.max_seqs, RAD_MTP_COUPLE_STATE_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
if (!dw.couple_draws || !dw.couple_state) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(ds->declare(b, nm, dg, dc, base_layer, *kv, tok_embd, "draft",
|
||||
nm.ckpt("lm_head.weight"), dw));
|
||||
|
||||
RadDrafterDecl drf{};
|
||||
drf.name = "dflash2";
|
||||
drf.kind = RAD_DRAFT_BLOCK;
|
||||
drf.depth = ctx->max_spec;
|
||||
drf.block = dc.block;
|
||||
drf.proposal = dw.tokens;
|
||||
drf.proposal_pitch = dc.steps();
|
||||
drf.window = dc.window;
|
||||
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1);
|
||||
if (drf.mask_token < 0) {
|
||||
fprintf(stderr, "radiance: museglimmer: this DFlash2 checkpoint declares no "
|
||||
"dflash_config.mask_token_id\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
if (ds->block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, ds->block_lo));
|
||||
|
||||
rad_note(b, "DFlash2 drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
|
||||
"ffn %lld, %s attention with a %lld-token window, %d trunk tap(s); one forward "
|
||||
"proposes %lld tokens through the candidate selector",
|
||||
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
|
||||
(long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
|
||||
(long long)dg.n_ff, dc.causal ? "causal" : "non-causal", (long long)dc.window,
|
||||
taps.n, (long long)dc.steps());
|
||||
if (dc.omul != 1.0 || dc.scap > 0.0)
|
||||
rad_note(b, "DFlash2 logits: output_multiplier %g, softcap %g", dc.omul, dc.scap);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,855 @@
|
||||
/* 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 <arch/rad_museglimmer_chat.h>
|
||||
#include "dflash2.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 {
|
||||
|
||||
} // 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{};
|
||||
|
||||
/* ---- Meta's DFlash or incoai's DFlash2, selected by draft.architectures. */
|
||||
bool have_df = false, have_df2 = false;
|
||||
MuseDflash df{};
|
||||
MuseDflash::Wire dfw{};
|
||||
Dflash2 df2{};
|
||||
Dflash2::Wire df2w{};
|
||||
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)meta_text_getf(meta, "qk_scale_factor", 3.87);
|
||||
m.post_eps = (float)meta_text_getf(meta, "post_norm_eps", 1e-8);
|
||||
m.out_mult = (float)meta_text_getf(meta, "output_multiplier", 0.19611613513818404);
|
||||
m.softcap = (float)meta_text_getf(meta, "final_logit_softcapping", 20.0);
|
||||
m.window = meta_text_geti(meta, "sliding_window", 2048);
|
||||
const double theta_rope = meta_text_getf(meta, "rope_parameters.rope_theta",
|
||||
meta_text_getf(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 = meta_text_gets(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 = meta_text_gets(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 drafter is declared last so its buffers cannot overlap trunk temporaries. */
|
||||
if (m.taps.n > 0) {
|
||||
if (muse_draft_is_dflash2(meta)) {
|
||||
RAD_ARCH_TRY(declare_muse_dflash2(&m.df2, &m.df2w, &m.kv_draft, b, nm, meta, ctx, g,
|
||||
m.taps, (int)g.n_layer, m.w_tok, m.w_lm_head));
|
||||
m.have_df2 = true;
|
||||
} else {
|
||||
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_df2) {
|
||||
if (batch->draft_pass > 0) m.df2.step(c, batch);
|
||||
else m.df2.context(c, batch);
|
||||
return;
|
||||
}
|
||||
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. The first Hessian sees the normalized input consumed by q/gate/k/v. */
|
||||
RAD_ISSUE(c, l.op_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T));
|
||||
if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, 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));
|
||||
if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, 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));
|
||||
if (l.cs_mlp >= 0) m.calib.tap(c, (size_t)l.cs_mlp, 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));
|
||||
if (l.cs_down >= 0) m.calib.tap(c, (size_t)l.cs_down, 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));
|
||||
if (m.cs_head >= 0) m.calib.tap(c, (size_t)m.cs_head, T);
|
||||
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;
|
||||
/* DFlash2 reads block_size from dflash_config; its anchor row proposes nothing. */
|
||||
if (muse_draft_is_dflash2(meta)) {
|
||||
const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 16);
|
||||
out->draft_depth = bs > 1 ? (int)(bs - 1) : 15;
|
||||
out->draft_depth_fixed = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Meta DFlash denoises `block_size` positions; the anchor proposes nothing. */
|
||||
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
@@ -36,7 +36,8 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
Pixtral vision;
|
||||
};
|
||||
static Model model;
|
||||
/* One per engine instance in the process, by slot (rad_builder.h, rad_build_slot). */
|
||||
static Model g_model[RAD_MAX_SLOTS];
|
||||
|
||||
/* JSON booleans reach plugins as 0/1, while out-of-tree callers may use their JSON spelling. */
|
||||
static bool false_value(const char* s) {
|
||||
@@ -86,7 +87,9 @@ static int read_rope(Geom& g, const RadModelMeta* meta) {
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->max_seqs <= 0) return RAD_E_INVAL;
|
||||
if (!b || !meta || !ctx || ctx->max_seqs <= 0 || ctx->rank < 0 ||
|
||||
rad_build_slot(ctx) >= RAD_MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->rank != 0 || ctx->world_size > 1 || ctx->is_draft || ctx->max_spec > 0) {
|
||||
std::fprintf(stderr, "radiance: nemotron35_embed serves BF16 at TP1, without drafting\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -116,8 +119,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_meta_geti(meta, "text_config.rope_parameters.original_max_position_embeddings", 0);
|
||||
if (!std::isfinite(beta) || beta < 0 || original <= 0) return RAD_E_INVAL;
|
||||
|
||||
model = Model{};
|
||||
Model& m = model;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.rerank =
|
||||
!std::strcmp(rad_meta_gets(meta, "architectures", ""), "Mistral3ForSequenceClassification");
|
||||
const char* architecture = rad_meta_gets(meta, "architectures", "");
|
||||
@@ -340,7 +343,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = model;
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
if (batch->enc) {
|
||||
m.vision.step(c, batch);
|
||||
@@ -399,6 +402,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} // namespace nemotron35_embed
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(nemotron35_embed, "mistral3", "", "0.5.0",
|
||||
"Nemotron-3.5-Embed/Rerank: experimental BF16 text/image retrieval, TP1")
|
||||
RAD_ARCH_PROBE(nemotron35_embed)
|
||||
|
||||
@@ -393,7 +393,7 @@ struct Model {
|
||||
LiliCorr lili{};
|
||||
LiliCorr::Wire lw{};
|
||||
};
|
||||
static std::unique_ptr<Model> models[MAX_RANKS];
|
||||
static std::unique_ptr<Model> models[MAX_SLOTS];
|
||||
static thread_local std::unique_ptr<Model> probe_model;
|
||||
|
||||
static int read_shape(const RadModelMeta* meta, Shape& s) {
|
||||
@@ -765,10 +765,11 @@ static int declare_lilicorr(RadBuilder* b, const RadModelMeta* meta, const RadBu
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[rad_build_slot(ctx)];
|
||||
slot = std::make_unique<Model>();
|
||||
auto& m = *slot;
|
||||
auto& g = m.g;
|
||||
@@ -1054,7 +1055,7 @@ static void dump_draft(RadCtx* c, const RadBatch* batch, const char* what, const
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
auto& m = *models[rad_rank(c)];
|
||||
auto& m = *models[rad_slot(c)];
|
||||
const int64_t T = batch->n_tok, E = m.g.n_embd;
|
||||
if (batch->enc) {
|
||||
m.radio.step(c, batch);
|
||||
@@ -1137,6 +1138,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
} // namespace nemotronh
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(nemotronh)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(nemotronh, "nemotronh", "", "0.1.0",
|
||||
"Nemotron-H (nemotron_h_omni/puzzle): Mamba-2, latent relu^2 MoE and NoPE attention")
|
||||
#endif
|
||||
@@ -71,7 +71,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The layer schedule, read from moe_every_n_layers rather than derived: a wrong interval would
|
||||
* declare a MoE layer whose tensors the checkpoint does not hold. Layer l is routed when
|
||||
@@ -93,7 +93,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
/* A 475M-parameter encoder fits one card; tensor parallelism would only add an all-reduce per
|
||||
* layer. */
|
||||
if (ctx->world_size > 1) {
|
||||
@@ -102,7 +103,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
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));
|
||||
@@ -441,7 +442,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
|
||||
if (T <= 0 || S <= 0) return;
|
||||
@@ -500,6 +501,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace nomicbert */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(nomicbert, "nomicbert", "", "0.1.0",
|
||||
"Nomic BERT (nomic-embed-text-v2-moe): a bidirectional post-norm encoder with "
|
||||
"NeoX rotary attention, dense and routed GELU feed-forwards, mean-pooled to one "
|
||||
|
||||
@@ -103,14 +103,16 @@ struct Model {
|
||||
};
|
||||
|
||||
/* Declare runs once per rank, in one process, on the rank's own thread (spec §1, §9), so the
|
||||
* model state is indexed by rank and read back in step() with rad_rank(). */
|
||||
static Model g_model[MAX_RANKS];
|
||||
* model state is per instance: indexed by the instance's slot (unique across every engine in the
|
||||
* process, rad_build_slot) and read back in step() with 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) 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[ctx->rank];
|
||||
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));
|
||||
@@ -479,7 +481,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
|
||||
/* An encoder pass runs only the vision tower (RadBatch::enc). */
|
||||
if (batch->enc) {
|
||||
@@ -539,9 +541,23 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Chained launches pay on the plain-bf16 trunk with a drafter and without one: every kernel of
|
||||
* its decode step but the gated delta net's two and the vocabulary GEMM has a chained form
|
||||
* (libr4d's rad_kernel_chain). Ms a decode step unchained / chained: Qwen3.5-0.8B on one R9700
|
||||
* 3.89 / 3.60 at one sequence and 4.72 / 4.46 at four; Qwen3.8-27B as bf16 on two, where the
|
||||
* bf16 GEMMs are nearly all of the step, 48.04 / 47.41 and 49.57 / 48.81. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace qwen35_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PROBE(qwen35_bf16)
|
||||
RAD_ARCH_PLUGIN(qwen35_bf16, "qwen35", "", "0.1.0",
|
||||
"Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), bf16 weights and activations, gated "
|
||||
"attention over paged KV every fourth layer and gated delta net between")
|
||||
|
||||
+126
-81
@@ -56,16 +56,17 @@
|
||||
*
|
||||
* Its differences are behind `#if QWEN35_W8A8`: check_format's method, the probe that learns the
|
||||
* trunk is int8 before the activations are declared (and refuses one that is not), and the plugin
|
||||
* identity. The int8 activation pairs follow from the probe. */
|
||||
* identity. The int8 activation pairs follow from the probe.
|
||||
*
|
||||
* Both macros together are `qwen35moe_w8a8`, the routed build with that trunk: the experts are
|
||||
* rotated too (int8 at a bf16 scale a 128 of K, or the four-bit forms) and read the int8 codes the
|
||||
* trunk's own quantisers write (rad_block_moe_fp8.h, MoeFP8::a8). */
|
||||
#ifndef QWEN35_MOE
|
||||
#define QWEN35_MOE 0
|
||||
#endif
|
||||
#ifndef QWEN35_W8A8
|
||||
#define QWEN35_W8A8 0
|
||||
#endif
|
||||
#if QWEN35_MOE && QWEN35_W8A8
|
||||
#error "qwen35_w8a8 is the dense build; a routed int8 trunk is not a format this file serves"
|
||||
#endif
|
||||
/* The plugin's name for a message, expanded once more so it is QWEN35_NS's value. */
|
||||
#define QWEN35_STR_X(x) #x
|
||||
#define QWEN35_STR(x) QWEN35_STR_X(x)
|
||||
@@ -152,6 +153,8 @@ struct Model {
|
||||
/* The trunk's linears are int8 (LinearFP8::i8), learned before the activations are declared
|
||||
* because it decides whether they carry an int8 code pair. Only qwen35_w8a8 sets it. */
|
||||
bool trunk_i8 = false;
|
||||
/* The int8 trunk's scale group: 128, or 256 for IQ8R (linear_w8h_group). */
|
||||
int64_t trunk_g8 = RAD_FP8_BLOCK;
|
||||
|
||||
/* the residual stream and the two vocabulary edges */
|
||||
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
|
||||
@@ -247,7 +250,7 @@ struct Model {
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
@@ -269,9 +272,9 @@ static int check_format(const RadModelMeta* meta) {
|
||||
/* The format the convert stated (the recipe's --set keys); the trunk probe in declare() holds
|
||||
* the weights to it. */
|
||||
if (!method || std::strcmp(method, "w8a8") != 0 || !fmt || std::strcmp(fmt, "fwht128") != 0) {
|
||||
fprintf(stderr, "radiance: qwen35_w8a8 serves a container converted for an int8 trunk "
|
||||
"(quant_method 'w8a8', fmt 'fwht128': data/recipes/"
|
||||
"q38-27b-w8a8-df2.recipe's --set keys); this one says '%s' / '%s'.\n",
|
||||
fprintf(stderr, "radiance: " QWEN35_STR(QWEN35_NS) " serves a container converted for an "
|
||||
"int8 trunk (quant_method 'w8a8', fmt 'fwht128': data/recipes/"
|
||||
"q38-27b-iq8r.recipe's --set keys); this one says '%s' / '%s'.\n",
|
||||
method ? method : "(none)", fmt ? fmt : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -401,22 +404,34 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
|
||||
dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
|
||||
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
|
||||
/* FP8 copies. The drafter's six linears are block-scaled fp8 over a bf16 checkpoint
|
||||
* (rad_fp8.h's DenseFP8), so every activation feeding one has an E4M3 copy and an f32 scale
|
||||
* plane. `srcq` is the largest (50 MiB at a 2048-token chunk and five taps) and halves the
|
||||
* bytes of the context pass's dominant GEMM. */
|
||||
dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3,
|
||||
{dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32,
|
||||
{dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
|
||||
dw.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
|
||||
dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd});
|
||||
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)});
|
||||
dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff});
|
||||
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
|
||||
/* The codes the drafter's six linears read: every activation feeding one has an 8-bit copy
|
||||
* and an f32 scale plane. E4M3 with a scale per 128 for block fp8 or MXFP4 linears (rad_fp8.h's
|
||||
* DenseFP8), int8 with a scale per 128 or IQ8R's 256 for rotated int8 ones, which the drafter's
|
||||
* `fc` tells apart.
|
||||
* `srcq` is the largest (50 MiB at a 2048-token chunk and five taps) and halves the bytes of
|
||||
* the context pass's dominant GEMM. */
|
||||
RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
|
||||
dc.fc_mapped = true;
|
||||
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
|
||||
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
if (dc.act_i8 && ((dc.n_taps * dg.n_embd) % dqg || dg.n_embd % dqg || qd % dqg ||
|
||||
dg.n_ff % dqg)) {
|
||||
fprintf(stderr, "radiance: a rotated int8 drafter takes widths in whole %lld-column scale groups; "
|
||||
"this one is n_embd %lld, q %lld, n_ff %lld\n", (long long)dqg,
|
||||
(long long)dg.n_embd, (long long)qd, (long long)dg.n_ff);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto dqs = [&](int64_t n) { return (n + dqg - 1) / dqg; };
|
||||
dw.srcq = decl_b(b, nm.f("df_srcq"), dqt, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, dqs(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("df_cq"), dqt, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, dqs(dg.n_embd)});
|
||||
dw.h2q = decl_b(b, nm.f("df_h2q"), dqt, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, dqs(dg.n_embd)});
|
||||
dw.atq = decl_b(b, nm.f("df_atq"), dqt, {qr, qd});
|
||||
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, dqs(qd)});
|
||||
dw.ffq = decl_b(b, nm.f("df_ffq"), dqt, {qr, dg.n_ff});
|
||||
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, dqs(dg.n_ff)});
|
||||
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
|
||||
dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank});
|
||||
dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd});
|
||||
@@ -520,9 +535,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
@@ -631,51 +647,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
/* ---- the three KV groups. The attention cache is bf16 by default; `kv_dtype` follows it.
|
||||
*
|
||||
* --kv-cache-dtype fp8 makes it E4M3. The cache is `n_head_kv * head_dim * 2` bytes per token
|
||||
* per layer (2 KiB per rank here), paid only by the 16 attention layers; the 48 delta-net
|
||||
* layers carry fixed-size state. At eight sequences of 16k that is 4.3 GB of reads per step,
|
||||
* most of the cost of depth at that concurrency, and fp8 halves it along with each sequence's
|
||||
* KV pool footprint.
|
||||
* --kv-cache-dtype i8 makes it the int8 cache (abi/rad_builder.h): K and V as int8 codes
|
||||
* with one f16 scale each per token and head, half the bf16 cache's bytes. The cache is paid
|
||||
* only by the 16 attention layers; the 48 delta-net layers carry fixed-size state. At eight
|
||||
* sequences of 16k the bf16 cache is 8.6 GB of reads per step, most of the cost of depth at
|
||||
* that concurrency, and int8 halves it along with each sequence's KV pool footprint.
|
||||
*
|
||||
* Off by default for quality: greedy continuations from a long prompt agree for a few hundred
|
||||
* tokens and then diverge, and the fp8 side can produce syntactically broken code where bf16
|
||||
* stays clean, which matters for a coding model.
|
||||
*
|
||||
* The descales stay at libr4d's default of 1.0 (vLLM's default too); the kernels index them
|
||||
* per (sequence, head), so calibrated descales need no other mechanism. The fp8kv attention
|
||||
* rows and `kv_store_fp8` are in libr4d, the core sizes a page from the group's dtype, and the
|
||||
* drafter's cache takes the same dtype (declare_dflash2). */
|
||||
* Off by default because it changes the model's output slightly. The core sizes a page from
|
||||
* the group's dtype, and the drafter's cache takes the same dtype (declare_dflash2). */
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = RAD_KV_FULL;
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
/* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with f16
|
||||
* scales, K E4M3 as above or int6 the same way (libr4d's fp8_v4 / k6_v4 rows). A token's row
|
||||
* is 25 or 22 * head_dim / 16 bytes instead of 2 * head_dim, so the group is declared at half
|
||||
* that and the core sizes pages from it; only those kernels read the layout. The drafter's
|
||||
* group stays E4M3 (declare_dflash2). The engine asks only for a layout probe() offered. */
|
||||
const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE;
|
||||
const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4" : nullptr;
|
||||
if (kvq != RAD_KVQ_NONE && !kvq_name) {
|
||||
fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (kvq_name && !(g.head_dim == 256 && g.n_head == 6 * g.n_head_kv)) {
|
||||
fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256, gqa 6 "
|
||||
"only; this model is head_dim %lld, gqa %lld\n", kvq_name,
|
||||
(long long)g.head_dim, (long long)(g.n_head_kv ? g.n_head / g.n_head_kv : 0));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32;
|
||||
fd.head_dim = g.head_dim * row16 / 32;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
/* The op parameter must use the spelling the rows band on, which is rad_dtype_name's. */
|
||||
g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype);
|
||||
if (kvq_name)
|
||||
rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a token "
|
||||
"and head instead of %lld", kvq_name, kvq == RAD_KVQ_V4 ? "E4M3" : "int6",
|
||||
(long long)(g.head_dim * row16 / 16), (long long)(2 * g.head_dim));
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
/* The SSM state cache is f32, or f16 under --state-cache-dtype f16 (RadBuildCtx::state_dtype).
|
||||
*
|
||||
@@ -718,6 +705,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RadEncoding enc{};
|
||||
m.trunk_i8 = weight_enc(b, nm.f("blk.%lld.ssm_inz.weight", (long long)l), &enc) &&
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
if (m.trunk_i8) m.trunk_g8 = linear_w8h_group(enc);
|
||||
break;
|
||||
}
|
||||
if (!m.trunk_i8) {
|
||||
@@ -735,7 +723,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* (143 MiB) beside its 285 MiB bf16 buffer. */
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8));
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8, true,
|
||||
m.trunk_g8));
|
||||
|
||||
m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {g.max_tok, g.n_head, 2 * g.head_dim});
|
||||
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim});
|
||||
@@ -751,7 +740,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* it must not share storage with transients. */
|
||||
m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, {rope_table_rows(g), m.n_rot},
|
||||
RAD_BUF_PERSIST);
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8, true,
|
||||
m.trunk_g8));
|
||||
|
||||
/* `gdn_in` is conv_dim + v_dim, not in_dim: a and b have their own buffer because the
|
||||
* checkpoint keeps them bf16, while the fp8 output gate is the tail of this one
|
||||
@@ -771,7 +761,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* Rank 3, as libr4d's scan and recurrent kernels require; the quantiser reads dim 0 as the
|
||||
* row. */
|
||||
m.a_go.x = decl_b(b, nm.f("gdn_o"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
|
||||
RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8));
|
||||
RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8, true,
|
||||
m.trunk_g8));
|
||||
|
||||
#if QWEN35_MOE
|
||||
/* ---- the routing geometry, read here so a refusal names the container's key. `n_ff` is
|
||||
@@ -850,24 +841,60 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_BUF_PERSIST);
|
||||
m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp});
|
||||
m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp});
|
||||
m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp});
|
||||
m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
|
||||
if (m.trunk_i8) {
|
||||
/* An int8 trunk's routed arm is int8 throughout: the gated product's rotated codes
|
||||
* at one scale a 128 of K, an expert's width a rank being whole 128s and not always
|
||||
* whole 256s (MoeFP8::a8). */
|
||||
m.a_eff.g8 = RAD_FP8_BLOCK;
|
||||
m.a_eff.q8 = decl_b(b, nm.f("moe_ffn.q8"), RAD_I8, {K, mc.n_ff_exp});
|
||||
m.a_eff.s8 = decl_b(b, nm.f("moe_ffn.s8"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
|
||||
m.a_eff.q8_fed = m.a_eff.q8_rot = true;
|
||||
} else {
|
||||
m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp});
|
||||
m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
|
||||
}
|
||||
m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd});
|
||||
if (mc.n_ff_shared > 0) {
|
||||
m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {R, g.n_embd});
|
||||
m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * mc.n_ff_shared});
|
||||
m.a_sff.x = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, mc.n_ff_shared});
|
||||
if (m.trunk_i8) {
|
||||
/* The shared expert's down projection is a trunk linear, and its input's codes
|
||||
* take the group its own weight is stored at, read from layer 0's through that
|
||||
* layer's own LinearFP8 (which then maps it once): a recipe keeps it at a 128
|
||||
* where a rank's share of its width is not whole 256s. */
|
||||
LinearFP8& sd = m.layers[0].mlp.sh_down;
|
||||
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.0.ffn_down_shexp"),
|
||||
{ nm.ckpt("model.language_model.layers.0.mlp."
|
||||
"shared_expert.down_proj.weight") }));
|
||||
const int64_t sg = sd.probed_i8 ? sd.probed_g8 : m.trunk_g8;
|
||||
RAD_ARCH_TRY(m.a_sff.declare_pair(b, nm, g, "shexp_ffn", mc.n_ff_shared, R, true,
|
||||
sg, "gated_had_quant_i8g"));
|
||||
} else {
|
||||
m.a_sff.q = decl_b(b, nm.f("shexp_ffn.q"), RAD_F8E4M3, {R, mc.n_ff_shared});
|
||||
m.a_sff.s = decl_b(b, nm.f("shexp_ffn.s"), RAD_F32, {R, fp8_blocks(mc.n_ff_shared)});
|
||||
}
|
||||
m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd});
|
||||
m.b_sgate = decl_b(b, nm.f("shexp_gate"), g.act_dtype, {R, 1});
|
||||
}
|
||||
if (mc.expert_rot) RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
|
||||
/* The experts' rotated copy of the block input. An int8 trunk whose norms write rotated
|
||||
* int8 codes (below) needs none: the experts read `h`'s own. Where they do not (the CPU
|
||||
* kernels), had_quant_act_i8g writes this one at a scale a 128. */
|
||||
const bool h_fed = m.trunk_i8 && rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g"));
|
||||
if (m.trunk_i8 && !h_fed) {
|
||||
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
m.a_hr.q8_fed = m.a_hr.q8_rot = true;
|
||||
} else if (mc.expert_rot && !m.trunk_i8) {
|
||||
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
|
||||
}
|
||||
}
|
||||
#else
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
|
||||
m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8, true,
|
||||
m.trunk_g8));
|
||||
#endif
|
||||
|
||||
#if QWEN35_W8A8
|
||||
@@ -881,7 +908,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g")))
|
||||
m.a_h.q8_fed = m.a_h.q8_rot = true;
|
||||
#if !QWEN35_MOE
|
||||
if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
|
||||
#endif
|
||||
/* The delta net's output likewise, from the decode conv fold's epilogue
|
||||
* (gdn_conv_recurrent_update_had) and had_quant_act_i8g on the other rows (GdnFP8::q_o). */
|
||||
if (rad_op_declared(b, "gdn_conv_recurrent_update_had") && rad_op_declared(b, "had_quant_act_i8g"))
|
||||
@@ -1669,7 +1698,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
#endif
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
|
||||
/* An encoder pass runs only the vision tower (RadBatch::enc). */
|
||||
if (batch->enc) {
|
||||
@@ -1796,17 +1825,22 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
* 0 when the container carries no drafter. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
/* --kv-cache-dtype fp8_v4 / k6_v4: libr4d's rows for them are the h256/gqa6 attention
|
||||
* family's (Qwen3.8-27B), so other geometries are refused at startup rather than in declare. */
|
||||
{
|
||||
const long long hd = meta->head_dim ? meta->head_dim
|
||||
: (meta->n_head ? meta->n_embd / meta->n_head : 0);
|
||||
const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head;
|
||||
if (hd == 256 && nkv > 0 && meta->n_head == 6 * nkv)
|
||||
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
|
||||
}
|
||||
/* The delta-net state cache is declared at RadBuildCtx::state_dtype. */
|
||||
out->state_f16_ok = 1;
|
||||
#if QWEN35_W8A8 && !QWEN35_MOE
|
||||
/* Chained launches pay on an int8 or a trellis trunk with and without its drafter: every
|
||||
* kernel of its decode chain has a chained form (libr4d's rad_kernel_chain), the two-rank
|
||||
* junctions among them. Qwen3.8-27B, ms a decode step unchained / chained, on two R9700: as
|
||||
* IQ8R 32.14 / 21.98 without a drafter and 36.54 / 26.52 with DFlash2 (40.75 / 32.09 at four
|
||||
* sequences), as IQ4R-S-V4 with DFlash2 29.32 / 20.46 (35.37 / 26.81). On one R9700, which
|
||||
* has no junction to wait behind, the IQ8R trunk measured 49.57 / 47.94 without a drafter and
|
||||
* 56.13 / 54.23 with DFlash2.
|
||||
*
|
||||
* Not the routed build: its grouped GEMMs, router and gather have no chained form, and
|
||||
* Qwen3.6-35B-A3B on two R9700s measured a decode step of 10.27 / 11.77 / 12.35 ms at 1, 4 and
|
||||
* 8 sequences with them against 10.25 / 11.58 / 12.25 without. */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
#endif
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (da && std::strstr(da, "DFlash2")) {
|
||||
const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8);
|
||||
@@ -1828,8 +1862,19 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
* expanded first, so these forward the expanded namespace. */
|
||||
#define QWEN35_PROBE_X(NS) RAD_ARCH_PROBE(NS)
|
||||
#define QWEN35_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
QWEN35_PROBE_X(QWEN35_NS)
|
||||
#if QWEN35_MOE
|
||||
#if QWEN35_MOE && QWEN35_W8A8
|
||||
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "w8a8_fwht128", "0.1.0",
|
||||
"Qwen3.5 / 3.6 MoE (35B-A3B), an int8 trunk and int8 experts: i8 weights rotated "
|
||||
"by a 128-wide Hadamard against int8 activations the same rotation quantises; the "
|
||||
"dense graph with a routed feed-forward (256 experts, 8 a token, and a shared "
|
||||
"expert), gated attention over paged KV every fourth layer and gated delta net "
|
||||
"between")
|
||||
/* An imported checkpoint is never a rotated int8 trunk: qwen35moe_fp8 serves those. */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
#elif QWEN35_MOE
|
||||
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0",
|
||||
"Qwen3.5 / 3.6 MoE (35B-A3B), block-scaled fp8 weights and fp8 activations: the "
|
||||
"dense graph with a routed feed-forward (256 experts, 8 a token, and a shared "
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/qwen35moe_w8a8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(qwen35moe_w8a8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(qwen35moe_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35moe_w8a8.cpp)
|
||||
@@ -0,0 +1,19 @@
|
||||
/* qwen35moe_w8a8 -- Qwen3.5 / 3.6 MoE (35B-A3B) with an int8 trunk and int8 experts.
|
||||
*
|
||||
* arch/qwen35_fp8/qwen35_fp8.cpp built a fourth time, with both of its switches: the routed
|
||||
* feed-forward of qwen35moe_fp8 and the rotated int8 trunk of qwen35_w8a8. Every linear of the
|
||||
* trunk is IQ8R (`i8` codes rotated by a 128-wide Hadamard, read at i8a8h against int8
|
||||
* activations), and the routed experts are rotated int8 at a bf16 scale a (row, 128 of K) or one
|
||||
* of the rotated four-bit forms, read by the grouped GEMM's int8 rows from the codes the trunk's
|
||||
* own quantisers write (arch/common/rad_block_moe_fp8.h, MoeFP8::a8).
|
||||
*
|
||||
* A plugin of its own for the reason qwen35_w8a8 is: the quantisation descriptor is half of the
|
||||
* selection key (spec §2.4), and a container converted with data/recipes/q36-35b-a3b-iq8r.recipe
|
||||
* says `qwen35moe` and `w8a8_fwht128`.
|
||||
*/
|
||||
#define QWEN35_MOE 1
|
||||
#define QWEN35_W8A8 1
|
||||
#define QWEN35_NS qwen35moe_w8a8
|
||||
#define QWEN35_ARCH_ID "qwen35moe"
|
||||
|
||||
#include "../qwen35_fp8/qwen35_fp8.cpp"
|
||||
@@ -411,12 +411,13 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
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) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
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));
|
||||
@@ -548,7 +549,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
/* An encoder pass runs the audio tower and nothing else (RadBatch::enc). */
|
||||
if (batch->enc) {
|
||||
m.aud.step(c, batch);
|
||||
@@ -615,6 +616,8 @@ static const RadAudioFormat* audio_format(const RadModelMeta* meta) {
|
||||
} /* namespace qwen3asr_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(qwen3asr_bf16, "qwen3asr", "", "0.1.0",
|
||||
"Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder; bf16 weights "
|
||||
"and activations")
|
||||
|
||||
@@ -95,6 +95,7 @@
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include <arch/rad_block_mtp_hc.h>
|
||||
#include <arch/rad_block_ple.h>
|
||||
#include <arch/rad_calib_full.h>
|
||||
#include <arch/rad_qsa.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
|
||||
@@ -102,6 +103,47 @@ namespace qwen4exp_fp8 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* The delta net's out projection read into the on-die cache beside its decode recurrent update
|
||||
* (GdnFP8::op_pf_out): the update runs one workgroup per (sequence, head) and leaves the memory
|
||||
* mostly idle, and the projection behind it otherwise streams its weight cold. All of the weight
|
||||
* (the read stops at its end), on steps of up to kPrefetchRows rows and kGdnOutPrefetchSeqs
|
||||
* sequences. Flash-Next at tp 2 on two R9700s under the draft head at depth 3, ms a step without ->
|
||||
* with: one stream 12.78 -> 12.58, two 17.12 -> 16.95, four 23.57 -> 23.52 (level, as eight with
|
||||
* the window opened to it). The connection matrices read the same way, beside the recurrent update
|
||||
* or beside the writes in front of the reads, cost more than they gave (one stream 12.69 -> 12.88
|
||||
* and 13.17): a read here pays ~2 us of launch for what it saves. */
|
||||
constexpr int64_t kGdnOutPrefetchBytes = (int64_t)8 << 20;
|
||||
constexpr int64_t kGdnOutPrefetchSeqs = 4;
|
||||
/* The rows from which a decode step is taken for a speculative verify, a step of several rows:
|
||||
* where the shared arm's place and the reads' workgroup count below help, against the one row of
|
||||
* a plain decode step, where both cost. ms a step at tp 2 with coupling, in one server with the
|
||||
* rounds interleaved, at two / three / four rows (chain 1 / 2 / 3) and at one: the arm's down
|
||||
* projection in front -0.28% / -0.21% / -0.25% and +0.38%; the reads at 32 workgroups -0.65% /
|
||||
* -0.35% / -0.31% and +0.41%. */
|
||||
constexpr int64_t kVerifyRows = 2;
|
||||
/* A full-attention layer's out projection likewise, read behind its q, k and v projections
|
||||
* (AttnGatedFP8::op_pf_o): the prologue and the attention between them and the projection are
|
||||
* short launches with the memory idle. Twelve layers, so less: five interleaved rounds, ms a step
|
||||
* without -> with, one stream 12.51 -> 12.45 (every round), two 16.88 -> 16.85. */
|
||||
constexpr int64_t kAttnOutPrefetchBytes = (int64_t)8 << 20;
|
||||
/* The workgroups of this model's weight reads on a verify step (the `prefetch` op's `blocks`, from
|
||||
* kVerifyRows rows): 32, half the kernel's own 64. The reads run beside the delta net's update,
|
||||
* the attention's prologue and the connections' reductions, all latency-bound kernels of a few
|
||||
* loads a block whose loads queue behind the read's, and at four rows the update lasts half again
|
||||
* as long as at one, so a slower read still lands. Chain 3 with coupling at tp 2, ms a step
|
||||
* against 64 in one server, interleaved: 16 +0.77%, 24 +0.14%, 32 -0.31%, 48 -0.24%, 128 +2.0%,
|
||||
* 256 +7.4%; -0.6% at 32 with the router's read beside. A one-row step keeps 64 (kVerifyRows). */
|
||||
constexpr int64_t kPrefetchBlocksVerify = 32;
|
||||
/* A layer's router likewise, read behind its mixer's out projection, beside the mixer's reduction
|
||||
* and the feed-forward's connection read (both latency, with the card's memory mostly idle): the
|
||||
* router is 2.5 MB of bf16 that its GEMM otherwise streams cold in front of a top-k that waits for
|
||||
* all of it. Chain 3 with coupling at tp 2, ms a step without -> with, each the mean of two
|
||||
* interleaved rounds in one server: 12.19 -> 12.13 (-0.42% and -0.93%); 12.14 -> 12.09 in another
|
||||
* session. The same read of the shared expert's two weights, or of the indexer's projection, moved
|
||||
* nothing (-0.02%, -0.04%, +0.04%), and of the mixer's first projection in front of its
|
||||
* connection read cost 1.0%: a read there takes the memory from the connection's own. */
|
||||
constexpr int64_t kRouterPrefetchBytes = (int64_t)4 << 20;
|
||||
|
||||
struct Layer {
|
||||
int full = 0;
|
||||
HyperConn hc_mix; /* in front of the attention or the delta net */
|
||||
@@ -115,6 +157,14 @@ struct Layer {
|
||||
* graph. Inert (no op) when the deployment has no vector or this layer is outside its range
|
||||
* (arch/common/rad_block_hc.h). */
|
||||
HcProject proj;
|
||||
/* The layer's calibration inputs (rad_calib_full.h, site_i8), -1 where this run records none:
|
||||
* the mixer's input (the delta net's in projection, or q, k and v) and its output projection's. */
|
||||
int cs_in = -1, cs_o = -1;
|
||||
/* The router's weight read beside the mixer's reduction (kRouterPrefetchBytes); 0 where the
|
||||
* deployment reads no weights ahead. */
|
||||
rad_op op_pf_router = 0;
|
||||
/* The same at a verify step's workgroup count (kPrefetchBlocksVerify), from kVerifyRows rows. */
|
||||
rad_op op_pf_router_v = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -125,6 +175,12 @@ struct Model {
|
||||
/* The trunk's linears are int8 (LinearFP8::i8), as read from the first delta-net layer's input
|
||||
* projection before the activation buffers are declared. */
|
||||
bool trunk_i8 = false;
|
||||
/* The trunk's int8 linears are stored rotated (i8a8h), read from the same weight: every
|
||||
* reader of the block input then takes the rotated codes the connections write. */
|
||||
bool trunk_rot = false;
|
||||
/* --calib-dir over the int8 trunk: the Hessian of each mixer linear's input, from the codes its
|
||||
* GEMM reads (rad_calib_full.h). */
|
||||
CalibFull calib;
|
||||
HyperConn::Config hccfg{};
|
||||
QsaIndexer::Config qsacfg{};
|
||||
QsaIndexer::Wire qsaw{};
|
||||
@@ -163,6 +219,9 @@ struct Model {
|
||||
* stays zero, since the bf16 source is `a_x`, unrotated. Declared only when the container asks
|
||||
* for a rotation; zero handles tell the MoE block the pair is absent. */
|
||||
ActFP8 a_hr{};
|
||||
/* The routed arm's activations are int8 (MoeFP8::a8): int8 connection codes under experts
|
||||
* with an int8 row. */
|
||||
bool arm8 = false;
|
||||
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
|
||||
@@ -205,6 +264,9 @@ struct Model {
|
||||
|
||||
rad_weight w_tok = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_rope_cs = 0, op_gather = 0, op_logits = 0;
|
||||
/* The indexer's within-step buffers store_keys touches are excluded from sharing (declare),
|
||||
* so a layer's keys may be issued behind its attention's launches (step_serial, QsaSide). */
|
||||
bool qsa_defer = false;
|
||||
|
||||
/* ---- media (arch/common/rad_block_vit.h): the vision tower and the scatter of its rows over
|
||||
* the token embeddings, declared only when the container carries a tower and the deployment
|
||||
@@ -215,7 +277,7 @@ struct Model {
|
||||
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The n-gram table's row count, by prime search.
|
||||
*
|
||||
@@ -268,12 +330,13 @@ static void block_slice(int64_t nb, int world, int64_t place, int64_t* lo, int64
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* A sizing declare writes scratch: the step reads g_model, filled by the real declare at the
|
||||
* real max_tok (RadBuildCtx::shape_probe). */
|
||||
static thread_local Model probe_model;
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[ctx->rank];
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[rad_build_slot(ctx)];
|
||||
/* The reset drops the pinned window copy (pipe_bounds); free it first -- a re-declare of the
|
||||
* same rank (every rebuild, every test case) otherwise overwrites the pointer and leaks the
|
||||
* pin. The copy is read only by a step's memcpys, and no step runs across a declare. */
|
||||
@@ -663,36 +726,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
/* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with
|
||||
* f16 scales, K E4M3 as above or int6 the same way (libr4d's gqa12 and four-rank gqa6
|
||||
* rows for these layers). A token's row is 25 or 22 * head_dim / 16 bytes instead of
|
||||
* 2 * head_dim, so the group is declared at half that and the core sizes pages from it;
|
||||
* only those kernels read the layout. The MTP head's layer shares this group. The engine
|
||||
* asks only for a layout probe() offered. */
|
||||
const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE;
|
||||
const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4"
|
||||
: nullptr;
|
||||
if (kvq != RAD_KVQ_NONE && !kvq_name) {
|
||||
fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* A rank's ratio: twelve at one and two ranks, six at four (each KV head replicated
|
||||
* across a rank pair). */
|
||||
if (kvq_name && !(g.head_dim == 256 && (g.gqa() == 12 || g.gqa() == 6))) {
|
||||
fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256 and a "
|
||||
"rank's gqa 12 or 6 only; this rank is head_dim %lld, gqa %lld\n",
|
||||
kvq_name, (long long)g.head_dim, (long long)g.gqa());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32;
|
||||
fd.head_dim = g.head_dim * row16 / 32;
|
||||
/* The MTP head's layer shares this group. */
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype);
|
||||
if (kvq_name)
|
||||
rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a "
|
||||
"token and head instead of %lld", kvq_name,
|
||||
kvq == RAD_KVQ_V4 ? "E4M3" : "int6", (long long)(g.head_dim * row16 / 16),
|
||||
(long long)(2 * g.head_dim));
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_LINEAR;
|
||||
@@ -747,6 +783,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{ nm.ckpt("%s.%lld.linear_attn.in_proj_qkv.weight", pre0, (long long)l),
|
||||
nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre0, (long long)l) }));
|
||||
m.trunk_i8 = m.layers[(size_t)l].gdn.in.probed_i8;
|
||||
/* Stored rotated (i8a8h: int8 codes or a narrower form on their grid, /fwht128): its
|
||||
* readers take had_quant_act_i8g's codes, one scale a 128 of K as the connections
|
||||
* write them. */
|
||||
RadEncoding enc{};
|
||||
m.trunk_rot = m.trunk_i8 &&
|
||||
weight_enc(b, nm.f("blk.%lld.ssm_inz.weight", (long long)l), &enc) &&
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
if (m.trunk_rot && linear_w8h_group(enc) != RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: qwen4exp: the trunk's rotated int8 linears keep a scale "
|
||||
"a %lld of K; the connections write the block input's codes at one "
|
||||
"a %d\n", (long long)linear_w8h_group(enc), RAD_FP8_BLOCK);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -762,8 +811,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_h = decl_b(b, nm.f("h_wide"), g.act_dtype, {T, HN});
|
||||
m.a_x.x = decl_b(b, nm.f("x"), g.act_dtype, {T, g.n_embd});
|
||||
if (ctx->shape_probe) {
|
||||
m.span_on = g_model[ctx->rank].span_on;
|
||||
m.pipe_on = g_model[ctx->rank].pipe_on;
|
||||
m.span_on = g_model[rad_build_slot(ctx)].span_on;
|
||||
m.pipe_on = g_model[rad_build_slot(ctx)].pipe_on;
|
||||
} else {
|
||||
m.span_on = ctx->max_mixed_tok > 0 && ctx->max_mixed_tok < g.max_tok &&
|
||||
g.max_tok > m.moecfg.rows;
|
||||
@@ -790,8 +839,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* linear: the trunk's are, and the routed experts then read the rotated copy or the bf16
|
||||
* plane. When experts read the plain E4M3 codes, the connections keep those and the int8
|
||||
* linears quantise for themselves. */
|
||||
m.hccfg.codes_i8 = (m.trunk_i8 && (m.moecfg.expert_rot || m.moecfg.expert_bf16)) ? 1 : 0;
|
||||
/* A read's rotated copy takes its plain codes' dtype, so beside int8 codes the routed arm is
|
||||
* int8 too: the experts read had_quant_act_i8g's codes through the grouped GEMM's int8 rows
|
||||
* (MoeFP8::a8), which the rotated four-bit plane, the codebook at E4M3 scales a 64 or 32 of K
|
||||
* and rotated int8 experts have. The codebook at a bf16 scale a 128 and the five-bit one do
|
||||
* not: under them the connections keep E4M3 codes, as for unrotated experts. */
|
||||
const bool exp8 = m.moecfg.expert_rot && !m.moecfg.expert_w5 && !m.moecfg.expert_w6 &&
|
||||
(!m.moecfg.expert_nl || m.moecfg.expert_g64);
|
||||
m.hccfg.codes_i8 = (m.trunk_i8 && (exp8 || m.moecfg.expert_bf16)) ? 1 : 0;
|
||||
m.a_x.q8_fed = m.hccfg.codes_i8 != 0;
|
||||
m.arm8 = m.hccfg.codes_i8 != 0 && exp8;
|
||||
/* A rotated trunk and the routed experts read one pair: the connections write the block
|
||||
* input's rotated codes as its own (HyperConn::xrot), and the routed arm takes those
|
||||
* (MoeFP8's gate_up input) with no second copy. */
|
||||
if (m.trunk_rot) {
|
||||
if (!m.hccfg.codes_i8) {
|
||||
fprintf(stderr, "radiance: qwen4exp: a rotated int8 trunk shares the block input's "
|
||||
"rotated codes with the routed experts, which then are rotated and "
|
||||
"have an int8 row (four-bit, the codebook at a 64 or 32 of K, int8), "
|
||||
"or plain bf16\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.a_x.q8_rot = true;
|
||||
}
|
||||
m.b_inj = decl_b(b, nm.f("hc_inj"), g.act_dtype, {T, m.hccfg.hc});
|
||||
|
||||
m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {T, g.n_head, 2 * g.head_dim});
|
||||
@@ -802,6 +872,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8));
|
||||
/* The gate epilogue in front of the int8 out projection writes its int8 codes itself. */
|
||||
m.a_attn.q8_fed = m.trunk_i8;
|
||||
m.a_attn.q8_rot = m.trunk_rot;
|
||||
/* The bf16 gate's own plane (AttnGatedFP8::Wire::gate); the fp8 path fuses it away. */
|
||||
if (g.w_bf16) m.b_gate = decl_b(b, nm.f("attn_gate"), g.act_dtype, {T, q_dim});
|
||||
/* The QSA indexer's planes, shared by every full-attention layer like `attn_out`. Declared
|
||||
@@ -845,6 +916,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{ g.max_tok, m.qsacfg.topk + 1 });
|
||||
m.qsaw.nsel = decl_b(b, nm.f("qsa_nsel"), RAD_I32, { g.max_tok });
|
||||
m.qsaw.sequ = decl_b(b, nm.f("qsa_sequ"), RAD_I32, { g.max_tok });
|
||||
if (m.qsaw.qk && m.qsaw.stage && m.qsaw.page && m.qsaw.bpos && m.qsaw.nc) {
|
||||
/* What store_keys reads and writes is in use behind the attention's launches when a
|
||||
* layer's keys are deferred behind them (QsaSide), past the last use the linear order
|
||||
* gives these buffers, so the planner must not lay an attention buffer over them.
|
||||
* A few MiB of arena (qk is the largest, max_tok x 640 bf16). */
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.qk));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.stage));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.page));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.bpos));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.nc));
|
||||
m.qsa_defer = true;
|
||||
}
|
||||
if (!m.qsaw.qk || !m.qsaw.q || !m.qsaw.stage || !m.qsaw.page ||
|
||||
!m.qsaw.bpos || !m.qsaw.nc || !m.qsaw.score || !m.qsaw.sel || !m.qsaw.nsel ||
|
||||
!m.qsaw.sequ)
|
||||
@@ -869,6 +952,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The delta net's output epilogue also writes its int8 codes; its prefill quantiser is the
|
||||
* int8 one. */
|
||||
m.a_go.q8_fed = m.trunk_i8;
|
||||
m.a_go.q8_rot = m.trunk_rot;
|
||||
|
||||
/* The model's expert count, not this rank's: the router is replicated and scores every
|
||||
* expert. */
|
||||
@@ -879,18 +963,38 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* PERSIST, not transient. `moe_scatter` writes the per-expert histogram and no declared op
|
||||
* reads it (rad_route_report is a handoff, not an op), so as a transient liveness would let a
|
||||
* later buffer alias it, and a wide prefill chunk would corrupt the counts (even negative).
|
||||
* One int32 per expert. */
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.moecfg.n_expert},
|
||||
RAD_BUF_PERSIST);
|
||||
*
|
||||
* The model's routing table (rad_route_table): a row for each trunk layer and one for the
|
||||
* draft head, at the model's expert count, which is the core's pitch whatever share of the
|
||||
* experts this rank computes. Each router writes its layer's row, so a report copies nothing
|
||||
* and a layer's counts last until its next pass. */
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32,
|
||||
{g.n_layer + 1, m.moecfg.n_expert_all}, RAD_BUF_PERSIST);
|
||||
RAD_ARCH_TRY(rad_route_table(b, m.b_ecnt));
|
||||
m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {ER});
|
||||
m.b_egu = decl_b(b, nm.f("moe_egu"), g.act_dtype, {ER, 2 * m.moecfg.n_ff_exp});
|
||||
m.a_eff.x = decl_b(b, nm.f("moe_eff"), g.act_dtype, {ER, m.moecfg.n_ff_exp});
|
||||
/* ER rows, not max_tok: an expert plane has one row per (token, slot). declare_qs's default
|
||||
* would make it `top_k` times too short and the gated quantiser would overrun it (see
|
||||
* ActFP8::declare_qs). */
|
||||
RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER));
|
||||
if (m.moecfg.expert_rot)
|
||||
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
|
||||
if (m.arm8) {
|
||||
/* The int8 routed arm's two pairs, rotated at a scale a 128 and written by their
|
||||
* producers: the gated product's by gated_had_quant_i8g, the input's by the read. */
|
||||
/* A trellis gate_up may be paired with W5NL down. Keep its E4M3 pair as well so that
|
||||
* the gated intermediate can use the down projection's own activation format. */
|
||||
RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER, true,
|
||||
m.moecfg.expert_iqr != 0, RAD_FP8_BLOCK));
|
||||
m.a_eff.q8_fed = m.a_eff.q8_rot = true;
|
||||
if (!m.trunk_rot) {
|
||||
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
m.a_hr.q8_fed = m.a_hr.q8_rot = true;
|
||||
}
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER));
|
||||
if (m.moecfg.expert_rot)
|
||||
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
|
||||
}
|
||||
m.b_edn = decl_b(b, nm.f("moe_edn"), g.act_dtype, {ER, g.n_embd});
|
||||
m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {T, g.n_embd});
|
||||
if (m.moecfg.n_ff_shared > 0) {
|
||||
@@ -901,6 +1005,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The shared expert's gated quantiser in front of its int8 down projection writes its codes
|
||||
* too. */
|
||||
m.a_sff.q8_fed = m.trunk_i8;
|
||||
m.a_sff.q8_rot = m.trunk_rot;
|
||||
m.b_sout = decl_b(b, nm.f("moe_sout"), g.act_dtype, {T, g.n_embd});
|
||||
m.b_sgate = decl_b(b, nm.f("moe_sgate"), g.act_dtype, {T, 1});
|
||||
}
|
||||
@@ -994,6 +1099,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
mw.x = m.b_h; mw.h = m.a_x; mw.hr = m.a_hr;
|
||||
mw.logits = m.b_rlogits; mw.ids = m.b_eids; mw.ew = m.b_ew;
|
||||
mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt;
|
||||
mw.ecnt_pitch = m.moecfg.n_expert_all;
|
||||
mw.egu = m.b_egu; mw.eff = m.a_eff; mw.edn = m.b_edn; mw.moe = m.b_emoe;
|
||||
mw.sgu = m.b_sgu; mw.sff = m.a_sff; mw.sout = m.b_sout; mw.sgate = m.b_sgate;
|
||||
|
||||
@@ -1006,6 +1112,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* its collective a second time at `overlap` 1, for the rows that leave the CUs to that work
|
||||
* (the lane rows of libr4d/r4d_rows.cpp). */
|
||||
const int pipe_overlap = m.pipe_on ? 1 : 0;
|
||||
/* GPTQ calibration of the trunk (rad_calib_full.h). A bf16 trunk is recorded at any rank count
|
||||
* from the bf16 inputs, a column-split one gathered to its whole width; an int8 trunk at one
|
||||
* rank from the codes the connections and the mixers write themselves, so each tap reads what
|
||||
* the GEMM after it reads. */
|
||||
if (ctx->calib_dir && *ctx->calib_dir && m.trunk_i8 &&
|
||||
(g.world > 1 || !m.a_x.q8_fed || !m.a_attn.q8_fed || !m.a_go.q8_fed)) {
|
||||
fprintf(stderr, "radiance: qwen4exp: --calib-dir records an int8 trunk under int8-routed "
|
||||
"experts at --tp 1 only\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, g.n_layer, std::max(q_dim, v_dim) * g.world,
|
||||
std::max<int64_t>(g.n_embd, std::max(q_dim, v_dim) * g.world)));
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.full = is_full_attention(l, interval) ? 1 : 0;
|
||||
@@ -1098,10 +1216,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
lay.attn.qsa_nsel = m.qsaw.nsel;
|
||||
lay.attn.qsa_sequ = m.qsaw.sequ;
|
||||
lay.attn.qsa_topk = m.qsacfg.topk;
|
||||
/* The exactness bound, below which prefill issues the cheaper dense attention.
|
||||
* Decode ignores it and always takes the sparse path, keeping that path exercised
|
||||
* on every step. */
|
||||
/* The exactness bound, at or below which a step of several rows a sequence
|
||||
* (prefill, a verify) issues the cheaper dense attention. Plain decode keeps the
|
||||
* sparse row's launch at every context, so that kernel is exercised on every
|
||||
* step. */
|
||||
lay.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1;
|
||||
/* At or below that bound the indexer scores nothing (AttnGatedFP8::qsa_use): a
|
||||
* row alone in its sequence is at the context's last position on this model (a
|
||||
* plain decode row; the core's and the card's `seqused` is its position + 1), and
|
||||
* pass_key() carries the exact bound's side of it. */
|
||||
lay.attn.qsa_table_rows = true;
|
||||
lay.attn.qsa_exact_host = true;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
|
||||
/* An attention-zero rank keeps no attention cache: its block is a fill of zeros
|
||||
@@ -1158,12 +1283,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the shared arm takes, so the routed arm declares no quantiser of its own. */
|
||||
HyperConn::Config fcfg = m.hccfg;
|
||||
HyperConn::Wire fw = hw;
|
||||
if (m.moecfg.expert_rot) { fcfg.rotate = 1; fw.rq = m.a_hr.q; fw.rs = m.a_hr.s; }
|
||||
if (m.moecfg.expert_rot && !m.trunk_rot) {
|
||||
fcfg.rotate = 1; fw.rq = m.a_hr.cq(); fw.rs = m.a_hr.cs();
|
||||
}
|
||||
RAD_ARCH_TRY(lay.hc_ffn.declare(b, nm, g, nm.f("blk.%lld.ffn_hc", (long long)l),
|
||||
fcfg, fw, ffns));
|
||||
|
||||
MoeFP8::Src ms{};
|
||||
ms.cfg = m.moecfg;
|
||||
/* The legacy expert tap can be limited to selected layers, including the MTP
|
||||
* layer below. Keep the whole-expert placement selected by m.moecfg.calib. */
|
||||
ms.cfg.calib = m.moecfg.calib && calib_layer_on((int)l);
|
||||
ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l);
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "layer",
|
||||
nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l), &ms));
|
||||
@@ -1193,6 +1323,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The control vector's projection for this layer, if the vector steers it. */
|
||||
RAD_ARCH_TRY(lay.proj.declare(b, nm.f("blk.%lld.proj", (long long) l), g, l, ctx->cvec,
|
||||
proj_on, m.b_h, m.hccfg.hc));
|
||||
|
||||
if (m.calib.records(l)) {
|
||||
/* Named by the container's weights, which is how a quantiser asks for a Hessian. */
|
||||
const ActFP8& ao = lay.full ? m.a_attn : m.a_go;
|
||||
const int64_t ko = lay.full ? q_dim : v_dim; /* this rank's columns of the output */
|
||||
const std::string L = "blk." + std::to_string(l);
|
||||
const std::string in_stem = L + (lay.full ? ".attn_qkv.input" : ".ssm_inz.input");
|
||||
const std::string in_lin = lay.full ? L + ".attn_qg," + L + ".attn_k," + L + ".attn_v"
|
||||
: L + ".ssm_inz";
|
||||
const std::string o_stem = L + (lay.full ? ".attn_output.input" : ".ssm_out.input");
|
||||
const std::string o_lin = L + (lay.full ? ".attn_output" : ".ssm_out");
|
||||
lay.cs_in = (int)m.calib.sites.size();
|
||||
if (m.trunk_i8) {
|
||||
const uint32_t dom = m.trunk_rot ? (uint32_t)RAD_FP8_BLOCK : 0u;
|
||||
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, in_stem, in_lin, m.a_x.q8, m.a_x.s8, g.n_embd, dom));
|
||||
lay.cs_o = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, o_stem, o_lin, ao.q8, ao.s8, ko, dom));
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, in_stem, in_lin, m.a_x.x, g.n_embd, g.n_embd));
|
||||
lay.cs_o = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, o_stem, o_lin, ao.x, ko, ko * g.world));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
|
||||
@@ -1216,6 +1369,47 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(m.mixer.declare(b, nm, g, nm.f("output_hc"), mc, mixw, mixs));
|
||||
}
|
||||
|
||||
/* ---- the issue order of a decode step's small launches (AttnGatedFP8::kv_first_rows,
|
||||
* MoeFP8::sh_down_first_lo): at decode and verify heights the k and v projections go in
|
||||
* front of the q|gate projection, and from kVerifyRows rows the shared down projection in
|
||||
* front of the routed down GEMM, so the card launches the small ones while the wide one is
|
||||
* still being placed. The same kernels on the same operands; only what a recorded pass
|
||||
* starts first changes. */
|
||||
{
|
||||
for (Layer& lay : m.layers) {
|
||||
if (lay.full) lay.attn.kv_first_rows = kPrefetchRows;
|
||||
lay.mlp.sh_down_first_lo = kVerifyRows;
|
||||
lay.mlp.sh_down_first_hi = kPrefetchRows;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the delta nets' out projections, read beside their decode recurrent updates
|
||||
* (kGdnOutPrefetchBytes), and the full-attention layers' beside the attention
|
||||
* (kAttnOutPrefetchBytes). At more than one rank; --weight-prefetch off declares none. */
|
||||
if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) {
|
||||
for (Layer& lay : m.layers) {
|
||||
if (lay.full) {
|
||||
lay.attn.op_pf_o = decl_prefetch(b, lay.attn.o.w, kAttnOutPrefetchBytes);
|
||||
lay.attn.op_pf_o_v = decl_prefetch(b, lay.attn.o.w, kAttnOutPrefetchBytes,
|
||||
kPrefetchBlocksVerify);
|
||||
lay.attn.pf_o_v_rows = kVerifyRows;
|
||||
continue;
|
||||
}
|
||||
lay.gdn.op_pf_out = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes);
|
||||
lay.gdn.pf_out_rows = kPrefetchRows;
|
||||
lay.gdn.pf_out_seqs = kGdnOutPrefetchSeqs;
|
||||
lay.gdn.op_pf_out_v = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes,
|
||||
kPrefetchBlocksVerify);
|
||||
lay.gdn.pf_out_v_rows = kVerifyRows;
|
||||
}
|
||||
for (Layer& lay : m.layers) {
|
||||
if (!lay.mlp.w_router) continue;
|
||||
lay.op_pf_router = decl_prefetch(b, lay.mlp.w_router, kRouterPrefetchBytes);
|
||||
lay.op_pf_router_v = decl_prefetch(b, lay.mlp.w_router, kRouterPrefetchBytes,
|
||||
kPrefetchBlocksVerify);
|
||||
}
|
||||
}
|
||||
|
||||
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)),
|
||||
@@ -1350,6 +1544,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ts.attn.o = nm.ckpt("%s.layers.0.self_attn.o_proj.weight", mpre);
|
||||
|
||||
ts.mlp.cfg = m.moecfg;
|
||||
ts.mlp.cfg.calib = m.moecfg.calib && calib_layer_on((int)g.n_layer);
|
||||
ts.mlp.router = nm.ckpt("%s.layers.0.mlp.gate.weight", mpre);
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "mtp", nm.ckpt("%s.layers.0.mlp.experts", mpre),
|
||||
&ts.mlp));
|
||||
@@ -1361,12 +1556,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* Set before declare(), as for the trunk: `attn_paged` declares `sel` and `seqused` as
|
||||
* reads, which must precede the op. */
|
||||
m.mtp.attn.kv_block = 4;
|
||||
/* The head's layer takes the trunk's issue order at decode heights (declare, above). */
|
||||
m.mtp.attn.kv_first_rows = kPrefetchRows;
|
||||
m.mtp.mlp.sh_down_first_lo = kVerifyRows;
|
||||
m.mtp.mlp.sh_down_first_hi = kPrefetchRows;
|
||||
if (m.qsaw.qk) {
|
||||
m.mtp.attn.qsa_sel = m.qsaw.sel;
|
||||
m.mtp.attn.qsa_nsel = m.qsaw.nsel;
|
||||
m.mtp.attn.qsa_sequ = m.qsaw.sequ;
|
||||
m.mtp.attn.qsa_topk = m.qsacfg.topk;
|
||||
m.mtp.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1;
|
||||
/* As the trunk's layers: a round's row is the head's context's last position
|
||||
* (ADV_ROUND), and the history pass is one row only where it commits one. */
|
||||
m.mtp.attn.qsa_table_rows = true;
|
||||
m.mtp.attn.qsa_exact_host = true;
|
||||
ts.qsa = m.qsacfg;
|
||||
ts.qsa.mode = m.mtp.attn.mode;
|
||||
ts.qsa.qk_proj = nm.ckpt("%s.layers.0.self_attn.indexer.index_qk_proj.weight", mpre);
|
||||
@@ -1452,7 +1655,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
static bool pipelined(const Model& m, int64_t T) {
|
||||
const int64_t R = m.moecfg.rows;
|
||||
if (!m.pipe_on || R <= 0 || T <= R) return false;
|
||||
if (m.moecfg.calib || dbg_resid_on() || !m.op_embed_ar) return false;
|
||||
if (m.moecfg.calib || m.calib.on || dbg_resid_on() || !m.op_embed_ar) return false;
|
||||
for (const Layer& l : m.layers) {
|
||||
if (!(l.full ? l.attn.issues_ar(T) : l.gdn.issues_ar(T))) return false;
|
||||
if (!l.mlp.issues_ar(T, R)) return false;
|
||||
@@ -1548,6 +1751,9 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
if (m.ple_layer == 0) m.ple.step(c, batch);
|
||||
for (int64_t p = 0; p < K; ++p) m.layers[0].hc_mix.read(c, T, r0(p), rn(p));
|
||||
}
|
||||
/* The pass's first full-attention layer with an indexer makes what every such layer shares of
|
||||
* its step (QsaIndexer::step, `first`). */
|
||||
bool qsa_first = true;
|
||||
for (int64_t li = 0; li < n; ++li) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
/* The mixer finishes its output a piece at a time where its last stages are per row and
|
||||
@@ -1556,7 +1762,11 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
MixAr ms{c, &l};
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = mix_ar_piece; pc.u = &ms; pc.cu = gcu;
|
||||
if (l.full) { l.qsa.step(c, l.attn.w.h, batch, pcu); l.attn.step(c, batch, false, &pc); }
|
||||
if (l.full) {
|
||||
l.qsa.step(c, l.attn.w.h, batch, pcu, l.attn.qsa_use(batch), qsa_first);
|
||||
if (l.qsa.on()) qsa_first = false;
|
||||
l.attn.step(c, batch, false, &pc);
|
||||
}
|
||||
else l.gdn.step(c, batch, false, &pc);
|
||||
auto ar_mix = [&](int64_t p) {
|
||||
if (l.full) l.attn.issue_ar(c, r0(p), rn(p));
|
||||
@@ -1601,6 +1811,18 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
}
|
||||
}
|
||||
|
||||
/* A full-attention layer's indexer keys behind its attention's launches (QsaIndexer::deferrable,
|
||||
* SideOps): store_keys's three stages in turn, one a call, and whatever is left at flush(). */
|
||||
struct QsaSide {
|
||||
RadCtx* c = nullptr;
|
||||
const QsaIndexer* q = nullptr;
|
||||
const RadBatch* batch = nullptr;
|
||||
int next = 1;
|
||||
void one() { if (next <= 3) q->step_part(c, batch, next++); }
|
||||
void flush() { while (next <= 3) one(); }
|
||||
static void at(void* u, int) { ((QsaSide*)u)->one(); }
|
||||
};
|
||||
|
||||
/* The trunk one stream at a time over the whole step: every step a span of 1 makes, and every
|
||||
* other where step_pipelined's conditions do not hold. */
|
||||
static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
|
||||
@@ -1621,15 +1843,46 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
|
||||
if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
|
||||
RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
|
||||
|
||||
/* The pass's first full-attention layer with an indexer makes what every such layer shares of
|
||||
* its step (QsaIndexer::step, `first`). */
|
||||
bool qsa_first = true;
|
||||
for (int64_t li = 0; li < (int64_t)m.layers.size(); ++li) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
/* Before the attention connection reads the stream, which is where the reference puts it. */
|
||||
if (li == m.ple_layer) m.ple.step(c, batch);
|
||||
l.hc_mix.read_pieces(c, T);
|
||||
/* The calibration taps read the codes the mixer's GEMMs read: its input before it runs,
|
||||
* its output projection's input before the feed-forward's connection reuses the pair. */
|
||||
if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, T);
|
||||
/* The indexer runs first, since the attention reads its selection. The block's input is
|
||||
* already normed and quantised by the connection (`ext_in`), so `w.h` is final. */
|
||||
if (l.full) { l.qsa.step(c, l.attn.w.h, batch, pcu); l.attn.step(c, batch); }
|
||||
if (l.full) {
|
||||
const int use = l.attn.qsa_use(batch);
|
||||
/* At decode heights within the exactness bound nothing of the layer reads the
|
||||
* indexer's keys or tail (they are for later steps), so only the projection stays in
|
||||
* front, beside the attention's own, and the three launches behind it ride behind the
|
||||
* attention's (QsaSide) instead of holding its projections back in turn: -0.3% to
|
||||
* -0.8% a step on chain 3 with coupling at tp 2. */
|
||||
if (m.qsa_defer && T <= kPrefetchRows && batch->phase == RAD_PHASE_DECODE &&
|
||||
l.qsa.deferrable(batch, use, qsa_first)) {
|
||||
QsaSide sd{c, &l.qsa, batch};
|
||||
const SideOps so{QsaSide::at, &sd};
|
||||
l.qsa.step_proj(c, l.attn.w.h, batch);
|
||||
l.attn.step(c, batch, true, nullptr, &so);
|
||||
sd.flush();
|
||||
} else {
|
||||
l.qsa.step(c, l.attn.w.h, batch, pcu, use, qsa_first);
|
||||
l.attn.step(c, batch);
|
||||
}
|
||||
if (l.qsa.on()) qsa_first = false;
|
||||
}
|
||||
else l.gdn.step(c, batch);
|
||||
if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, T);
|
||||
/* The router's weight, read beside the write's reduction and the read behind it. */
|
||||
if (batch->phase == RAD_PHASE_DECODE)
|
||||
prefetch_beside(c, l.op_pf_router_v && T >= kVerifyRows ? l.op_pf_router_v
|
||||
: l.op_pf_router,
|
||||
l.mlp.w_router, T);
|
||||
l.hc_mix.write(c, T, 0, T);
|
||||
dbg_resid(c, (int)li, "mix", g.n_embd, m.b_h, m.a_x.x);
|
||||
l.hc_ffn.read_pieces(c, T);
|
||||
@@ -1639,10 +1892,11 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
|
||||
l.proj.step(c, batch, 0, T);
|
||||
dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x);
|
||||
}
|
||||
m.calib.after_step(c, T);
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
@@ -1669,8 +1923,12 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
* re-filling is idempotent. */
|
||||
if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
|
||||
RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
|
||||
/* The n-gram rows of the pass's newest tokens, for the verify step that runs them:
|
||||
* hashed ahead of the head, fetched once the whole pass is issued (PleLayer::hint_ids). */
|
||||
if (m.ple_layer >= 0) m.ple.hint_ids(c, batch);
|
||||
m.mtp.qsa_win_cu = pipe_bounds(c, batch, m);
|
||||
m.mtp.step(c, batch);
|
||||
if (m.ple_layer >= 0) m.ple.hint_fetch(c, batch);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1700,33 +1958,29 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (!c || !batch) return 0;
|
||||
if (batch->enc) return 1;
|
||||
/* Mixed batches split the query rows into decode and prefill subsets before attention; the
|
||||
* whole-batch host summary cannot key those subset geometries exactly. */
|
||||
if (batch->phase == RAD_PHASE_MIXED) return 0;
|
||||
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
/* Decode, verify and draft passes (the MTP head attends over the same KV group): every
|
||||
* attention launch covers all the pass's sequences, and the shape fields the core keys (n_tok,
|
||||
* n_seq, max_q_len, n_spec, draft_pass) fix each launch's q_len band and units. The live KV
|
||||
* length enters a split launcher's count only through the cap of eight 48-key tiles a split
|
||||
* (rad_prefill_splits_law; every head_dim 256 launcher has P_TILE 48), and from 64 splits up
|
||||
* the cap no longer binds. Keying that cap level lets these passes be recorded while each launch
|
||||
* still splits by its exact live length: answering 0 left them unrecorded (issue #402), and the
|
||||
* core's keyed bound for a plugin without the callback rounds the length up a bucket, which split
|
||||
* a short single-stream verify into several partials with a merge (x1 203 against 219 tok/s). */
|
||||
if (batch->phase != RAD_PHASE_PREFILL || batch->draft_pass != 0 || batch->n_spec > 0) {
|
||||
if (!m.kv_full || !used_max_h || !batch->kv) return 0;
|
||||
int group = -1;
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
/* Which side of the indexer's exactness bound the step is on by the attention group's exact
|
||||
* host bound, by which the full-attention layers and the indexer decide whether the step
|
||||
* needs scores (AttnGatedFP8::qsa_within, qsa_exact_host). The core's key holds only the
|
||||
* rounded context bound, so the side is keyed here: one more recording of each pass kind as a
|
||||
* request crosses the bound. `sel` is 2 within the bound and 0 past it or where it is
|
||||
* unknown, which is where the blocks fall back to the rounded bound the core keys. */
|
||||
uint64_t sel = 0;
|
||||
if (used_max_h && batch->kv && m.kv_full && m.qsacfg.budget > 0 && m.qsacfg.ratio > 0)
|
||||
for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv_full) { group = i; break; }
|
||||
if (group < 0) return 2; // no full-attention KV in this pass: nothing splits by length
|
||||
const int used = used_max_h[group];
|
||||
if (used <= 0) return 0; // Missing host summary is not the same as an empty KV cache.
|
||||
constexpr int tile = 48;
|
||||
const int ctx = (m.g.max_ctx > 0 && used >= m.g.max_ctx) ? (int)m.g.max_ctx : used;
|
||||
const int cap = std::min(((ctx + tile - 1) / tile) / 8, 64);
|
||||
return 3 + (uint64_t)cap;
|
||||
}
|
||||
if (batch->kv[i].group == m.kv_full) {
|
||||
if (used_max_h[i] > 0 &&
|
||||
used_max_h[i] <= m.qsacfg.budget + m.qsacfg.ratio - 1) sel = 2;
|
||||
break;
|
||||
}
|
||||
/* A decode pass, a speculative verify or an MTP draft included, issues every launch at the
|
||||
* step's keyed context bound (RadArgs::kv_used_max_h), never the live maximum, so the core's
|
||||
* key holds its geometry. */
|
||||
if (batch->phase == RAD_PHASE_DECODE) return 1 | sel;
|
||||
/* Mixed batches split the query rows into decode and prefill subsets before attention, which
|
||||
* read the live maximum. The whole-batch host summary cannot key those subset geometries
|
||||
* exactly, nor a drafter's or a verify's rows inside a prefill pass. */
|
||||
if (batch->phase == RAD_PHASE_MIXED || batch->draft_pass != 0 || batch->n_spec > 0) return 0;
|
||||
|
||||
bool has_full_attention = false;
|
||||
for (const Layer& layer : m.layers) {
|
||||
@@ -1734,7 +1988,7 @@ uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (layer.attn.kv_block != 4) return 0;
|
||||
has_full_attention = true;
|
||||
}
|
||||
if (!has_full_attention) return 1;
|
||||
if (!has_full_attention) return 1 | sel;
|
||||
if (m.g.head_dim != 256 || (m.g.gqa() != 6 && m.g.gqa() != 12) || !m.kv_full ||
|
||||
!used_max_h || !batch->kv || batch->n_kv_groups <= 0)
|
||||
return 0;
|
||||
@@ -1760,7 +2014,10 @@ uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
const int bq = nwarps * 16 / m.g.gqa();
|
||||
const int splits = rad_prefill_splits_for_live(bq, tile, q_len, total_q, num_seqs,
|
||||
kv_heads, m.g.max_ctx, used, wgps);
|
||||
return rad_prefill_grid_key(q_len, bq, splits, kv_heads, num_seqs, nwarps * 32);
|
||||
const uint64_t grid = rad_prefill_grid_key(q_len, bq, splits, kv_heads, num_seqs, nwarps * 32);
|
||||
/* 0 stays "unknown"; the side of the bound rides in a bit the grid key's mix does not leave
|
||||
* meaningful, so two sides are two keys. */
|
||||
return grid ? ((grid << 2) | 1 | sel) : 0;
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
@@ -1772,23 +2029,12 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", "mtp_num_hidden_layers", 0) > 0)
|
||||
out->draft_depth = 3;
|
||||
out->shape_probe_ok = 1; /* declare() writes scratch under shape_probe */
|
||||
/* --kv-cache-dtype fp8_v4 / k6_v4: libr4d has their rows for the QSA layers' geometry
|
||||
* (head_dim 256, twelve queries per KV head; gqa6 with 4-token pages at four ranks), so other
|
||||
* geometries are refused at startup rather than in declare. */
|
||||
{
|
||||
const long long hd = meta->head_dim ? meta->head_dim
|
||||
: (meta->n_head ? meta->n_embd / meta->n_head : 0);
|
||||
const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head;
|
||||
if (hd == 256 && nkv > 0 && meta->n_head == 12 * nkv)
|
||||
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
|
||||
}
|
||||
/* The gated residual applies a control vector after every block's write (HcProject). */
|
||||
out->control_vector_ok = 1;
|
||||
/* Chained launches pay with the MTP drafter: the speculative step's small kernels wait on the
|
||||
* previous one on the card instead of behind a queue barrier (libr4d/r4d_chain.h). On 2x R9700,
|
||||
* sampled at temperature 1 with a 25k prompt, MTP depth 3, with the chained hc_read forms:
|
||||
* 1/2/4/8/16 streams 174/291/458/657/851 -> 207/339/493/647/843 tok/s. */
|
||||
out->chain_pays = 1;
|
||||
/* A pass is about 930 launches, nearly all dependent, and the kernels of its decode heights
|
||||
* have chained forms: on two R9700 a full pass under the draft head went from 13.9 to 12.5 ms
|
||||
* and the step without the head from 9.98 to 9.17 ms at one sequence. */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1796,6 +2042,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(qwen4exp_fp8)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(qwen4exp_fp8, "qwen4exp", "", "0.1.0",
|
||||
"Qwen4-Exp (Qwen3.8-Flash-Next): hybrid Gated DeltaNet / gated attention, a gated "
|
||||
"residual four streams wide and 512 routed experts, from a dense bf16 checkpoint "
|
||||
|
||||
@@ -29,9 +29,11 @@
|
||||
*
|
||||
* ============================== WHAT IS QUANTISED ==============================
|
||||
*
|
||||
* One plugin serves bf16 and block-fp8 containers: every linear of the language model and of the
|
||||
* DiT's blocks is a LinearFP8, which reads whatever the container holds (rad_fp8.h), and the model
|
||||
* is bf16 throughout when the first DiT projection is plain. The small linears around them
|
||||
* One plugin serves bf16, block-fp8 and rotated int8 (IQ8R) containers: every linear of the
|
||||
* language model and of the DiT's blocks is a LinearFP8, which reads whatever the container holds
|
||||
* (rad_fp8.h), and the model is bf16 throughout when the first DiT projection is plain. That
|
||||
* projection also says whether the linears are rotated int8, and then the activations they read
|
||||
* carry int8 codes in place of the E4M3 pair (declare_act). The small linears around them
|
||||
* (txt_in, img_in, the timestep MLP, the shared modulation, norm_out, proj_out), the vision tower
|
||||
* and the VAE stay bf16 in both, since they are read once per pass or less.
|
||||
*
|
||||
@@ -150,6 +152,11 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
std::vector<DitLayer> dit;
|
||||
LinearFP8 qkv0{}; /* layer 0's qkv, as the probe that chose bf16 or fp8 mapped it */
|
||||
/* The linears of both networks are rotated int8 (IQ8R, or the 128-group int8 before it), read
|
||||
* off that same probe: the activations then carry int8 code pairs with one scale per (token,
|
||||
* `g8` columns) in place of the E4M3 pair. */
|
||||
bool i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
int64_t C = 64; /* latent channels */
|
||||
rad_weight w_pout = 0;
|
||||
rad_op op_nout_ln = 0, op_pout = 0, op_euler = 0;
|
||||
@@ -168,7 +175,7 @@ struct Model {
|
||||
std::string lat_mean, lat_std;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A space-separated list off the container (rad-convert flattens arrays that way). */
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
@@ -239,6 +246,13 @@ static int check_format(const RadModelMeta* meta) {
|
||||
}
|
||||
|
||||
/* ================================================================== declare */
|
||||
/* An activation's code pair, `x` already declared: E4M3, or int8 for a rotated int8 model
|
||||
* (ActFP8::declare_pair). */
|
||||
static int declare_act(RadBuilder* b, Names& nm, const Geom& g, const Model& m, ActFP8& a,
|
||||
const char* name, int64_t n, const char* fed_op) {
|
||||
return a.declare_pair(b, nm, g, name, n, 0, m.i8, m.g8, fed_op);
|
||||
}
|
||||
|
||||
static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
Geom& g = m.gt;
|
||||
Names& nm = m.nm;
|
||||
@@ -253,14 +267,14 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_th, "te.h", g.n_embd, "had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_tattn, "te.attn", q_dim, "had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_tffn, "te.ffn", g.n_ff, "gated_had_quant_i8g"));
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd),
|
||||
@@ -632,16 +646,16 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
/* ---- the blocks */
|
||||
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_hm, "dit.hm", D, "had_quant_act_i8g"));
|
||||
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd });
|
||||
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_attn, "dit.attn", qd, "had_quant_act_i8g"));
|
||||
m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D });
|
||||
/* More than one rank: the all-reduces of b_ao's halves run on the second lane (step_blocks). */
|
||||
if (g.world > 1) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ao));
|
||||
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_ffn, "dit.ffn", g.n_ff, "gated_had_quant_i8g"));
|
||||
|
||||
/* The rotary: three sections of adjacent pairs, (frame, row, column), each on its own ladder. */
|
||||
const std::vector<double> ax = meta_list(meta, "transformer.axes_dims_rope");
|
||||
@@ -667,12 +681,15 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
{ y, m.b_mod, x }, { x });
|
||||
};
|
||||
/* gate_add, ln_mod and the quantiser as one op, where the linears are fp8: `delta` is the
|
||||
* branch the norm adds in first, none for the first block's. */
|
||||
const bool fuse_norm = !g.w_bf16;
|
||||
* branch the norm adds in first, none for the first block's. An int8 model's is the rotating
|
||||
* twin, ln_mod_had_quant_i8g, where the kernels serve it and the codes are fed; otherwise it
|
||||
* takes the three apart. */
|
||||
const bool fuse_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "ln_mod_had_quant_i8g");
|
||||
const bool fuse_norm = m.i8 ? fuse_i8 : !g.w_bf16;
|
||||
auto ln_mod_q = [&](rad_buf delta) {
|
||||
rad_op op = RAD_OP(b, "ln_mod_quant_fp8",
|
||||
rad_op op = RAD_OP(b, m.i8 ? "ln_mod_had_quant_i8g" : "ln_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("group", m.a_hm.cg()),
|
||||
RAD_INT("gated", delta ? 1 : 0), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
if (!op) return op;
|
||||
@@ -812,8 +829,9 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
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(check_format(meta));
|
||||
@@ -859,10 +877,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.transformer_blocks.0.attn.to_k.weight",
|
||||
"transformer.transformer_blocks.0.attn.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
const bool known = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e);
|
||||
const bool plain = known && rad_enc_is(&e, "plain");
|
||||
gd.w_bf16 = plain;
|
||||
m.gt.w_bf16 = plain;
|
||||
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
|
||||
if (m.i8) m.g8 = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
/* ---- the latent's normalisation, rounded to bf16 by the ops that read it */
|
||||
@@ -982,7 +1002,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.gt.rank, m.gt.world, meta_list(meta, "pipeline.sample_sigmas").empty() ? "" : " Turbo",
|
||||
(long long)m.gt.n_layer, (long long)m.gt.n_head, (long long)m.gt.n_head_kv,
|
||||
(long long)gd.n_layer, (long long)gd.n_head, (long long)gd.n_ff,
|
||||
gd.w_bf16 ? "bf16" : "block-fp8", m.media ? ", vision tower with deepstack" : "");
|
||||
gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8",
|
||||
m.media ? ", vision tower with deepstack" : "");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1064,7 +1085,7 @@ static void step_blocks(RadCtx* c, const Model& m, int64_t R, int64_t S, const R
|
||||
const bool split = g.world > 1 && S == 1 && !slot && R >= 2;
|
||||
const int64_t hr0[2] = { 0, split ? R / 2 : R }, hn[2] = { hr0[1], R - hr0[1] };
|
||||
const int nh = split ? 2 : 1;
|
||||
const int64_t nD = D / RAD_FP8_BLOCK;
|
||||
const int64_t nD = D / m.a_hm.cg();
|
||||
|
||||
/* A half's all-reduce: on lane 1 behind everything lane 0 has issued, when split. */
|
||||
auto all_reduce = [&](rad_op op, int64_t r0, int64_t n) {
|
||||
@@ -1168,7 +1189,7 @@ static void step_encode(RadCtx* c, const Model& m, const uint16_t* px, int64_t h
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const RadGenBatch* G = batch->gen_b;
|
||||
if (!batch->gen || !G) {
|
||||
rad_step_fail(c, "qwenimage21 is an image generator and runs generator passes only");
|
||||
@@ -1301,6 +1322,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(qwenimage21)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(qwenimage21, "qwenimage21", "", "0.1.0",
|
||||
"Qwen-Image 2.1 / 2.1-Turbo: Qwen3-VL-8B conditioning, a 7.1B single-stream "
|
||||
"diffusion transformer over a cached block-causal prefix, and a 2-D RGBA VAE; "
|
||||
|
||||
+7
-4
@@ -450,7 +450,7 @@ struct Model {
|
||||
rad_op op_dscale = 0, op_dcast = 0, op_rgb = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== the recorded UNet's issue */
|
||||
RadOperand Net::opd(RadCtx* c, const Opd& o, const Geo& g) const {
|
||||
@@ -913,13 +913,14 @@ static int declare_decoder(RadBuilder* b, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: sdxl runs on one card; serve it with a tensor-parallel size "
|
||||
"of 1\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -1202,7 +1203,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "sdxl is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1229,6 +1230,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(sdxl)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(sdxl, "sdxl", "", "0.1.0",
|
||||
"Stable Diffusion XL and its finetunes (Illustrious, NoobAI, Pony): CLIP ViT-L and "
|
||||
"OpenCLIP bigG text encoders, a 2.6B UNet sampled by k-diffusion's Euler, Euler "
|
||||
|
||||
@@ -59,7 +59,7 @@ struct Model {
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_ds = false;
|
||||
};
|
||||
static Model models[MAX_RANKS];
|
||||
static Model models[MAX_SLOTS];
|
||||
|
||||
/* Whether the container carries a drafter at all (`--draft-model` merged one under `draft.`), and
|
||||
* whether this file implements it. A drafter this plugin cannot run is refused at declare rather
|
||||
@@ -172,8 +172,10 @@ static bool needs_span(const Span& s, int64_t total, const Geom& g) {
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = models[ctx->rank];
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = models[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
/* geom_from's even-only split cannot express a ragged GQA/FFN world. Read the whole geometry,
|
||||
@@ -399,7 +401,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rope.theta = (float)theta[kind];
|
||||
a.rq = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head, 0, rot[kind], "neox"), {m.q}, {m.q});
|
||||
a.rk = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head_kv, 0, rot[kind], "neox"), {m.k}, {m.k});
|
||||
a.attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
a.attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), RAD_INT("window", kind ? window : 0),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
@@ -468,7 +470,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
/* A drafter pass; the sign gives the kind. Positive is the query pass, which denoises the whole
|
||||
* block and proposes from it; negative is the context pass, which turns the tokens the trunk
|
||||
@@ -567,7 +569,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
static uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (!c || !batch) return 0;
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[rad_slot(c)];
|
||||
int group = -1;
|
||||
if (batch->kv) for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv) { group = i; break; }
|
||||
@@ -615,6 +617,8 @@ static const RadChatFormat* chat_format(const RadModelMeta*) { return spark_chat
|
||||
}
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(spark25_bf16)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(spark25_bf16, "spark25", "", "0.1.0", "Spark X2.6 BF16")
|
||||
RAD_ARCH_CHAT_FORMAT(spark25_bf16)
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
|
||||
@@ -39,11 +39,13 @@ struct Request {
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
inline uint64_t pass_key(const Request& r) {
|
||||
if (r.enc) return 1;
|
||||
if (r.draft_pass != 0) return 0;
|
||||
/* Mixed and speculative passes can launch attention on sub-batches whose exact geometry
|
||||
* is not represented by the whole-batch summary. */
|
||||
if (r.phase == kPhaseMixed || r.n_spec > 0) return 0;
|
||||
if (r.phase != kPhasePrefill) return 1;
|
||||
/* A decode pass, a speculative verify or a draft included, issues every launch at the step's
|
||||
* keyed context bound (RadArgs::kv_used_max_h), never the live maximum, so the core's key
|
||||
* holds its geometry. */
|
||||
if (r.phase == kPhaseDecode) return 1;
|
||||
/* Mixed, drafting and speculative prefill passes can launch attention on sub-batches whose
|
||||
* exact geometry is not represented by the whole-batch summary. */
|
||||
if (r.phase == kPhaseMixed || r.draft_pass != 0 || r.n_spec > 0) return 0;
|
||||
if (r.head_dim != kHeadDim || r.gqa != kGqa || r.kv_heads <= 0 || !r.kv_group_found)
|
||||
return 0;
|
||||
/* For a singleton, these equalities prove the R4D q_len band and total_q used by its launch.
|
||||
|
||||
@@ -61,7 +61,7 @@ struct Model {
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_ds = false;
|
||||
};
|
||||
static Model models[MAX_RANKS];
|
||||
static Model models[MAX_SLOTS];
|
||||
|
||||
/* Whether the container carries a drafter at all (`--draft-model` merged one under `draft.`), and
|
||||
* whether this file implements it. A drafter this plugin cannot run is refused at declare rather
|
||||
@@ -186,9 +186,11 @@ static int check_format(const RadModelMeta* meta) {
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
Model& m = models[ctx->rank];
|
||||
Model& m = models[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
/* geom_from's even-only split cannot express a ragged GQA/FFN world. Read the whole geometry,
|
||||
@@ -454,7 +456,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rope.theta = (float)theta[kind];
|
||||
a.rq = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head, 0, rot[kind], "neox"), {m.q}, {m.q});
|
||||
a.rk = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head_kv, 0, rot[kind], "neox"), {m.k}, {m.k});
|
||||
a.attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
a.attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), RAD_INT("window", kind ? window : 0),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
@@ -520,7 +522,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
/* A drafter pass; the sign gives the kind. Positive is the query pass, which denoises the whole
|
||||
* block and proposes from it; negative is the context pass, which turns the tokens the trunk
|
||||
@@ -621,7 +623,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
static uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (!c || !batch) return 0;
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[rad_slot(c)];
|
||||
int group = -1;
|
||||
if (batch->kv) for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv) { group = i; break; }
|
||||
@@ -669,6 +671,8 @@ static const RadChatFormat* chat_format(const RadModelMeta*) { return spark25_bf
|
||||
}
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(spark25_w8a8)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(spark25_w8a8, "spark25", "w8a8_fwht128", "0.1.0",
|
||||
"Spark X2.6 with an int8 trunk: i8 weights with a bf16 scale a 128 of K, rotated "
|
||||
"by a 128-wide Hadamard, against int8 activations the same rotation quantises")
|
||||
|
||||
@@ -100,7 +100,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The per-MoE-layer norm and shared arm. The MoE block declares no norm in external-input mode,
|
||||
* and the shared expert must read the same normed row the routed experts do; the block's gather
|
||||
@@ -178,9 +178,10 @@ static int declare_moe_norm_and_shared(RadBuilder* b, Model& m, int l) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
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));
|
||||
@@ -488,7 +489,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
|
||||
if (batch->enc) {
|
||||
m.enc.step(c, batch);
|
||||
@@ -543,9 +544,22 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Chained launches pay on the plain-bf16 trunk: every kernel of its decode step but the cache's
|
||||
* two-dimensional copy and the vocabulary GEMM has a chained form (libr4d's rad_kernel_chain).
|
||||
* Unlimited-OCR on one R9700, ms a decode step unchained / chained: 2.79 / 2.49 at one sequence
|
||||
* and 4.51 / 4.19 at four. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace unlimitedocr_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PROBE(unlimitedocr_bf16)
|
||||
RAD_ARCH_PLUGIN(unlimitedocr_bf16, "unlimitedocr", "", "0.1.0",
|
||||
"baidu/Unlimited-OCR decoder: 12-layer Llama-MoE (64 experts top-6 + 2 shared), "
|
||||
"bf16 weights and activations, full rotary MHA, with the DeepEncoder "
|
||||
|
||||
Reference in new issue
Block a user