Repository navigation
[HIP] Perf/opus moe sort latency - #8316
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
8534125 to
eb3ff25
Compare
WAITING ON AUTHORPR Self-ReviewRevision Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision. Questions to answer in the PR description
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
There was a problem hiding this comment.
🟡 Changes recommended
The chunk path has critical correctness issues: duplicate expert IDs cause write races and double-counted output, while topk values above 256 bypass validation and produce incorrect packed route slots.
2 open issues
What changed in this PR
This PR reduces Opus MoE sorting overhead in fused-MoE inference by replacing the large-token mesh path with a two-launch chunked counting sort, without changing public call signatures.
Changes:
- Add Count and Place kernels for token capacities of at least 2048 when shared memory permits, retaining a mesh fallback.
- Reduce workspace requirements and remove obsolete sorting kernels and the workspace-clear trait flag.
- Add output-contract tests, including shorter weight tensors, and extend graph capture/replay coverage to Opus.
| File | Description |
|---|---|
op_tests/test_moe_sorting.py |
Adds contract checks and Opus graph replay coverage; updates comments naming removed kernels. |
csrc/py_itfs_cu/moe_sorting_opus_kernels.cu |
Removes the obsolete workspace-clear flag from binding arguments. |
csrc/include/moe_sorting_opus.h |
Implements chunked sorting, updates dispatch and workspace sizing, and removes the superseded mesh stages. |
Review effort: Balanced
|
@valar-cop review |
There was a problem hiding this comment.
🔵 Needs a closer look
Critical unresolved bugs cause duplicate expert routes to race and be counted twice during reduction, while top-k values above 256 overflow the packed slot field and select incorrect route data.
2 open issues
Review effort: Balanced
There was a problem hiding this comment.
🟡 Changes recommended
A permitted all-NaN router output can trigger a device trap in the sorter, and the new top-k boundaries lack regression coverage despite fallback paths that leave outputs unwritten.
3 open issues
1 resolved since last review
Review effort: Balanced
There was a problem hiding this comment.
🟡 Changes recommended
Missing top-k 255/256 tests for chunk and mesh-fallback paths leave the advertised supported range unverified, particularly because the binding discards fallback failures.
2 open issues
2 resolved since last review
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because newly accepted top-k 255/256 outputs can produce negative input-row offsets in downstream consumers, while rejection-only boundary tests leave successful-path correctness unverified.
No open issues 🎉
3 resolved since last review
Review effort: Balanced
…sort; shrink the workspace
… valid tokens; run the cuda-graph test on Opus
- Place keeps the first route of a repeat, as the mesh path does - Reject top-k > 256 in the C++ entry; binding checks raise, not abort - Add op tests for repeated experts and the top-k limit
5324143 to
7a93797
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Newly accepted top-k 255/256 configurations cause signed-ID decoding to select negative or incorrect MXFP scale rows, and successful boundary and scale-gather regression tests are missing.
2 open issues
Review effort: Balanced
- fused_moe.py takes main's version: main moved the sort helpers to aiter/moev2/segments/sort.py, which now allocates the persist-es expert table (AITER_MXFP4_G2_ES=1) and passes it to the Opus sort. - moe_sorting_opus.h: from 2048 tokens main sorts with the chunk kernels (#8316), which did not write the expert table. The chunk Place kernel now writes it from one more workgroup, after the groups' ones. The counting sort is shared with the multi-phase P23 kernel (impl::moe_sorting_write_expert_info). - mxmoe_dispatcher.py: main launches the GEMM2 through the AOT cache (#8600), so the launcher has no _cf after a launch. The persist-es grid takes its blocks per CU from a compile-only flyc.compile, before the first launch. Sort outputs and expert table (GLM-5.2 routing, 512 to 16384 tokens) match the previous commit. Persist-es route rows byte-identical to the previous persist-es; fused_moe outputs with and without AITER_MXFP4_G2_ES byte-identical (2k, 4k). GLM-5.2 GEMM2, MI355X, one GPU, cold, us, mean of 3 rounds, against the previous commit: 2k 4k fp4 route rows prev 101.3 134.6 new 100.5 134.3



Summary
From a token capacity of 2048 upward, the Opus MoE sort now runs as a two-launch chunked counting sort instead of four launches around an
[expert, token]mesh. For routing produced by a top-k router (distinct expert ids per token) every output is unchanged bit for bit; the sort kernels' GPU time drops by a median of 42% (best 83%) across the 682 tuned fused-MoE configs on MI355X, with none slower. A token that names one expert twice keeps one route, as before. Top-k above 256, which the sorted ids cannot encode, is now rejected with an error.Motivation
Fused MoE sorts routes by expert on every call. With 896 experts, top-k 16 and 4096 tokens the four sort kernels took about 26 µs, against about 105 µs for GEMM1 + GEMM2, and most of that was not work: a kernel with nothing to do still cost 3–5 µs, and each dependent round of loads from cold memory cost another 1–3 µs. The mesh path paid for four launches and several such rounds regardless of how many routes there were. This path serves nearly every tuned config at 2048 tokens and above, so the cost was shared by almost all large-batch MoE inference.
Changes
csrc/include/moe_sorting_opus.h: addMoeSortingChunkCountKernelandMoeSortingChunkPlaceKerneland dispatch to them when the token capacity is at least 2048 and Place's LDS ((68 + 4 * E) * 4bytes) fits 64 KB, i.e. E ≤ 4079; otherwise the existingP0_v2+P23pair is used.reverse_sorted = -1and no sorted output. Bucket padding (comm_fused_moe_runtime.py) writes rows of expert 0, so such rows do reach the sort.moe_sorting_opus()returns -1 for top-k > 256 before the chunk kernels, since the sorted ids keep the top-k slot in 8 bits.csrc/py_itfs_cu/moe_sorting_opus_kernels.cu: raise for top-k > 256 (the mesh path printed a message and returned for top-k ≥ 255 from 512 tokens, which the binding ignored), and enter withAiterThrowGuardso that a failedAITER_CHECKraises a PythonRuntimeErrorinstead of aborting the process.MoeSortingClearWorkspaceKernel,MoeSortingMultiPhaseKernel_P0_v1,MoeSortingMultiPhaseKernel_P1, their dispatch macros, and theclear_workspace_inside_apitrait flag. Also removeMoeSortingMultiPhaseKernel_P01, which nothing dispatched (onmaineither), withMOE_SORTING_FUSE_MP_01and its workspace semaphore. The path below 2048 tokens and the one-shot kernel are untouched.moe_sorting_opus_get_workspace_sizereturns the size of the count table for the chunk path, e.g. 57 KB instead of 3.67 MB at 4096 tokens / 896 experts. Below 2048 tokens it is 128 bytes smaller, without the semaphore. It is still non-zero wherever the multi-phase path is taken.fused_moe.py, to any GEMM, or to any tuned config.Performance (if applicable)
Metric: sum of the GPU execution time of the Opus sort kernels inside one
fused_moecall, from the per-kernel table ofAITER_LOG_MORE=1. Each config row is 5 independent processes per side, base and head alternating on the same GPU, medians compared. Base ismainat120f57ea7, head is7203b5dae, hardware is MI355X (gfx950, 256 CU). The later commits (one route per repeated expert, the top-k checks, the removal of the never-dispatchedP01kernel) are not in these runs; the overhead of the first is measured separately below.A row counts as faster or slower only when the two sides' ranges do not overlap; otherwise it is reported as overlap, whatever the medians say.
Tuned configs with token capacity >= 2048
op_tests/test_moe_2stage.py, one single-case command per tuned row (cu_num256, 41 config files), each with the model's own quantization type, activation and tuned kernels. 682 of the 683 rows have a result; the test itself skips the remaining one on both sides.93 rows overlapped in the first pass and were measured a second time, which replaces the first: 80 separated, 13 overlapped again. In those 13 the head median is 13% to 52% below the base median and the overlap comes from one or two high head samples out of five; such high samples are as frequent on base as on head (about 6% of each side's samples), cause not investigated.
Per model and shape. A line covers every tuned row of that shape across the model's config files (its quantization variants); "Change" is the change of the sort time over those rows.
The rest of the call (every non-sort kernel) changed by a median of +0.04%: 679 rows overlap, 2 are faster and 1 is slower (MiniMax M3 fp4, 129 / 5 at 16384 tokens: +0.8% and +2.5% in the two passes, about 6 and 20 µs, next to a sort saving of 22 µs; not investigated).
Expert-parallel calls (expert mask, valid token count below the capacity)
op_tests/test_moe_ep.pyin the version of the EP32 branch (it adds-a/--activation), casesg1u1_a8w4_mxfp4andg1u1_a4w4_mxfp4, one command per EP row of the tuned configs with token capacity >= 2048: 157 rows, same protocol. To hit a tuned row the command uses the row's local expert count times the EP degree as the global expert count, so these are the tuned shapes, not the models' real routing.128 rows dispatched to their tuned kernel and ran the new sort kernels: mean −38.6%, median −41.0%, best −56.4%; 126 faster, 2 overlap (in both passes), 0 slower. The other 29 are not counted: 21 fell back to a default kernel and 9 rows at 2048 tokens were rounded below 2048 by the script and ran the unchanged path (1 row is in both groups). The rest of the call changed by a median of −0.01%, with no row slower.
Known weak spot: EP rows at 32768 tokens with top-k 2 or 3 gain little. The two overlapping rows are DeepSeek V4.1 rows of this kind (−1.4% and −3.8%); the other rows of this kind gain 4% to 8%. Where the remaining time goes has not been measured.
Overhead of keeping one route per repeated expert
Standalone HIP-graph replay of
moe_sorting_opus()on MI355X, chunk path, router-like ids,7203b5daeagainst the head, 5 + 5 processes alternating, medians:7203b5dae(µs)The ranges overlap on every row. The top-k checks are host-side integer comparisons.
Known limitations
P0_v2+P23, where each expert's block scans every route. This is slower thanmain'sP0_v1+P1+P23: at E = 4096, top-k 8, +21% to +27% at 4096 tokens and +61% to +106% at 16384 tokens (two measurements with different inputs and GPUs). No current model reaches this expert count.Testing
Tested on MI355X (gfx950) only; see "Validation and unverified scope".
Documentation
The sort's interface and its outputs for valid routing are unchanged; the algorithm and the input contract are described in the header comment above the new kernels.
Dependencies
Breaking Changes
main. Neither choice was specified.RuntimeErrorinmoe_sorting_opus_fwd, andmoe_sorting_opus()returns -1 on the chunk path. Before, depending on the token count, the sort wrote wrong top-k slots or printed a message and left its outputs unwritten.moe_sorting_opus_fwdnow raises aRuntimeErrorinstead of aborting the process.moe_sorting_opus_get_workspace_size, asfused_moe.pydoes. The value it returns for a token capacity of 2048 and above is now much smaller, and 128 bytes smaller below; a caller that hard-codes the old size still works (the buffer is larger than needed), one that asserts on the exact value does not.PR Self-Review
Reviewed revision
e4a52065542ace2f5970ae0b4b05a2ffc1554299Behavior and intent
For router output (distinct expert ids per token), behavior visible to callers does not change: sorted token ids, weights, expert ids, the valid counts, the zeroed range of
moe_buf, rank-local expert ids and both auxiliary outputs are bit-identical tomain. A token that names one expert twice keeps one route as before, possibly a different one of the repeats. What changes is how the sort is computed from 2048 tokens upward (two launches, no mesh), how large its workspace is, and that top-k > 256 is rejected with an error. The existing path spent most of its time on per-launch cost and cold loads rather than on routes.Validation and unverified scope
Hardware: MI355X, gfx950, 256 CU. Base
mainat120f57ea7.Verified:
main: 480 cases (15 shapes × no mask / contiguous mask / random mask / empty mask × full, equal, smaller and zero valid token count × with and without invalid expert ids), every output hashed in separate processes for base and head: 0 differ. Run at7203b5dae.python op_tests/test_moe_sorting.py(default matrix) at7203b5dae: exit code 0, 386 summary rows, cuda-graph capture/replay passes for both FlyDSL and Opus.logits_difffromtest_moe_2stage.pyis identical between base and head on 445 of the 682 rows and differs below the printed precision on most others; 6 rows differ by more than 0.1% relative, not investigated. 20 mxfp8 rows exceed 1e-3 on both sides equally. Fromtest_moe_ep.py,logits_diffis identical on all 157 EP rows.7203b5dae: with a weights tensor shorter than the ids, the previous revision faulted on 3 of 5 inputs; the head passes all 5, and the contract test now uses such a tensor.reverse_sorted = -1; the token field of every sorted slot, the valid counts and the sorted expert ids are identical tomain. The same check fails on7203b5dae(two routes in one slot).moe_sorting_opus()returns -1 for top-k 257 at 2048 tokens; callingmoe_sorting_opus_fwdfrom C++ with top-k 257 throws and restores the throw mode afterwards; top-k 255 and 256 at 2048 tokens run and write their outputs.Not verified:
test_moe_2stage.py); they ran a fallback kernel and are included in the 682 only as sort timings. 1 Qwen3.8 2400B row at 32768 tokens is skipped by the test itself on both sides.P01kernel (see Performance).PR-specific question
The host selects the chunk kernels per call when all of the following hold:
topk_idsand fp32topk_weights(the binding checks the weights; the dispatch handles only this pair);moe_sorting_opus_get_workspace_size(...)is non-zero (dispatch policy 2, or 0 when the automatic policy prefers multi-phase);topk_ids.shape[0]≥ 2048.num_local_tokensdoes not enter the choice, so a captured CUDA graph keeps its path on replay;(68 + 4 * E) * 4bytes, fits 64 KB, the host-sideopus::get_smem_size()on every target: E ≤ 4079.There is no architecture-specific code in the new kernels; they were validated on gfx950 only. Below 2048 tokens the unchanged
P0_v2+P23pair runs; from E = 4080 the same pair runs as a fallback (slower, see Known limitations).Unsupported inputs:
moe_sorting_opus_fwdraises,moe_sorting_opus()returns -1 ahead of the chunk kernels. This also bounds Place's per-thread owner mask to 16 routes per chunk.reverse_sorted = -1and no sorted output, so slot counts and slots agree.[0, E)and rows at or pastnum_local_tokensare not routed (-1inreverse_sortedandlocal_topk_ids), as before; weights are read for valid tokens only.Changed op tests
op_tests/test_moe_sorting.py:test_moe_sorting_opus_contract(new): calls the binding directly on shapes real models use (896 experts / top-k 16 / tile height 96 with a rank's contiguous share of the experts, among others) and checks every output bit for bit, including what no existing test looked at: the zeroed range ofmoe_buf, zero pad weights, rank-local ids and both auxiliary outputs. It passes a weights tensor holding the valid tokens only, which catches reads past it. It passes onmainas well, so it pins the behavior the rewrite keeps.test_moe_sorting_cuda_graph_capture(wastest_moe_sorting_flydsl_cuda_graph_capture): takes abackendargument and the main loop now runs it for Opus too. Not redundant: the Opus sort reads the valid token count on the device, and nothing checked that a replay with a different count than the captured one gives the right result.test_moe_sorting_opus_repeated_experts(new): rows that repeat an expert, rows of expert 0 as bucket padding writes them, and repeats of experts outside the rank's mask, at 4096 tokens (chunk path) and 1024 tokens (mesh path). Checks that each routed (token, expert) keeps one route, that its slot holds its token, top-k slot and weight, and that the sorted tokens equal a sort of the ids without the repeats. Not redundant: every other test draws ids withtopk, which never repeats an expert.test_moe_sorting_opus_topk_limit(new): top-k 257 raises aRuntimeErrorfrom the binding. Not redundant: no test covered the top-k limit.