Fold HYV3 TP1 shared combination into the routed gather

Prepare a unity-gate plane once per step and use the existing gather at TP1 while preserving routed BF16 rounding before the shared add. Retain independent arm reductions and combination at TP2, with multi-pass graph and routing-rounding checks.
This commit is contained in:
Constantin authored and StillDeadcode committed 2026-10-27 18:28:46 +01:00
1 parent 36c39efdca
commit 9916dcace3
5 files changed
+70 -38

No files matched your search

+20 -12
View File
@@ -189,8 +189,12 @@ struct MoeFP8 {
int swiglu_quant = 0;
/* A shared arm without its sigmoid gate: the gate plane is filled with 1. */
int shared_ungated = 0;
/* Add the routed and shared BF16 outputs in FP32, then round once to BF16, as HYV3's
* enable_moe_fp32_combine path does. This bypasses moe_gather's fused shared-arm add. */
/* At TP1 the caller may fill the ungated arm's ones plane once for the whole step,
* rather than each layer/pass filling the same plane again. */
int shared_one_external = 0;
/* Add the already-rounded routed and shared BF16 outputs in FP32, then round to BF16.
* At TP1 the ungated gather preserves both roundings; TP>1 reduces each arm separately
* before combining, so its gather cannot fold the shared output. */
int shared_fp32_combine = 0;
/* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for
* Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8`
@@ -628,6 +632,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
src.shared)) return RAD_E_INVAL;
const bool shared = c.n_ff_shared > 0 && (src.shared || src.shared_mlp_gate);
if (shared && c.shared_ungated && src.shared_gate) return RAD_E_INVAL;
if (c.shared_one_external && (!shared || !c.shared_ungated || !w.sgate || g.world != 1))
return RAD_E_INVAL;
if (c.shared_fp32_combine && (!shared || !w.moe || std::strcmp(g.dtype, "bf16"))) {
fprintf(stderr, "radiance: layer %d requests an FP32 shared/routed combine without its "
"BF16 shared arm and routed output\n", l);
@@ -1318,10 +1324,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
if (!b_gram_dne || !op_gram_dne) return RAD_E_INVAL;
}
/* Normally the gather folds the shared arm in, saving a dispatch and round trip. HYV3 asks
* for an FP32 addition of the two already-rounded BF16 outputs, so it gathers routed output
* separately and combines the two arms below. */
const bool separate_fp32_combine = shared && c.shared_fp32_combine;
/* The gather rounds the routed sum to BF16 before adding the rounded shared product.
* At TP1 a unity gate therefore preserves HYV3's FP32 combine exactly. TP>1 must first
* reduce each arm independently, and cannot combine them inside the local gather. */
const bool separate_fp32_combine = shared && c.shared_fp32_combine &&
(g.world > 1 || !c.shared_ungated);
gfold = shared && !separate_fp32_combine;
for (int form = scatter_inv ? 0 : 1; form < 2 && !op_gather; ++form) {
rad_buf grd[5] = { w.edn, w.ew, form ? w.sorted : w.inv, w.sout, w.sgate };
@@ -1414,7 +1421,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
if (separate_fp32_combine) {
/* BF16 add widens both inputs to FP32, adds, then rounds once to BF16: exactly the
* former cast + cast + F32 add + cast chain. Keep the routed gather's BF16 rounding
* and the separate TP reductions; folding the shared arm into the gather is different. */
* and the separate TP reductions; a local gather cannot fold those reductions. */
op_combine = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", "bf16")),
@@ -1575,10 +1582,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* buffers are step-tall, so the pass offset applies as in an MlpFP8 slice. */
inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
bool gate_done) const {
/* `gate_done`: the fused router already wrote this pass's gate. An FP32 combine does not
* consume the ungated arm's ones plane, so skip its otherwise redundant fill. */
/* `gate_done`: the fused router already wrote this pass's gate. A separate FP32 combine
* reads no ones plane. At TP1 an ungated folded gather does, unless the caller prepared the
* whole step's ones plane once (shared_one_external). */
if (!gate_done && c.shared_ungated) {
if (!c.shared_fp32_combine)
if (gfold && !c.shared_one_external)
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.sgate, r0, rows, 1));
} else if (!gate_done) {
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
@@ -1783,12 +1791,12 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
/* The gather last, since with the fold it reads the shared arm (`sout`, `sgate`); it writes
* the block's delta into `h.x`. */
if (c.shared_fp32_combine || !gather_taken(g, T, gather_out_rows, gather_out_rows6))
if (op_combine || !gather_taken(g, T, gather_out_rows, gather_out_rows6))
RAD_ISSUE_N(c_, op_gather, rows, brows(w.edn, rows * k), brow_slice(w.ew, r0, rows, k),
brows(gather_inv ? w.inv : w.sorted, rows * k),
gfold ? brow_slice(w.sout, r0, rows, g.n_embd) : RAD_NONE,
gfold ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
brow_slice(c.shared_fp32_combine ? w.moe : w.h.x, r0, rows, g.n_embd));
brow_slice(op_combine ? w.moe : w.h.x, r0, rows, g.n_embd));
if (op_moe_ar)
RAD_ISSUE_N(c_, op_moe_ar, rows * g.n_embd,
brow_slice(w.moe, r0, rows, g.n_embd), RAD_NONE);
+13 -2
View File
@@ -51,7 +51,7 @@ struct Model {
MoeFP8::Wire mw{};
rad_weight token = 0, final_norm = 0, lm_head = 0;
rad_op embed = 0, embed_ar = 0, final_rms = 0, gather = 0, logits_op = 0;
rad_op embed = 0, embed_ar = 0, shared_one = 0, final_rms = 0, gather = 0, logits_op = 0;
std::vector<Layer> layers;
};
@@ -234,6 +234,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 2.826);
mc.shared_ungated = 1;
mc.shared_fp32_combine = 1;
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);
@@ -266,6 +267,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
!HYV3_FP8_SOURCE));
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;
}
/* ---- Token embedding and head. */
#if HYV3_GGUF_SOURCE
@@ -350,7 +358,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
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
// embedding directly; the final feed-forward keeps its add for the plain output norm.
// Keep the collectives in the same places and the routed/shared FP32 combine separate.
// Keep collective placement and both routed/shared BF16 rounding points.
status = lay.attn.declare(b, nm, g, (int)l, m.kv_full, aw, as, l > 0, false);
if (status < 0) {
fprintf(stderr, "radiance: hyv3: attention layer %lld declaration failed (%d)\n",
@@ -461,6 +469,9 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
brows(m.x, batch->n_tok), RAD_NONE);
// All TP1 ungated gathers read this same ones plane; no per-layer fill or combine launch.
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);
+9 -5
View File
@@ -297,7 +297,10 @@ MLP followed by 47 layers routing top-8 of 128 experts. The routed and shared ML
768 in the checkpoint tensors. Attention applies per-head Q/K RMSNorm before NeoX RoPE. Routing selects
with sigmoid scores plus the correction bias, but normalizes the selected unbiased scores and
multiplies them by 2.826. Routed and shared BF16 outputs are reduced independently at TP2, then added
in FP32 and rounded once to BF16 before the residual add.
in FP32 and rounded once to BF16 before the residual add. At TP1 the existing ungated gather
preserves those two arm roundings and folds their addition; the plugin prepares one shared ones
plane for the whole step. Each residual add except the final one folds into the following norm,
which normalizes the BF16-rounded sum. The final norm still reads a materialized residual stream.
Convert the public FP8 checkpoint with
`data/recipes/hy-memory-30b-a3b-fp8.recipe`; it preserves the E4M3 codes and expands the checkpoint's
@@ -315,10 +318,11 @@ This is distinct from the BF16-derived block-FP8 artifact tested below.
The BF16 checkpoint can be converted without quantizing any weights, or with
`data/recipes/hy-memory-30b-a3b-bf16-w4.recipe`, which quantizes attention projections, the first
dense MLP and routed experts to INT4. Shared MLPs, router, norms, embeddings and the output head stay
BF16. The asymmetric linear W4A8 and signed expert W4A8 kernels use dynamic INT8 activations.
BF16-source block-FP8 and MXFP4 recipes quantize experts and regular linears; the W8 recipe quantizes
regular linears and the output head while routed experts remain BF16. Use TP2 at serve time if one
device cannot hold the model and cache.
BF16. At decode the asymmetric linear W4 kernel narrows BF16 activations to F16 on load;
above 64 rows its tiled path uses dynamic INT8 activations. The signed-I4 expert path uses
block-scaled E4M3 activations. BF16-source block-FP8 and MXFP4 recipes quantize experts and regular
linears; the W8 recipe quantizes regular linears and the output head while routed experts remain
BF16. Use TP2 at serve time if one device cannot hold the model and cache.
The local llama.cpp Q4_K_M source is supported by `arch/hyv3_gguf` and
`data/recipes/hy-memory-30b-a3b-gguf-q4k-to-w4.recipe`. It decodes Q4_K/Q6_K source tensors and
+8 -5
View File
@@ -3296,7 +3296,7 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat
if (shared) want = h_to_bf16(h_bf16(want) + h_bf16(shv[t * n + c]));
exact = exact && base[t * n + c] == want;
}
ok(("GLM gather preserves F32 mixture weights" + at).c_str(), exact);
ok(("MoE gather preserves F32 weights and BF16 arm rounding" + at).c_str(), exact);
}
struct Var { int form; const char* name; bool wide; };
static const Var kVar[] = {
@@ -3368,9 +3368,12 @@ static void moe_gather_case(const Plugin& pl) {
{ 2048, 2560, 10, "sigmoid", true }, /* Qwen3.8-Flash-Next's chunk, timed */
};
for (const MoeGatherShape& sh : kSh) moe_gather_at(pl, r, sh);
// HYV3's TP1 shared combine is the unity-gate form. Preserve the routed BF16 narrow
// before adding the shared BF16 output, at decode and past the self-scan boundary.
for (int64_t m : { 1, 4, 65 })
for (bool shared : { false, true })
moe_gather_at(pl, r, { m, 4096, 8, shared ? "none" : nullptr, false }, true);
for (int64_t n : { 2048, 4096 })
for (bool shared : { false, true })
moe_gather_at(pl, r, { m, n, 8, shared ? "none" : nullptr, false }, true);
}
/* ------------------------------------------------------- the vocab-parallel top-R, end to end
@@ -6248,8 +6251,8 @@ static void i8a8h_rot(const Plugin& pl, const char* row, int64_t M, int64_t N, i
}
/* Single-row reduction vs the unchanged padded-row epilogue. MB=2 forces the latter without
* changing a split or a WMMA. Check ragged columns, narrow projections and HYV3's shared MLP. */
/* A single row's outputs must not depend on covering one or two M tiles per block. Keep each
* split fixed and check ragged columns, narrow projections and HYV3's shared MLP, with guards. */
static void bf16_one_row_identity(const Plugin& pl, int64_t N, int64_t K) {
const RadKernelInfo* r = find(pl, "gemm_bf16_nt_m64");
if (!r) { ok("bf16 one-row bytes", false, "row absent"); return; }
+20 -14
View File
@@ -722,6 +722,7 @@ TEST(hyv3_folds_residual_adds_into_the_next_norm_but_materializes_the_final_outp
CHECK_EQ(m.layers[0].attn.nq_h.src, m.x);
CHECK_EQ(m.layers[0].dense_mlp.nq_h.res, m.x);
CHECK_EQ(m.layers[0].dense_mlp.op_add, (rad_op)0);
CHECK_EQ(m.shared_one != 0, world == 1);
for (size_t l = 0; l < m.layers.size(); ++l) {
CHECK_EQ(m.layers[l].attn.op_add, (rad_op)0);
if (l == 0) continue;
@@ -730,22 +731,28 @@ TEST(hyv3_folds_residual_adds_into_the_next_norm_but_materializes_the_final_outp
CHECK_EQ(m.layers[l].moe.nq_h.src, m.h.x);
CHECK_EQ(m.layers[l].moe.nq_h.res, m.x);
CHECK_EQ(m.layers[l].moe.op_add != 0, l + 1 == m.layers.size());
CHECK(m.layers[l].moe.op_combine != 0); // retain the separate BF16-rounded arms
CHECK_EQ(m.layers[l].moe.op_combine != 0, world > 1);
CHECK_EQ(m.layers[l].moe.gfold, world == 1); // both arms still round before adding
const RecOp* norm = b.op_of(m.layers[l].moe.nq_h.op);
REQUIRE(norm);
CHECK(std::find(norm->reads.begin(), norm->reads.end(), m.x) != norm->reads.end());
CHECK(std::find(norm->writes.begin(), norm->writes.end(), m.x) != norm->writes.end());
}
CHECK_EQ(count_op(b, "add"), 3); // two routed/shared combines, one final residual
CHECK_EQ(count_op(b, "add"), world > 1 ? 3 : 1); // TP2 combines each reduced arm separately
for (int rows : { 1, 8, 65, 2049, 4096 }) {
RadBatch batch = decode_batch(); batch.n_tok = rows; batch.max_q_len = rows;
RadCtx run{}; run.b = &b; run.batch = &batch; run.rank = rank;
hyv3_bf16::step(&run, &batch);
CHECK(lint_step(b, {&run}).empty());
int final_adds = 0;
for (const auto& issue : run.issues)
int final_adds = 0, ones = 0;
for (const auto& issue : run.issues) {
if (issue.op == m.layers.back().moe.op_add) ++final_adds;
if (issue.op == m.shared_one) ++ones;
for (size_t l = 1; l < m.layers.size(); ++l)
CHECK(issue.op != m.layers[l].moe.op_sgate); // no per-layer ones fills
}
CHECK_EQ(final_adds, (rows + 2047) / 2048);
CHECK_EQ(ones, world == 1 ? 1 : 0);
}
}
}
@@ -814,18 +821,16 @@ TEST(hyv3_fp8_declares_dense_then_sigmoid_moe_with_fp32_combine) {
CHECK_EQ(moe.c.n_ff_exp, 768); CHECK_EQ(moe.c.n_ff_shared, 768);
CHECK_EQ(moe.c.expert_f32_scale, 1);
CHECK_EQ(moe.c.route_scale, 2.826); CHECK_EQ(moe.c.sigmoid_router, 1);
CHECK_EQ(moe.c.shared_fp32_combine, 1); CHECK_EQ(moe.gfold, false);
CHECK_EQ(moe.c.shared_fp32_combine, 1); CHECK_EQ(moe.gfold, true);
const RecOp* gather = b.op_of(moe.op_gather);
CHECK(gather != nullptr);
CHECK_EQ(gather->writes.size(), 1u);
CHECK_EQ(gather->writes[0], moe.w.moe);
REQUIRE(moe.op_combine);
const RecOp* combine = b.op_of(moe.op_combine);
REQUIRE(combine);
CHECK_EQ(combine->op, std::string("add"));
CHECK_EQ(std::string(pstr(combine, "dtype")), std::string("bf16"));
CHECK(combine->reads == (std::vector<rad_buf>{moe.w.moe, moe.w.sout}));
CHECK(combine->writes == (std::vector<rad_buf>{moe.w.h.x}));
CHECK_EQ(gather->writes[0], moe.w.h.x);
CHECK_EQ(moe.op_combine, (rad_op)0);
CHECK(model.shared_one != 0);
CHECK(gather->reads == (std::vector<rad_buf>{moe.w.edn, moe.w.ew,
moe.gather_inv ? moe.w.inv : moe.w.sorted,
moe.w.sout, moe.w.sgate}));
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch;
@@ -835,7 +840,7 @@ TEST(hyv3_fp8_declares_dense_then_sigmoid_moe_with_fp32_combine) {
if (run.issues[i].op == h) return (int)i;
return -1;
};
const int gather_i = issue_of(moe.op_gather), add_i = issue_of(moe.op_combine);
const int gather_i = issue_of(moe.op_gather), add_i = issue_of(moe.op_add);
CHECK(gather_i >= 0 && add_i >= 0 && gather_i < add_i);
REQUIRE(moe.op_sigmoid_scatter);
CHECK(issue_of(moe.op_sigmoid_scatter) >= 0);
@@ -862,6 +867,7 @@ TEST(hyv3_fp8_tensor_parallel_partitions_experts_and_shared_width) {
CHECK_EQ(moe.c.shared_lo, rank * 384);
CHECK_EQ(moe.c.shared_hi, (rank + 1) * 384);
CHECK(moe.op_moe_ar && moe.op_shared_ar && !moe.op_ar);
CHECK(moe.op_combine && !moe.gfold && !model.shared_one);
CHECK(find_w(b, rank == 0 ? "blk.1.ffn_gate_up_exps.0.weight"
: "blk.1.ffn_gate_up_exps.64.weight") != nullptr);
CHECK_EQ(model.g.n_ff, 3456);