Repository navigation
[Triton/Gluon] [HIP] [Perf] gfx1250: wave32 register top-k for MoE routing - #7733
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
There was a problem hiding this comment.
🟡 Changes recommended
The new dispatch can break Dynamo compilation and regress overflow-row performance, while the benchmark can produce false tie-order failures on gfx942/gfx950.
3 open issues
What changed in this PR
This PR accelerates MoE top-k routing on gfx1250 with wave32 HIP register kernels and redirects eligible biased-sigmoid calls from Triton to HIP.
Changes:
- Extends the single-wave register path to wave32 and adds a multi-wave biased-sigmoid kernel.
- Adds dispatch checks for supported shapes, alignment, and output strides.
- Expands correctness tests and updates benchmarks to preserve direct Triton comparisons.
| File | Description |
|---|---|
op_tests/triton_tests/moe/moe_routing/test_topk_gating.py |
Checks Triton results and public dispatch against HIP. |
op_tests/test_moeTopkSoftmax.py |
Adds tie, stride, mixed-bias, and multi-wave test cases. |
op_tests/test_moe_topk_gating.py |
Benchmarks the Triton specialization directly against HIP. |
csrc/kernels/topk_softmax_kernels_group.cu |
Implements wave32 register paths and their launch gates. |
aiter/ops/topk.py |
Routes eligible gfx1250 inputs to the HIP multi-wave kernel. |
Review effort: Balanced
topk_reg_kernel was gated to wave64, so on gfx1250 routing without a group filter took the LDS kernel, and biased_grouped_topk sent its E=512..1024 sigmoid shapes to the Triton kernel: about 7.2 us per call for the Kimi-K3 router at decode. - topk_reg_kernel runs at wave32. Lanes stage two candidates each, so up to 64 still take the fast path; wave64 keeps its single-slot code. The wave32 EPL list reuses wave64 instantiations only. - topk_reg_mw_kernel: biased sigmoid top-k at wave32 with a workgroup of E / 128 waves per row, for E = 512, 768, 896 and 1024, topk <= 16, BF16 logits and a BF16 or FP32 bias. Same ids and weight bits as the row-per-wave kernels. - biased_grouped_topk sends the rows that fit the multi-wave kernel to biased_grouped_topk_hip instead of the Triton kernel. Kimi-K3 router on MI455X: 7.24 -> 1.45 us per call at one token and 54.96 -> 10.43 us at 8192 tokens. Device code for gfx942 and gfx950 is unchanged. Co-authored-by: Claude Opus 5.5 <[email protected]>
HERD routing with K = 16 asks biased_grouped_topk for the top 17. The multi-wave kernel's renormalization read a fixed 16 lanes, its only bound at 16; the fallback's filler search holds for topk <= 32. The sum now reads kTopKRegMwMaxTopK = 17 lanes, so topk 17 on gfx1250 takes the kernel instead of the Triton one, and the op tests cover it. Each multi-wave instantiation gains one readlane and one add; device code for gfx942 and gfx950 is unchanged. Co-authored-by: Claude Opus 5.5 <[email protected]>
Follow-ups from review of the wave32 register top-k: - Wave32 builds compile the topk_reg_kernel EPLs only the wave64 dispatch launches (2, 3 and 14) to empty kernels. Device-only compile of topk_softmax_kernels_group.cu: gfx1250 117 s instead of 172 s (162 s on main), gfx1100 114 s and gfx1201 111 s instead of 162 s. Every kernel that runs compiles to the same instructions as before; gfx942 and gfx950 still compile to main's instructions. - topk_reg_mw_kernel: static_assert the 16-bit logits its sigmoid depends on instead of keeping an FP32 branch nothing launches; one lambda ranks and pushes the two-slot candidates (same instructions). - static_assert that kTopKRegMwMaxTopK leaves lane 31 past topk: the two-slot ranking parks ranks past the wave there, and the fallback draws its fillers from ids 0..31. - The Python and C++ gates of the multi-wave kernel point at each other. A row the Python gate admits and the C++ gate rejects aborts in the LDS kernel on an FP32 bias at E = 768 and 896. - LAUNCHER_TOPK_REG drops a wave-size check that always held. - kTopKRegCandCap's comment quotes the shapes that reach wave32 topk_reg_kernel (E=896 takes the multi-wave kernel): at topk 16 one slot per lane would overflow on up to ~0.16% of random rows, each adding 25-45 us to its launch on MI455X. - op tests: 40 tied candidates at E=128 (biased) and E=256 (softmax, and biased with an FP32 bias), which wave32 topk_reg_kernel stages two per lane. The multi-wave kernel keeps one case per wave count, the two-slot rank, the degenerate rows and Kimi-K3's inputs; its separate tables fold into the existing ones. Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Cursor <[email protected]>
…directly biased_grouped_topk now sends aligned BF16 rows of E = 512, 768, 896 and 1024 to the HIP multi-wave kernel, so test_exact_sigmoid_topk_herd_widths no longer reached the Triton kernel: its K+1 widths (5, 9 and 17), which it pads to a power of two with masked stores, went untested, and the ids == hip_ids check compared the HIP kernel with itself. Unaligned rows and E=900 still take the Triton kernel. The test now calls the Triton kernel through _gfx1250_exact_sigmoid_topk and checks it against biased_grouped_topk_hip for both bias dtypes. The HIP kernel takes an FP32 bias at these shapes now, so the early return for one goes. test_exact_sigmoid_topk_matches_torch asserts that its unaligned rows miss the multi-wave kernel, so a wider gate cannot take its Triton coverage away unnoticed. Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Cursor <[email protected]>
- The kernel is not limited to decode batches: at E = 512 and 1024 it beats topk_reg_kernel from 1 to 8192 tokens on MI455X. - An FP32 bias is read with a 16-byte load, not an 8-byte one. - ds_permute wraps its targets mod 32, which is why the two-slot path clamps ranks past the wave to lane 31; the wrap does not send them there. Comment-only: the preprocessed source is unchanged. Co-authored-by: Cursor <[email protected]>
- topk_reg_mw_kernel: its groups only set the pivot and are not topk_reg_kernel's lanes; a pivot at or below the -inf key means fewer than topk finite group maxima, not fewer than topk finite scores. - Both gate cross-references: a row the Python gate admits and the C++ gate rejects falls through to topk_reg_kernel at E = 512 and 1024 with topk <= 16, else to the LDS kernel, which aborts on an FP32 bias. - test_moeTopkSoftmax.py: the multi-wave kernel at topk 1, and its fallback taking one of 880 tied experts. References padded to 260 experts check E=128 and E=252 (masked last round) against the LDS kernel at either wave size. - test_topk_gating.py: biased_grouped_topk gives the HIP results on the HERD-width rows; Triton and HIP weights agree to 1e-6. - test_moe_topk_gating.py: the biased-sigmoid benchmark times the Triton kernel itself, which biased_grouped_topk now skips for aligned rows. The kernel source change is comment-only: the preprocessed source is unchanged. Co-authored-by: Cursor <[email protected]>
… only The Triton kernel keeps the gfx1250 wave32 tie order, so on wave64 GPUs tied scores could fail the ID check against biased_grouped_topk_hip. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…kernel _gfx1250_reg_mw_fits reads data_ptr(), which Dynamo cannot trace: it added a graph break, and an error under fullgraph=True, for every call it was asked about. Under torch.compile it now returns False before reaching it, so compiled calls take the Triton kernel, as on main. Co-Authored-By: Claude Opus 5.5 <[email protected]>
5ca479f to
fb63a13
Compare
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (3)
- Gate both new wave32 paths to gfx1250, or run them on RDNA.
csrc/kernels/topk_softmax_kernels_group.cu:LAUNCHER_TOPK_REGand thetopk_reg_mw_kernelgate inbiased_grouped_topk()checkget_warp_size_func() == 32, not the arch. Sogrouped_topkandbiased_grouped_topk_hipon gfx1100/gfx1201 now run kernels that were only compiled there, never run. Either add an arch check, or post atest_moeTopkSoftmax.pyrun on an RDNA GPU (theci:windowsR9700 runner is gfx1201). - Take the gate from one source instead of a hand mirror. The
_gfx1250_reg_mw_fitsdocstring inaiter/ops/topk.pysays "keep the two in step" with the C++ gate._GFX1250_REG_MW_EXPERTS/_GFX1250_REG_MW_MAX_TOPKcopymw_waves ∈ {4,6,7,8}/kTopKRegMwMaxTopK, and thetopk <= 17term can never fail because the caller already requirestopk ∈ _GFX1250_SIGMOID_TOPKS. Expose the shape/dtype contract as one memoised C++ query, astopk_sampled_supportsdoes, and keep only the pointer-alignment terms in Python. - Run the new gfx1250 path in CI once.
test_topk_gating.pyisskipif not gfx1250, the MI35X jobs cannot reachtopk_reg_mw_kernel, and the gfx1250 job needs theci:gfx1250-ffm-tritonlabel. Add the label and link the green run.
Non-blocking:
- On the Triton test changes: Triton is still tested through the public entry for unaligned rows and E=900 (
test_exact_sigmoid_topk_matches_torch). Calling the kernel directly in the HERD-width test is fine. No test covers thetorch.compilebranch, though. Under compile, traced calls keep Triton and eager calls go to HIP. The weights then differ by ULPs (the test allows 1e-6 Triton vs HIP), and rows with fewer finite scores than topk fill differently. Please document this in_gfx1250_reg_mw_fitsand add a compiled-call test. op_tests/test_moe_topk_gating.py: import the publicexact_sigmoid_biased_topkfromaiter.ops.triton.moe.moe_routing.topk_gatinginstead of the private_gfx1250_exact_sigmoid_topk. Useget_gfx_runtime() in ("gfx1250", "gfx1250-strict")astopk.pydoes, notstartswith.- Comments: step 4 of the
topk_reg_mw_kernelheader should also mention the!fastrows (pivot at -inf orn_cand < topk). Drop the measured numbers ("~0.16%", "25-45 us", "4096 rows"), or point to the script that produced them. emit_legacy_ordered_topk's two-slot branch (warp_rank_desc_slots) andwave32_rank_desc_dpp2both rank 64 keys on wave32. Consider sharing one of them.
Reviewed at fb63a13. Merges cleanly into current main, including #7922, which changes a different op (topk_gating). Has a one-line import conflict with #7846 in test_moe_topk_gating.py. The Copilot data_ptr and gfx942 benchmark items are fixed; the all-tie fallback cost is a documented tradeoff.
…e gate Both wave32 register paths (topk_reg_kernel at wave32 and topk_reg_mw_kernel) now require gfx1250, checked per device through get_device_gfx, instead of a wave size of 32: RDNA GPUs compile them but have never run them, so they keep main's kernels. The shape and dtype contract of topk_reg_mw_kernel lives in topk_reg_mw_args_ok, which the HIP entry uses and Python reaches through the new topk_reg_mw_supports binding, memoised per device. The Python mirror constants are gone; _gfx1250_reg_mw_fits keeps only the pitch and alignment terms and documents the torch.compile split, which a new test covers. test_moe_topk_gating.py uses the public Triton entry and an exact arch check; comments drop unsourced measurements and name the fallback rows of topk_reg_mw_kernel. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e path topk_reg_mw_kernel now reads its four logits and four bias values per lane through load_quad, a memcpy into the vector: well-defined at any alignment, and gfx1250 (unaligned-access mode) still issues it as one global_load_b64 or _b128. The HIP entry drops its data_ptr() alignment check and keeps only the pitch term. _gfx1250_reg_mw_fits no longer reads data_ptr() and no longer sends traced calls to Triton. topk_reg_mw_supports enters a traced graph as a constant (torch.compiler.assume_constant_result), with E and topk made Python ints first so dynamic shapes trace too; otherwise Dynamo traces into the op, whose fake gives no answer. Compiled and eager calls now take the same kernel. Tests: unaligned logits and bias take the HIP kernel with the bits of an aligned copy and match torch and Triton; the compiled-call test checks the gate traces with fullgraph (static and dynamic) and that compiled and eager calls agree bit for bit; test_moeTopkSoftmax adds three unaligned cases. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Addressed in 6d3e239 and 95ff9c0:
Non-blocking:
Checked on CPU:
On MI455X at 95ff9c0: |
|
MI455X (gfx1250) at b197607, after a clean rebuild of
So the |
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (2)
No bugs found at b197607: kernel numerics, wave64 default path and the Python/C++ gates all check out. Two text fixes are left, and both are needed before merge.
- Fix four comments that give the wrong reason or scope (Nit):
csrc/kernels/topk_softmax_kernels_group.cu:1183-1185: the hi/lo split fma does not give "the same float".tdiffers by 1 ulp for some bf16 inputs, and 0 gives -0 vs +0. Only the sigmoid bits match, for every bf16/fp16 input. Say "the same sigmoid bits", as 1635371 did.aiter/ops/topk.py:142("Every row is then aligned as the first one is") and.cu:2720("The pitch must be whole quads"): since 95ff9c0,load_quadreads at any alignment and the base address is not checked, sostride(0) % 4 == 0gives no alignment. State the real reason: it is the validated range, and it keeps other pitches on Triton, whichtest_exact_sigmoid_topk_matches_torchrelies on (pitch E+17). Keep the term..cu:50-52: onlybiased_grouped_topkrows (one group, BF16 logits, topk <= 17) taketopk_reg_mw_kernel.grouped_topkat E=768/896 goes to LDS on wave32, because EPL 24/28 are not in the W32 list.op_tests/test_moeTopkSoftmax.py:1113: "(E + 4 would take topk_reg_kernel)" is false for E=128 at wave32 (EPL 5 goes to LDS).
- Correct the PR body, and the squash text where it says the same (Nit):
- "checks one-finite, all-NaN and all-zero rows against their exact expected ids and weights" (body lines 11, 55, 71):
test_grouped_topk_stable(:501-537) checks exact weights, but for ids it only checks that they are valid and distinct and what the winner is. Say that. - Drop "The MI455X rerun is pending" (lines 13, 56); your b197607 MI455X log is posted.
- "checks one-finite, all-NaN and all-zero rows against their exact expected ids and weights" (body lines 11, 55, 71):
Also please resolve the open Copilot thread on .cu:2447 (all-tie rows go to the fallback). That tradeoff was accepted earlier and is listed under Known limits; reply saying so before resolving. Branch rules block merge on open threads.
Pre-existing, not required here:
- Every HIP top-k kernel writes both outputs with
topk_ids.stride(0), so directbiased_grouped_topk_hipcalls with unequal row strides misplace the weights, as on main. test_topk_gating.py:14skips ongfx1250-strict.
CI: the only failure, Standard shard 0 tests/test_ar_rmsnorm_routing (should_fly_allreduce_rmsnorm), comes from main; main fixed it in #8313. Merging main clears it.
Reviewed at b197607 (deep; two independent passes, 4+3 hunters incl. ecc:review-pr, 4 verifiers, C2). Already fixed: dead compile machinery removed, public op compiled with fullgraph; dev_max_/dev_min_<uint32_t>, wave_reduce and sigmoid_neg_log2e reused (fallback max probed lane by lane on gfx12 DPP/permlanex16, sigmoid bits checked over all bf16/fp16); -7 refills; moe_op.h text; wave64 skips topk_reg_mw_args_ok (3 wave-size lookups vs 4 on main). The pitch and E=768/896 comments were already wrong at 1635371; I missed them in earlier rounds.
- sigmoid_neg_log2e: the hi/lo split fma gives the same sigmoid bits as the f64 product for every bf16/fp16 input, not the same float (t can differ by 1 ulp, and 0 gives -0 vs +0). - Row pitch of whole quads for topk_reg_mw_kernel: load_quad reads at any alignment, so the term gives no alignment. It is the validated range, and it keeps other pitches on Triton, which test_exact_sigmoid_topk_matches_torch relies on (pitch E + 17). - Wave32 EPL list: only biased_grouped_topk rows with one group, BF16 logits and topk <= 17 at E=768/896 take topk_reg_mw_kernel; grouped_topk at those sizes takes the LDS kernel at wave32. - ref260 test note: E + 4 would take topk_reg_kernel at wave64, but not for E=128 at wave32 (EPL 5 takes LDS). Testing: test_grouped_topk_stable checks one-finite, all-NaN and all-zero rows for exact weights; for ids it checks that they are valid and distinct and, for one-finite rows, the winner. MI455X at b197607: test_moeTopkSoftmax.py passes, test_topk_gating.py 48 passed, and the biased-sigmoid section of test_moe_topk_gating.py passes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pk-mw Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks @valarLip. Fixed in c0c7586; a753954 merges current main (incl. #8313 for
I replied on the Copilot |
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (3)
I found no correctness bugs at a753954. The gfx942/gfx950 routes and their host cost are unchanged from main, and the merge of main touches none of the PR files. What is left: one small host-cost fix on gfx1250, and text fixes. Two of the text fixes correct wording I suggested last round. Sorry for that.
- Check the cheap terms of
_gfx1250_reg_mw_fitsbefore the memoised query (Important; any default-path slowdown counts as Important here).aiter/ops/topk.py:135-147. On gfx1250, 1/1 calls that stay on Triton as on main (E=900, a pitch that is not a multiple of 4, unequal weights/ids row strides) now pay +0.8 to 2.3 us of host time per call. I measured it with concurrent pinned-core pairs and base/base and head/head controls. Fix: evaluategating_output.stride(0) % 4 == 0 and topk_weights.stride(0) == topk_ids.stride(0)before_reg_mw_supports_cached(...). Every route stays the same, and the pitch and stride cases go back to main's cost. - Make the comments match the dispatch code (Nit):
csrc/kernels/topk_softmax_kernels_group.cu:51-53: the gate at:2729-2731istopk_grp == num_expert_group, not "one group". 8/8 and 4/4 calls at E=768 BF16 also taketopk_reg_mw_kernel, through both the HIP op and the Python op. The pitch term was also dropped. Suggested: "Only biased_grouped_topk rows without a group filter (topk_grp == num_expert_group), BF16 logits, a pitch of whole quads and topk <= 17 at E=768 and 896 take topk_reg_mw_kernel; the rest, grouped_topk among them, take LDS at wave32.".cu:2722-2724: this C++ entry never reaches Triton. A pitch that fails the check falls through totopk_reg_kernel(E=512/1024, topk 4..16) or LDS. Suggested: "The pitch must be whole quads, the validated range; other pitches fall through to topk_reg_kernel or LDS below. biased_grouped_topk applies the same term, so rows the Triton kernel takes stay on it (test_exact_sigmoid_topk_matches_torch relies on that, pitch E + 17).".cu:1116-1117:topk_reg_kernelalso runs at wave32 now, so "the wave64 launcher gate enforces topk <= 32" should say "topk <= wave size / 2 (32 at wave64, 16 at wave32)". The fallback-trigger line at.cu:1086lists only one of its three triggers.op_tests/test_moeTopkSoftmax.py:1038,:1108and:1120say "wave32" (or "multi-wave kernel"), but these hold only on gfx1250. On RDNA wave32 these BF16-logit/FP32-bias cases reach the mixed-biasAITER_CHECKin LDS (.cu:2384). Say "gfx1250".
- Correct the PR body and the squash text (Nit):
- "Outputs are refilled with -7 before each public call":
test_exact_sigmoid_topk_matches_torchwrites intotorch.empty_stridedoutputs (test_topk_gating.py:120-141). Name the HERD-width, unaligned-base and compiled-call tests instead. - "Wave64 instantiations compile to empty kernels at wave32": only EPL 2, 3 and 14 do (
.cu:861), as your Changes bullet says. - "Python takes this path only with one group" is true only for
_gfx1250_reg_mw_fits. Calls withnum_expert_group == topk_group > 1go to the HIP op and now take the register kernels on gfx1250, with the same result because every group is selected. Say so. - Squash text: c0c7586's "0 gives -0 vs +0" is wrong (my wording). ±0 give the same bits on both paths; only
tdiffers, by 1 ulp, for 114 tiny bf16 inputs. Also, b197607's "only E=900 and other pitches take the Triton kernel" misses unequal output row strides (topk.py:146). Use the body's Changes section as the squash message.
- "Outputs are refilled with -7 before each public call":
Optional: warp_rank_desc_slots (.cu:364) and wave32_rank_desc_dpp (.cu:1262) give the same live ranks. Either use the DPP one in emit_legacy_ordered_topk, or add one line on why the readlane form stays.
CI: 46 pass, 0 fail. All review threads are resolved.
Reviewed at a753954 (deep; two independent passes, A: 2 hunters + 2 verifiers + C2, B: 4 hunters + ecc reviewers + 8 verifiers + C2). Already fixed: "same sigmoid bits" (.cu:1186), the ref260 E+4 note, "exact expected ids" and "rerun pending" in the body, the Copilot .cu thread. Missed earlier: .cu:1086/1116, the test "wave32" notes and the gate cost come from older commits; I did not raise them before.
…ents
_gfx1250_reg_mw_fits checks the row pitch and the equal output row
strides before _reg_mw_supports_cached, so calls with a pitch that is
not a multiple of 4 or unequal output strides skip the query. Pure
boolean terms, so the route is the same for every input.
Comments now match the dispatch code: the topk_reg_mw_kernel gate is
topk_grp == num_expert_group plus the pitch term; a failing pitch in the
C++ entry falls through to topk_reg_kernel or LDS, never Triton; the
topk_reg_kernel launcher bounds topk by wave size / 2; its fallback
note lists all three triggers; the test notes that hold only on gfx1250
say so; and emit_legacy_ordered_topk says why it keeps the readlane
rank.
Squash text (the PR description's Changes section):
- `topk_reg_kernel` runs at wave32 for no group filter, E % 4 == 0,
ceil(E / 32) in {4, 6, 8, 16, 32} and 4 <= topk <= 16, with two
candidate slots per lane. At wave32 the instantiations only wave64
launches (EPL 2, 3 and 14) compile to empty kernels.
- `topk_reg_mw_kernel` (wave32): E = 128 x {4, 6, 7, 8}, topk <= 17,
BF16 logits with a row pitch that is a multiple of 4, BF16 or FP32
bias, at any pointer alignment (gfx1250 vector loads take unaligned
addresses).
- Both wave32 paths are gated to gfx1250 and gfx1250-strict by arch
(`topk_reg_w32_arch_ok`, checked after the wave size, so wave64 never
queries it); RDNA GPUs keep main's kernels.
- `biased_grouped_topk` on gfx1250 sends the one-group rows that fit the
new kernel to `biased_grouped_topk_hip`. The shape/dtype test is the
kernel's own, exposed as the memoised `topk_reg_mw_supports` binding;
Python adds the row-pitch term and equal weights/ids row strides (the
HIP op writes both with the row stride of `topk_ids`), checks those
two before the memoised query, and reads no `data_ptr()`.
`biased_grouped_topk` is an opaque custom op, so `torch.compile` never
traces this gate: a compiled call runs it on the real tensors and
picks the same kernel as an eager one. E=900, pitches that are not a
multiple of 4 and unequal weights/ids row strides keep the Triton
kernel. Calls with `num_expert_group == topk_group > 1` go to the HIP
op as on main and on gfx1250 now also reach the register kernels,
whose gate is `topk_grp == num_expert_group`; with every group
selected, the group filter drops no expert.
- Tests: `test_moeTopkSoftmax.py` compares the new paths' random and
tied rows bit for bit with the LDS kernel, including logits and bias
one element past an aligned base, and checks one-finite, all-NaN and
all-zero rows for their exact expected weights and for valid, distinct
ids (plus the winning id of one-finite rows). The HERD-width test in
`test_topk_gating.py` and the biased-sigmoid benchmark in
`test_moe_topk_gating.py` call the Triton kernel directly, since
`biased_grouped_topk` now sends their rows to the HIP kernel; the test
also checks that it does. New tests check that unaligned logits and
bias take the HIP kernel with the bits of an aligned copy, and that a
compiled call of `biased_grouped_topk` returns the eager call's bits.
The benchmark runs only on gfx1250, since the Triton kernel keeps the
wave32 tie order.
Corrections to earlier commit messages of this branch, which the squash
keeps:
- c0c7586: +0 and -0 do not differ: both paths give t = -0 for +0
and t = +0 for -0. t differs only for 114 bf16 inputs with
|x| <= 4.1e-36, by 1 ulp, and for no fp16 input (IEEE emulation on
CPU).
- b197607: E=900, pitches that are not a multiple of 4 and unequal
weights/ids row strides take the Triton kernel, not only E=900 and
other pitches.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@valarLip thanks. Addressed at 993d5f8: 1. Cheap terms first (
The trade-off is in the last row. Contiguous E=900 passes both stride terms, so it now reads them before the query. On this harness that costs 0.42 us more than at a753954. I see no way to skip the query for it without copying the C++ shape rule into Python. Putting only the pitch term first (pitch, query, strides) would cost contiguous E=900 +170 ns instead of +417 ns, but would leave the unequal-strides case at a753954's cost. I kept your order. Tell me if you prefer the other one. 2. Comments
3. PR body and squash text
|
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (5)
No correctness bugs at 993d5f8: routes match a753954 on every input, and gfx942/gfx950 cost and device code equal main. Item 1 is a slowdown that my r53 ask caused. Sorry for that.
- Fold the multi-wave test into
_can_use_gfx1250_exact_sigmoid_topkso no stride is read twice (Important; default-path cost).aiter/ops/topk.py:119-149,:494-507. On gfx1250, contiguous E=900 calls keep main's Triton route but now cost about +1.7 µs per call over main (+0.8 µs over a753954). Unequal output strides cost +1.5 µs. Cause:_gfx1250_reg_mw_fitsre-readsstride(0),.device, shapes and dtypes that_can_usehas just read. Three independent paired-core runs agree; the controls are within ±0.2 µs. Fix: keep the strides,deviceand bias dtype that_can_usealready reads in locals. After its gfx1250 check, end withreturn not (pitch % 4 == 0 and w_pitch == id_pitch and _reg_mw_supports_cached(experts, topk, torch.bfloat16, bias_dtype, device.index)), and delete_gfx1250_reg_mw_fits. The query stays the only shape source. This leaves E=900 at about +0.25 µs (the lru lookup) and the pitch and stride cases at +0.1 µs. gfx950 is unchanged. Routes are identical over 3M inputs. Update the tests that call_gfx1250_reg_mw_fitsor assert_can_use(test_topk_gating.py:133,140,219,237,289,290,323). - Put the arch query after the cheap terms in the C++ gates (Important).
csrc/kernels/topk_softmax_kernels_group.cu:2438-2443:(reg_lanes == 64 || topk_reg_w32_arch_ok())runs beforeE % 4, the EPL bound and the topk range. On RDNA, eachgrouped_topk/biased_grouped_topk_hipcall without a group filter now pays aget_device_gfx()(hipGetDevice + mutex + map) that main skipped, and the answer is always false. gfx1250 calls that stay on LDS pay it too. Move it to the last term. At:2735-2737, teststride_gating % 4 == 0beforetopk_reg_mw_args_ok. Every route stays the same, and wave64 is unaffected. - Fix the comments (Nit):
.cu:444-445: this branch iskSlots == 2and builds only at wave32. Suggested: "Not wave32_rank_desc_dpp: that ranks all 32 * kSlots slots, while this stops at n_cand, so the common n_cand <= WARP_SIZE row takes one warp_rank_desc.".cu:2726-2732and:51-55(my r53 wording): a row that misses the gate with BF16 logits and an FP32 bias does not reach LDS. At E=768/896, or E=512/1024 with topk < 4 or 17, it fails the mixed-dtypeAITER_CHECK(:2389), as on main.:51-55also leaves out the bias-dtype term. Say both.topk_reg_mw_kernel:1453:pivot > kNegInfKey && n_cand >= topknever decides. NaN keys are at least -inf, son_cand >= topkalways holds, and a -inf pivot givesn_cand == E > 64. Drop both terms and the header text:1180-1181.:1089-1092: "fewer than topk candidates" cannot happen intopk_reg_kerneleither (the -inf pivot term there is live).
- Add the missing test cases (Nit). Removing the equal-stride term or the memoised query from the gate fails no test. Neither does deleting EPL 6/16/32 from
AITER_TOPK_REG_LAUNCH_EPLS_W32. Add:- E=512 BF16, pitch 512, weights stride != ids stride: Triton route, correct weights.
- E=900 contiguous through
biased_grouped_topk: Triton route. - wave32
topk_reg_kernelrows at E=192, 512 and 1024 (e.g.grouped_topksoftmax).
- Update the squash text (Nit): the head commit says a failing pitch "falls through to topk_reg_kernel or LDS"; add the FP32-bias abort. Also add the gate and test changes above.
CI: 41 pass, 1 pending (MI35X shard 6), 0 fail. All review threads are resolved.
Reviewed at 993d5f8 (deep; two independent passes. A: 3 hunters + ecc:review-pr + 3 verifiers + C2. B: 3 hunters + 2 verifiers + route/timing run). Already fixed: stride terms first, .cu:51/1089/1116/2722 text, test "gfx1250" notes, body and squash corrections (±0 claim checked exactly). Missed earlier: items 2-4 cover code unchanged since b197607 or older; I did not raise them before.
…eap terms first _can_use_gfx1250_exact_sigmoid_topk now ends with the multi-wave test, so biased_grouped_topk reads each stride, shape, dtype and the device once: it keeps the row pitch, both output row strides, the bias dtype and the device in locals and, after the gfx1250 check, returns False when the pitch is whole quads, the output row strides are equal and the memoised topk_reg_mw_supports accepts the row. _gfx1250_reg_mw_fits is gone. Routes match a753954 and 993d5f8 for every input of a CPU probe (762,048 inputs x 4 mocked queries x 4 archs). In the C++ gates the arch query runs last: LAUNCHER_TOPK_REG tests topk_reg_w32_arch_ok() after E % 4, the EPL bound and the topk range, and the topk_reg_mw_kernel gate tests stride_gating % 4 before topk_reg_mw_args_ok. Same routes; host code only. topk_reg_mw_kernel drops `pivot > kNegInfKey && n_cand >= topk`, which never decides: every key is at least float_order_key(-inf) (NaN is keyed as -inf), the topk-th group maximum is reached by at least topk keys, and a -inf pivot is reached by all E >= 512 keys, which already takes the fallback. Only the eight topk_reg_mw_kernel instances change on gfx1250 (14 fewer instructions each); gfx942 and gfx950 device code is unchanged. Comments: emit_legacy_ordered_topk's two-slot branch builds only at wave32 and says why it is not wave32_rank_desc_dpp; topk_reg_kernel's fallback has two triggers, not three; the EPL list note and the topk_reg_mw_kernel gate note add the bias dtype and the FP32-bias abort. Tests: test_exact_sigmoid_topk_triton_route checks that E=512 with unequal weights/ids row strides and contiguous E=900 stay on the Triton kernel with the reference's ids and weights; it fails if the equal-stride term or the memoised query is dropped from the gate. test_moeTopkSoftmax adds FP16-logit, FP32-bias rows at E=192, 512 and 1024, which only the register path takes, so dropping EPL 6, 16 or 32 from AITER_TOPK_REG_LAUNCH_EPLS_W32 aborts them on gfx1250. The other route assertions use _can_use_gfx1250_exact_sigmoid_topk. Squash text (the PR description's Changes section): - `topk_reg_kernel` runs at wave32 for no group filter, E % 4 == 0, ceil(E / 32) in {4, 6, 8, 16, 32} and 4 <= topk <= 16, with two candidate slots per lane. At wave32 the instantiations only wave64 launches (EPL 2, 3 and 14) compile to empty kernels. - `topk_reg_mw_kernel` (wave32): E = 128 x {4, 6, 7, 8}, topk <= 17, BF16 logits with a row pitch that is a multiple of 4, BF16 or FP32 bias, at any pointer alignment (gfx1250 vector loads take unaligned addresses). A row that misses this gate falls through to `topk_reg_kernel` or LDS, except that BF16 logits with an FP32 bias have no LDS path: at E=768/896, or E=512/1024 with topk < 4 or 17, such a row fails the mixed-dtype `AITER_CHECK`, as on main. - Both wave32 paths are gated to gfx1250 and gfx1250-strict by arch (`topk_reg_w32_arch_ok`), the last term of each gate, so wave64 never queries it and other calls query it only after the cheaper terms pass; RDNA GPUs keep main's kernels. - `biased_grouped_topk` on gfx1250 sends the one-group rows that fit the new kernel to `biased_grouped_topk_hip`. `_can_use_gfx1250_exact_sigmoid_topk` reads each tensor property once and ends with the kernel's own shape/dtype test, exposed as the memoised `topk_reg_mw_supports` binding, after the row-pitch term and equal weights/ids row strides (the HIP op writes both with the row stride of `topk_ids`); it reads no `data_ptr()`. `biased_grouped_topk` is an opaque custom op, so `torch.compile` never traces this gate: a compiled call runs it on the real tensors and picks the same kernel as an eager one. E=900, pitches that are not a multiple of 4 and unequal weights/ids row strides keep the Triton kernel. Calls with `num_expert_group == topk_group > 1` go to the HIP op as on main and on gfx1250 now also reach the register kernels, whose gate is `topk_grp == num_expert_group`; with every group selected, the group filter drops no expert. - Tests: `test_moeTopkSoftmax.py` compares the new paths' random and tied rows bit for bit with the LDS kernel, including logits and bias one element past an aligned base and FP16-logit, FP32-bias rows at the wave32 EPLs 6, 16 and 32, and checks one-finite, all-NaN and all-zero rows for their exact expected weights and for valid, distinct ids (plus the winning id of one-finite rows). The HERD-width test in `test_topk_gating.py` and the biased-sigmoid benchmark in `test_moe_topk_gating.py` call the Triton kernel directly, since `biased_grouped_topk` now sends their rows to the HIP kernel; the test also checks that it does. New tests check that unaligned logits and bias take the HIP kernel with the bits of an aligned copy, that a compiled call of `biased_grouped_topk` returns the eager call's bits, and that E=512 with unequal output row strides and contiguous E=900 stay on the Triton kernel with correct results. The benchmark runs only on gfx1250, since the Triton kernel keeps the wave32 tie order. Corrections to earlier commit messages of this branch, which the squash keeps: - c0c7586: +0 and -0 do not differ: both paths give t = -0 for +0 and t = +0 for -0. t differs only for 114 bf16 inputs with |x| <= 4.1e-36, by 1 ulp, and for no fp16 input (IEEE emulation on CPU). - b197607: E=900, pitches that are not a multiple of 4 and unequal weights/ids row strides take the Triton kernel, not only E=900 and other pitches. - 993d5f8: a row that fails the pitch term falls through to topk_reg_kernel or LDS, except that BF16 logits with an FP32 bias have no LDS path and fail the mixed-dtype AITER_CHECK (E=768/896, or E=512/1024 with topk < 4 or 17), as on main. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the review. All five items are addressed in e7019b4 (one commit on top of 993d5f8). 1. Multi-wave test folded into
2. Arch query last in the C++ gates (
3. Comments
4. Missing tests
5. Squash text: in the e7019b4 message, the Changes section now covers:
A correction to 993d5f8's message ("falls through to topk_reg_kernel or LDS") is added to the list the squash keeps. The PR description's Changes section is updated to match. Validation: black and ruff are clean, the JIT build for gfx1250 passes, and the asm diff is as above.
|
|
@valarLip could you take another look when you have a moment? All five items from your review at 993d5f8 are addressed in e7019b4; the item-by-item reply and the MI455X results are in my comment above. CI is green at e7019b4 (45 passed, 0 failed), every review thread is resolved, and the branch has no conflicts with main. The PR is only waiting for your re-review. |
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (1)
All five items from my 993d5f8 review are fixed at e7019b4, and I found no bugs in the delta. The gate fold keeps every route unchanged: the old _mw_fits passed gating_output.dtype, which input_ok already pins to BF16. Removing fast from topk_reg_mw_kernel also changes nothing: every row has n_cand >= topk, and a -inf pivot gives n_cand = E > 64, so such a row already took the fallback. The new route test does reach biased_grouped_topk_hip through the custom-op wrapper, and the FP16/FP32-bias rows fail when EPL 6/16/32 are dropped. One text fix is left. The wrong wording came from me.
- Scope the FP32-bias abort sentence to rows that fail only the pitch term (Nit; my r55 wording was incomplete).
- Where:
csrc/kernels/topk_softmax_kernels_group.cu:2733-2736, the matching bullet in the PR description / squash Changes list, and the same sentence in the PR body. - Problem: the comment reads "A row that misses this gate with BF16 logits and an FP32 bias never reaches LDS: at E=768/896, or E=512/1024 with topk < 4 or 17, it fails …". Read as a full list, it leaves out two kinds of rows that also hit the mixed-dtype
AITER_CHECK:- group-filtered rows (
topk_grp != num_expert_group) at E=512/1024, at any topk; - E=512/1024 rows with topk > 17.
- group-filtered rows (
- The list is exact only for rows that fail the pitch term alone, which is how your 993d5f8 correction note already scopes it.
- Suggested wording: "A BF16-logit, FP32-bias row that fails only the pitch term goes to topk_reg_kernel at E=512/1024 with 4 <= topk <= 16; otherwise (E=768/896, or topk < 4 or 17) it fails the mixed-dtype AITER_CHECK in LAUNCH_KERNEL, as on main."
:51-56is correct as written; leave it.
- Where:
CI: all required checks pass at e7019b4. All 3 review threads are resolved. The branch merges cleanly with current main, and the three main commits since the branch point touch these files without interacting with this PR.
Reviewed at e7019b4 (deep, delta re-review; two independent passes: A orchestrator delta + route/kernel trace, B independent hunter). Already fixed: gate folded into _can_use_gfx1250_exact_sigmoid_topk with locals, _gfx1250_reg_mw_fits deleted, arch query last in LAUNCHER_TOPK_REG, pitch before topk_reg_mw_args_ok, .cu:446/1092/1184/1348 text, dead fast term dropped, Triton-route test (E=512 unequal strides, E=900), FP16/FP32-bias rows at E=192/512/1024, squash corrections.
…the pitch term A BF16-logit, FP32-bias row that fails only the pitch term reaches topk_reg_kernel at E=512/1024 with 4 <= topk <= 16; the mixed-dtype AITER_CHECK is hit otherwise. Comment only. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Fixed in 6a8a527 (comment only). The sentence at Nothing was rebuilt for this commit: |
…pk-mw Co-Authored-By: Claude Fable 5.2 <[email protected]>
…pk-mw Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
@valarLip could you take another look? Your review of 2026-11-24 found no bugs at e7019b4 and left one text fix.
|
…pk-mw Conflicts with #7338 (readlane/DPP top-k) in two files: - csrc/kernels/topk_softmax_kernels_group.cu: both sides' helpers stay (warp_rank_desc_slots; warp_rank_desc_upto, lane_serial_sum). emit_legacy_ordered_topk is main's template <bool UNROLLED> with this branch's slot split: the one-slot arm (wave64) takes main's unrolled rank tiers, the two-slot arm (wave32) is unchanged, and the renorm tail is main's. main's ballot compaction and readlane pivot merge without conflict and now also run at wave32 for EPL 4, 6 and 8. - op_tests/test_moeTopkSoftmax.py: thirty_two_way_tie keeps pattern id 7, forty_way_tie takes 8 (the id only seeds the rows). main's padding loop gives 260 for the two ref260 cases, so ref_experts goes and the cases move into stable_cases. Device code of module_moe_asm: gfx942 and gfx950 match main for every kernel main has; on gfx1250 only topk_reg_kernel EPL 4, 6 and 8 change against aa3a0de. Not run on a GPU. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Merged main 4960107 (5344e7f) to resolve the conflict with #7338, which rewrote parts of
Checked on CPU: On MI455X (one idle GPU, module rebuilt from this tree): |
valarLip
left a comment
There was a problem hiding this comment.
✅ LGTM
Thanks. The one item from my e7019b4 review is fixed, and the merge with main's #7338 is resolved correctly. I found no bugs in the delta.
Prior asks
- The FP32-bias abort sentence is now scoped to rows that fail only the pitch term. Fixed in the suggested wording at
csrc/kernels/topk_softmax_kernels_group.cu:2805-2808and in the Changes bullet of the description.:51-56is untouched. All earlier asks were confirmed fixed at e7019b4, and the delta does not touch them.
Merge with #7338
emit_legacy_ordered_topk(.cu:430-521):- At wave64,
kTopKRegCandCap / WARP_SIZE == 1, so only thekSlots == 1arm builds. That arm is main's code line for line: the unrolledwarp_rank_desc_upto<8/16>tiers, the barrier and the store.live/ci/keyare now declared inside the arm. cand_idxsits at the same offset as on main (kTopKRegCandCap= 64 = main'sWARP_SIZE).- So gfx942/gfx950 behave exactly as on main.
- At wave64,
- At wave32,
topk_reg_kernelnow uses main's ballot compaction and readlane pivot for EPL 4/6/8 as well. That is correct there:- The emit ranks by a unique (score, tie rank) key, so slot order does not matter.
- Positions are written only after
n_cand <= 64. - The pivot lane
topk - 1is at most 15 (topk <= reg_lanes / 2). - The
-inftails of a masked last round (E=252) never passv >= pivot. lane_serial_sum<8>adds +0.0f for lanes >= topk, so the renorm bits match the serial loop.
- Test:
- Main's padding loop gives 260 for both former
ref_experts=260cases. Every padded reference (260, 516, 772, 900, 1028) misses the wave64 and wave32 EPL lists and the multi-wave sizes, so it takes LDS at both wave sizes, as the new comment says. - Over E = 4..2048 (step 4), only E=764 would pad to a multi-wave width (768), and no case uses it.
forty_way_tiemoving to id 8 only changes the seed.
- Main's padding loop gives 260 for both former
Root cause vs patch
Root problem: topk_reg_kernel assumed wave64, so gfx1250 routing fell back to LDS or Triton. The PR makes the register kernel wave-size generic (two candidate slots per lane at wave32). It adds one multi-wave kernel whose shape contract has a single source, topk_reg_mw_args_ok, which Python queries through topk_reg_mw_supports. The gfx1250 gate is the last term and limits the new paths to the validated arch; the wave64 kernels are untouched. Verdict: root fix.
Merge note: squash with the description's Changes section, not the commit list. Some commit messages are stale at head, e.g. "Not run on a GPU" in 5344e7f: MI455X was run afterwards (54 stable rows err 0, test_topk_gating.py 50 passed).
CI: 44 pass, 25 skipped, 0 fail at 5344e7f. All 3 review threads are resolved. The PR merges cleanly into current main.
Reviewed at 5344e7f (re-review after e7019b4, passes A+B, both LGTM independently; true delta = old replayed onto merge base 4960107 -> head: 6a8a527 comment fix + merge of #7338). Already fixed: all prior asks incl. the FP32-bias abort scope.

Summary
topk_reg_kernelran only at wave64, so on gfx1250 most top-k calls without a group filter took the LDS kernel, andbiased_grouped_topkused a Triton kernel at E = 512, 768, 896 and 1024. This PR runstopk_reg_kernelat wave32 and addstopk_reg_mw_kernel, a biased sigmoid top-k with one workgroup per row. The Kimi-K3 router (E=896, topk 16) on MI455X goes from 7.23 to 1.46 us per call at 1 token and from 54.9 to 10.3 us at 8192 tokens. gfx942 and gfx950 compile to the same instructions as main.Changes
topk_reg_kernelruns at wave32 for no group filter, E % 4 == 0, ceil(E / 32) in {4, 6, 8, 16, 32} and 4 <= topk <= 16, with two candidate slots per lane. At wave32 the instantiations only wave64 launches (EPL 2, 3 and 14) compile to empty kernels.topk_reg_mw_kernel(wave32): E = 128 x {4, 6, 7, 8}, topk <= 17, BF16 logits with a row pitch that is a multiple of 4, BF16 or FP32 bias, at any pointer alignment (gfx1250 vector loads take unaligned addresses). A row that misses this gate falls through totopk_reg_kernelor LDS, except that BF16 logits with an FP32 bias have no LDS path: such a row that fails only the pitch term goes totopk_reg_kernelat E=512/1024 with 4 <= topk <= 16, and otherwise (E=768/896, or topk < 4 or 17) fails the mixed-dtypeAITER_CHECKinLAUNCH_KERNEL, as on main.topk_reg_w32_arch_ok), the last term of each gate, so wave64 never queries it and other calls query it only after the cheaper terms pass; RDNA GPUs keep main's kernels.biased_grouped_topkon gfx1250 sends the one-group rows that fit the new kernel tobiased_grouped_topk_hip._can_use_gfx1250_exact_sigmoid_topkreads each tensor property once and ends with the kernel's own shape/dtype test, exposed as the memoisedtopk_reg_mw_supportsbinding, after the row-pitch term and equal weights/ids row strides (the HIP op writes both with the row stride oftopk_ids); it reads nodata_ptr().biased_grouped_topkis an opaque custom op, sotorch.compilenever traces this gate: a compiled call runs it on the real tensors and picks the same kernel as an eager one. E=900, pitches that are not a multiple of 4 and unequal weights/ids row strides keep the Triton kernel. Calls withnum_expert_group == topk_group > 1go to the HIP op as on main and on gfx1250 now also reach the register kernels, whose gate istopk_grp == num_expert_group; with every group selected, the group filter drops no expert.test_moeTopkSoftmax.pycompares the new paths' random and tied rows bit for bit with the LDS kernel, including logits and bias one element past an aligned base and FP16-logit, FP32-bias rows at the wave32 EPLs 6, 16 and 32, and checks one-finite, all-NaN and all-zero rows for their exact expected weights and for valid, distinct ids (plus the winning id of one-finite rows). The HERD-width test intest_topk_gating.pyand the biased-sigmoid benchmark intest_moe_topk_gating.pycall the Triton kernel directly, sincebiased_grouped_topknow sends their rows to the HIP kernel; the test also checks that it does. New tests check that unaligned logits and bias take the HIP kernel with the bits of an aligned copy, that a compiled call ofbiased_grouped_topkreturns the eager call's bits, and that E=512 with unequal output row strides and contiguous E=900 stay on the Triton kernel with correct results. The benchmark runs only on gfx1250, since the Triton kernel keeps the wave32 tie order.Tested on MI455X at 6d3e239 (before the alignment term was dropped):
test_moeTopkSoftmax.py,test_topk_gating.pyand the biased-sigmoid section oftest_moe_topk_gating.pypass. At 95ff9c0 on MI455X:test_moeTopkSoftmax.pypasses (incl. 3 unaligned-input cases bit for bit against the LDS kernel),test_topk_gating.py48 passed (unaligned-base and compiled-call tests included), and the biased-sigmoid benchmark passes for E 512-1024, topk 4/8/16, 1/64/8192 tokens. At b197607 (review cleanup: shared helpers, dead compile code removed): gfx942 and gfx950 device code is identical to the previous head; on gfx1250 only the two wave reductions intopk_reg_mw_kernel's fallback change (same results, 8 more VALU ops per fallback pick). On MI455X after a clean rebuild ofmodule_moe_asm:test_moeTopkSoftmax.pypasses (425 checks),test_topk_gating.py48 passed, and the biased-sigmoid section oftest_moe_topk_gating.pypasses (log posted in the PR conversation). Later commits change comments and merge main. At e7019b4 the Python gate reads each tensor property once (_gfx1250_reg_mw_fitsfolded into_can_use_gfx1250_exact_sigmoid_topk), the C++ gates test the arch query last, andtopk_reg_mw_kerneldrops a pivot/count test that never decides (only its eight instances change on gfx1250; gfx942 and gfx950 device code is unchanged). A CPU probe of the dispatch (762,048 inputs x 4 mocked C++ queries x gfx1250, gfx1250-strict, gfx950 and gfx1201) gives the same route as a753954 and 993d5f8 for every input; the host cost of the gate, measured on CPU with the kernels stubbed, is +0.15 us over main for contiguous E=900 and +0.03 to +0.04 us for the pitch and stride cases (993d5f8: +0.82 and +0.18 to +0.44 us). At e7019b4 on MI455X after a cleanmodule_moe_asmrebuild:test_moeTopkSoftmax.py(421 checks),test_topk_gating.py(50 passed, new route test included) and the biased-sigmoid section pass.Known limits:
topk_reg_kernel's fallback. With all-zero logits a launch is 5 to 22 us slower than main's LDS kernel (E = 128 to 1024); the multi-wave kernel stays faster than main on such rows.Performance
MI455X (gfx1250), BF16, renormalized; time per call in a CUDA graph of 200 calls, median of 7 replays.
grouped_topksoftmax, E=512, topk 8, 1 tokenbiased_grouped_topk_hip, E=192, topk 8, 8192 tokensUnaligned logits/bias (offset view, pitch % 4 == 0), MI455X, one HIP graph of 200 calls, median of 7 replays, 3 interleaved rounds, 48 shapes (E 512/768/896/1024, topk 8/16, 1/64/8192 tokens, BF16/FP32 bias):
E=896, topk 16, 8192 tokens: HIP unaligned 10.9 us vs Triton 51.1 us. All HIP variants are bitwise equal to each other.
Across 60 register-kernel shapes (E = 128 to 1024, 1 to 8192 tokens) the change is -1% to -60% with identical outputs. Compiling
topk_softmax_kernels_group.cufor gfx1250 takes 117 s instead of 162 s on main.PR Self-Review
Reviewed revision
5344e7f
Behavior and intent
topk_reg_kernelnow also runs at wave32 (two candidate slots per lane), so on gfx1250 most top-k calls without a group filter no longer fall back to the LDS kernel.topk_reg_mw_kernel(wave32): biased sigmoid top-k with one workgroup per row for E = 512/768/896/1024, topk <= 17, BF16 logits, BF16 or FP32 bias.biased_grouped_topkon gfx1250 sends rows that fit the new kernel tobiased_grouped_topk_hipinstead of the Triton kernel.Validation and unverified scope
op_tests/test_moeTopkSoftmax.py,op_tests/triton_tests/moe/moe_routing/test_topk_gating.pyand the biased-sigmoid section ofop_tests/test_moe_topk_gating.pypass; random and tied rows of the new paths are compared bit for bit with the LDS kernel, and degenerate rows (one finite, all NaN, all zero) for their exact expected weights and valid, distinct ids (plus the one-finite winner).module_moe_asmrebuild (all pass; log posted in the PR conversation). Commits after b197607 change comments, merge main, fold the multi-wave test into_can_use_gfx1250_exact_sigmoid_topk, reorder pure boolean gate terms (same route for every input in a CPU probe against a753954 and 993d5f8), and drop a never-deciding test intopk_reg_mw_kernel(gfx1250 asm of its eight instances changes; gfx942/gfx950 asm unchanged). At e7019b4 on MI455X after a clean rebuild the three tests pass, and each of the three mutations (equal-stride term, memoised query, EPL 6/16/32) fails its test.csrc/kernels/topk_softmax_kernels_group.cuon top of e7019b4 (git diff e7019b49 6a8a5272is that comment only); nothing was rebuilt or re-run for it.csrc/kernels/topk_softmax_kernels_group.cuandop_tests/test_moeTopkSoftmax.py.emit_legacy_ordered_topkis main'stemplate <bool UNROLLED>with this PR's slot split: the one-slot arm (wave64) takes main's unrolled rank tiers, the two-slot arm (wave32) is unchanged, the renorm tail is main's. In the test, main's padding loop replacesref_experts(it gives the same 260 for both cases) andforty_way_tietakes seed id 8 next to main'sthirty_two_way_tie(7), so its six rows draw another 40 hot experts than the ones run on MI455X. CPU only:module_moe_asmbuilds for gfx942, gfx950 and gfx1250; device asm per kernel of its five sources: gfx942 and gfx950 are identical to main 4960107 for all 1440 kernels main has (the 8topk_reg_mw_kernelinstances are the only additions); on gfx1250, against aa3a0de, 1248 of 1448 kernels are identical, the 180topk_reg_kernelinstances at EPL 4, 6 and 8 take main's ballot compaction, readlane pivot and unrolled renorm sum (5 to 28 fewer instructions and 4 to 9 more VGPRs each; rank code unchanged), and 20 EPL-32 softmax instances keep the same instructions with two blocks placed differently. The stable test's own logic passes on CPU with the two HIP ops modelled in torch (54 cases; all 41 padded references take the LDS kernel at both wave sizes); black and ruff are clean. MI455X, one idle GPU, imagerocm/fw-bringup:gfx1250-minimax-m3-20261112,module_moe_asmrebuilt from this tree:python3 op_tests/test_moeTopkSoftmax.pyexits 0 (54 stable rows, err 0);python3 -m pytest -q op_tests/triton_tests/moe/moe_routing/test_topk_gating.py: 50 passed;python3 op_tests/test_moe_topk_gating.py --section biased-sigmoid --num-experts 512,768,896,900,1024 --topk 4,8,16 -d bf16 --num-tokens 1,64,8192exits 0. Timing A/B oftopk_reg_kernelat E = 128, 192 and 256 (54 shapes, aa3a0de and this head alternating, two rounds): ids and weight bits equal in every shape; this head / aa3a0de median 1.017 and 0.972 in the two rounds (range 0.93 to 1.03), against 1.015 (up to 1.06) between the two aa3a0de runs, so no difference beyond run-to-run noise. Unverified: the absolute E = 128 to 256 register-kernel timings of this description are aa3a0de's and were not re-measured.test_kda_gating.pyimport error that failed Triton shard 5 here, [Triton/Gluon] Fix the fast_launch import in kda_gating #8713; five standard shards of the a1277ed run stopped in their test step after 15 minutes with no log kept): no conflicts, and main changed none of this PR's files in between. Nothing was rebuilt or re-run on a GPU for it.op_tests/test_gemm_a4w4.pyin CI): no conflicts. Since the previous merge, main changed neither the kernel source norcsrc/include/moe_op.h; inaiter/ops/topk.pyit changed only thetop_k_per_row_decodedispatch ([FlyDSL] [JIT] Adaptive decode Top-K kernel, dispatched by one measured gate #5677), not the gate this PR edits. black and ruff are clean; nothing was rebuilt or re-run on a GPU for the merge.PR-specific question
Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?
topk_reg_kernelat wave32: no group filter, E % 4 == 0, ceil(E / 32) in {4, 6, 8, 16, 32}, 4 <= topk <= 16. At wave32, EPL 2, 3 and 14 (launched only at wave64) compile to empty kernels.topk_reg_mw_kernel: wave32, E in {512, 768, 896, 1024}, topk <= 17, BF16 logits, BF16 or FP32 bias._can_use_gfx1250_exact_sigmoid_topk, after its gfx1250 runtime check): HIP when the row stride is a multiple of 4, the weights/ids row strides are equal andtopk_reg_mw_supports(memoised per device, checked last) accepts E, topk and the dtypes; every stride, shape, dtype and the device is read once. No pointer-alignment term: the kernel's loads take any alignment. E=900, other pitches and unequal output row strides keep the Triton kernel.biased_grouped_topkis an opaque custom op, so compiled and eager calls run this gate on the same tensors and take the same kernel.topk_reg_mw_args_okin C++, used by both the HIP entry andtopk_reg_mw_supports. Python adds the pitch, which the HIP entry checks too, and equal weights/ids row strides, since the HIP op writes both with the row stride oftopk_ids. The HIP entry also requirestopk_grp == num_expert_group; the Python gate is consulted only for one-group calls, where it holds. HIP op calls withnum_expert_group == topk_group > 1also reach the register kernels on gfx1250; with every group selected, the group filter drops no expert.topk_reg_w32_arch_ok, per device, the last term of each gate); RDNA wave32 GPUs take main's kernels, and wave64 calls never query the arch. A BF16-logit row with an FP32 bias that misses the register gates aborts on the mixed-dtype check, as on main.Changed op tests
op_tests/test_moeTopkSoftmax.pytopk_reg_kernel(40-way ties, two slots per lane; FP16 logits with FP32 bias at EPL 6, 16 and 32, which only the register path takes) andtopk_reg_mw_kernel(E 512-1024, topk 1-17, Kimi-K3 FP32 bias, strided and unaligned logits and bias, tied rows) bit for bit against the LDS kernel; one-finite, all-NaN and all-zero rows against their exact expected weights, with ids checked valid and distinct (and the winner of one-finite rows).op_tests/test_moe_topk_gating.pyexact_sigmoid_biased_topkdirectly and is skipped off gfx1250.biased_grouped_topkwould route these rows to HIP, so the benchmark would compare HIP with HIP.op_tests/triton_tests/moe/moe_routing/test_topk_gating.pybiased_grouped_topk_hip(now including FP32 bias); thatbiased_grouped_topkroutes rows with a pitch of whole quads to the HIP kernel, unaligned bases included (same bits as an aligned copy, same ids as torch and Triton), while other pitches stay on Triton; that atorch.compiled call ofbiased_grouped_topk(fullgraph=True, static and dynamic shapes) returns the eager call's bits, and that E=512 with unequal weights/ids row strides and contiguous E=900 stay on the Triton kernel (a stub in place of the HIP op fails the test) with the reference's results. The HERD-width, unaligned-base and compiled-call tests start each public call from outputs filled with -7.