Repository navigation
[HIP] [MoE] topk_gating, topk_softmax: keep ids distinct when a row runs out of valid experts - #8385
mjkvaak-amd wants to merge 10 commits into
Conversation
…uns out of valid experts A row with fewer than topk valid (non-NaN) experts repeated ids: an all-NaN row routed every slot to expert 0 in most topk_gating paths and in topk_softmax. The kernels scrubbed a NaN selection score to -INFINITY, the same value that marks a cleared winner or an exhausted merge lane, so once the valid experts ran out the argmax tie went to a fake or already-taken index. Repeated ids are not inert at weight 0: the fused MoE kernels queue every (token, expert) pair, and the persistent EMSORT kernels size each expert's queue for at most one entry per token. A dummy forward with NaN rows (vLLM warmup on Qwen3.8-Flash-Next TP2) overflows it and the GPU faults. Invalid selection scores (NaN, and -inf in topk_softmax) are now -FLT_MAX: below every real score, above the -INFINITY markers. Weights of such slots stay 0 in topk_gating (the smem kernels' sentinel guard now also covers -FLT_MAX); moeSoftmax no longer lets one NaN poison the whole row, and moeTopK ranks a NaN probability as 0. Finite rows, including -inf-masked ones, give bit-identical ids and weights. The starved-row check in test_moe_topk_gating.py now also requires distinct ids on every row, and test_topk_softmax.py gains a NaN-row test for the fused and moeTopK paths. Signed-off-by: Mikko Tukiainen <[email protected]> Co-authored-by: Cursor <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
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 |
|
@valar-cop review |
valar-cop
left a comment
There was a problem hiding this comment.
some changes needed..
vllm qwen3.8-flash-next tp2 startup rerun at current head? and any run of the changed kernels on gfx942 (E=128 opt_n) or gfx1250 wave32?
ci green.
A row whose logits are all NaN or -inf loads as -FLT_MAX everywhere and normalized to a uniform 1/E, so it still routed to topk experts. It now gets weight 0 on its topk distinct ids, as topk_gating weights a dead row. Both fused topkGatingSoftmax variants test the reduced row max, and moeSoftmax writes 0 probabilities for the moeTopK fallback. Finite rows are unchanged. test_topk_softmax_nan_rows_distinct_ids runs with renorm on and off, adds an all -inf row, and asserts the weights: 0 on dead rows, and a short row weighted on exactly its valid experts, summing to 1. Co-authored-by: Cursor <[email protected]> Signed-off-by: Mikko Tukiainen <[email protected]>
|
|
@valar-cop review |
zoe-cop
left a comment
There was a problem hiding this comment.
Reviewed eca9789 against 27a3ab6 on MI355X/gfx950 with separate JIT caches. The PR softmax pytest suite passes (81 passed, 1 skipped), and the selected topk_gating NaN/Inf sweep passes all 48 configurations. The intended HIP NaN/dead-row behavior works in these tests. Two remaining issues are described inline: a finite-boundary regression and CI coverage of the new softmax cases. This is scoped native-op validation; I did not rerun the full serving model or the gfx942/gfx1250 paths.
An invalid expert (NaN or -inf input) loaded as -FLT_MAX so it would outbid the -INFINITY that marked a selected one, but -FLT_MAX is also a finite score. A row of finite -FLT_MAX logits came out of topk_softmax as a dead row at weight 0, a -FLT_MAX expert among -inf ones lost its weight, and in topk_gating a -FLT_MAX selection score (a -FLT_MAX correction bias) tied with the NaN experts and lost its slot to expert 0. Invalid experts load as -inf again, as before this PR, and a selected expert (or a lane with none left) is marked NaN instead: below -inf, and never an input value, since NaN inputs are scrubbed at load. A scan seeded with the marker replaces it with the first value left; the warp max (v_max_f32, IEEE maxNum) and ballot already pass over it. Dead rows are again the ones whose max is -inf (topk_softmax's fallback tests its sum, since its max starts at -FLT_MAX). On finite inputs the results are bit-identical to the previous head and to main. Tests: a -FLT_MAX boundary case for each op, and test_topk_softmax.py now runs its cases when executed as a script, which is how .github/scripts/aiter_test.sh runs it. Co-authored-by: Cursor <[email protected]> Signed-off-by: Mikko Tukiainen <[email protected]>
Replace the pytest cases with a @benchmark sweep of topk_softmax against a torch reference (us, TB/s, err) and a boundary-row benchmark asserting the NaN / -inf / -FLT_MAX rows, driven by main() with argparse and printed as markdown tables, so CI's python3 entry point runs it directly. Co-authored-by: Cursor <[email protected]> Signed-off-by: Mikko Tukiainen <[email protected]>
| if(val > max_val) | ||
| // processed first and only updated if > (not >=). A selected expert | ||
| // (NaN) seeding max_val gives way to the first one left. | ||
| if(val > max_val || max_val != max_val) |
There was a problem hiding this comment.
The finite-min regression and the script entry point are fixed, and I verified the 288 regular + 34 boundary softmax configurations and the 48-case gating NaN sweep on gfx950. However, the current head has a measurable regression on ordinary finite inputs. Could we address the common-path cost of the NaN taken marker before treating this as performance-neutral?
Comparing 66a00dc3 against base 27a3ab62 on the same gfx950/256-CU GPU and ROCm 7.2.4 image, K=8:
| Operation | T / E | dtype | Base | Head | Latency increase |
|---|---|---|---|---|---|
| topk_softmax | 4 / 512 | BF16 | 7.243 us | 10.662 us | 47.2% |
| topk_softmax | 4096 / 128 | BF16 | 6.618 us | 8.856 us | 33.8% |
| topk_softmax_fused_shared_gate | 4096 / 256 | BF16 | 8.468 us | 11.103 us | 31.1% |
All three use renormalization; the shared-gate case uses two shared experts, hidden size 256 and scale 0.75. I first reproduced this with run_perftest(testGraph=True), then confirmed it without the Torch profiler using HIP events around warmed graph replay in base/head/head/base order. The first row was +47.5% and +47.1% in the two paired runs. Outputs and IDs were bit-identical across all 56 finite-input configurations checked. Most register-based sigmoid/sqrtsoftplus cases stayed close to base, so this is concentrated in particular paths.
The additional NaN-aware scan/reduction logic also runs for ordinary inputs. Please optimize that path or update the performance evidence for this exact revision and establish an explicit acceptance of the tradeoff, including model impact if needed. The older performance table does not cover the current marker implementation. These are routing-op graph timings, not an end-to-end model slowdown.
There was a problem hiding this comment.
Confirmed. The explicit NaN skip in every argmax step was the cost. I found two ways forward:
- Keep
-FLT_MAXvalid, cheaper marker (aee08aa, ready locally). Your three cases go from +46% / +31% / +31% to +1.6% / +4.4% / +3.6% over main. Across T 1-16384 and E 64-512,topk_softmaxis about +3-4% on most shapes (max +8%), the fused shared gate +3%, andtopk_gatingis within noise except E=512 (up to +7%). - Back to the previous eca9789's marker: about +1-2% over base. The cost is the case from your previous review: an input logit of exactly
-FLT_MAXcounts as masked (weight 0). BF16 can't represent it, and in FP32 it's the usual mask value, so we'd document it instead of paying for it.
Both keep ids distinct and weights finite on rows with too few valid experts, and both are bit-identical to main on finite inputs. I personally lean to 2. Is documenting the -FLT_MAX case acceptable to you?
Summary
topk_gatingandtopk_softmaxrepeat expert ids on a row with fewer thantopkvalid (non-NaN) experts. An all-NaN row gets expert 0 in every slot. This PR makes every row returntopkdistinct ids. Finite inputs are bit-identical.Motivation
Repeated ids are not inert at weight 0. The fused MoE kernels queue every (token, expert) pair, and the persistent EMSORT kernels size each expert's queue for at most one entry per token (#7901). vLLM warmup forwards on Qwen3.8-Flash-Next MXFP4 TP2 produce all-NaN rows,
topk_gatingroutes them all to expert 0, andfmoe_bf16_pertokenMXfp4_g1u1_emsort_silu_16x320faults the GPU before the server starts.Cause: a NaN selection score is scrubbed to
-INFINITY, the same value that marks a taken expert or an exhausted merge lane. Once the valid experts run out, the argmax tie picks a fake or already-taken index.Reproducer (MI355X):
Changes
-FLT_MAXinstead of-INFINITY. They stay below every real score and above the taken or exhausted markers. This applies in everytopk_gatingkernel (opt,opt_multiwave,opt_vwave,opt_n,prefill_n,topk_gating_kernel,smem_n) and in the fusedtopk_softmaxkernels.-FLT_MAXslot, so dead-row weights stay 0. They now scrub NaN for sigmoid/sqrtsoftplus too.moeSoftmax/moeTopK(non-power-of-two E): one NaN no longer turns the whole row's weights into NaN.topk_softmax(both fusedtopkGatingSoftmaxvariants andmoeSoftmax): a row with no finite logit gets weight 0 on itstopkdistinct ids, as intopk_gating. Before, its-FLT_MAXlogits normalized to a uniform 1/E, so the row still routed totopkexperts.Performance (if applicable)
test_moe_topk_gating.pydefaults, geomean per section (11–1080 configs each)test_moeTopkSoftmax.pydefaults, HIPtopk_softmax(68 configs)Unchanged kernels in the same runs moved by 0.4% or less, so these differences are noise.
Testing
Documentation
The contract is the
topk_gatingone: distinct ids on every row, and weight 0 on a row with no valid expert. It is stated in the code comments and asserted in the op tests.Dependencies
Breaking Changes
None. Only rows containing NaN change: their filler slots name distinct experts. In
topk_softmax, their weights are finite instead of NaN, and a row with no finite logit gets weight 0 instead of 1/E.PR Self-Review
Reviewed revision
6507f98
Behavior and intent
A row with fewer than
topkvalid experts now getstopkdistinct ids, instead of repeats that overflow the per-expert queues of the fused MoE kernels. See Motivation.Validation and unverified scope
The head 6507f98 only merges
maininto 3843816; the PR diff is unchanged.MI355X. The
test_topk_softmax.pyand server results are at 3843816. The sweeps are atmainf35545c plus dd86a0d; the head only differs on rows with no finite logit:python op_tests/test_moe_topk_gating.py(all default sections) andpython op_tests/test_moeTopkSoftmax.py: pass.pytest op_tests/test_topk_softmax.py: 81 passed, 1 skipped. The new test fails onmain, and its 8nan_rowscases fail on dd86a0d with dead-row weights of 1/E.python op_tests/test_moe_topk_gating.py --section nan --num-experts 64,128,256,384,512 --topk 1,2,4,6,8,10 -d bf16: 334 of 540 configs fail the new distinct-id check onmain; 12 fail here. Those 12 are E=512 softmax at T ≥ 4096 and fail identically onmain, including k=1, so they aren't an id problem. They are the known smem-fallback case the default sweep leaves out.-infmasks and bias): 1530 configs give identical ids and weights tomain. They spantopk_gating(3 score functions, E 64–640, T 1–16384, k 1–10) andtopk_softmax(E 64–512, T 1–8192, k 1–8).--enable-hc-sp: faults without the fix. With it, the server passes graph capture and serves: arithmetic checks 3/3, 63/64 right on a 64-way concurrent burst. It ran on the stack's AITER 0.1.29 with this PR backported, minus theopt_vwavehunk, a kernel 0.1.29 doesn't have.topk_softmax_asm, whichfused_moe.fused_topkprefers on gfx942/gfx950 for(128, 4/6/8),(256, 6/8),(384, 8)and(640, 8), is a prebuilt kernel this PR doesn't change. A row with any NaN, or with no finite logit, still comes back from it astopkcopies of expert E-1 with NaN weights. vLLM's router callstopk_softmaxdirectly and doesn't reach it.MI325X (gfx942) at the head 3843816:
pytest op_tests/test_topk_softmax.py: 81 passed, 1 skipped.python op_tests/test_moe_topk_gating.py(all default sections) andpython op_tests/test_moeTopkSoftmax.py: pass. The grouped top-k sections oftest_moeTopkSoftmax.pyprint allclose warnings, at a similar count onmain(54 against 51), and this PR doesn't touch them.opt_nkernel for sigmoid and sqrtsoftplus, and its 36 configs in the--section nansweep (T = 4096, 16384) pass.--section nan --num-experts 64,128,256,384,512 --topk 1,2,4,6,8,10 -d bf16: 528 of 540 pass. The 12 failures are the same E=512 softmax T ≥ 4096 configs as on MI355X.-infmasks and bias): 570 configs identical tomainfb6c170.topk_softmax_asmbreaks on NaN and dead rows as on gfx950.Unverified: MI250X, gfx1250, and the wave32-only
opt_multiwavepath.PR-specific question
No path selection changes: the dispatcher, the arch, dtype and shape gates, and the kernels' supported inputs are as on
main. The edit touches everytopk_gatingkernel, for fp16/bf16/fp32 gating, every E/T/topk the dispatcher already routes, and every score function, plus both legacytopk_softmaxpaths. What keeps other inputs unchanged is that the edit only rewrites NaN and-infscores:fmaxf(x, -FLT_MAX)is the identity for finitex, and the guardmax_val <= -FLT_MAXonly matches the sentinels, since real scores are softmax/sigmoid/sqrtsoftplus plus a finite bias. Finite inputs therefore run the same arithmetic as before, which the 1530-config bit-identity check confirms.Changed op tests
op_tests/test_moe_topk_gating.py:_starved_rows_oknow requires distinct ids on every row. It used to check dead rows on weights only, and its docstring allowed repeats, which is what this PR fixes.op_tests/test_topk_softmax.py: newtest_topk_softmax_nan_rows_distinct_ids, with renorm on and off. It covers an all-NaN row and an all--infrow (weight 0 everywhere), a row withtopk - 1valid experts (weighted on exactly those), and an almost-all--infrow. It runs on the fused path (E = 64, 256, 512) and themoeSoftmax/moeTopKpath (E = 160). The file had no NaN coverage.