Repository navigation
[HIP] topk_gating: single-wave register kernel for wave32 (gfx1250) - #7922
Conversation
On wave32, route topk <= 8 to a new kernel, topk_gating_kernel_opt_vwave: one wave per token, no LDS, no barrier. Lane p holds WPT contiguous lists of EPT experts (vector loads), sorts each with sort_network_desc, then picks the top-k with one DPP max + ballot per pick, unrolled to 8. - E=64/128/256: WPT=1, the reg kernel's layout and results, at every T. - E=384: WPT=2 up to T=1024 (multiwave WPT=4 before). - topk > 8, softmax and wave64 keep their kernels. Ties: the winner is still the lowest lane (as since ROCm#4965), but lanes now map to e % 64 for E=384 (was e % 128) and e % 32 for E=256 at T <= 256 (was e % 256), so the expert picked among exactly equal scores can change there. E=256 no longer changes tie order with the token count. sort_network_desc and compute_score gain an opt-in select form (same result), used by the new kernel and the reg kernel only; every other kernel's ISA is unchanged on gfx950 and gfx1250. Bit checks (12840 cases: E=64/128/256/384/512, topk 1-8, NaN/inf, ties, bias, pad rows, shared expert, strided/misaligned, fp32 logits): - gfx1250: identical to the original kernels with the dispatch moved to the new tie order; identical to HEAD except the tie cases above. - gfx950: identical to HEAD. op_tests/test_moe_topk_gating.py passes on gfx1250 and gfx950. gfx1250, CUDA graph, us, topk=8 (before -> after): E=64 T=1 2.02->1.47 T=256 2.50->2.00 T=16384 6.52->4.86 E=128 T=1 2.69->1.53 T=256 3.15->2.08 T=16384 7.93->5.56 E=256 T=1 3.68->1.66 T=256 4.23->2.22 T=16384 11.28->7.17 E=384 T=1 4.16->2.01 T=256 4.66->2.56 T=1024 5.09->3.02 gfx950: neutral to 5% faster (reg kernel E=128/256/384). gfx1201 (wave32) is untested.
🏷️ 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 alignment-dependent E=384/WPT=2 scalar-load fallback lacks regression coverage for offset logits, offset bias, and odd row strides.
1 open issue
What changed in this PR
This PR optimizes HIP topk_gating for wave32 GPUs with a single-wave, register-only kernel for top-k values up to 8, reducing selection overhead in MoE routing.
Changes:
- Adds the new kernel with alignment-aware vector loads and unrolled selection.
- Routes E=64/128/256 and E=384 at T<=1024 to it, preserving existing softmax, wave64, and larger-top-k dispatch paths.
- Adds select-based score and sorting helpers for targeted kernel optimizations.
| File | Description |
|---|---|
csrc/include/topk_gating_kernels.cuh |
Adds the single-wave kernel, load helpers, and dispatch logic; updates score and sorting helpers. |
Review effort: Balanced
|
@aiter-bot review |
|
aiter-bot — queued behind 1 review(s); expect to start in about 22 min. The box reviews one PR at a time. |
aiter-bot
left a comment
There was a problem hiding this comment.
ROCm/aiter PR #7922 — [HIP] topk_gating: single-wave register kernel for wave32 (gfx1250)
Review (advisory):
Validation (deterministic): NOT RUN — the PR changes runtime code but ships no test target; the changed path csrc/include/topk_gating_kernels.cuh is executed at run time, so the missing target is a finding in its own right (auto-validation also disabled on this box, REVIEW_AUTO_VALIDATE=0)
Perf (advisory): NOT RUN — no perf target (the PR changes runtime code but ships no test target); the op test's embedded run_perftest could not be run by hand either — this box has no GPU access (/dev/kfd permission denied); the PR's own numbers are author-measured on gfx1250/gfx950 only
Size: 352 lines / 1 files
Design (advisory): wave32 topk<=8 routing moves to a single-wave register kernel whose per-lane contiguous expert lists (WPT=2 only for E=384 T<=1024) replace the multiwave kernel's LDS+barrier+serial merge, trading a changed tie order (e % C) for constant-index selection
Human: recommend valarLip review whether PR #7922's changed tie order on gfx1250 (E=384 T<=1024, E=256 T<=256) and the unmeasured select-form sort in the reg kernel on gfx942 are acceptable for downstream MoE consumers
📝 [verified] Among exactly equal selection scores the expert picked on gfx1250 changes for E=384 (T <= 1024, tie key e % 64 was e % 128) and E=256 (T <= 256, e % 32 was e % 256), and where a bias creates the tie the stored weight can differ — downstream golden-value comparisons of topk_gating output on gfx1250 will diff (1830 tie cases in the author's own dump). Reviewer should ask whether any downstream consumer (vLLM/SGLang accuracy gates) compares topk_gating ids or weights bit-exactly on gfx1250.
3 finding(s) posted inline, on the lines they are about:
csrc/include/topk_gating_kernels.cuh:400— switches the sort inside the shared topk_gating_kernel_opt to the select form, which recompiles that kernel…csrc/include/topk_gating_kernels.cuh:1756— The new kernel dispatches only under get_warp_size_func() == 32 (csrc/include/topk_gating_kernels.cuh:1756),…csrc/include/topk_gating_kernels.cuh:323-325— keeps a duplicate #undef _CAS_DESC from the macro refactor
…ct sort to gfx950 / gfx1250 Address review: - The single-wave kernel dispatches on gfx1250 only; other wave32 targets (gfx1201, ...) keep the multiwave / reg kernels as before this branch. - The reg kernel's select-form sort compiles on gfx950 and gfx1250 only, where it was measured; gfx942 and gfx1201 ISA is identical to the base revision. - Drop a duplicate #undef _CAS_DESC. - op test: new "unaligned" section. Logits one element past an aligned base (odd row stride), aligned logits with an odd row stride, and a bias one element past an aligned base must route bit for bit as the aligned launch.
There was a problem hiding this comment.
🟡 Changes recommended
The process-wide architecture cache can launch a 32-lane-only kernel on an incompatible device, and prefill-only test invocations can fail with a KeyError when the configuration grid is empty.
3 open issues
Review effort: Balanced
…ned grid Address review: - topk_gating_vwave_arch() caches per HIP device, as get_warp_size_func() does, so a process that drives gfx1250 and a wave64 GPU never launches the 32-lane kernel on the wave64 one. - op test: the unaligned section only sweeps T <= 1024; skip it when no requested token count qualifies (e.g. --num-tokens 4096) instead of indexing an empty frame.
There was a problem hiding this comment.
🔵 Needs a closer look
The gfx1250 kernel and gfx950 sorting changes require hardware-level correctness and latency review, with no independently head-matched validation available and no GPU validation possible in this environment.
2 resolved since last review
Review effort: Balanced
…ager reject ROCm#7922 moved the gfx1250 HIP top-k for 384 experts to the single-wave kernel, which is at least as fast as the Triton kernel under graph replay, so gfx1250 leaves SQRTSOFTPLUS_384_ARCHS and keeps the HIP kernel. gfx1250-strict still runs multiwave<384, 4> (the single-wave kernel is gated to gfx1250), so its entry and layout stay. topk_gating checks score_func, need_renorm, the shared columns and the expert count inline before the 384-expert predicate. The predicate reads the arch entry from a module-level value set at its first call, and queries the capture state after the scalar checks and before the tensor checks. The output checks shared with the gfx1250 sigmoid path move into one helper, and sqrtsoftplus_384_topk reads the runtime arch once. Co-Authored-By: Claude Opus 5.5 <[email protected]>
On gfx1250 the E=384 single-wave kernel (WPT=2) stopped at 1024 tokens and 1025..2048 rows fell to prefill_n (TPW=1), which is slower there. That range is the DSv4.1 decode width with speculative tokens at high concurrency (several hundred requests times the verify width) and the small prefill chunks. Extend the single-wave dispatch to T <= 2048; other wave32 targets keep the multiwave kernel up to 1024 as before, and T > 2048 keeps prefill_n. Results are the same set of experts and weights; as with T <= 1024, only the expert picked among exactly equal (logit, bias) scores follows the single-wave lane order instead of prefill_n's. The op test sweeps T = 2048 by default. Depends on ROCm#7922 (the single-wave kernel); this branch carries its two commits until it merges. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…count (#8056) * topk_gating gfx1250: E=384 single-wave kernel up to 2048 tokens On gfx1250 the E=384 single-wave kernel (WPT=2) stopped at 1024 tokens and 1025..2048 rows fell to prefill_n (TPW=1), which is slower there. That range is the DSv4.1 decode width with speculative tokens at high concurrency (several hundred requests times the verify width) and the small prefill chunks. Extend the single-wave dispatch to T <= 2048; other wave32 targets keep the multiwave kernel up to 1024 as before, and T > 2048 keeps prefill_n. Results are the same set of experts and weights; as with T <= 1024, only the expert picked among exactly equal (logit, bias) scores follows the single-wave lane order instead of prefill_n's. The op test sweeps T = 2048 by default. Depends on #7922 (the single-wave kernel); this branch carries its two commits until it merges. Co-Authored-By: Claude Opus 5.5 <[email protected]> * topk_gating gfx1250: E=384 single-wave kernel at every token count Drop the T <= 2048 bound on the gfx1250 E=384 single-wave dispatch. The kernel runs one wave per token with no cross-token work, so nothing in it degrades with T, and it stays ahead of prefill_n (TPW=1) at large T as well. This also gives E=384 one tie order at every T on gfx1250, as E=64/128/256 already have. Other wave32 targets keep the multiwave kernel up to 1024 tokens and prefill_n above it; other arches are unchanged. The op test's unaligned section now runs the whole --num-tokens list instead of T <= 1024, so it reaches every T the single-wave kernel takes. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>



Summary
On gfx1250, route
topk_gatingwith topk <= 8 to a new single-wave register kernel,topk_gating_kernel_opt_vwave. It is 1.3-2.2x faster than the current kernels for E=64/128/256/384 and beats the Triton kernel from #7846 on E=384 by 7-17%.Motivation
On gfx1250 the existing paths leave most of the time above the empty-kernel floor (~1.43 us) in the per-pick selection loop: the reg kernel indexes its sorted list with a runtime cursor, and the multiwave kernel (E=256/384) adds LDS, a barrier and a serial per-wave merge.
Changes
topk_gating_kernel_opt_vwave<.., NUM_EXPERTS, WPT, ..>: one wave per token, no LDS, no barrier. Lane p holds WPT contiguous lists of EPT experts (vector loads when aligned, decided on the host), sorts each withsort_network_desc, then picks the top-k with one DPP max + ballot per pick, unrolled to 8, with constant register indexing.sort_network_descandcompute_scoregain an opt-in select form (same result), used by the new kernel and, on gfx950 / gfx1250 only, by the reg kernel. On gfx942 and gfx1201 every kernel's ISA is identical to the base revision.op_tests/test_moe_topk_gating.py: newunalignedsection.Performance (if applicable)
CUDA graph (
run_perftest(testGraph=True)), bf16 logits, fp32 bias, sqrtsoftplus, renorm, topk=8, us. Min of two runs, GPU locked.E=384 on gfx1250 vs the Triton kernel of #7846 (same setup): 2.01 vs 2.38 us at T=1, 2.56 vs 2.91 at T=256, 3.02 vs 3.58 at T=1024; topk=6 is 7-17% faster as well.
Padded CUDA-graph batches (
num_valid_rows= 1/8, 1/2 or all of the rows, topk=6) on gfx1250: E=256 rows 16-2048 2.2-5.1 -> 1.85-2.6 us, E=384 rows 16-1024 3.6-4.4 -> 2.2-2.8 us.Testing
Tested on gfx1250 and gfx950 (MI355X); see "Validation and unverified scope".
Documentation
Internal kernel selection only; the op's API and documented behavior are unchanged.
Dependencies
Breaking Changes
None in the API. Among exactly equal selection scores, the expert picked can change on gfx1250 for E=384 (T <= 1024) and E=256 (T <= 256), see below.
PR Self-Review
Reviewed revision
0fdd358
Behavior and intent
Ties are still resolved to the lowest lane, as since #4965, but lanes map to e % 64 for E=384 (was e % 128) and to e % 32 for E=256 at T <= 256 (was e % 256). So the expert picked among exactly equal scores can change there on gfx1250; weights of tied experts are equal, so routing weights are unaffected except where a bias creates the tie. A side effect: E=256 no longer changes its tie order with the token count (T <= 256 used multiwave, T > 256 the reg kernel). torch.topk does not define an order among equal values either, so a consumer that compares ids bit for bit on gfx1250 already depends on this kernel's choice; the op test checks ties by score, not by id. Outside gfx1250 the selection is unchanged.
Validation and unverified scope
Bit-exact dumps of ids and weight bits, 12840 cases: E=64/128/256/384/512, topk 1-8, random / exact ties / NaN+inf rows, no/fp32/bf16 bias, renorm on/off, pad rows, shared expert, strided and misaligned logits/bias, fp32 logits.
python op_tests/test_moe_topk_gating.py(all sections, default arguments) on gfx1250 at this revision:All topk_gating benchmarks passed!, includingunaligned(720 configurations, 0 bad). On gfx950 it passed on an earlier revision of this branch; this revision is bit-identical to the base there on the cases above.topk_sqrtsoftplus.cu: gfx942 and gfx1201 all 330 kernel instantiations identical to the base; gfx950 and gfx1250 onlytopk_gating_kernel_optchanges andtopk_gating_kernel_opt_vwaveis added.Unverified: gfx942 runtime (its ISA is unchanged), topk > 8 paths beyond the op test. CI runs on MI35X, where the new kernel does not dispatch; the
unalignedsection runs there against the existing kernels.PR-specific question
The new kernel runs only when the current HIP device is gfx1250 (
get_gpu_arch() == "gfx1250", cached per device), score function sqrtsoftplus or sigmoid (softmax needs the full-row sum and keeps its kernels), topk <= 8, and E in {64, 128, 256} at any T or E = 384 at T <= 1024; anything else takes the kernel it took before. Vector loads (E=384, WPT=2) are used only when the logits base, the row stride and the bias base are all multiples of 2 elements, checked on the host per launch; otherwise the same kernel uses scalar loads, which theunalignedsection checks bit for bit against the aligned launch. The topk <= 8 bound is checked in the dispatch macro before the launch, so the kernel's 8-pick unrolled loop never sees a larger topk.Changed op tests
op_tests/test_moe_topk_gating.py: newunalignedsection. For each E, T <= 1024, topk, score function and dtype, logits one element past an aligned base (odd row stride), aligned logits with an odd row stride, and a bias one element past an aligned base must give the same ids and weight bits as the contiguous aligned launch. No existing section uses offset or strided logits, so the scalar-load fallback of the new kernel had no coverage.