arch/gemma4: route a decode step in one launch -- libr4d's fused router, top-k and sort

At decode heights the router GEMM (128 x 2816), its top-k and the expert sort are each one small
workgroup's work behind a full dispatch: --profile-ops put the three at ~0.27, 0.29 and 0.24 ms a
step across the 30 MoE layers. libr4d already fuses them for the Qwen MoE blocks --
`router_topk_scatter` for the pair, `router_gemm_topk_scatter` with the GEMM in front -- and
documents both as byte-identical to the launches they replace, so the routing does not move.

arch/gemma4 now asks for them as rad_block_moe_fp8.h does: the pair up to the sort's
single-workgroup bound (1024 routing slots, 128 rows at top-8), the GEMM form up to the skinny
GEMM's decode band (64 rows), and the separate ops for a pass past either, declared regardless.
The per-expert scale and the experts' input norm sit between them in the issue order and read only
the ids and weights the fused op writes. Two launches a MoE layer the fewer at decode, 60 a step.

arch_test: a decode step routes with the fused op; refused, with the pair; both refused, with the
three separate ops -- and the per-expert scale and the gather run in every case.

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 171dcee15b
commit 29f981fd6c
2 files changed
+96 -6

No files matched your search

+27
View File
@@ -3676,3 +3676,30 @@ TEST(gemma4_feed_forward_join_writes_the_next_input_norm) {
CHECK_EQ(count_issued(issued, "logits_gemm"), 1);
}
}
/* At decode heights the router, its top-k and the sort are one launch (libr4d's
* router_gemm_topk_scatter); refused, the pair (router_topk_scatter) behind the router GEMM; both
* refused, the three separate ops as before. The routing's buffers are the same either way. */
TEST(gemma4_routes_a_decode_step_in_one_launch) {
for (int refuse = 0; refuse < 3; ++refuse) {
RadBuilder b;
if (refuse >= 1) b.refuse.insert("router_gemm_topk_scatter");
if (refuse >= 2) b.refuse.insert("router_topk_scatter");
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, "router_gemm_topk_scatter"), refuse == 0 ? 6 : 0);
CHECK_EQ(count_issued(issued, "router_topk_scatter"), refuse == 1 ? 6 : 0);
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, "moe_gather"), 6);
}
}