gemma4k, arch/gemma4: expert_scale -- per_expert_scale on the routing weights in one launch

Gemma 4 multiplies each renormalised routing weight by per_expert_scale of the expert it chose.
In the conventional vocabulary that is an `embed_lookup` of the [n_expert, 1] table by the ids
and a `mul` into the weights -- two launches a MoE layer, a few dozen elements each at decode
(--profile-ops: ~0.26 and ~0.22 ms a step across the 30 layers). gemma4k's `expert_scale` is the
pair as one kernel, ew = bf16(ew * w_e[id]), with an id outside the table reading 0 as
embed_lookup's missed row does: one product rounded once, so the pair's value bit for bit.

Like the joins it has no libref row on purpose, so arch/gemma4 falls back to the pair wherever
gemma4k is not loaded, and RADIANCE_GEMMA4_FUSE=0 turns it off with them. 30 launches a step the
fewer.

g4k_emu: device and host rows against the pair over 32 shapes -- top-k 1 and 8, pitched rows,
pads and one-past-the-end ids, rows past M untouched -- every element equal. arch_test: a decode
step scales in one launch, and in two with it refused. docs/OPS.md: the row and its paragraph;
GUIDE: what the switch now covers.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
AshlynandClaude Opus 5.5 committed 2026-10-12 14:40:04 -05:00
1 parent 29f981fd6c
commit 0d95046f6f
11 files changed
+289 -25

No files matched your search

+24 -1
View File
@@ -3699,7 +3699,30 @@ TEST(gemma4_routes_a_decode_step_in_one_launch) {
CHECK_EQ(count_issued(issued, "router_topk"), refuse == 2 ? 6 : 0);
CHECK_EQ(count_issued(issued, "moe_scatter"), refuse == 2 ? 6 : 0);
/* the per-expert scale and the experts' gather run whichever form routed */
CHECK_EQ(count_issued(issued, "embed_lookup"), 1 + 6);
CHECK_EQ(count_issued(issued, "expert_scale"), 6);
CHECK_EQ(count_issued(issued, "moe_gather"), 6);
}
}
/* The per-expert scale is one launch where gemma4k serves `expert_scale`, and the table lookup and
* the multiply where it does not -- the same buffers read and written either way. */
TEST(gemma4_scales_the_routing_weights_in_one_launch) {
for (int refuse = 0; refuse < 2; ++refuse) {
RadBuilder b;
if (refuse) b.refuse.insert("expert_scale");
RadModelMeta meta = gemma4_moe_meta();
RadBuildCtx ctx = build_ctx();
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
RadBatch batch = decode_batch();
c.batch = &batch;
gemma4::step(&c, &batch);
CHECK(c.step_fail.empty());
const std::vector<std::string> issued = issued_ops(b, c);
CHECK_EQ(count_issued(issued, "expert_scale"), refuse ? 0 : 6);
CHECK_EQ(count_issued(issued, "embed_lookup"), refuse ? 1 + 6 : 1); /* + the token embedding */
CHECK_EQ(count_issued(issued, "mul"), refuse ? 6 : 0);
for (const auto& o : b.ops)
if (o.resolved) CHECK(o.uses_declared);
}
}