feat(qwen4exp): support calibrated U5 gate/W5 down recipe

This commit is contained in:
Constantin authored and StillDeadcode committed 2026-11-16 17:58:41 +01:00
1 parent 157959fd80
commit ba3ebd380f
7 files changed
+401 -17

No files matched your search

+20 -10
View File
@@ -810,7 +810,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
fmt_of(e, enc, fe, nmv);
if (fe[0] == 3 && fe[1] == 3) continue;
for (int i = 0; i < 2; ++i) {
if (family(want) && family(fe[i])) fmt[i] = fe[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_w5_down = a8f && want == 11 && i == 1 && fe[i] == 7;
if (family(want) && (family(fe[i]) || mixed_w5_down)) fmt[i] = fe[i];
fenc[i] = enc[i];
}
break;
@@ -1079,9 +1082,12 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
"architecture declared the routed arm's codes E4M3\n", l);
return RAD_E_UNSUPPORTED;
}
const bool down_w5_fp8 = a8 && fmt[0] == 11 && fmt[1] == 7;
if (a8) {
const bool pair = w.eff.q8 && w.eff.s8 && w.eff.q8_rot && w.eff.g8 == RAD_FP8_BLOCK;
if (!pair || !c.expert_rot || !kServed8[fmt[0]] || !kServed8[fmt[1]] || c.calib ||
const bool down_supported = down_w5_fp8 ? (w.eff.q && w.eff.s && kServed[fmt[1]])
: kServed8[fmt[1]] != nullptr;
if (!pair || !c.expert_rot || !kServed8[fmt[0]] || !down_supported || c.calib ||
c.swiglu_limit > 0) {
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 "
@@ -1105,7 +1111,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* experts' encoding or the kernel is not a candidate. */
gu_trellis = fmt[0] == 11;
const char* const edtype[2] = { a8 ? kServed8[fmt[0]] : kServed[fmt[0]],
a8 ? kServed8[fmt[1]] : kServed[fmt[1]] };
a8 && !down_w5_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 {
@@ -1302,9 +1308,13 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to
* the rotated op at no extra launch. */
gq_exp.fuse_clamped = c.swiglu_quant != 0;
/* Fed int8, `eff` names the rotating int8 quantiser itself (ActFP8::q8_rot). */
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
false, rot && !a8, 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_w5_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_w5_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),
@@ -1321,13 +1331,13 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
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 ? 0 : 1;
const int cut = a8 && !down_w5_fp8 ? 0 : 1;
rad_op h = ncls == 4
? 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, {w.eff.cq(), w.eff.cs(), w.sorted, w.eoff}, {w.edn});
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
@@ -1925,7 +1935,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
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.cq(), rows * k), brows(w.eff.cs(), 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]),
@@ -1934,7 +1944,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.cq(), rows * k), brows(w.eff.cs(), 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),
+59 -2
View File
@@ -152,6 +152,13 @@ struct MtpHcBlock {
MoeFP8 mlp{};
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
/* The selected draft calibration also records the bf16 attention input shared by
* qg/k/v, independently of the expert gate's later input. */
rad_buf b_attn_gram = 0;
rad_op op_attn_gram = 0;
const char* attn_gram_stem = nullptr;
mutable int64_t attn_gram_rows = 0;
mutable bool attn_gram_done = false;
/* Media rows over the head's embedding (see MtpBlockFP8::media). Set before declare when the
* program has an encoder. */
@@ -258,6 +265,20 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
* order. */
RAD_ARCH_TRY(hc_attn.declare(b, nm, g, nm.f("mtp.attn_hc"), hc, HyperConn::Wire{w.hw, w.x, w.inj},
src.hc_attn));
if (src.mlp.cfg.calib) {
/* Only a BF16 source supplies domain-0 inputs for this calibration. The input
* is replicated, so each TP rank records the same width and GPTQ sums them. */
if (!src.mlp.cfg.expert_bf16 || !w.attn.h.x) return RAD_E_UNSUPPORTED;
attn_gram_stem = nm.f("blk.%d.attn_qg", l);
b_attn_gram = decl_b(b, nm.f("blk.%d.mtp_attn_gram", l), RAD_F32,
{g.n_embd, g.n_embd}, RAD_BUF_PERSIST);
op_attn_gram = rw(b, RAD_OP(b, "gram_accum",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.attn.h.x, b_attn_gram}, {b_attn_gram});
if (!b_attn_gram || !op_attn_gram) return RAD_E_INVAL;
}
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
attn.ar_out_take = hc_attn.ar_take();
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn,
@@ -471,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. */
@@ -493,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;
@@ -513,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));
@@ -524,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)
+8 -2
View File
@@ -936,8 +936,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
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. */
RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER, true, false,
RAD_FP8_BLOCK));
/* 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,
@@ -1238,6 +1240,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
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));
@@ -1462,6 +1467,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));
+4
View File
@@ -1284,6 +1284,10 @@ extern "C" int r4d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) {
return rad_gated_quant_fp8(a, stream, false);
}
extern "C" int r4d_rad_gated_had_quant_fp8(const RadArgs* a, RadStream stream) {
return rad_gated_quant_fp8(a, stream, true);
}
/* Its int8 twin, had_quant_act_i8g's codes: pairs only with a weight stored at dtype i8a8h. */
extern "C" int r4d_rad_gated_had_quant_i8g(const RadArgs* a, RadStream stream) {
return rad_gated_quant_fp8(a, stream, true, true);
+12 -2
View File
@@ -3789,6 +3789,9 @@ static const RadOpSchema kSchemas[] = {
"the two-rank exact all-reduce of x and rmsnorm_quant_i8g after it, in one kernel."),
SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
"silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."),
SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
"Gated product rounded to bf16, FWHT128, and per-group E4M3 quantisation; "
"the optional bf16 output is the unrotated product."),
SCHEMA("gated_had_quant_i8g", pGatedQuantFp8, oGatedQuantFp8,
"gated_had_quant_fp8 at int8 codes: silu(a)*b or sigmoid(a)*b, a `group`-wide Hadamard "
"and had_quant_act_i8g's quantiser, in one pass. `out_bf16` receives the UNROTATED "
@@ -9308,8 +9311,15 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
/* `silu_mul` + `quant_act_fp8`, silu arm only (r4d_fuse.cpp). */
r4d_fuse_gated_quant_fp8 },
/* The rotated twin, for a down projection whose weight is stored at w4a8h. No fusion hook:
* nothing emits `silu_mul` + `had_quant_act_fp8`; the MoE block declares this op directly. */
/* The rotated E4M3 twin, used by rotated codebook down projections. */
{ "gated_had_quant_fp8", "gated_had_quant_fp8", "quant",
"a bf16-rounded gated product, FWHT128, and the per-group E4M3 activation quantiser",
"n a multiple of 128; packed gate then up; group 128",
"bf16 in, E4M3 codes and f32 scales, with optional unrotated bf16 product",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGatedHadQuantFp8), NOTUNE,
nullptr, nullptr, r4d_rad_gated_had_quant_fp8, nullptr, nullptr, nullptr,
r4d_shape_gated_quant_fp8 },
/* Its int8 twin, for a down projection whose weight is stored at i8a8h. */
{ "gated_had_quant_i8g", "gated_had_quant_i8g", "quant",
+71 -1
View File
@@ -14986,6 +14986,75 @@ static void fused_quant_fp8_numeric(const Plugin& pl) {
else same("gate_quant_fp8 at int8 codes is byte-identical to sigmoid + mul + quant_act_i8g");
}
/* Rotated E4M3 gated output: compare its bf16 product to silu_mul and its FWHT and
* quantised values against an independent host butterfly. */
if (const RadKernelInfo* ghf = find(pl, "gated_had_quant_fp8")) {
rc = launch_row(smu, { T(d_gu, RAD_BF16, { M, 2 * K }), T(d_y[0], RAD_BF16, { M, K }) },
{ PI("M", M), PI("n", K), PS("dtype", "bf16") });
if (rc == RAD_OK)
rc = launch_row(ghf, { T(d_gu, RAD_BF16, { M, 2 * K }),
T(d_q[1], RAD_F8E4M3, { M, K }),
T(d_s[1], RAD_F32, { M, nkb }),
T(d_y[1], RAD_BF16, { M, K }) },
{ PI("M", M), PI("n", K), PI("group", 128),
PS("dtype", "bf16"), PS("act", "silu") });
if (rc != RAD_OK) {
ok("gated_had_quant_fp8 vs host FWHT", false, "rc=" + std::to_string(rc));
} else {
std::vector<uint16_t> ref((size_t)(M * K)), out(ref.size());
std::vector<uint8_t> codes((size_t)(M * K));
std::vector<float> scales((size_t)(M * nkb));
st_memcpy(ref.data(), d_y[0], ref.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(out.data(), d_y[1], out.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(codes.data(), d_q[1], codes.size(), hipMemcpyDeviceToHost);
st_memcpy(scales.data(), d_s[1], scales.size() * 4, hipMemcpyDeviceToHost);
size_t bad_product = 0, bad_scale = 0, bad_code = 0;
for (size_t i = 0; i < ref.size(); ++i) bad_product += ref[i] != out[i];
for (int64_t r = 0; r < M; ++r) for (int64_t b = 0; b < nkb; ++b) {
float v[128];
for (int i = 0; i < 128; ++i) v[i] = rad_bf16_to_f32(ref[(size_t)(r*K+b*128+i)]);
for (int step = 1; step < 128; step *= 2)
for (int i = 0; i < 128; i += 2 * step)
for (int j = 0; j < step; ++j) {
const float x = v[i+j], y = v[i+j+step];
v[i+j] = x+y; v[i+j+step] = x-y;
}
float mx = 0.0f;
for (float x : v) mx = std::max(mx, std::fabs(x));
const float want = mx > 0 ? mx / 448.0f : 1.0f;
const float got = scales[(size_t)(r*nkb+b)];
bad_scale += !std::isfinite(got) || std::fabs(got-want) > std::max(1e-7f, want*1e-5f);
for (int i = 0; i < 128; ++i) {
const size_t at = (size_t)(r*K+b*128+i);
const float decoded = rad_load_f32(codes.data(), RAD_F8E4M3, at) * got;
bad_code += !std::isfinite(decoded) || std::fabs(decoded-v[i]) > std::max(1e-6f, mx*0.065f);
}
}
ok("gated_had_quant_fp8 matches host FWHT and E4M3 tolerance",
!bad_product && !bad_scale && !bad_code,
"product=" + std::to_string(bad_product) + " scale=" + std::to_string(bad_scale) +
" code=" + std::to_string(bad_code));
const auto saved_codes = codes;
const auto saved_scales = scales;
rc = launch_row(ghf, { T(d_gu, RAD_BF16, { M, 2 * K }),
T(d_q[1], RAD_F8E4M3, { M, K }),
T(d_s[1], RAD_F32, { M, nkb }), T(nullptr, RAD_BF16, {}) },
{ PI("M", M), PI("n", K), PI("group", 128),
PS("dtype", "bf16"), PS("act", "silu") });
st_memcpy(codes.data(), d_q[1], codes.size(), hipMemcpyDeviceToHost);
st_memcpy(scales.data(), d_s[1], scales.size() * 4, hipMemcpyDeviceToHost);
ok("gated_had_quant_fp8 without bf16 output keeps codes and scales",
rc == RAD_OK && codes == saved_codes && scales == saved_scales);
}
rc = launch_row(ghf, { T(d_gu, RAD_BF16, { M, 2 * K }), T(d_q[1], RAD_I8, { M, K }),
T(d_s[1], RAD_F32, { M, nkb }), T(nullptr, RAD_BF16, {}) },
{ PI("M", M), PI("n", K), PI("group", 128),
PS("dtype", "bf16"), PS("act", "silu") });
ok("gated_had_quant_fp8 refuses int8 codes", rc != RAD_OK);
} else {
ok("gated_had_quant_fp8 is registered", false, "row absent");
}
/* --- the rotated int8 twins, against their producer and had_quant_act_i8g ---
*
* For a trunk stored at i8a8h: the bf16 output must not move (it is unrotated), and codes and
@@ -33226,7 +33295,8 @@ static void device_phase(const Plugin& pl) {
/* The fused quantisers are checked against the kernels they replace, gated on their own
* rows. */
if (sel("rmsnorm_quant_fp8") || sel("gated_quant_fp8") || sel("gate_quant_fp8") ||
sel("rmsnorm_had_quant_i8g") || sel("gated_had_quant_i8g")) {
sel("gated_had_quant_fp8") || sel("rmsnorm_had_quant_i8g") ||
sel("gated_had_quant_i8g")) {
if (!g_case) std::printf("\nthe fp8 fusions, against the pair each one replaces\n");
fused_quant_fp8_numeric(pl);
}
+227
View File
@@ -2633,6 +2633,233 @@ TEST(the_encodings_the_model_holds_choose_the_flash_next_kernels) {
CHECK(!p.layers[0].hc_mix.mix_e4m3);
}
/* The input to gate_up and the gated input to down are distinct activations: a trellis
* gate may read rotated int8 while a W5NL down reads a rotated E4M3 gated product. */
TEST(flashnext_trellis_gate_and_w5nl_down_use_separate_activation_formats) {
RadEncoding tq{};
rad_enc_clear(&tq);
rad_enc_copy_str(tq.scheme, "trellis");
rad_enc_add_plane(&tq, "codes", RAD_U5, 1, 1);
rad_enc_add_plane(&tq, "scale", RAD_F32, 1, 0);
const int t = rad_enc_add_table(&tq, "trellis", RAD_I8, 1 << 16, 1);
tq.plane[t].block[0] = 128;
rad_enc_add_table(&tq, "trellis.mad", RAD_U32, 2, 1);
rad_enc_add_plane(&tq, "scale.col", RAD_F32, 0, 128);
rad_enc_copy_str(tq.transform, "fwht128");
RadEncoding w5{};
rad_enc_clear(&w5);
rad_enc_copy_str(w5.scheme, "affine");
rad_enc_add_plane(&w5, "codes", RAD_U5, 1, 1);
rad_enc_add_plane(&w5, "scale", RAD_F8E4M3, 1, 64);
rad_enc_add_plane(&w5, "scale.1", RAD_F32, 0, 0);
rad_enc_add_table(&w5, "table", RAD_F32, 1, 32);
rad_enc_copy_str(w5.transform, "fwht128");
REQUIRE(rad_enc_valid(&tq));
REQUIRE(rad_enc_valid(&w5));
RadEncoding r8 = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
rad_enc_copy_str(r8.transform, "fwht128");
REQUIRE(rad_enc_valid(&r8));
for (int rank = 0; rank < 2; ++rank) {
RadModelMeta meta = qwen4exp_meta();
RadBuildCtx c = build_ctx(rank, 2);
c.max_tok = 64; c.max_seqs = 2; c.max_spec = 0; c.max_ctx = 4096;
RadBuilder b;
b.encs = { { "ffn_gate_up_exps", tq }, { "ffn_down_exps", w5 },
{ "ssm_inz.weight", tq }, { "attn_qg.weight", tq } };
for (const char* name : { "qsa_qk.weight", "attn_k.weight", "attn_v.weight",
"attn_output.weight", "ssm_out.weight",
"ffn_gate_up_shexp", "ffn_down_shexp" })
b.encs.push_back({ name, r8 });
REQUIRE_EQ(qwen4exp_fp8::declare(&b, &meta, &c), RAD_OK);
const auto& m = qwen4exp_fp8::g_model[rank];
const auto& moe = m.layers[0].mlp;
CHECK_EQ(moe.fmt[0], 11);
CHECK_EQ(moe.fmt[1], 7);
CHECK(m.a_eff.q && m.a_eff.s && m.a_eff.q8 && m.a_eff.s8);
CHECK_EQ(moe.gq_exp.a.cq(), m.a_eff.q);
CHECK_EQ(moe.gq_exp.a.cs(), m.a_eff.s);
const RecOp* gate = b.op_of(moe.op_gu);
const RecOp* down = b.op_of(moe.op_dn);
const RecOp* quant = b.op_of(moe.gq_exp.op);
REQUIRE(gate && down && quant);
CHECK_EQ(quant->op, std::string("gated_had_quant_fp8"));
REQUIRE(!down->reads.empty());
CHECK_EQ(down->reads[0], m.a_eff.q);
bool gate_i8 = false, down_w5 = false;
for (const auto& p : gate->p) gate_i8 |= p.key == "dtype" && p.sval == "i8a8h";
for (const auto& p : down->p) down_w5 |= p.key == "dtype" && p.sval == "w5nl64a8h";
CHECK(gate_i8);
CHECK(down_w5);
/* Declaration alone cannot verify the step's actual wiring. Inspect the issued
* gate -> rotated E4M3 producer -> down chain on each TP rank as well. */
std::unique_ptr<Kit> k = kit(b, { 1 }, {});
RadCtx ctx;
ctx.b = &b;
ctx.batch = &k->b;
qwen4exp_fp8::step(&ctx, &k->b);
const RecIssue *gu_issue = nullptr, *quant_issue = nullptr, *dn_issue = nullptr;
size_t igu = 0, iq = 0, idn = 0;
for (size_t i = 0; i < ctx.issues.size(); ++i) {
const RecIssue& issue = ctx.issues[i];
if (issue.op == moe.op_gu) { gu_issue = &issue; igu = i; }
if (issue.op == moe.gq_exp.op) { quant_issue = &issue; iq = i; }
if (issue.op == moe.op_dn) { dn_issue = &issue; idn = i; }
}
REQUIRE(gu_issue && quant_issue && dn_issue);
CHECK(igu < iq && iq < idn);
REQUIRE(gu_issue->opd.size() >= 9);
REQUIRE(quant_issue->opd.size() >= 3);
REQUIRE(dn_issue->opd.size() >= 2);
CHECK_EQ(gu_issue->opd.back().handle, quant_issue->opd[0].handle);
CHECK_EQ(quant_issue->opd[1].handle, m.a_eff.q);
CHECK_EQ(quant_issue->opd[2].handle, m.a_eff.s);
CHECK_EQ(dn_issue->opd[0].handle, quant_issue->opd[1].handle);
CHECK_EQ(dn_issue->opd[1].handle, quant_issue->opd[2].handle);
CHECK_EQ(dn_issue->opd[0].offset, quant_issue->opd[1].offset);
CHECK_EQ(dn_issue->opd[1].offset, quant_issue->opd[2].offset);
CHECK(gu_issue->opd[0].handle != quant_issue->opd[1].handle);
}
}
/* The MTP-only expert tap must see history rows even in chunks that would ordinarily
* store only KV. When round 1 is needed it selects after, not before, the routed block. */
TEST(flashnext_mtp_calibration_runs_the_history_rows_through_the_experts) {
for (int rank = 0; rank < 2; ++rank) {
RadModelMeta meta = qwen4exp_meta();
RadBuildCtx build = build_ctx(rank, 2);
build.max_tok = 64; build.max_seqs = 2; build.max_spec = 1; build.max_ctx = 4096;
RadBuilder b;
REQUIRE_EQ(qwen4exp_fp8::declare(&b, &meta, &build), RAD_OK);
auto& model = qwen4exp_fp8::g_model[rank];
REQUIRE(model.have_mtp);
auto k = kit(b, {}, { 8 }, 10);
k->b.draft_pass = -1;
k->b.phase = RAD_PHASE_DECODE;
k->out = { 0, 1, 2, 3, 4, 5, 6, 7 };
k->b.out_ids = k->out.data();
k->b.n_out = 8;
k->dout = { 7 };
k->b.draft_out_ids = k->dout.data();
auto issue = [](const RadCtx& ctx, rad_op op) {
for (size_t i = 0; i < ctx.issues.size(); ++i)
if (ctx.issues[i].op == op) return (int)i;
return -1;
};
/* A normal history-only chunk skips the expensive draft feed-forward. */
k->b.n_draft_out = 0;
model.mtp.mlp.c.calib = 0;
RadCtx normal{ .b = &b, .batch = &k->b, .rank = rank, .world = 2 };
model.mtp.step(&normal, &k->b);
CHECK_EQ(issue(normal, model.mtp.mlp.op_gu), -1);
model.mtp.mlp.c.calib = 1;
for (int incomplete : { 0, 1, 7 }) {
k->b.n_out = incomplete;
RadCtx invalid{ .b = &b, .batch = &k->b, .rank = rank, .world = 2 };
model.mtp.step(&invalid, &k->b);
CHECK(!invalid.step_fail.empty());
CHECK_EQ(issue(invalid, model.mtp.mlp.op_gu), -1);
}
k->b.n_out = 8;
RadCtx tap{ .b = &b, .batch = &k->b, .rank = rank, .world = 2 };
model.mtp.step(&tap, &k->b);
CHECK(tap.step_fail.empty());
CHECK(issue(tap, model.mtp.mlp.op_gu) >= 0);
CHECK(issue(tap, model.mtp.mlp.op_dn) >= 0);
CHECK_EQ(issue(tap, model.mtp.op_dsel), -1);
CHECK_EQ(issue(tap, model.mtp.op_logits), -1);
k->b.n_draft_out = 1;
RadCtx draft{ .b = &b, .batch = &k->b, .rank = rank, .world = 2 };
model.mtp.step(&draft, &k->b);
const int dn = issue(draft, model.mtp.mlp.op_dn);
const int select = issue(draft, model.mtp.op_dsel);
const int back = issue(draft, model.mtp.op_dback);
const int logits = issue(draft, model.mtp.op_logits);
CHECK(dn >= 0 && dn < select && select < back && back < logits);
/* Once the target was written the ordinary history fast path returns. */
model.mtp.mlp.calib_done = true;
k->b.n_draft_out = 0;
RadCtx done{ .b = &b, .batch = &k->b, .rank = rank, .world = 2 };
model.mtp.step(&done, &k->b);
CHECK_EQ(issue(done, model.mtp.mlp.op_gu), -1);
model.mtp.mlp.c.calib = 0;
model.mtp.mlp.calib_done = false;
}
}
/* Run this case separately with RADIANCE_CALIB_DIR set and RADIANCE_CALIB_LAYERS=8:
* the synthetic model has eight trunk layers, so 8 is its MTP layer. */
TEST(flashnext_mtp_calibration_selects_only_the_requested_layer) {
const char* dir = std::getenv("RADIANCE_CALIB_DIR");
const char* layers = std::getenv("RADIANCE_CALIB_LAYERS");
if (!dir || !*dir || !layers || std::strcmp(layers, "8") != 0) {
CHECK(true); /* the ordinary suite does not enable a calibration */
return;
}
for (int rank = 0; rank < 2; ++rank) {
RadModelMeta meta = qwen4exp_meta();
RadBuildCtx c = build_ctx(rank, 2);
c.max_tok = 64; c.max_seqs = 2; c.max_spec = 1; c.max_ctx = 4096;
RadBuilder b;
const RadEncoding bf16 = rad_enc_plain(RAD_BF16);
b.encs = { { "ffn_gate_up_exps", bf16 }, { "ffn_down_exps", bf16 } };
REQUIRE_EQ(qwen4exp_fp8::declare(&b, &meta, &c), RAD_OK);
auto& m = qwen4exp_fp8::g_model[rank];
CHECK(m.moecfg.calib);
for (const auto& layer : m.layers) {
CHECK_EQ(layer.mlp.c.calib, 0);
CHECK_EQ(layer.mlp.op_gram_gu, 0u);
}
CHECK_EQ(m.mtp.mlp.c.calib, 1);
CHECK(m.mtp.op_attn_gram);
CHECK(m.mtp.b_attn_gram);
CHECK(m.mtp.mlp.op_gram_gu);
CHECK(m.mtp.mlp.op_gram_dn);
CHECK(m.mtp.mlp.op_gram_dne);
CHECK_EQ(m.mtp.mlp.c.n_ff_exp, 640);
CHECK_EQ(m.mtp.mlp.c.n_expert, 256);
/* The fake stream cannot populate per-expert offsets; retain the pooled tap
* and lint the full trunk -> calibrated history issue order instead. */
m.mtp.mlp.op_gram_dne = 0;
auto k = kit(b, {}, { 8 }, 10);
RadCtx trunk{ .b = &b, .batch = &k->b, .rank = rank, .world = 2 };
qwen4exp_fp8::step(&trunk, &k->b);
/* The trunk samples only its last prompt row. Serial history separately names
* all eight of the trunk's wide hidden rows as its own out_ids. */
k->out = { 0, 1, 2, 3, 4, 5, 6, 7 };
k->b.out_ids = k->out.data();
k->b.n_out = 8;
k->b.draft_pass = -1;
k->b.phase = RAD_PHASE_DECODE;
k->b.n_draft_out = 1;
k->dout = { 7 };
k->b.draft_out_ids = k->dout.data();
RadCtx history{ .b = &b, .batch = &k->b, .rank = rank, .world = 2 };
qwen4exp_fp8::step(&history, &k->b);
CHECK(history.step_fail.empty());
CHECK_EQ(m.mtp.attn_gram_rows, 8);
CHECK(issue_of(b, history, "gram_accum") != nullptr);
const auto lint = lint_step(b, { &trunk, &history });
for (const std::string& problem : lint) std::fprintf(stderr, "MTP tap lint: %s\n", problem.c_str());
CHECK(lint.empty());
k->b.n_draft_out = 0; /* an intermediate, history-only prefill chunk */
RadCtx middle{ .b = &b, .batch = &k->b, .rank = rank, .world = 2 };
qwen4exp_fp8::step(&middle, &k->b);
CHECK(middle.step_fail.empty());
const auto mlint = lint_step(b, { &trunk, &middle });
for (const std::string& problem : mlint)
std::fprintf(stderr, "MTP history-only lint: %s\n", problem.c_str());
CHECK(mlint.empty());
}
}
/* A quantised container may keep one linear as the checkpoint holds it. Flash-Next's recipe leaves
* the QSA indexer's projection plain bf16 (its top-k is a hard choice between blocks), so in a
* four-bit model with fp8 linears it is declared bf16 and read by `gemm_nt` over its input's bf16