Skip to content

[MoE] Public two-stage fused_moe API: fused_moe_prepare_stage2 / fused_moe_run_stage2 (per-slot output, replaceable stage-2 operands) - #7135

Merged
yifehuan merged 6 commits into
ROCm:mainfrom
fanxingran:fxr/moe-stage-api
Nov 18, 2026

Conversation

@fanxingran

@fanxingran fanxingran commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Some MoE callers need to act between the two stages of fused_moe, or need stage 2's output per route instead of summed. Today they can only do it through the private _fused_moe_impl(_stage2_override=...) hook and by re-deriving FlyDSL kernel arguments themselves, or by adding one more flag to fused_moe for each case. Three cases from vLLM's Muse Spark ROCm runner (MXFP4, 256 experts, top-8, a per-route RMSNorm before the top-k sum):

  1. Per-route outputs without repeating the input. The per-route norm needs [T, top_k, H]. vLLM gets it by repeating the input top_k times and calling fused_moe with top-1 routes, so quantization, sorting and stage 1 work on 8x more rows ([ROCm][Perf] Muse Spark: run the AITER MXFP4 experts on the native top-k routes vllm-project/vllm#63290).
  2. A column-sharded stage 2 under TP. At TP > 1 each rank's stage 2 produces partial sums of every route over all H columns, which vLLM then reduce-scatters. Gathering the MXFP4 stage-1 output and scales across ranks and running stage 2 against w2 rows [E, H/tp, I] gives exact per-route outputs on H/tp columns instead ([ROCm][Perf] Muse Spark: column-shard the MXFP4 MoE down projection at TP prefill vllm-project/vllm#63263). That needs to replace a2, a2_scale, w2, w2_scale between the stages.
  3. Both at once, which is what vLLM wants by default at TP prefill. With one flag per feature this becomes a matrix of combinations inside fused_moe.

This PR adds a small public two-stage API instead, so callers compose these themselves. It is meant to show the problem and one possible shape of the fix. If maintainers prefer a different design, or want to implement it themselves, we are happy to close this PR in favour of theirs.

Technical Details

from aiter.fused_moe import (
    fused_moe_prepare_stage2,
    fused_moe_run_stage2,
    supports_stage2_overrides,
)

# fused_moe's arguments up to gate_mode, same positions and defaults
inputs = fused_moe_prepare_stage2(x, w1, w2, topk_weight, topk_ids, ..., config_shape=None)
out = fused_moe_run_stage2(inputs)                     # == fused_moe(...)
routes = fused_moe_run_stage2(inputs, out=buf, per_slot=True)  # [T, topk, model_dim], unsummed
cols = fused_moe_run_stage2(inputs, per_slot=True,     # replaced operands
                            w2=w2_rows, w2_scale=w2_rows_scale,
                            a2=gathered_a2, a2_scale=gathered_a2_scale)
  • Naming: fused_moe_prepare_stage2 runs the sorting and stage 1 and returns what stage 2 needs; fused_moe_run_stage2 runs stage 2 on it. They are unrelated to the existing fused_moe_1stage (the one-kernel MoE), which the earlier names fused_moe_stage1 / fused_moe_stage2 were easy to confuse with.
  • fused_moe_prepare_stage2 runs the existing _fused_moe_impl (same dispatch, sorting and stage 1) and returns a MoeStage2Inputs instead of calling stage 2. It takes fused_moe's arguments, in their positions and with their defaults, up to gate_mode (incl. block_size_M, the pads, biases, splitk, beta / linear_beta), plus keyword-only quant_type_a / quant_dtype_a / quant_dtype_a2 / deterministic. The fused_moe arguments that select another pipeline are not accepted: the shared-expert tensors (FHMoE), stage2_scatter, herd_topk, and output (pass out to fused_moe_run_stage2). Its only public fields are the stage-1 output a2 / a2_scale, the operands a caller may gather or replace; the selected stage-2 callable and the sorted routes stay private, so AITER can change them freely. It is implemented with the existing _stage2_override hook, so fused_moe itself is untouched.
  • config_shape=(token_num, topk) selects the kernels and tuned row as for a call of that shape. vLLM passes the shape of its current repeated-input call (T * top_k, 1), so the native-route call runs exactly the kernels that are tuned and validated today (only stage 2 writes per route instead of summing).
  • fused_moe_run_stage2(inputs) with no options runs the stage 2 fused_moe would run.
  • Reuse: inputs may be run more than once (e.g. with different w2 rows). The default summed output without out is the buffer the sorting prepared (zeroed for accumulating kernels), so it is returned once per inputs; a second such call raises RuntimeError and asks for out, which is zeroed as needed. A caller's out must be contiguous, of the expected shape/dtype/device, and must not overlap a2.
  • per_slot=True writes each route's (router-weighted) output to its own row. Under EP, rows of masked experts are zero in an out allocated by the call and left as they are in a caller's out. w2/w2_scale and a2/a2_scale replace the stage-2 operands; the GEMM shape follows them. A replacing operand must be contiguous, on stage 1's device and keep the dtype and rows of the one it replaces (a2 the routes or sorted slots, w2 the experts), the reduction dims of w2 and a2 must still match, the scales must be E8M0 with enough rows and groups, and an operand of another shape needs its scale; otherwise ValueError before any kernel runs.
  • The options are supported for the FlyDSL MXFP4 stage-2 families, which size the GEMM from their operands and already have per-route outputs internally:
    • flydsl_moe_stage2 (v1): return_per_slot=True;
    • FlyDSL v2 layout GEMM2: the reduce epilogue's per-(token, slot) rows, written to the caller's buffer and not reduced.
      supports_stage2_overrides(metadata) tells a caller up front (a config lookup, nothing compiled) whether a config qualifies (FlyDSL MXFP4 stage 2, no split-K stage 1, no stage-2 bias, no aux sort); fused_moe_run_stage2 checks the same on the captured stage 2 and raises NotImplementedError for other configs, so the caller keeps its existing path. Pipelines without a separate stage 2 (one-stage, full implementations, and the direct paths that return before stage 2) raise RuntimeError in fused_moe_prepare_stage2.
  • Wrapper changes: _flydsl_stage2_wrapper / _flydsl_v2_stage2_wrapper take an optional per_slot_out; _fused_moe_impl takes an optional _config_shape; the _stage2_override check for one-stage configs moves before the full-impl dispatch, so it also covers full implementations. Defaults leave every fused_moe call unchanged. The one behavior change: a _stage2_override caller (today the comm-fused MoE runtime) whose config selects a FlyDSL full implementation now gets the same RuntimeError as for one-stage configs, instead of the override being skipped silently.

AI assistance was used in this PR.

Test Plan

  • New op_tests/test_moe_stage_api.py (pytest, gfx950), on a Muse Spark TP8 rank shape (E 256, top-8, model_dim 4096, inter_dim 512, MXFP4 x MXFP4):
    • fused_moe_run_stage2(fused_moe_prepare_stage2(...)) against fused_moe;
    • per_slot=True with config_shape=(T * 8, 1) against fused_moe on the input repeated 8 times with top-1 unit weights;
    • w2 replaced by its two row halves: the concatenated outputs equal the full-w2 output (bitwise for per_slot);
    • replaced a2 (zeros give zeros);
    • case 2 simulated on one GPU: two "ranks" each run stage 1 on half of inter_dim, their a2 / a2_scale columns are concatenated, and stage 2 runs against each half of the w2 rows; the result matches fused_moe on the full weights;
    • a bf16 (CK) config: plain fused_moe_run_stage2 equals fused_moe, per_slot raises NotImplementedError;
    • the summed output is returned once per inputs and again with out; fused_moe_prepare_stage2 matches fused_moe's parameters up to gate_mode; mismatched replacing operands (device, contiguity, rows, dtype, widths, scale dtype, rows and groups, out overlapping a2) raise ValueError.
  • fused_moe regression: the same fused_moe calls (Muse TP repeated-input keys 64 / 512 / 8192, native top-8, EP with expert_mask, a bf16 CK case) before and after this PR.
  • Kernel benchmark on Muse Spark rank shapes: fused_moe on the repeated input (what vLLM does today) vs fused_moe_prepare_stage2 / fused_moe_run_stage2(per_slot=True) on the native routes with the same kernels.
  • End to end in vLLM ([ROCm][Perf] Muse Spark: MXFP4 MoE on native routes and column-sharded at TP prefill, via AITER's two-stage API vllm-project/vllm#64461, which uses this API for cases 1–3).

Test Result

MI355X (gfx950), rocm/atom-dev nightly (flydsl 0.5.0) with this branch merged with main 403b24d:

  • op_tests/test_moe_stage_api.py: 16 passed.
  • fused_moe regression, main vs this branch on the same compiled modules: the cases that are bit-identical between two main runs (repeated-input keys 512 / 8192, EP top-8 T=16) are bit-identical with this branch. The others use atomic stage-2 kernels that already differ between two main runs, by the same amount (max abs 0.0039–0.0156 main-vs-main, 0.0039–0.0156 branch-vs-main).

Measured on the earlier revision (AITER 0.1.26 container with this PR's fused_moe.py, main's Muse rows); the rename and checks do not change the kernels called:

  • Kernel benchmark, one MoE layer, median us, per_slot output bitwise equal to the repeated-input fused_moe in every row:
split tokens repeated input (us) staged per-slot (us) speedup
TP8 (E 256, I 512) 16 227.2 202.5 1.12x
TP8 128 304.1 279.6 1.09x
TP8 1024 364.0 318.2 1.14x
TP8 4096 706.3 461.9 1.53x
TP8 8192 1243.6 623.3 2.00x
EP8 (E 32 local, I 4096) 1 210.8 182.0 1.16x
EP8 16 242.1 215.4 1.12x
EP8 128 302.3 279.1 1.08x
EP8 1024 333.9 303.5 1.10x
EP8 4096 628.6 399.6 1.57x
EP8 8192 1087.8 511.6 2.13x

TP8 T=1 maps to a one-stage row in that CSV, so fused_moe_prepare_stage2 raises RuntimeError as documented (vLLM only takes the staged path from 65 tokens). With the default configs the speedups are similar (TP8 1.07x–2.14x, EP8 1.08x–2.12x).

  • End to end, amd/Muse-Spark-Open-816B-A42B-Quark-MXFP4 on 8x MI355X with DSpark speculative decoding (details in the vLLM PR):
    • TP8, per-route outputs plus column-sharded stage 2 (cases 1–3): TTFT −13% at 2k, −34% at 8k / 16k input; output throughput +17% at concurrency 16 / 32; GSM8K 0.949 → 0.953 (within noise).
    • TP1 x EP8, per-route outputs (case 1): TTFT −8% to −13%; output throughput +10% / +12%; GSM8K identical on all 1319 questions and greedy outputs identical.

PR Self-Review

Reviewed revision

64fab51

Behavior and intent

Adds the public fused_moe_prepare_stage2 / fused_moe_run_stage2 / supports_stage2_overrides API. Callers can now get per-route stage-2 outputs (per_slot=True) and replace a2 / a2_scale / w2 / w2_scale between the stages. Today this is only possible through the private _stage2_override hook plus re-deriving FlyDSL kernel arguments, or one more fused_moe flag per case, and the cases above need them combined. fused_moe calls are unchanged. The one behavior change: a _stage2_override caller whose config selects a FlyDSL full implementation now gets RuntimeError, as one-stage configs already do, instead of the override being skipped silently.

Validation and unverified scope

On MI355X (gfx950), at this revision (merged with main 403b24d), on the AITER of a rocm/atom-dev nightly with this branch's Python:

  • python -m pytest op_tests/test_moe_stage_api.py: 16 passed.
  • fused_moe regression main vs this branch: results in Test Result above.
  • black and ruff check (0.16.0) pass.

On the earlier revision 4948264 (AITER 0.1.26 container): the kernel benchmark and vLLM end to end (vllm-project/vllm#64461: 44 passed, 3 skipped in its staged-MoE tests).

Unverified:

PR-specific question

Before this PR, every case in op_tests/test_moe_stage_api.py fails at import, because fused_moe_prepare_stage2, fused_moe_run_stage2 and supports_stage2_overrides do not exist. No existing canonical test covers this behavior. test_moe.py, test_moe_2stage.py and test_moe_ep.py call fused_moe end to end, and no op test exercises _stage2_override, return_per_slot or replaced stage-2 operands. The new test compares against fused_moe, so it reuses the canonical path as its reference instead of duplicating it.

Changed op tests

op_tests/test_moe_stage_api.py (new, gfx950, Muse Spark TP8 rank shape E 256 / top-8 / model_dim 4096 / inter_dim 512, MXFP4):

  • test_staged_matches_fused_moe: fused_moe_run_stage2(fused_moe_prepare_stage2(...)) equals fused_moe.
  • test_per_slot_matches_repeated_input: per_slot=True with config_shape=(T * 8, 1) equals fused_moe on the 8x repeated input with top-1 unit weights.
  • test_per_slot_sums_to_default: on the config fused_moe selects for the top-8 call (the v1 FlyDSL stage 2), the per-route rows sum to the default output.
  • test_replaced_w2_rows: the outputs with each half of the w2 rows, concatenated, equal the full-w2 output.
  • test_replaced_a2: a replaced a2 is actually used (zeros give zeros).
  • test_split_intermediate_gather: the TP column-sharded case on one GPU (stage 1 on halves of inter_dim, gathered a2 / a2_scale, stage 2 on halves of the w2 rows) equals fused_moe on the full weights.
  • test_bf16_default_and_rejected_overrides: on a bf16 CK config, plain fused_moe_run_stage2 equals fused_moe and per_slot raises NotImplementedError.
  • test_rejected_unsupported_capture: a captured FlyDSL MXFP4 stage 2 without an a2 scale (split-K), with bias2, or after the aux sort refuses per_slot.
  • test_prepare_takes_fused_moe_arguments: fused_moe_prepare_stage2 has fused_moe's parameters, positions and defaults up to gate_mode, and its defaults for the keyword-only ones.

test_staged_matches_fused_moe also checks that a second summed run without out raises and that one with out gives the same result; test_rejected_operand_mismatch covers device, contiguity, scale dtype, rows and groups, and an out overlapping a2.

None of these is redundant: each covers one option of the new API, and no other op test calls it.

Submission Checklist

@fanxingran
fanxingran requested a review from a team October 29, 2026 06:54
@github-actions

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 7135 --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.

@fanxingran

Copy link
Copy Markdown
Contributor Author

Hi @yifehuan, could you take a look when you have time?

This PR adds a small public two-stage API for fused_moe (fused_moe_stage1 / fused_moe_stage2), so callers can work between the two stages instead of reaching into _fused_moe_impl, and without adding one more fused_moe flag per use case. vLLM's Muse Spark ROCm path uses it for per-route outputs and a column-sharded stage 2 under TP (vllm-project/vllm#64461): TTFT -34% at 8k/16k and +17% throughput at TP8 on MI355X.

The main goal is to make the need clear. If the AITER team prefers a different design, or would rather implement this themselves, we are happy to close this PR and move vLLM to the official API. Any feedback on the direction is welcome.

…age2

Add fused_moe_stage1(), which runs the sorting and stage 1 of fused_moe and
returns the stage-2 operands (MoeStage2Inputs), and fused_moe_stage2(), which
runs the stage 2 fused_moe would run, or optionally:

- per_slot=True: one row per route, [token_num, topk, model_dim], unsummed;
- replaced w2 / w2_scale and a2 / a2_scale (e.g. w2 output rows, or the
  intermediate gathered across ranks).

The options are supported for the FlyDSL MXFP4 stage-2 kernels (v1 and v2
layout); supports_stage2_overrides(metadata) reports it for a config.
fused_moe_stage1(config_shape=(token_num, topk)) selects the kernels and tuned
row of a call of that shape. fused_moe itself is unchanged.

Signed-off-by: fanxingran <[email protected]>
@aiter-bot

aiter-bot commented Oct 30, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision 64fab51c6621 · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

Adds the public `fused_moe_prepare_stage2` / `fused_moe_run_stage2` / `supports_stage2_overrides` API. Callers can now get per-route stage-2 outputs (`per_slot=True`) and replace `a2` / `a2_scale` / `w2` / `w2_scale` between the stages. Today this is only possible through the private `_stage2_override` hook plus re-deriving FlyDSL kernel arguments, or one more `fused_moe` flag per case, and the cases above need them combined. `fused_moe` calls are unchanged. The one behavior change: a `_stage2_override` caller whose config selects a FlyDSL full implementation now gets `RuntimeError`, as one-stage configs already do, instead of the override being skipped silently.

Validation and unverified scope

On MI355X (gfx950), at this revision (merged with main 403b24d8b), on the AITER of a `rocm/atom-dev` nightly with this branch's Python:
- `python -m pytest op_tests/test_moe_stage_api.py`: 16 passed.
- `fused_moe` regression main vs this branch: results in Test Result above.
- `black` and `ruff check` (0.16.0) pass.

On the earlier revision 4948264 (AITER 0.1.26 container): the kernel benchmark and vLLM end to end (vllm-project/vllm#64461: 44 passed, 3 skipped in its staged-MoE tests).

Unverified:
- gfx942 and other archs (the op test skips off gfx950).
- The full-implementation `RuntimeError` path with the comm-fused MoE runtime on multiple GPUs; that path was not run.
- A full build of this branch: the compiled modules came from the image's AITER (2 days behind main); AITER CI has not run yet.
- vLLM end to end with the new names; vllm-project/vllm#64461 will switch to them.
- The overrides on CK / ASM / Triton stage-2 kernels are not supported by design and raise `NotImplementedError`.

PR-specific question

Before this PR, every case in `op_tests/test_moe_stage_api.py` fails at import, because `fused_moe_prepare_stage2`, `fused_moe_run_stage2` and `supports_stage2_overrides` do not exist. No existing canonical test covers this behavior. `test_moe.py`, `test_moe_2stage.py` and `test_moe_ep.py` call `fused_moe` end to end, and no op test exercises `_stage2_override`, `return_per_slot` or replaced stage-2 operands. The new test compares against `fused_moe`, so it reuses the canonical path as its reference instead of duplicating it.

Changed op tests

`op_tests/test_moe_stage_api.py` (new, gfx950, Muse Spark TP8 rank shape E 256 / top-8 / model_dim 4096 / inter_dim 512, MXFP4):
- `test_staged_matches_fused_moe`: `fused_moe_run_stage2(fused_moe_prepare_stage2(...))` equals `fused_moe`.
- `test_per_slot_matches_repeated_input`: `per_slot=True` with `config_shape=(T * 8, 1)` equals `fused_moe` on the 8x repeated input with top-1 unit weights.
- `test_per_slot_sums_to_default`: on the config `fused_moe` selects for the top-8 call (the v1 FlyDSL stage 2), the per-route rows sum to the default output.
- `test_replaced_w2_rows`: the outputs with each half of the `w2` rows, concatenated, equal the full-`w2` output.
- `test_replaced_a2`: a replaced `a2` is actually used (zeros give zeros).
- `test_split_intermediate_gather`: the TP column-sharded case on one GPU (stage 1 on halves of `inter_dim`, gathered `a2` / `a2_scale`, stage 2 on halves of the `w2` rows) equals `fused_moe` on the full weights.
- `test_bf16_default_and_rejected_overrides`: on a bf16 CK config, plain `fused_moe_run_stage2` equals `fused_moe` and `per_slot` raises `NotImplementedError`.
- `test_rejected_unsupported_capture`: a captured FlyDSL MXFP4 stage 2 without an `a2` scale (split-K), with `bias2`, or after the aux sort refuses `per_slot`.
- `test_prepare_takes_fused_moe_arguments`: `fused_moe_prepare_stage2` has `fused_moe`'s parameters, positions and defaults up to `gate_mode`, and its defaults for the keyword-only ones.

`test_staged_matches_fused_moe` also checks that a second summed run without `out` raises and that one with `out` gives the same result; `test_rejected_operand_mismatch` covers device, contiguity, scale dtype, rows and groups, and an `out` overlapping `a2`.

None of these is redundant: each covers one option of the new API, and no other op test calls it.

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot did not review the current head SHA

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • PASS — Aiter Test Gate: passed

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

@fanxingran

Copy link
Copy Markdown
Contributor Author

@yifehuan friendly ping on this one. The CI workflows are still waiting for approval (action_required, fork PR); could you approve the run when you have a moment? The branch merges cleanly with current main (incl. #7130 / #7110 / #6430 in fused_moe.py), and the PR self-review check passes. The API is built on the _stage2_override hook from #4985; vllm-project/vllm#64461 uses it and is tracked in vllm-project/vllm#64632.

Comment thread aiter/fused_moe.py Resolved
Comment thread aiter/fused_moe.py Resolved

@shantipriya-amd shantipriya-amd 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.

The design approach and performance results look good, however a couple of clarifications: has this been validated on a multi-GPU EP/TP deployment, or only the single-GPU simulated-ranks test in this PR? And could a kernel-level benchmark (isolated from the downstream vLLM integration) be shared or considered?

@fanxingran

Copy link
Copy Markdown
Contributor Author

@shantipriya-amd Thanks for the review, both inline comments are addressed in 526b53b.

Multi-GPU: yes, beyond the simulated-rank test, it runs on 8×MI355X through the vLLM integration (TP8 and TP8+EP8) with GSM8K matching the baseline.

Kernel-level benchmark (isolated, MI355X, CUDA graph, µs; MXFP4 FlyDSL, 256 experts, topk 8, hidden 4096), stage API vs. feeding stage 1 a repeated input:

tokens TP8 repeated TP8 stage API EP8 repeated EP8 stage API
1024 268 185 241 169
2048 410 245 378 215
4096 683 328 595 260
8192 1200 500 1075 409

Outputs are bitwise identical to the repeated-input path.

No change for existing callers: with v0.1.27's test_moe_2stage.py over 8 quant types, ordinary fused_moe dispatches to identical kernels, and outputs stay within stock run-to-run noise.

Could you approve the CI workflows for this fork PR? Thanks!

Resolve conflicts in aiter/fused_moe.py (keep both sides) and wrap
fused_moe_stage1 in drop_presort_on_error, as fused_moe is.

Signed-off-by: fanxingran <[email protected]>
@fanxingran

Copy link
Copy Markdown
Contributor Author

@shantipriya-amd Both inline comments are addressed in 526b53b, and I answered the multi-GPU and kernel-level benchmark questions above. Is there anything else you'd like changed?

@yifehuan vllm-project/vllm#64461 depends on this PR, and its reviewer asked for this one to be merged in AITER first. Could you take a look when you have time? The op-test workflows are also still waiting for approval, since this is a fork PR. Thanks!

Resolve the conflict in the arguments of _flydsl_stage2_wrapper: keep
per_slot_out and main's fused shared expert arguments.

Signed-off-by: fanxingran <[email protected]>
…age2

fused_moe_stage1 read like fused_moe_1stage, the one-kernel MoE.

fused_moe_prepare_stage2 takes fused_moe's arguments, in their positions
and with their defaults, up to gate_mode, plus keyword-only quant_type_a,
quant_dtype_a, quant_dtype_a2 and deterministic. It raises RuntimeError
for every pipeline without a separate stage 2, including the direct paths
that return before stage 2.

fused_moe_run_stage2 returns the sorting's summed buffer only once per
inputs (pass out= to run again), zeroes the per-slot output it allocates,
rejects an out that overlaps a2, and checks that replacing operands are
contiguous and on stage 1's device, and that their scales are E8M0 with
enough rows and groups. Like supports_stage2_overrides, it refuses
per_slot and replaced operands behind a split-K stage 1, with a stage 2
bias, or after the aux sort.

Signed-off-by: fanxingran <[email protected]>
@fanxingran fanxingran changed the title [MoE] Public two-stage fused_moe API: fused_moe_stage1 / fused_moe_stage2 (per-slot output, replaceable stage-2 operands) [MoE] Public two-stage fused_moe API: fused_moe_prepare_stage2 / fused_moe_run_stage2 (per-slot output, replaceable stage-2 operands) Nov 17, 2026
@fanxingran

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Updated in 64fab51, on top of a merge with current main (a2fd848, which resolves the conflict in _flydsl_stage2_wrapper's arguments):

  • Names: fused_moe_stage1 / fused_moe_stage2 are now fused_moe_prepare_stage2 / fused_moe_run_stage2, so they no longer read like fused_moe_1stage. MoeStage2Inputs and supports_stage2_overrides keep their names.
  • Arguments: fused_moe_prepare_stage2 now takes fused_moe's arguments, in the same positions and with the same defaults, up to gate_mode, plus keyword-only quant_type_a, quant_dtype_a, quant_dtype_a2 and deterministic. The docstring lists the ones it does not take: the shared-expert tensors, stage2_scatter, herd_topk and output.
  • No stage 2: every pipeline without a separate stage 2 now raises RuntimeError. That includes the direct paths on main that return before stage 2, which used to hit an assert.
  • Reuse and output: the summed output without out is the sorting's buffer, so fused_moe_run_stage2 returns it once per inputs. A second call raises and asks for out. The per-slot out it allocates is zeroed, and a caller's out must not overlap a2.
  • Operand checks: replacing operands must be contiguous and on stage 1's device, and the scales must be E8M0 with a group per 32 values of the reduction dim. w2_scale is checked for enough rows, or for the old shape when w2 is not replaced. per_slot and replaced operands are refused at run time for the configs supports_stage2_overrides excludes (split-K stage 1, stage-2 bias, aux sort), not only for non-FlyDSL kernels.

On MI355X: op_tests/test_moe_stage_api.py 16 passed, including new tests for the parameter list, the single-use output and the new checks. fused_moe main vs this branch, on the same compiled modules, is bit-identical wherever two main runs are, and differs by the same amount elsewhere (atomic kernels).

@fanxingran

Copy link
Copy Markdown
Contributor Author

@yifehuan All review comments are addressed in 64fab51 (details in the comment above), and CI is green, including all required checks. Is there anything else I should do before this can be approved and merged? vllm-project/vllm#64461 is waiting on it. Thanks!

@yifehuan yifehuan 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

@yifehuan
yifehuan merged commit ca7cfa1 into ROCm:main Nov 18, 2026
andrei-kochin added a commit to sshlyapn/aiter that referenced this pull request Nov 18, 2026
Resolve aiter/fused_moe.py: keep both the fused router API (this PR) and the public two-stage API fused_moe_prepare_stage2 / fused_moe_run_stage2 (ROCm#7135), and pass config_M to _resolve_quant_dtypes.

Signed-off-by: Andrei Kochin <[email protected]>
Co-authored-by: Cursor <[email protected]>
ZLkanyo009 added a commit that referenced this pull request Nov 18, 2026
…n route

aiter/fused_moe.py conflicted with three main commits:

- #8075 (ee71544) routes fused_moe_ through the kernel plugin interface
  and decorates the public fused_moe with drop_presort_after instead of
  drop_presort_on_error. Taken as is. fused_moe_'s _eager_body is now the
  plugin's routed wrapper, so the eager call that skips the torch.ops
  dispatch still asks the providers first; the plan cache and scratch sort
  sit below the route, in the native body. The op test checks that the
  directly called body is the fused_moe route.
- #7135 (ca7cfa1) sizes the config lookup by config_M / config_topk
  (_config_shape). The plan's recorded get_2stage_cfgs arguments use them,
  and a call with _config_shape takes no plan, like one with
  _stage2_override.
- #8179 (a6c759b) imports drop_presort_on_error again; taken as is.
vgokhale added a commit that referenced this pull request Nov 18, 2026
…educe-scatter

aiter/fused_moe.py: keep main's per_slot_out (#7135) next to this PR's
scatter_intermediate on _flydsl_v2_stage2_wrapper, and reject both at once.

Signed-off-by: Vinayak Gokhale <[email protected]>
fanxingran added a commit to fanxingran/vllm that referenced this pull request Nov 19, 2026
ROCm/aiter#7135 landed with fused_moe_stage1 / fused_moe_stage2 renamed to
fused_moe_prepare_stage2 / fused_moe_run_stage2; arguments are unchanged.

Signed-off-by: fanxingran <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants