Repository navigation
[MoE] Public two-stage fused_moe API: fused_moe_prepare_stage2 / fused_moe_run_stage2 (per-slot output, replaceable stage-2 operands) - #7135
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
30625e1 to
d9d5d53
Compare
|
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]>
d9d5d53 to
4948264
Compare
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
|
@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 |
shantipriya-amd
left a comment
There was a problem hiding this comment.
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?
…from the config Signed-off-by: fanxingran <[email protected]>
|
@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:
Outputs are bitwise identical to the repeated-input path. No change for existing callers: with v0.1.27's 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]>
Signed-off-by: fanxingran <[email protected]>
|
@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]>
|
Thanks for the review. Updated in 64fab51, on top of a merge with current main (a2fd848, which resolves the conflict in
On MI355X: |
|
@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! |
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]>
…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.
…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]>
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]>
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 tofused_moefor 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):[T, top_k, H]. vLLM gets it by repeating the inputtop_ktimes and callingfused_moewith 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).Hcolumns, which vLLM then reduce-scatters. Gathering the MXFP4 stage-1 output and scales across ranks and running stage 2 againstw2rows[E, H/tp, I]gives exact per-route outputs onH/tpcolumns instead ([ROCm][Perf] Muse Spark: column-shard the MXFP4 MoE down projection at TP prefill vllm-project/vllm#63263). That needs to replacea2,a2_scale,w2,w2_scalebetween the stages.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
fused_moe_prepare_stage2runs the sorting and stage 1 and returns what stage 2 needs;fused_moe_run_stage2runs stage 2 on it. They are unrelated to the existingfused_moe_1stage(the one-kernel MoE), which the earlier namesfused_moe_stage1/fused_moe_stage2were easy to confuse with.fused_moe_prepare_stage2runs the existing_fused_moe_impl(same dispatch, sorting and stage 1) and returns aMoeStage2Inputsinstead of calling stage 2. It takesfused_moe's arguments, in their positions and with their defaults, up togate_mode(incl.block_size_M, the pads, biases,splitk,beta/linear_beta), plus keyword-onlyquant_type_a/quant_dtype_a/quant_dtype_a2/deterministic. Thefused_moearguments that select another pipeline are not accepted: the shared-expert tensors (FHMoE),stage2_scatter,herd_topk, andoutput(passouttofused_moe_run_stage2). Its only public fields are the stage-1 outputa2/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_overridehook, sofused_moeitself 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 2fused_moewould run.inputsmay be run more than once (e.g. with differentw2rows). The default summed output withoutoutis the buffer the sorting prepared (zeroed for accumulating kernels), so it is returned once perinputs; a second such call raisesRuntimeErrorand asks forout, which is zeroed as needed. A caller'soutmust be contiguous, of the expected shape/dtype/device, and must not overlapa2.per_slot=Truewrites each route's (router-weighted) output to its own row. Under EP, rows of masked experts are zero in anoutallocated by the call and left as they are in a caller'sout.w2/w2_scaleanda2/a2_scalereplace 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 (a2the routes or sorted slots,w2the experts), the reduction dims ofw2anda2must still match, the scales must be E8M0 with enough rows and groups, and an operand of another shape needs its scale; otherwiseValueErrorbefore any kernel runs.flydsl_moe_stage2(v1):return_per_slot=True;reduceepilogue'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_stage2checks the same on the captured stage 2 and raisesNotImplementedErrorfor 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) raiseRuntimeErrorinfused_moe_prepare_stage2._flydsl_stage2_wrapper/_flydsl_v2_stage2_wrappertake an optionalper_slot_out;_fused_moe_impltakes an optional_config_shape; the_stage2_overridecheck for one-stage configs moves before the full-impl dispatch, so it also covers full implementations. Defaults leave everyfused_moecall unchanged. The one behavior change: a_stage2_overridecaller (today the comm-fused MoE runtime) whose config selects a FlyDSL full implementation now gets the sameRuntimeErroras for one-stage configs, instead of the override being skipped silently.AI assistance was used in this PR.
Test Plan
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(...))againstfused_moe;per_slot=Truewithconfig_shape=(T * 8, 1)againstfused_moeon the input repeated 8 times with top-1 unit weights;w2replaced by its two row halves: the concatenated outputs equal the full-w2output (bitwise forper_slot);a2(zeros give zeros);inter_dim, theira2/a2_scalecolumns are concatenated, and stage 2 runs against each half of thew2rows; the result matchesfused_moeon the full weights;fused_moe_run_stage2equalsfused_moe,per_slotraisesNotImplementedError;inputsand again without;fused_moe_prepare_stage2matchesfused_moe's parameters up togate_mode; mismatched replacing operands (device, contiguity, rows, dtype, widths, scale dtype, rows and groups,outoverlappinga2) raiseValueError.fused_moeregression: the samefused_moecalls (Muse TP repeated-input keys 64 / 512 / 8192, native top-8, EP withexpert_mask, a bf16 CK case) before and after this PR.fused_moeon the repeated input (what vLLM does today) vsfused_moe_prepare_stage2/fused_moe_run_stage2(per_slot=True)on the native routes with the same kernels.Test Result
MI355X (gfx950),
rocm/atom-devnightly (flydsl 0.5.0) with this branch merged with main 403b24d:op_tests/test_moe_stage_api.py: 16 passed.fused_moeregression, 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:per_slotoutput bitwise equal to the repeated-inputfused_moein every row:TP8 T=1 maps to a one-stage row in that CSV, so
fused_moe_prepare_stage2raisesRuntimeErroras 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).amd/Muse-Spark-Open-816B-A42B-Quark-MXFP4on 8x MI355X with DSpark speculative decoding (details in the vLLM PR):PR Self-Review
Reviewed revision
64fab51
Behavior and intent
Adds the public
fused_moe_prepare_stage2/fused_moe_run_stage2/supports_stage2_overridesAPI. Callers can now get per-route stage-2 outputs (per_slot=True) and replacea2/a2_scale/w2/w2_scalebetween the stages. Today this is only possible through the private_stage2_overridehook plus re-deriving FlyDSL kernel arguments, or one morefused_moeflag per case, and the cases above need them combined.fused_moecalls are unchanged. The one behavior change: a_stage2_overridecaller whose config selects a FlyDSL full implementation now getsRuntimeError, 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-devnightly with this branch's Python:python -m pytest op_tests/test_moe_stage_api.py: 16 passed.fused_moeregression main vs this branch: results in Test Result above.blackandruff 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:
RuntimeErrorpath with the comm-fused MoE runtime on multiple GPUs; that path was not run.NotImplementedError.PR-specific question
Before this PR, every case in
op_tests/test_moe_stage_api.pyfails at import, becausefused_moe_prepare_stage2,fused_moe_run_stage2andsupports_stage2_overridesdo not exist. No existing canonical test covers this behavior.test_moe.py,test_moe_2stage.pyandtest_moe_ep.pycallfused_moeend to end, and no op test exercises_stage2_override,return_per_slotor replaced stage-2 operands. The new test compares againstfused_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(...))equalsfused_moe.test_per_slot_matches_repeated_input:per_slot=Truewithconfig_shape=(T * 8, 1)equalsfused_moeon the 8x repeated input with top-1 unit weights.test_per_slot_sums_to_default: on the configfused_moeselects 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 thew2rows, concatenated, equal the full-w2output.test_replaced_a2: a replaceda2is actually used (zeros give zeros).test_split_intermediate_gather: the TP column-sharded case on one GPU (stage 1 on halves ofinter_dim, gathereda2/a2_scale, stage 2 on halves of thew2rows) equalsfused_moeon the full weights.test_bf16_default_and_rejected_overrides: on a bf16 CK config, plainfused_moe_run_stage2equalsfused_moeandper_slotraisesNotImplementedError.test_rejected_unsupported_capture: a captured FlyDSL MXFP4 stage 2 without ana2scale (split-K), withbias2, or after the aux sort refusesper_slot.test_prepare_takes_fused_moe_arguments:fused_moe_prepare_stage2hasfused_moe's parameters, positions and defaults up togate_mode, and its defaults for the keyword-only ones.test_staged_matches_fused_moealso checks that a second summed run withoutoutraises and that one withoutgives the same result;test_rejected_operand_mismatchcovers device, contiguity, scale dtype, rows and groups, and anoutoverlappinga2.None of these is redundant: each covers one option of the new API, and no other op test calls it.
Submission Checklist