Skip to content

[HIP] [MoE] topk_gating, topk_softmax: keep ids distinct when a row runs out of valid experts - #8385

Open
mjkvaak-amd wants to merge 10 commits into
ROCm:mainfrom
mjkvaak-amd:mtukiain/topk-nan-distinct-ids
Open

mjkvaak-amd wants to merge 10 commits into
ROCm:mainfrom
mjkvaak-amd:mtukiain/topk-nan-distinct-ids

Conversation

@mjkvaak-amd

@mjkvaak-amd mjkvaak-amd commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

topk_gating and topk_softmax repeat expert ids on a row with fewer than topk valid (non-NaN) experts. An all-NaN row gets expert 0 in every slot. This PR makes every row return topk distinct 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_gating routes them all to expert 0, and fmoe_bf16_pertokenMXfp4_g1u1_emsort_silu_16x320 faults 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):

import torch, aiter
from aiter.ops.moe_op import topk_softmax

torch.set_default_device("cuda")
E, K = 512, 10
for T in (4, 4096):
    g = torch.randn(T, E, dtype=torch.bfloat16)
    g[0] = float("nan")                                       # no valid expert
    g[1] = float("nan")
    g[1, 5:14] = torch.arange(1, 10, dtype=torch.bfloat16)    # 9 valid, topk 10
    w, i = torch.empty(T, K), torch.empty(T, K, dtype=torch.int32)
    aiter.topk_gating(w, i, g, None, need_renorm=True, score_func="softmax")
    print(f"topk_gating  T={T}:", i[0].tolist(), i[1].tolist())

g = torch.randn(4, E)
g[0] = float("nan")
w, i = torch.empty(4, K), torch.empty(4, K, dtype=torch.int32)
topk_softmax(w, i, torch.empty_like(i), g, True)
print("topk_softmax T=4:   ", i[0].tolist(), "weights finite:", bool(w.isfinite().all()))
main:
topk_gating  T=4: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [13, 12, 11, 10, 9, 8, 7, 6, 5, 0]
topk_gating  T=4096: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [13, 12, 11, 10, 9, 8, 7, 6, 5, 9]
topk_softmax T=4:    [496, 496, 496, 496, 496, 496, 496, 496, 496, 496] weights finite: False
this PR:
topk_gating  T=4: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [13, 12, 11, 10, 9, 8, 7, 6, 5, 0]
topk_gating  T=4096: [0, 1, 2, 3, 256, 257, 258, 259, 4, 5] [13, 12, 11, 10, 9, 8, 7, 6, 5, 0]
topk_softmax T=4:    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] weights finite: True

Changes

  • Invalid selection scores become -FLT_MAX instead of -INFINITY. They stay below every real score and above the taken or exhausted markers. This applies in every topk_gating kernel (opt, opt_multiwave, opt_vwave, opt_n, prefill_n, topk_gating_kernel, smem_n) and in the fused topk_softmax kernels.
  • The smem kernels' sentinel guard also zeroes a -FLT_MAX slot, so dead-row weights stay 0. They now scrub NaN for sigmoid/sqrtsoftplus too.
  • Legacy moeSoftmax/moeTopK (non-power-of-two E): one NaN no longer turns the whole row's weights into NaN.
  • topk_softmax (both fused topkGatingSoftmax variants and moeSoftmax): a row with no finite logit gets weight 0 on its topk distinct ids, as in topk_gating. Before, its -FLT_MAX logits normalized to a uniform 1/E, so the row still routed to topk experts.

Performance (if applicable)

Hardware Workload/configuration Before After Change
MI355X test_moe_topk_gating.py defaults, geomean per section (11–1080 configs each) 1.00 0.989–1.005 within ±1.1%
MI355X test_moeTopkSoftmax.py defaults, HIP topk_softmax (68 configs) 1.00 0.988 −1.2%

Unchanged kernels in the same runs moved by 0.4% or less, so these differences are noise.

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X
  • Tested on MI300X (gfx942, on an MI325X)

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

The contract is the topk_gating one: 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

  • No new third-party dependencies added
  • New dependencies are listed and justified below

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 topk valid experts now gets topk distinct 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 main into 3843816; the PR diff is unchanged.

