Skip to content

perf: optimize MXFP4 MoE decode with fused sorting, quantization, and compact scales - #4443

Closed
yuychang wants to merge 7 commits into
ROCm:mainfrom
yuychang:yuychang/fused-moe-sort-quant
Closed

yuychang wants to merge 7 commits into
ROCm:mainfrom
yuychang:yuychang/fused-moe-sort-quant

Conversation

@yuychang

@yuychang yuychang commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

The gfx950 flydsl_moe1_afp4_wfp4_* decode path launches separate kernels to
sort routes, quantize BF16 activations, and expand per-token scales for GEMM1.
At small batches, this plumbing is launch-bound.

This PR adds an opt-in path that fuses sorting with activation quantization and
lets GEMM1 consume compact scales directly, removing two launches. It is
default-off and falls back to the existing path when ineligible.

Technical Details

  • Add mxfp4_moe_sort_quant_fwd, which fuses route sorting, BF16-to-MXFP4
    quantization, and routed-output zeroing.
  • Add FlyDSL a_scale_compact support so GEMM1 reads per-token E8M0 scales
    without mxfp4_moe_sort_fwd.
  • Preserve compact and conventional kernels under distinct cache names, with
    support for k_wave 1, 2, and 4.
  • Make the tuner select the shortest adjusted Stage1 + Stage2 combination,
    including intermediate quantization costs for non-fused Stage1 kernels.
  • Validate the live architecture, device placement, dtypes, and output-buffer
    sizes before launching the fused kernel.

The fused kernel is limited to gfx950, model_dim=7168, block_m=32,
M in [1, 128], and (num_experts, topk) in {(256, 8), (384, 8), (385, 9)}.
The default dispatch uses it for (256, 8) and (384, 8).

The newer MXMOE family selected for (385, 9) already performs inline
activation quantization and consumes compact scales in GEMM1, so it bypasses
this optimization. The (385, 9) kernel instantiation remains available to
callers that pin a compatible legacy config, but this PR makes no performance
claim for MXMOE.

Set SGLANG_AITER_FUSED_DECODE_SORT_QUANT=auto to enable the fused path.
SGLANG_AITER_FUSED_DECODE_COMPACT_SCALE controls compact scale consumption and
inherits the sort/quant setting when unset.

Test Plan

pytest op_tests/test_mxfp4_fused_sort_quant.py -v
pytest op_tests/tuning_tests/test_fmoe_tune_objective.py -v
python op_tests/op_benchmarks/hip/bench_mxfp4_moe_decode_layer.py --reps 2

The GPU suite compares routing metadata and quantized outputs with the existing
operators, checks compact-scale GEMM1 for k_wave 1/2/4, exercises CUDA Graph
replay, and covers the Python dispatch gates.

Test Result

  • op_tests/test_mxfp4_fused_sort_quant.py: 70 passed on gfx950.
  • op_tests/tuning_tests/test_fmoe_tune_objective.py: 14 passed.
  • ruff and black: clean.

The end-to-end results below are only for (E, topk) = (384, 8). Dispatch
inspection confirmed that every row used this PR's fused kernel and compact
scale consumer; MXMOE results are intentionally excluded.

M Baseline (us) Fused + compact (us) Speedup
1 35.76 27.00 1.32x
2 41.61 31.30 1.33x
4 49.63 40.04 1.24x
8 65.20 51.93 1.26x
16 86.19 77.46 1.11x
32 115.00 108.21 1.06x
64 161.75 163.78 0.99x
128 193.85 189.09 1.03x

This is a 1.06-1.33x improvement for M <= 32; M=64/128 is neutral within
run-to-run noise. Accuracy remained in the same range as the baseline.

Submission Checklist

@yuychang
yuychang requested review from a team and Copilot July 29, 2026 17:19
@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:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
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: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
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 4443 --add-label <label>

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.

Pull request overview

This PR introduces an opt-in fast path for gfx950 MXFP4 MoE decode by fusing route sorting + activation quantization into a single kernel and enabling FlyDSL stage-1 GEMM to consume compact per-token activation scales directly (eliminating the sorted-scale expansion step).

