Skip to content

[FlyDSL] Fix LDS race in MoE sorting p23 kernel - #7349

Merged
Bernard-Liu merged 13 commits into
ROCm:mainfrom
cpersson-amd:fix/flydsl-moe-sort-p23-lds-race
Dec 2, 2026
Merged

Bernard-Liu merged 13 commits into
ROCm:mainfrom
cpersson-amd:fix/flydsl-moe-sort-p23-lds-race

Conversation

@cpersson-amd

@cpersson-amd cpersson-amd commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

In p23_kernel, every wave reads my_start/my_end = cumsum[my_expert(+1)] from LDS. Step 3 then overwrites cumsum[tid] = local_idx. Without an expert mask there is no barrier between the two. A lagging wave can then read already-overwritten boundaries (my_start == my_expert) and write sorted_expert_ids/sorted_token_ids at the wrong offsets. That drops entries, which leaves MoE output rows uninitialized (NaN), and can fill whole ranges of sorted_expert_ids with the wrong expert id. With a mask, the barriers in the mask prefix sum hide the race.

p23_kernel is the last kernel of both multiphase paths, so every FlyDSL sort above the oneshot limit (16 tokens for E=384) is affected: the 2-kernel path up to 2048 tokens and the 4-kernel path above it.

It shows up when other kernels run on the same CUs as the sort. In vLLM, DeepSeek-V4.1-Flash TP4 with speculative decoding and the mHC/shared-expert overlap gave thousands of NaN decode steps in 5 minutes at c16 (AITER_USE_FLYDSL_MOE_SORTING=1, M=96, E=384). With this barrier: 0 NaN steps and 0 sort mismatches.

Changes

  • aiter/ops/flydsl/kernels/moe_sorting_kernel.py: add a gpu.barrier() before the Step 3 cumsum[tid] store in p23_kernel. The output is unchanged except that the race is gone.
  • op_tests/test_moe_sorting.py: test_moe_sorting_flydsl_under_contention, a regression test (see below).

Performance

FlyDSL sort, CUDA-graph replay of 100 sorts, same GPU, mean of 2 runs:

Hardware Workload/configuration Before After Change
MI355X E=384, topk=6, M=96 6.76 us 6.77 us +0.1%
MI355X E=384, topk=6, M=1024 8.17 us 8.18 us +0.1%
MI355X E=256, topk=8, M=96 5.77 us 5.79 us +0.3%

@msaffari-amd measured the same on MI300X (within ±0.25%).

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI300X (by @msaffari-amd, see review)
  • Tested on MI355X

Documentation

  • No documentation change is needed: internal kernel fix.

Dependencies

  • No new third-party dependencies added

Breaking Changes

None

PR Self-Review

Reviewed revision

9f8a834

Behavior and intent

The FlyDSL multiphase sort (p23_kernel, no expert mask, any M above the oneshot limit) no longer reads its expert's LDS boundaries after another wave has overwritten them. Before this change, the output was only correct if every wave in the workgroup finished reading cumsum[my_expert(+1)] before any wave did the Step 3 store. Under concurrent load a lagging wave could see my_start == my_expert and write sorted_expert_ids/sorted_token_ids at the wrong offsets. That dropped entries, which left MoE output rows uninitialized (NaN in vLLM), and could give blocks the wrong expert id.

Validation and unverified scope

  • test_moe_sorting_flydsl_under_contention on MI355X: without the barrier, 25–41 of 200 sorts are wrong in every one of 18 runs on 8 GPUs (some with wrong expert ids). With it, 0 in every run.
  • python3 op_tests/test_moe_sorting.py -e 32 256 40 385 384 -t 5 8 6 7 6 on MI355X (gfx950): all 482 cases pass with FlyDSL error 0. This covers with and without the expert mask, padding, valid/all-empty/mixed routing, CUDA-graph capture/replay, and E up to 385.
  • vLLM DeepSeek-V4.1-Flash TP4 on MI355X (dummy weights, DSpark speculative decoding, c16, 300 s, two servers): thousands of NaN decode steps and wrong sorts before the fix, 0 after.
  • MI300X (@msaffari-amd): the race reproduces at M=96, 1024 and 9000 without the barrier (2,663 of 12,000 runs wrong at M=96/1024), and the barrier removes every failure. The compiled kernel differs by exactly one s_barrier.
  • Unverified: on MI355X the race reproduces only on the 4-kernel path (M=9000). At M=96 and 1024 it did not show in isolation, even with the same contention (it did in vLLM and on MI300X), so the regression test uses M=9000. Not tested on MI250X. Accuracy with real weights was not re-measured.
  • Rechecked at 9f8a834 on a new node: 37/200 wrong without the barrier, 0/200 with it.

PR-specific question

The main risk of the new barrier is a hang, which would happen if some threads in the workgroup didn't reach it. It sits inside if is_sort_block:, which depends only on bid and so is uniform across the workgroup. It's at the same nesting level as the existing barriers before it (after the prefix sum) and after it (before my_local_idx), and the only divergent branch before it (bid == 0 & tid == 0, the num_valid_ids store) has already closed. The zero-fill blocks never enter this branch. Evidence: the full test_moe_sorting.py matrix above, including graph replay, and the vLLM runs complete with no hangs. The other risk is extra latency, which the benchmark table covers.

Changed op tests

op_tests/test_moe_sorting.py::test_moe_sorting_flydsl_under_contention runs 200 FlyDSL sorts (token=9000, E=384, topk=6) while a GEMM and VALU kernels run on a side stream. Outputs are poisoned before every sort. sorted_ids, sorted_weights, sorted_expert_ids and num_tokens_post_padded are compared against the torch reference, and moe_buf must come back zeroed. The other sorting tests run the sort alone, and they pass with and without the barrier. This one fails on the old kernel in every run on MI355X. It takes about 2 s.

AI assistance

Developed with AI assistance (Claude). I reviewed every change and ran the tests and benchmarks on MI355X.

In p23_kernel every wave reads my_start/my_end = cumsum[my_expert(+1)] from
LDS and then Step 3 overwrites cumsum[tid] = local_idx. Without an expert
mask there is no barrier between the two, so a lagging wave can read its
already-overwritten boundaries (my_start == my_expert), write
sorted_expert_ids/sorted_token_ids at the wrong offsets and drop entries.
With the mask, the mask prefix sum's barriers happened to hide this.

Add a workgroup barrier before the Step 3 store.

Co-authored-by: Cursor <[email protected]>
@cpersson-amd
cpersson-amd requested a review from a team November 2, 2026 19:28
@github-actions github-actions Bot added the FlyDSL label Nov 2, 2026
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
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 gfx1201 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 7349 --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.

@aiter-bot

aiter-bot commented Nov 2, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision b9fe2758f8a5 · 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. What behavior would each changed op test fail on before this PR, and why is that coverage not already provided by an existing canonical test?
  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.

@msaffari-amd

msaffari-amd commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Review: LGTM, tested on MI300X (gfx942)

I tested this PR on 8× MI300X. The fix is correct. I could reproduce the bug without the barrier, and the barrier removed every failure.

What I checked

  • Root cause: p23_kernel reads my_start and my_end from cumsum in LDS. Step 3 then overwrites the same locations with cumsum[tid] = local_idx. With no expert mask, nothing orders the two steps, so a lagging wave can read the overwritten values.
  • ISA: the compiled kernel differs by exactly one s_barrier. The boundary values are already in SGPRs when each wave reaches it.
  • No hang risk: the barrier is inside if is_sort_block, which depends only on bid, so every thread in the workgroup reaches it.

Test results

I poisoned the output buffers, compared against a reference, and ran a GEMM and a VALU kernel on a second stream to create contention.

Test Without the barrier With the barrier
E=384/256, topk=6/8, M=96/1024, 3000 runs each 2,663 / 12,000 runs wrong 0 / 12,000
E=385 and E=384, M=9000, 1500 runs each 282 to 986 / 1500 wrong 0
test_moe_sorting.py -e 32 256 40 385 384 -t 5 8 6 7 6 passes passes

Performance (CUDA-graph replay of 100 sorts, interleaved A/B, 9 rounds):

E / topk / M Before After Change
384 / 6 / 96 6.741 µs 6.758 µs +0.25%
384 / 6 / 1024 9.664 µs 9.683 µs +0.20%
256 / 8 / 96 5.761 µs 5.771 µs +0.18%
256 / 8 / 1024 9.251 µs 9.237 µs −0.16%

Tested on MI300X only (MI250X not tested).

Two things I noticed

  1. The bug is worse than described. A lagging wave can fill a large range of sorted_expert_ids with the wrong expert id. I saw values like 31, 63, 127 and 255 across 296 of 297 blocks. That gives wrong-expert results, not only NaN.
  2. M > 2048 is also affected. The description says "16 < M ≤ 2048", but p23_kernel is shared with the four-kernel path. M=9000 failed most often in my tests.

Suggestions (not blocking)

  • Update the description to mention M > 2048 and the wrong expert ids.
  • Tick MI300X in the testing checklist.
  • Optional: a regression test would help, since test_moe_sorting.py passes with and without the barrier. In my runs, 200 iterations at E=384, M=1024 with a second stream running a GEMM caught the bug reliably on the old kernel. Happy to share my script if useful.

msaffari-amd
msaffari-amd previously approved these changes Nov 12, 2026
Regression test for the p23_kernel LDS race: 200 FlyDSL sorts at
token=9000, E=384, topk=6 with a GEMM and VALU kernels on a side stream,
outputs poisoned before every sort and checked against the torch
reference. On MI355X the kernel without the barrier fails 25-41 of 200
sorts in every run; with it, 0.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Carl Persson <[email protected]>
@cpersson-amd

Copy link
Copy Markdown
Contributor Author

Thanks for the review and for testing on MI300X @msaffari-amd!

  • M > 2048: you're right. p23_kernel ends both multiphase paths, so every sort above the oneshot limit is affected. The description now says so.
  • Wrong expert ids: added to the description. I see it on MI355X too, though less often than dropped entries.
  • MI300X: ticked, with credit to your run.
  • Regression test: added test_moe_sorting_flydsl_under_contention (aeb84a3) along the lines you suggested: poisoned outputs, a GEMM and VALU kernels on a side stream, and every sort checked against the torch reference. On MI355X the race only reproduced in isolation at M=9000, not at 96 or 1024, so the test uses token=9000, E=384, topk=6. Without the barrier it fails 25–41 of 200 sorts in every one of 18 runs on 8 GPUs; with it, 0. It takes about 2 s. If your script catches M=1024 on MI300X with something my version doesn't do, I'd be glad to see it and add that case too.

Comment thread op_tests/test_moe_sorting.py Resolved
Comment thread op_tests/test_moe_sorting.py Resolved
cpersson-amd and others added 2 commits November 27, 2026 05:59
…on test

Also run every requested iteration: the last batch may be partial, so
iters below or not a multiple of the batch size are no longer dropped.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Carl Persson <[email protected]>
@Bernard-Liu

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.

LGTM

ci green.

@Bernard-Liu

Copy link
Copy Markdown
Contributor

conflict with main, pls solve first

# Conflicts:
#	op_tests/test_moe_sorting.py
@cpersson-amd

Copy link
Copy Markdown
Contributor Author

Merged main and resolved the test_moe_sorting.py conflict with #8316. The contention test now runs after the FlyDSL/Opus CUDA-graph loop, and the full test passes on MI355X.

@Bernard-Liu
Bernard-Liu merged commit 4fb090d into ROCm:main Dec 2, 2026
60 checks passed
yelkhamra added a commit to yelkhamra/aiter that referenced this pull request Dec 2, 2026
…call

flydsl_moe_sorting_fwd kept the multiphase sort workspace in a module-level
_workspace_cache keyed only by device and passed the same buffer to every
call. Token counts above the oneshot limit (e.g. M >= 17 for E=384,
topk=6) write their expert mesh and per-expert counts there. Graphs captured
while the same cached allocation is reused record the same scratch address.
Two such graphs replayed at the same time on different streams overwrite
each other's scratch, and sorted_ids, sorted_weights, sorted_expert_ids
and num_valid_ids come back wrong although each graph's inputs are valid.

Allocate the workspace with torch.empty on every call, as _moe_sorting_impl
already does for the Opus workspace (ROCm#3047). Each call writes every
workspace word it uses before reading it, so nothing depends on an earlier
call. Under capture the buffer comes from the capturing graph's memory
pool; in eager mode the caching allocator keeps reuse stream-ordered.
Kernels, launch arguments, outputs and the public signature are unchanged.

The p23 LDS barrier that the concurrent regression also exercises is on
main via ROCm#7349 (4fb090d). This commit is rebased onto that main and
carries only the workspace change; its companion commit is dropped.

Tests:
- tests/test_flydsl_moe_sorting_workspace.py (CPU): two multiphase calls
  must receive distinct workspaces, oneshot calls none. Fails before this
  change, passes after.
- op_tests/test_moe_sorting.py: test_moe_sorting_flydsl_concurrent_graph_replay
  captures eight FlyDSL sorts in each of two graphs and replays both on two
  streams. Each attempt queues both graphs behind one gate event that a
  spin kernel keeps pending; an attempt counts only if the gate is still
  pending after both launches, i.e. neither graph could start before the
  other was queued. Ten such attempts are required within twenty (the spin
  doubles after an unconfirmed attempt, up to 2^24 cycles); otherwise the
  test raises RuntimeError (precondition not confirmed) instead of passing.
  Every sort must match the torch reference exactly (checkAllclose with
  rtol=0, atol=0), including weight 0 in padding slots. Oneshot shapes
  (no workspace) are skipped. An earlier version of this test without the
  gate passed on the unpatched wrapper on gfx950 while a standalone
  reproducer showed failures on the same GPU.

Signed-off-by: Yaakoub El Khamra <[email protected]>
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.

6 participants