MI355X. The test_topk_softmax.py and server results are at 3843816. The sweeps are at main f35545c plus dd86a0d; the head only differs on rows with no finite logit:

  • python op_tests/test_moe_topk_gating.py (all default sections) and python op_tests/test_moeTopkSoftmax.py: pass.
  • pytest op_tests/test_topk_softmax.py: 81 passed, 1 skipped. The new test fails on main, and its 8 nan_rows cases 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 on main; 12 fail here. Those 12 are E=512 softmax at T ≥ 4096 and fail identically on main, including k=1, so they aren't an id problem. They are the known smem-fallback case the default sweep leaves out.
  • Bit-identity on finite inputs (with -inf masks and bias): 1530 configs give identical ids and weights to main. They span topk_gating (3 score functions, E 64–640, T 1–16384, k 1–10) and topk_softmax (E 64–512, T 1–8192, k 1–8).
  • Qwen3.8-Flash-Next TP2 vLLM server with --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 the opt_vwave hunk, a kernel 0.1.29 doesn't have.
  • topk_softmax_asm, which fused_moe.fused_topk prefers 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 as topk copies of expert E-1 with NaN weights. vLLM's router calls topk_softmax directly 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) and python op_tests/test_moeTopkSoftmax.py: pass. The grouped top-k sections of test_moeTopkSoftmax.py print allclose warnings, at a similar count on main (54 against 51), and this PR doesn't touch them.
  • E=128 dispatches the gfx942-only opt_n kernel for sigmoid and sqrtsoftplus, and its 36 configs in the --section nan sweep (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.
  • Bit-identity on finite inputs (with -inf masks and bias): 570 configs identical to main fb6c170.
  • topk_softmax_asm breaks on NaN and dead rows as on gfx950.

Unverified: MI250X, gfx1250, and the wave32-only opt_multiwave path.

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 every topk_gating kernel, for fp16/bf16/fp32 gating, every E/T/topk the dispatcher already routes, and every score function, plus both legacy topk_softmax paths. What keeps other inputs unchanged is that the edit only rewrites NaN and -inf scores: fmaxf(x, -FLT_MAX) is the identity for finite x, and the guard max_val <= -FLT_MAX only 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_ok now 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: new test_topk_softmax_nan_rows_distinct_ids, with renorm on and off. It covers an all-NaN row and an all--inf row (weight 0 everywhere), a row with topk - 1 valid experts (weighted on exactly those), and an almost-all--inf row. It runs on the fused path (E = 64, 256, 512) and the moeSoftmax/moeTopK path (E = 160). The file had no NaN coverage.

…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]>
@mjkvaak-amd
mjkvaak-amd requested a review from a team November 20, 2026 12:23
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter standard tests on MI35X
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 8385 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

@github-actions github-actions Bot added the HIP label Nov 20, 2026
@aiter-bot

aiter-bot commented Nov 20, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 66a00dc3abb9 · mode shadow

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

  1. What behavior does this PR change, and why is the existing behavior insufficient?
  2. What did you validate, and what remains unverified? Include commands, hardware/configuration and results.
  3. Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?
  4. For every changed op_tests/ file, what behavior does it cover and why is it not redundant? Write None if no op test changed.

Edit the PR Self-Review section in the PR description. Include the current revision SHA; this comment refreshes automatically.

Missing or invalid answers

  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@yzhou103

Copy link
Copy Markdown
Contributor

@valar-cop review

@valar-cop valar-cop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread op_tests/test_topk_softmax.py Resolved
Comment thread csrc/kernels/topk_softmax_kernels.cu Resolved
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]>
@mjkvaak-amd

Copy link
Copy Markdown
Contributor Author

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.

  • Flash-Next TP2: with --enable-hc-sp it starts and serves, on the stack's AITER 0.1.29 with this PR backported.
  • gfx942: ran on MI325X at 3843816, and the results match MI355X (updated the PR body):
    • E=128 dispatches opt_n, and its 36 NaN-row configs pass.
    • test_topk_softmax.py: 81 passed, 1 skipped. test_moe_topk_gating.py defaults pass.
    • The NaN sweep fails only the E=512 softmax T >= 4096 configs, which fail on main too.
    • Finite inputs: 570/570 configs bit-identical to main.
    • The asm kernel breaks the same way as on gfx950.
  • gfx1250: I don't have one.

@yzhou103

Copy link
Copy Markdown
Contributor

@valar-cop review

@valar-cop

Copy link
Copy Markdown

@yzhou103 re-checked eca9789: earlier points are addressed and nothing new came up.. LGTM from my side.

@zoe-cop zoe-cop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread csrc/kernels/topk_softmax_kernels.cu Resolved
Comment thread op_tests/test_topk_softmax.py Resolved
mjkvaak-amd and others added 2 commits December 1, 2026 02:55
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]>
@mjkvaak-amd
mjkvaak-amd requested a review from zoe-cop December 1, 2026 12:41
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@mjkvaak-amd mjkvaak-amd Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed. The explicit NaN skip in every argmax step was the cost. I found two ways forward:

  1. Keep -FLT_MAX valid, 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_softmax is about +3-4% on most shapes (max +8%), the fused shared gate +3%, and topk_gating is within noise except E=512 (up to +7%).
  2. 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_MAX counts 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?

@mjkvaak-amd
mjkvaak-amd requested a review from zoe-cop December 2, 2026 14:28

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants