Skip to content

[FlyDSL] MoE: one-workgroup E128 expert sort and routed-slots + shared-expert reduce - #8556

Merged
ganyi1996ppo merged 7 commits into
ROCm:mainfrom
ganyi1996ppo:ganyi/moe-sort-reduce
Nov 27, 2026
Merged

ganyi1996ppo merged 7 commits into
ROCm:mainfrom
ganyi1996ppo:ganyi/moe-sort-reduce

Conversation

@ganyi1996ppo

@ganyi1996ppo ganyi1996ppo commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two small FlyDSL building blocks for E=128 / small-M MoE decode and short prefill, both ported from the amd-kernels MiniMax-M3.1 MoE (credited in the source headers; nothing imports amd_kernels):

  1. moe_sorting_onewg (aiter/ops/flydsl/kernels/moe_sorting_onewg.py): the whole expert sort of up to 512 tokens in ONE workgroup (LDS histogram, one-wave scan of the 64 expert pairs, table built in LDS, 16 B stores). Same table contract as moe_sorting (token | slot << 24, padding (topk << 24) | M, num_valid_ids = [rows, M], per-block expert ids). Opt-in through a new moe_sorting(..., unordered=True) kwarg (requires accumulate=False, no EP mask, E == 128, M <= 512, gfx950; anything else falls through to the existing sorts). The pair order inside an expert is unspecified, so use it only when every (token, slot) pair owns its own output row (route-reduce stage2, or a tile kernel writing [M, topk, H]).
  2. moe_slots_shared_reduce (.../moe_slots_shared_reduce.py): bf16(sum_k fp32(parts[t,k]) + fp32(shared[t])) in one pass, slots in order then the shared expert, fp32 accumulation. Bitwise equal to the generic FlyDSL topk reduction over a [M, topk+1, H] buffer and to the amd-kernels original.

fused_moe's default dispatch is not changed (the kwarg defaults to False). No ATOM change is needed for the aiter side: ATOM reaches sorting through fused_moe. The MiniMax-M3.1 production wiring (tile kernels that write per-slot rows, then these two ops) lands with the expert-tile and router PRs of this series.

Performance (MI355X / gfx950, 1 GPU, E=128 top4, CUDA-graph replay, A/B/A/B in one lease, us)

M bm amd-kernels sort this PR aiter default (opus) aiter flydsl
1-64 16 1.95-2.04 2.00-2.03 4.9-5.7 3.3-5.9
128 16 2.14 2.16 5.44 5.5
512 16 2.93 2.95 7.9 6.1
1-64 32 2.18-2.27 2.17-2.19 5.4-6.4 3.3-5.9
512 32 3.17 3.18 7.9 6.1