Changes:

  • Adds a new HIP op mxfp4_moe_sort_quant_fwd that fuses route sorting, BF16→MXFP4 quantization, and routed-output zeroing for the targeted decode shapes.
  • Extends FlyDSL MoE stage-1 compilation/runtime with a_scale_compact so GEMM1 can gather compact (tokens, model_dim/32) E8M0 scales directly.
  • Integrates the path into fused_moe.py behind environment-variable gates and adds a new regression test + benchmarks.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
csrc/py_itfs_cu/moe_sorting_opus_kernels.cu Adds the fused gfx950 decode sort+quant kernel and its host launcher.
csrc/include/moe_sorting_opus.h Declares the new fused sort+quant entrypoint.
csrc/include/rocm_ops.hpp Exposes mxfp4_moe_sort_quant_fwd via pybind.
aiter/ops/moe_sorting_opus.py Adds the Python-side @compile_ops declaration for the new op.
aiter/ops/flydsl/kernels/mixed_moe_gemm_2stage.py Implements compact-scale gathering in GEMM1 and splits A/B scale prefetch paths.
aiter/ops/flydsl/moe_kernels.py Threads the new a_scale_compact option through compile and runtime wrappers.
aiter/fused_moe.py Adds env-gated selection, fused sort+quant integration, compact-scale gating, and prequantized stage-1 plumbing.
op_tests/test_mxfp4_fused_sort_quant.py New regression suite covering fused sort+quant and compact-scale FlyDSL equivalence.
op_tests/op_benchmarks/hip/bench_mxfp4_moe_sort_quant.py New benchmark for pre-GEMM plumbing latency (baseline vs fused variants).
op_tests/op_benchmarks/hip/bench_mxfp4_moe_decode_layer.py New end-to-end MoE layer benchmark via the existing harness.
op_tests/op_benchmarks/hip/bench_mxfp4_moe_compact_scale_gemm1.py New benchmark isolating GEMM1 compact-scale vs conventional layout costs.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread aiter/fused_moe.py
Comment on lines +2781 to +2786
if prequantized_a1 is not None:
assert quant_type == QuantType.per_1x32
assert prequantized_a1_scale is not None
a1 = prequantized_a1
a1_scale = prequantized_a1_scale
elif not metadata.prequant:
Comment on lines +371 to +380
using namespace aiter::mxfp4_moe;

AITER_CHECK(hidden_states.dtype() == AITER_DTYPE_bf16,
__func__,
": hidden_states must be BF16");
AITER_CHECK(topk_ids.dtype() == AITER_DTYPE_i32 &&
topk_weights.dtype() == AITER_DTYPE_fp32,
__func__,
": expected int32 topk_ids and fp32 topk_weights");
const int topk = topk_ids.dim() == 2 ? static_cast<int>(topk_ids.size(1)) : 0;
Comment on lines +19 to +21
pytestmark = pytest.mark.skipif(
not torch.cuda.is_available(), reason="ROCm/CUDA device is required"
)
@zufayu
zufayu requested a review from yadaish July 30, 2026 02:37
yuychang added 4 commits July 30, 2026 02:57
Introduces the operator only; nothing dispatches to it yet.

- Add `mxfp4_moe_sort_quant_fwd`, a gfx950 kernel that folds route sorting,
  BF16->MXFP4 activation quantization and routed-output zeroing into one
  16-CTA launch for H=7168 / block_m=32 decode batches of M in [1, 128]
- Instantiate the expert histogram for (num_experts, topk) in {(256,8),
  (384,8), (385,9)}; `num_experts` is an explicit argument so routes that
  share a topk cannot alias each other's instantiation
- Emit compact per-token E8M0 scales of shape (tokens, model_dim/32) rather
  than the sorted-row layout, leaving the conversion to the caller
- Add correctness tests against `moe_sorting` and both existing quantizers for
  all three routes and M from 1 to 128, including non-power-of-2 tails, plus a
  CUDA graph capture/replay test
- Add `bench_mxfp4_moe_sort_quant.py` comparing the kernel against the
  separate sort + quantize + scale-sort sequence
…ernel

Uses the kernel added in the previous commit. Scales are still converted to
the sorted-row layout, so no GEMM change is required.

