perf(k3.1): route the decode MoE rows in the latent gather on gfx950 #3496
🟡 Nit: This duplicates the A8W4 apply-kernel-name check from _latent_input_projections (line 2811). If the apply kernel is ever renamed or a second FP8-consuming apply is added, the two sites can drift and the routed path would silently stop handing over the gathered FP8 latent (the apply would re-quantize, costing a launch and potentially differing bits). Consider hoisting the name into a module constant or a small _reuses_gathered_fp8() helper shared by both call sites.
🟡 Nit: test_latent_input_gather_codegen guards the non-routed kernel against VGPR spills and verifies the poll cycles re-read their words and vote with one lane mask, but there is no codegen guard for this kernel. The routed variant packs the register-hungry bitonic router sort and the MFMA down projection into the same launch as the Lamport polls, which is exactly where a spill or a mis-compiled poll loop would appear first — and it would regress silently since the hardware test only checks bits, not the assembly. Consider extending the codegen test to compile iris_k3moe_latent_input_gather_routed with the same assertions.
Review summary
Reviewed this PR's own commit (1a2a008df) against its stacked base zhewenyu/k31-c1-kda-boundary: the routed latent-input gather kernel, its host wrapper and guard, the model-side early-return path, and the tests.
Findings: 0 🔴 Important, 2 🟡 Nit, 0 🟣 Pre-existing.
Verified in detail:
_k3_route_row reproduces the separate routing launch: same split-order FP32 partial sums with the publisher's negative-zero sanitization, the same packed-key tie break (lower expert first), the same normalization/scaling, and the same self-sort placement and padding as _kimi3_self_sorted_routes. The scratch offsets (K3_ROUTE_SELF_MASKS, parity mask buffers, counters, epoch) match _kimi3_sigmoid_bias_topk_sorted_kernel exactly, so stream-ordered sharing of one scratch is sound, including alternation with the >32-row helper-sort path, which uses the other scratch region.down_sync arrival/departure counters self-reset within the launch with no lost-wakeup window (all SiTU adds complete before any down tile passes its await; all down tiles pass before the last one zeroes), and the dispatch order keeps every waiter behind its signalers except the mutually-waiting route programs, which stay within the first ~176 workgroups, matching the existing ≤32-row self-sort pattern.PER_ROW, 112 down tiles, sorted-capacity formula identical to kimi3_sigmoid_bias_topk_sorted), tokens/split_stride/down_out_stride are do_not_specialize, and the graph test wraps capture in assert_no_triton_compile. Offsets stay well under int32 at the routed row cap._situ_sorted_routes/_situ_input_fp8 are consume-once in the apply and reset on every fallback path, the routed early return matches the fallback's (routed, shared_partial) contract, and _topk_ready record/wait are both fork-gated so skipping them is consistent.The hardware test is strong: bit-level comparison against the separate launches at 2–16 rows, ties forced via zero rows and a coarse bias, interleaving with the mailbox-sharing all-reduce, scratch shared with the separate routing kernel, captured-graph replays with one rank late, and the 17-row decline.
Incremental review summary
Reviewed this push's commit (b5c807db5), which responds to both earlier review comments:
KimiLinearMoE._apply_reads_gathered_fp8() and shared by both latent gather call sites — resolves the earlier nit on kimi_k3.py.test_latent_input_gather_codegen is now parametrized over routed and compiles iris_k3moe_latent_input_gather_routed with the same VGPR-spill and poll-cycle (word re-read + single lane-mask vote) assertions — resolves the earlier nit on latent_gather.py. Scoping the whole-word store assertion to the unrouted kernel is correct, since the routed kernel intentionally writes the SiTU input through in BF16.Checked the new test's constexpr list and signature map against the routed kernel's full argument list: all five routed-only constexprs are supplied and every pointer/scalar arg resolves to the right type.
Findings: 0 🔴 Important, 0 🟡 Nit, 0 🟣 Pre-existing. No new issues introduced by this push.
<!-- lightseek-pr-description -->
Description checked against the current changes (7a21be5f9457).
Further updates to this PR will refresh its description and this comment.
<!-- lightseek-pr-style-review -->
<!-- style-review-revision:b22d0906daeb0106b934943865ff44ada484a650d4369811f015b3fe6b179164 -->
<!-- style-review-content:a4ad096b84c67b625a52e3a78b6ee85d711880a79df5157ee1246401324bd197 -->
Style LGTM.
<!-- lightseek-pr-style-review -->
<!-- style-review-revision:56901414e085465ec1ed1b9c6c972a577d89bb500cefc4dce300b6c174d8735f -->
<!-- style-review-content:837e13d548597df51e8f7a8dda45cdce8f8410cebcc2968f5e6cfa82f0f733e0 -->
Style LGTM.
<!-- lightseek-pr-style-review -->
The new private helper \_apply\_reads\_gathered\_fp8 has no docstring, although it carries an explanatory comment about how the gathered FP8 reads are applied, which shows its logic is not obvious. A docstring is mandatory for a function with non-obvious logic or nontrivial size, and the neighboring private helpers in this class all document themselves with docstrings. Turn the existing explanatory comment into a docstring as the first statement of \_apply\_reads\_gathered\_fp8, briefly describing what the helper does with the gathered FP8 reads, and keep any purely implementation-facing remarks as inline comments.
<!-- lightseek-pr-style-review -->
<!-- style-review-revision:34c2bc1e50537dc861a6fc166d471eabe605f4ae28f23b71fcb6649e0234bd72 -->
<!-- style-review-content:3f59c410f2efcad94d60011aebcc6ec9c3e035f8f1a169167797ee774fa33537 -->
3 style findings. See inline comments.
<!-- lightseek-pr-style-review -->
This docstring summary line is 89 characters long. Docstring summary lines must remain within the line-length limit, and this line exceeds both the guide's 80-character rule and the 88-column width used by the repository's formatter; a docstring summary is not reflowed automatically, so it must be shortened by hand. Shorten the summary so the line fits, for example: """\\latent\_input\_gather\\ that also routes rows and projects the shared experts.
<!-- lightseek-pr-style-review -->
This docstring summary line is 91 characters long. Docstring summary lines must remain within the line-length limit, and this line exceeds both the guide's 80-character rule and the 88-column width used by the repository's formatter; a docstring summary is not reflowed automatically, so it must be shortened by hand. Shorten the summary so the line fits, for example: """\\iris\_k3moe\_latent\_input\_gather\\ that also routes and projects shared experts.
<!-- lightseek-pr-style-review -->
<!-- style-review-revision:0b2e5b2ddcd66325403094af9f921c37dcccbc578a3d8a6f32da8d605fa15fc2 -->
<!-- style-review-content:a79564f65d072d7941d7bc049f278fac841dafe93af2ff1eca34eecbce9ab303 -->
1 style finding. See inline comments.
<!-- lightseek-pr-style-review -->
The docstring says the routes and their expert sort are those of the separate sorted routing launch, bit for bit. The change's own eight-GPU test compares this fused path against latent\_input\_gather followed by kimi3\_sigmoid\_bias\_topk\_sorted and checks the top-k ids, the sort counts and the sort order exactly, but the top-k weights and the sorted weights only with rtol=2e-7, so the float weights can differ in their last bits between the two launches. Because the routes include those weights, the unqualified bit-for-bit claim overstates the guarantee for a caller choosing between the fused and separate launches. Qualify the claim, for example: the route ids and their expert sort match the separate sorted routing launch bit for bit, while the float weights agree up to float rounding; or drop bit for bit and say the routes and their expert sort match that launch.
<!-- lightseek-pr-style-review -->
The new helper \_k3\_ordered\_key has no docstring even though its body is a non-obvious bit trick: it maps float bits onto an orderable unsigned key \(fully inverting negative patterns, flipping only the sign bit otherwise\) so the packed score keys that \_k3\_top16 sorts compare correctly. Style guide section 3.8.3 makes a docstring mandatory for every function with non-obvious logic, and every other nontrivial helper in this new file \(\_k3\_order\_pairs, \_k3\_top16, \_k3\_await\_count, \_k3\_route\_row, \_k3\_shared\_down\_tile\) has one; only the self-evident one-liners \(\_k3\_add, \_k3\_max\_pair, \_k3\_sleep\) go without. Add a short docstring, e.g. one line stating that the function maps FP32 bits to a monotonically ordered uint32 key \(negatives fully inverted, non-negatives sign-flipped\) for the bitonic top-k in \_k3\_route\_row.
<!-- lightseek-pr-style-review -->
<!-- style-review-revision:d3020c5afadb27f5f3b89c7458ad5cc4fad3d430aa662ef32fd9ae5d75ff9f9a -->
<!-- style-review-content:40001ad9fe0b2a9ab97baf42e80f457b57fa90bf38313196c4bba4b5e94629d2 -->
2 style findings. See inline comments.
<!-- lightseek-pr-style-review -->
The new helper \_k3\_popcount has no docstring even though its five-line SWAR population count over the expert-arrival masks \(magic constants 0x55555555, 0x33333333, 0x0F0F0F0F, 0x01010101\) is non-obvious logic that a reader must decode before trusting the route-offset arithmetic in \_k3\_route\_row. Style guide section 3.8.3 makes a docstring mandatory for every function with non-obvious logic, and the comparable nontrivial helpers in this file are all documented. Add a short docstring, e.g. one line stating that the function returns the per-word set-bit count of the uint32 mask lanes as int32, matching the neighboring documented helpers.
<!-- lightseek-pr-style-review -->
<!-- style-review-revision:d8dd043d35de0e3485681ac7bb19d0a36543715f99a91396e300d8f027ec45eb -->
<!-- style-review-content:98b3a004f8ecb2965f338fe8edb9809d107c3afd6c1ed4f3007abda4d5d81fea -->
Style LGTM.
Can we add docs to explain the fancy bitwise arithmetic here?
Can we use something other than the kernel registration name? Maybe add a new attribute to the plan?
🟡 Nit: The False default is a defensive fallback: moe_plan always emits supports_fp8_per_tensor_input, so a missing key can only mean a plan that didn't come from moe_plan or a renamed/misspelled key — and the default would silently drop the FP8 handoff (the apply re-quantizes the BF16 latent), a hidden performance regression rather than an error. The established pattern for this trait family is a direct-indexing property on the experts layer, like supports_prequantized_input (python/tokenspeed/runtime/layers/moe/expert.py:727), which fails loudly on a missing key. Consider self.experts.plan["supports_fp8_per_tensor_input"], ideally as a supports_fp8_per_tensor_input property next to its sibling.
🟡 Nit: No test covers this trait end to end: the runtime tests in test_kimi_k3_config.py set plan["supports_fp8_per_tensor_input"] by hand, so if the frozenset({True}) declaration in ops/moe/gluon.py or this extraction were dropped (or the key misspelled on either side), nothing fails — the gather just stops handing over the FP8 latent and the apply silently re-quantizes, the fallback-hides-perf-regression case AGENTS.md calls out. test_kimi3_mxfp4_situ_selection_on_cdna4 (tokenspeed-kernel/test/test_kernel_api_selection.py:4374) already builds the real plan for both A8W4 situ kernels and asserts per-kernel route-sort traits; one more line there, assert plan["supports_fp8_per_tensor_input"] is (ep_size == 1), would guard the declaration and this extraction together.
<!-- lightseek-pr-style-review -->
latent\_input\_gather\_routed is annotated as returning a bare tuple, but it always returns the same fixed five-element tuple of heterogeneous values, \(router\_logits, routed\_input, routes, shared\_partial, routed\_fp8\), as its own docstring spells out. A fixed number of elements with different types is exactly the case typed tuples cover, and the neighboring \_latent\_input\_partials added in the same change annotates its return as tuple\[torch.Tensor, int, int\], so the bare tuple hides this interface from type checkers and readers. Spell out the element types, e.g. -> tuple\[torch.Tensor, torch.Tensor, tuple\[torch.Tensor, ...\], torch.Tensor, tuple\[torch.Tensor, torch.Tensor\] \| None\], wrapping the signature as needed to stay within the line limit.
<!-- lightseek-pr-style-review -->
<!-- style-review-revision:90c8b3a25c7fa6272f456294ebd0a849e611831c8fc067221dd67e9e487260c5 -->
<!-- style-review-content:5cf01ca58bd3ce798801b90fdec0025ec5382bf93dc16277c6e7408534d189b2 -->
1 style finding. See inline comments.
<!-- lightseek-pr-style-review -->
<!-- style-review-revision:df613d1ae783a6aebf32e63318acf9483c638eba3b56f03afa8c883a09aecce0 -->
<!-- style-review-content:5f6710e5f979fb3bbc9e869218ac1fb03a0b2da487415dde279d788a31db25f0 -->
Style LGTM.
Approved these changes.
antiagainst
Yu-Zhewen
Stacked on #3495.
Summary
Through 16 replicated decode rows, the latent gather's launch now also routes each row, replacing the separate sorted routing launch and its wait for the gather.
Results
One MoE layer on 8x MI355X, averaged over 92 layers, CUDA graph:
| Rows | Before | After |
|---:|---:|---:|
| 8 | 23.44 µs | 19.55 µs |
| 12 | 23.63 µs | 20.44 µs |
InferenceX AgentX at concurrency 1 on 8x MI355X, against its parent, averaged over two same-node pairs (each pair runs both builds for an hour on one node): interactivity +2.7%, throughput +1.1%. Runs of one build agree within about 0.6% in interactivity.
Test Plan
On gfx950:
test_iris_moe_latent_gather.pyon 8 GPUs: the routed gather against the gather plus the separate routing launch at 2–16 rows, eagerly and in a captured graph with a late rank, interleaved with the MoE all-reduce on the shared mailboxes; it declines 17 rows.test_kimi_k3_config.py: the MoE block hands the gather's routes, expert sort and quantized latent to the experts, and falls back where the gather declines.