So the sort is on par with the amd-kernels original and 2.5-3x faster than aiter's current sort at these shapes. Reduce (moe_slots_shared_reduce, H=6144, top4): 1.9-2.15 us at M<=128, 2.57 us at 256, 4.37 us at 512, equal to amd-kernels within 0.1 us (bit-identical output). Kernel-level gain of the sort vs aiter's default (opus) sort, block 16: 2.00-2.03 us vs 4.9-5.7 us at 1-64 rows, 2.95 vs 7.9 us at 512 rows; the reduce is at parity with amd-kernels. Not measured on its own end to end (the integrated gain of the decode chain is in #8676).

Tests

op_tests/test_moe_sorting.py: test_moe_sorting_onewg (E=128; topk 4 and 8; bm 16/32/64; M = 1..512; random / skewed / identical-routing cases; compares the table with the torch reference up to the pair order inside an expert: num_valid_ids, block expert ids, per-expert pair sets, weights, pad sentinel; plus CUDA-graph capture/replay with fresh routing) and test_moe_slots_shared_reduce (bitwise vs an fp32 sequential reference). Both pass on gfx950; the sort test also exercises the fall-through for shapes that do not fit one workgroup.

Review follow-ups (pushed)

Dropped routes: moe_slots_shared_reduce(..., topk_ids=, num_experts=) masks slots whose id is outside [0, E) (one i32 load per slot; 44.74 vs 44.64 us at 16 rows, 86.29 vs 86.38 us at 128 rows per decode layer, i.e. no cost, same bits for valid ids), instead of zero-filling the slot buffer (+1.8 us / +4.4 us). Device checks on topk_ids / topk_weights, an extra table row for topk 1/2/3/6 configs (regression test test_moe_sorting_onewg_table_boundary, run from the script entry point on gfx950). Main was merged into the branch (moe_sorting now lives in aiter/moev2/segments/sort.py).

Review

Run through the repo's review-pr rules by hand by an independent reader (the skill's fetch step needs a PR number). Findings fixed: arch gate (gfx950 only, wave64 DPP scan), dispatch_policy/CK-backend guard on the new branch, shape/dtype checks on the reduce wrapper, docstring for the order and id-range preconditions, unused code. An earlier draft also switched fused_moe's route-reduce stage2 to unordered=True; that was dropped because no verified end-to-end path exercised it. Known limitation: kernels still use the legacy buffer_ops helpers (bounded-record resources and 16 B masked stores); migrating to buffer tensors is a follow-up.

Merge order / dependencies

Independent of the mega_moe_tp stack (#8548 -> #8553 -> #8555 -> #8676): it touches only the sort entry (aiter/moev2/segments/sort.py, re-exported from aiter/fused_moe.py), the two new moe_* kernels and op_tests/test_moe_sorting.py, so it can merge at any time. #8676 contains this PR's commits and uses moe_slots_shared_reduce (with the topk_ids mask) and, through the stack, the one-workgroup sort.

PR Self-Review

Reviewed revision

af8c5cc

Behavior and intent

Adds the one-workgroup E128 expert sort and the routed-slots + shared-expert reduce, opt-in via moe_sorting(unordered=True); the default dispatch is unchanged.

Validation and unverified scope

Sort 2.00-2.03 us vs 4.9-5.7 us for aiter's default (opus) sort at 1-64 rows; reduce at parity with amd-kernels. Not verified end to end on its own (see #8676); the last test-only commit (af8c5cce8) was not re-run on a GPU.

PR-specific question

No CI, workflow or permission change in this PR.

Changed op tests

  • op_tests/test_moe_sorting.py: one-workgroup sort vs the torch reference up to the pair order (including the topk 1/2/3/6 table-boundary cases and a check that unordered=True actually takes that path) and the slots + shared reduce (including dropped routes).

🤖 Generated with Claude Code

…expert reduce

moe_sorting_onewg: single-workgroup LDS sort for E == 128, M <= 512 (no
output clearing), 2-3x faster than the multi-phase sorts; opt-in through
moe_sorting(unordered=True), used by fused_moe for route-reduce stage2.
moe_slots_shared_reduce: fp32 sum of routed slots plus the shared expert
to bf16 in one pass (bitwise equal to the generic topk reduction).
Techniques credit: amd-kernels sort_a16w4 / reduce_slots_shared.

Co-Authored-By: Claude <[email protected]>
@ganyi1996ppo
ganyi1996ppo requested review from a team and a balanced review from Copilot November 24, 2026 09:06
@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 8556 --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.

@aiter-bot

aiter-bot commented Nov 24, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision af8c5cce8413 · 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 — PR-specific question is too short to show concrete reasoning (9 units; need 14)
  • FAIL — validation answer must explicitly state what remains unverified (or say none with a reason)

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

…reduce extent

- moe_sorting_onewg / moe_slots_shared_reduce launch under the tensors' device and key the compiled
  handle per device (a FlyDSL handle is device bound; one process on several GPUs reused cuda:0's).
- moe_slots_shared_reduce asserts CUDA tensors on one device and a < 2 GiB parts buffer (32-bit
  buffer-resource extents and offsets).
- test docstring no longer claims equality with the generic reduction it does not compare against.

Co-Authored-By: Claude <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

A critical i32 byte-span overflow can create zero-bound routed-load descriptors for accepted inputs, alongside unresolved device-handle reuse, tensor-device validation, and regression-test gaps.

5 open issues
What changed in this PR

This PR adds two FlyDSL building blocks for small-batch MoE execution: an opt-in expert sort and a fused routed-slot/shared-expert reduction. Default fused_moe dispatch remains unchanged.

Changes:

  • Add a single-workgroup E128 sorter for supported gfx950 shapes through moe_sorting(unordered=True).
  • Add ordered FP32 accumulation of routed slots and the shared expert, producing BF16 output.
  • Extend sorting tests with routing distributions, fallback cases, graph replay, and reduction comparisons.
File Description
op_tests/​test_moe_sorting.py Adds sort, graph-replay, fallback, and reduction checks.
aiter/​ops/​flydsl/​kernels/​moe_sorting_onewg.py Implements the single-workgroup expert sort and support predicate.
aiter/​ops/​flydsl/​kernels/​moe_slots_shared_reduce.py Implements fused routed-slot and shared-expert reduction.
aiter/​fused_moe.py Adds guarded, opt-in unordered sorting dispatch.

Review effort: Balanced

Comment thread op_tests/test_moe_sorting.py Resolved
Copilot AI balanced review requested due to automatic review settings November 24, 2026 13:44
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

ROCm/aiter PR #8556 — [FlyDSL] MoE: one-workgroup E128 expert sort and routed-slots + shared-expert reduce

Adds an opt-in moe_sorting(..., unordered=True) that sorts E=128, M<=512 routes in one workgroup on gfx950, plus a FlyDSL kernel that reduces the routed slot rows and the shared expert in fp32 with one bf16 rounding.

Review (advisory): ⚠️ NEEDS WORK -- not independently refuted
Validation (deterministic): NOT RUN -- the auto-run's evidence was rejected (jsonschema missing on the review host); by hand on gfx950 (035 GPU 0, head 41145f6): test_moe_sorting_onewg and test_moe_slots_shared_reduce pass (2 passed), and unordered=True with dispatch_policy=1, accumulate=True or an EP mask returns the legacy 5-tuple
Perf (advisory): MEASURED -- E=128 bm=32 M=1..512 topk 4/8, host-timed 200 iters on one GPU back to back, default 28-34 us vs flydsl 20-25 us vs onewg 18.2-18.4 us (1.1-1.9x), 1 run
Size: 694 lines / 4 files
Design (advisory): the decision that unordered pair order inside an expert is acceptable to callers, expressed as an opt-in kwarg on the shared moe_sorting entry point
Human: recommend valarLip review whether an unordered kwarg on the shared fused_moe.py moe_sorting is the right contract for #8556 (callers must give every pair its own output row)

⚠️ [verified] aiter/fused_moe.py moe_sorting(unordered=False) and aiter/ops/flydsl/kernels/moe_slots_shared_reduce.py have no caller in aiter, so nothing activates until a consumer passes unordered=True or calls the reduce. Reviewer should ask which ATOM PR consumes each and whether it is linked.
⚠️ [verified] The PR says "2.5-3x faster than aiter's current sort" with no output attached. A same-GPU back-to-back host-timed run measured 18.3 us (onewg) vs 24-25 us (flydsl) vs 28-34 us (default), 1.1-1.9x, python overhead included. Author must attach the benchmark output and name the baseline for the 2.5-3x figure, or restate it.
⚠️ [verified] moe_sorting(..., unordered=True) documents "every id must be in [0, E)" but never checks it: on gfx950 a topk id of -1 (an EP-dropped route) ran without error and returned num_valid_ids = [2848, 40], i.e. LDS indexed out of range with no signal. Author must state in the ATOM consumer that EP and dropped-route runs never pass unordered=True, or add a cheap device-side check.
📝 [inferred] moe_sorting_onewg.py and moe_slots_shared_reduce.py use the legacy buffer_ops.create_buffer_resource/buffer_load/buffer_store; the flydsl-kernel-authoring skill says these remain for un-migrated kernels and prefers make_buffer_tensor with copy atoms. Reviewer should ask the owner whether new kernels should use the buffer-view API now; migrating was not attempted because the sort kernel's masked 16 B stores make it non-trivial.

Fixed on the branch in 41145f6: compiled handles are now keyed per device and launched under the tensors' device, the reduce asserts CUDA tensors on one device and a parts buffer under 2 GiB (32-bit buffer extents), and a test docstring no longer claims a comparison it does not make.

🤖 Generated with Claude Code

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Unresolved capacity and routing-validation defects can cause assertion failures or out-of-bounds accesses, while fallback tests discard mismatch results and can silently accept incorrect outputs.

4 open issues
4 previously missed issues

In code that hasn't changed since last review

Medium severity Reserve a dummy row for small-topk launch shapes

aiter/​ops/​flydsl/​kernels/​moe_sorting_onewg.py:149

onewg_supported() accepts shapes where this rounding leaves no space for the dummy row at MS: on gfx950, M=1/topk=1/block_m=16 selects tier 64 and produces MS=TAB=1024, so assert TAB > MS fails before compilation. Reserve at least MS + 1 rows before rounding; removing the assertion alone would leave dummy writes out of bounds. Add a small-topk regression case, since the current sweep only covers topk 4 and 8.

Medium severity Validate routing shapes, dtypes, contiguity, and devices

aiter/​ops/​flydsl/​kernels/​moe_sorting_onewg.py:343

Neither this entry point nor _flydsl_moe_sorting_onewg() checks matching routing shapes or devices: contiguous CUDA int32 IDs shaped [1,4] and fp32 weights shaped [1,1] pass the dispatch gate, but the kernel indexes four weights. CPU or off-device weights also pass that gate. Validate matching shapes, expected dtypes, contiguity and the same CUDA device here before launching; these metadata-only checks remain graph-safe and cover both entry points.

Low severity Use the supported buffer-tensor API in new kernels

aiter/​ops/​flydsl/​kernels/​moe_slots_shared_reduce.py:46

These new kernels introduce fresh buffer_ops load/store paths, although aiter/ops/flydsl/AGENTS.md:32-33 reserves that compatibility layer for older kernels and requires buffer tensors plus fx.copy for new code. This also applies to the new sorter’s resource creation and global stores. The explicit byte bounds do not require the legacy layer: fx.rocdl.make_buffer_tensor supports bounded resources. Please use the supported buffer-tensor/copy API in both new kernels, preserving the bounds and masked-store behavior, rather than adding new paths that immediately need migration.

Low severity Benchmark both kernels and assert shared comparison results

op_tests/​test_moe_sorting.py:313

The two new tests do not follow the op-test harness required by .claude/skills/aiter-op-test/SKILL.md:19-40: neither uses @benchmark/run_perftest or emits latency/throughput/error rows, and the reduction uses only a local torch.equal comparison instead of an asserted fp32 checkAllclose result. The existing benchmark at test_moe_sorting.py:537-652 never sets unordered=True, so it does not measure the new sorter either. Please add both kernels as timed candidates with standard summary rows and asserted shared comparisons (zero tolerances for exact results); retain the bitwise assertion as an additional check.

1 resolved since last review

Review effort: Balanced

ganyi1996ppo and others added 2 commits November 25, 2026 19:05
…table, device check, assert fallback errors

- moe_sorting_onewg: size the LDS table for MS + 1 rows. When MS / 4 was a multiple of the thread count (topk=1 / 2 at the 64-token tier, topk=3 at 384, topk=6 at 192), TAB == MS and the compile-time `TAB > MS` assert fired for a call onewg_supported accepted. The table grows only in those 15 (topk, block_m, tier) cases.
- _flydsl_moe_sorting_onewg: require CUDA topk_ids and topk_weights on one device before dispatch.
- test_moe_sorting: the one-workgroup case body is a helper that also asserts the fallback branch's mismatch ratios are zero; a boundary test covers topk 1 / 2 / 3 / 6.

Co-Authored-By: Claude <[email protected]>
… zero

GEMM2 never writes the slot row of an id outside [0, E) (a dropped route), and the reduction summed that uninitialized row. With topk_ids / num_experts the kernel loads the slot's id (one i32 per slot, L1-resident) and masks the routed load, which reads zero out of range; valid slots keep the unmasked kernel's bits. Zero-filling the slot buffer instead cost +1.8 us (16 rows) / +4.4 us (128 rows) per decode layer, measured.

Co-Authored-By: Claude <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 01:23
ganyi1996ppo added a commit to ganyi1996ppo/aiter that referenced this pull request Nov 26, 2026
… into moe-decode-fmoe-tuner

# Conflicts:
#	aiter/fused_moe.py
ganyi1996ppo added a commit to ganyi1996ppo/aiter that referenced this pull request Nov 26, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The direct entry point lacks metadata validation for tensor layout, device, dtype, and capacity, allowing raw stores to corrupt memory for strided or undersized outputs.

4 open issues
1 previously missed issue

In code that hasn't changed since last review

High severity Validate tensor metadata and output capacity before launching

aiter/​ops/​flydsl/​kernels/​moe_sorting_onewg.py:348

The direct entry point accepts strided or undersized outputs because it checks only the supported shape. Raw stores ignore the stride in sorted_ids=backing[::2] and can overrun undersized allocations because their byte bounds come from the input shape. Before launching, use metadata-only checks to validate input shape/dtype/layout, every tensor's device, and output dtype/layout/minimum capacity.

2 resolved since last review

Review effort: Balanced

Comment thread op_tests/test_moe_sorting.py Resolved
Comment thread op_tests/test_moe_sorting.py Resolved
main moved moe_sorting into aiter/moev2/segments/sort.py; the one-workgroup
sort hook (_flydsl_moe_sorting_onewg, moe_sorting(unordered=...)) is ported
there and re-exported from aiter.fused_moe.

Co-Authored-By: Claude <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 02:48
… entry point

CI runs op_tests/test_moe_sorting.py with python3, so a test function without
a caller never ran. Call it on gfx950 (the path it asserts is gfx950-only).

Co-Authored-By: Claude <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The new tests skip boundary cases in CI, fail on unsupported GPUs, and lack verification of public unordered dispatch and reproducible benchmarks for both kernels.

7 open issues

Review effort: Balanced

Comment thread op_tests/test_moe_sorting.py Resolved
Comment thread op_tests/test_moe_sorting.py Resolved
Copilot AI balanced review requested due to automatic review settings November 26, 2026 02:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The tests can pass without exercising the public one-workgroup dispatch, and the performance sweep omits both new kernels, leaving dispatch correctness and latency regressions unchecked.

4 open issues
3 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 04:45
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

Status for the Copilot overviews (latest on 3a3de9b23) and the aiter-bot self-review: inline findings are answered in their threads (fixed in e6327e1 / da67b48 / d5f44d1 / af8c5cc); tracked with a decision pending: buffer_ops migration and the benchmark / checkAllclose op-test flow. The description now has the PR Self-Review section for revision af8c5cc.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The new kernels lack runnable timed performance coverage, and their numerical checks bypass the required comparison helper and its mismatch diagnostics.

3 open issues
1 resolved since last review

Review effort: Balanced

@yadaish yadaish left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

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.

4 participants