- Add `SGLANG_AITER_FUSED_DECODE_SORT_QUANT` and
  `_is_fused_decode_sort_quant_enabled`, which re-checks every assumption the
  kernel makes; `AITER_CHECK` aborts rather than raises, so this gate is the
  only guard and is deliberately exhaustive
- Skip the path when `ksplit > 1`, where stage 1 expects unquantized BF16 and
  quantizes inline, so prequantizing here would feed it the wrong dtype
- Warn once when the tuned config uses the aux-sort a4w4 family, which already
  fuses quantization into GEMM1, so enabling the flag never silently does
  nothing
- Thread `prequantized_a1`/`prequantized_a1_scale` through `fused_moe_2stages`
  so stage 1 skips its own quantization
- Add gate tests for the accepted and rejected shapes, and assert the wrapper
  returns a sorted-row scale tensor
Independent of the sort+quant kernel: any caller holding per-token scales can
use it.

- Add an `a_scale_compact` compile option so stage 1 indexes per-token E8M0
  scales of shape (tokens, K/32) directly, instead of requiring the sorted-row
  layout that `mxfp4_moe_sort_fwd` materializes
- Derive the token index from the packed sorted id already resident in LDS,
  which keeps addressing correct for multi-K-wave (`k_wave` 2 and 4) tilings
  including the odd K tail
- Split A-scale and B-scale prefetch so the compact path can defer the A-scale
  gather until the `sorted_ids` LDS write is visible
- Tag compact variants `_asc4` in the module name so they cannot alias the
  conventional kernel in the on-disk cache
- Assert compact and conventional layouts produce bit-identical stage-1 output
  across `k_wave` 1/2/4 and both BF16 and FP4 outputs, and that the compact
  path is CUDA graph replay safe
Joins the fused sort+quant kernel to the compact-scale GEMM, removing the
`mxfp4_moe_sort_fwd` launch from the decode path entirely.

- Add `SGLANG_AITER_FUSED_DECODE_COMPACT_SCALE` (falling back to the
  sort+quant variable) and hand the kernel's compact scales straight to stage
  1 when the tuned kernel parses as a compatible FlyDSL row
- Accept every `k_wave` and every M in [1, 128]: compact addressing costs
  5-12% in stage 1 on the multi-K-wave rows the tuner picks at M <= 8, but
  deleting the ~4us sorted-scale expansion more than pays for it against a
  30-65us layer
- Retune `waves_per_eu`, `b_nt`, `tile_n` and `xcd_swizzle` for the
  single-K-wave compact variants at M of 8, 16, 32 and 64, where dropping the
  scale gather shifts the balance toward N-wave parallelism; multi-K-wave rows
  keep their tuned parameters
- Fall back to the sorted-row conversion whenever the compact path is not
  eligible, so correctness never depends on this gate
- Assert the gate engages on the tuned row at every decode M for both the
  (384, 8) and (256, 8) routes, guarding against re-introducing a
  `k_wave == 1` restriction
- Add `bench_mxfp4_moe_compact_scale_gemm1.py` (stage 1, compact versus
  sorted-row scales, covering the multi-K-wave rows) and
  `bench_mxfp4_moe_decode_layer.py` (end-to-end layer, feature on and off)
@yuychang
yuychang force-pushed the yuychang/fused-moe-sort-quant branch from ecb584f to 9e904b6 Compare July 30, 2026 03:00
yuychang added 3 commits July 30, 2026 03:39
- keep fused and non-fused Stage1 candidates separate until launch costs are applied
- charge non-fused Stage1 kernels for the intermediate quantization consumed by Stage2
- select the minimum unrounded Stage1 + Stage2 latency, with one-stage kernels using Stage2=0
- cover deduplication, quantization penalties, combined-pair selection, and rounding ties with CPU tests
- use the live runtime architecture for Python dispatch and fall back cleanly when detection fails
- reject non-gfx950 and cross-device calls before the gfx950-only kernel can trap
- validate routing output dtypes and routed-output buffer capacity before launch
- replace optimization-sensitive asserts with explicit prequantized-input errors
- gate the GPU regression suite on a live ROCm gfx950 device and cover runtime-arch fallback
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Oct 7, 2026
@yuychang

yuychang commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Generalize our approach in #6165.

@yuychang yuychang closed this Oct 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale The PR hasn't been updated in 2 weeks

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants