Skip to content

[HIP] [JIT] [MoE] NVFP4 routed-expert MoE for gfx950 - #7606

Merged
yzhou103 merged 15 commits into
ROCm:mainfrom
sshlyapn:sshliapn/features/cdna4_nvfp4_moe
Nov 19, 2026
Merged

yzhou103 merged 15 commits into
ROCm:mainfrom
sshlyapn:sshliapn/features/cdna4_nvfp4_moe

Conversation

@sshlyapn

@sshlyapn sshlyapn commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

This PR adds NVFP4 MoE support for the MiniMax-M3.1 model on MI355X (gfx950), focusing on the decode stage of a prefill/decode (PD) disaggregated setup. MiniMax-M3.1 ships its routed experts in NVFP4. AITER has no NVFP4 MoE today, so these weights have to be re-quantized (for example to MXFP4) before they can run, and that costs accuracy. With this PR the experts run directly on the shipped NVFP4 weights, and per layer the decode MoE is faster than MXFP4 for most decode batch sizes (see Performance).

Accuracy. MiniMax-M3.1-Flash 1P1D PD on MI355X, DSpark k=3 speculative decoding with real acceptance; only the decode-side routed-expert MoE differs between arms. AIME26 pass@1, 4 runs x 16 repeats x 30 problems per arm:

decode MoE AIME26 pass@1 std (runs) spec acceptance length
MXFP8 (AITER, reference) 90.00 1.63 2.60
MXFP4 (AITER, re-quantized) 88.49 1.20 2.51
NVFP4 (this PR, native weights) 90.10 0.88 2.58
  • NVFP4 vs MXFP8 is +0.10 pp (paired t p 0.89), so accuracy is the same.
  • MXFP4 vs MXFP8 is -1.51 pp (p 0.07-0.11, borderline). With one earlier run per arm added, it is -1.71 pp (sign p 0.023).
  • Speculative decoding acceptance also drops with MXFP4: AL is 3.5% below MXFP8. With NVFP4 it is 0.9% below.

What it does

NVFP4 weights are read as shipped and decoded to f16. The packed E2M1 weights and the E4M3 per-16 block scales are loaded from HBM unchanged, apart from a one-time tile/scale preshuffle at load time. In registers, each fp4 pair goes to f16 via v_cvt_scalef32_pk_f16_fp4 and is multiplied by its E4M3 block scale in f16. This step is exact: at most 6 significant bits. The per-expert global multiplier (1 / weight_global_scale) is applied in fp32 in the epilogue: stage 1 before the activation, stage 2 folded into the routing weight.

Compute. f16 MFMA (mfma_f32_16x16x32_f16) with fp32 accumulation. bf16 activations are cast to f16, and f16 activations are used directly. Activations are not quantized. The activation is SwiGLU-OAI (gate clamped at 7.0, up clamped to [-7, 7], alpha 1.702), and the stage-1 output is kept in f16.

Three launches per MoE call:

  • fused sort + X cast to f16 + output zeroing;
  • stage 1 (gate/up GEMM + SwiGLU-OAI);
  • stage 2 (down GEMM, weighted atomic reduce into the bf16 or f16 output).

Large batches. When T * topk > 4096 or E > 512, the op uses AITER opus moe_sorting and stage-1 kernels that read bf16 X directly (same weights and scale layouts).

CUDA graphs. There is no host sync; the op uses the current stream and the torch allocator, so it can be captured in a CUDA graph. The prebuilt module loads when the weights are wrapped; per-kernel JIT builds and dispatch tables resolve on the first call of a shape (eager warmup), never during replay.

Performance vs MXFP4

Per-layer benchmark, M3.1 TP4 shape (H 6144, I 768, E 128, top-4, bf16 in/out, MI355X). Baseline: the full AITER fused_moe MXFP4 a4w4 call with its native E128/top-4 tuned rows (#6942). Each arm calls 8 MoE layers with distinct weights back to back inside one CUDA graph, so weights come from HBM (cold); time per layer = replay time / 8. Arms are interleaved in paired rounds with rotated order; the ratio is the geomean of the per-round NVFP4 / MXFP4 ratios (< 1 = NVFP4 faster).

Routing modes:

  • s0: uniform random top-4.
  • s1 / s2: skewed, logit bias +1 / +2 on 16 of the 128 experts. Per-layer statistics of routing captured from M3.1 PD decode are closest to s1, with a max expert load near s2.

Synthetic routing, NVFP4 / MXFP4 per layer:

T s0 s1 s2
1 0.612 0.613 0.614
2 0.715 0.723 0.721
4 0.744 0.726 0.699
8 0.868 0.848 0.785
16 0.899 0.895 0.780
32 0.959 0.905 0.816
64 0.988 0.927 0.804
128 1.018 0.988 0.900
256 1.023 1.024 0.961
512 1.013 0.997 0.964
640 1.060 1.018 1.114
768 1.144 1.092 1.124
1024 1.413 1.149 1.194

Time per layer at s0, NVFP4 vs MXFP4: T 1 15.5 vs 25.3 us, T 8 46.0 vs 52.8 us, T 64 146.6 vs 148.3 us, T 512 186.3 vs 183.3 us.

Tuned shapes: MiniMax-M3.1 TP4

aiter/configs/moe_nvfp4_dispatch.csv ships per-T kernel pairs for MiniMax-M3.1 (H 6144, E 128, top-4, bf16, 256 CUs):

  • TP4 (I 768): rows at T = 1, 2, 3, 4, 6, 8, 16, 32, 48, 64, 96, 128, 256, 512, 640, 1024, 2048, 4096, 8192, 16384. The configs come from tuning on synthetic per-layer routing and were checked on routing captured from real M3.1 decode.
  • TP8 (I 384): rows at T = 1, 2, 4, 8, 16, 32, 64, 120, 128, 256, 512, 1024. TP8 has no large-batch row, so T > 1024 uses the default rule.
  • Other shapes: any shape that passes the shape check (H and I multiples of 128, see Known limits) uses a built-in default rule, and a one-time warning per shape / path / T bucket says that no tuned row exists. A tuned shape is added with a CSV row. AITER_CONFIG_MOE_NVFP4=<file> points the op at a different CSV.

The kernel name is the kernel config, for example nvfp4_moe_s1_32x256_xdma_waves8_wbuf2x128_xbuf3_gs6_xcdremap. It encodes the tile, the X placement, waves, the weight/X ring, the scale group size and options. aiter/jit/utils/moe_nvfp4_common.py parses and canonicalizes it.

Building. The prebuilt module module_moe_nvfp4 contains the kernels of the shipped CSV plus the default-rule kernels. Any other name in a CSV row is JIT-built on first use into its own module (module_moe_nvfp4_k_<name>) and reused from the JIT cache afterwards.

API

Direct call:

from aiter import NvFp4MoeWeights, moe_nvfp4

# once per layer (w13: [E, 2I, H/2] fp4x2, sc13: [E, 2I, H/16] E4M3, g13: [E, 2] fp32, ...)
W = NvFp4MoeWeights(w13, sc13, w2, sc2, g13, g2)
out = moe_nvfp4(W, x, topk_ids, topk_w)  # x bf16/f16 [T, H] -> same dtype

Through fused_moe: pass fp4x2 w1 / w2 in the shuffle_weight(w, (16, 32)) layout, E4M3 w1_scale / w2_scale in the shuffle_scale_nvfp4_moe layout (aiter/ops/shuffle.py), plus the new w1_global_scale / w2_global_scale arguments. Options the kernels do not implement raise a ValueError instead of silently falling back: EP expert_mask, bias, doweight_stage1, prequantized activations, padding, non-SwiGLU activations, swiglu_limit other than 7.0, stage2_scatter, and herd_topk.

Tests

  • op_tests/test_moe_nvfp4.py (MI355X): 51 passed. It checks against a dequantized fp32 torch reference at relative tolerance 1e-2 and covers:
    • M3.1 TP4 and TP8 shapes, T 1, 8, 64, 1024, 2048, bf16 and f16;
    • the fused_moe path;
    • a JIT-built CSV kernel loaded through AITER_CONFIG_MOE_NVFP4;
    • 15 fused_moe error cases.
  • Out-of-tree correctness harness: 10 shapes (M3 TP4/TP8/EP4, GLM-5.3, DeepSeek-V4.1, Kimi-3.1, generic group sizes) with 0 bad; per-T TP4 regression (194 cases, E128/E256/E384, top-4/top-8, edge T) with 0 bad.
  • ISA: the final readability commits (Cfg field names, name parsing moved to Python) are ISA-identical on all 389 tuned kernels to the code they refactor.
  • Dispatch CSV: a CPU check confirms that the repeated power-of-two rows change no pick: same kernel pair as the table without them for every T from 1 to 20000 on both paths, and the same kernel name set (prebuilt module).
  • JIT: a new CSV row triggers the per-kernel JIT build in both the shipped CSV and the env CSV, and a second process reuses the cached module without rebuilding.
  • Lint: ruff 0.16.0 and black 26.3.0 are clean.

Known limits

  • gfx950 only.
  • Stage 2 reduces with atomics, so outputs are not bitwise deterministic run to run.
  • bf16 activations are cast to f16. Values with |x| > 65504 would overflow to inf; not checked per model.
  • H and I must be multiples of 128, and H / 128 must be even. I / 128 must be even or exactly 3.
  • No EP (expert_mask), no bias, no activation quantization, SwiGLU-OAI only.
  • Per-layer losses vs MXFP4 at T > 512 (up to 1.41x, listed above); small losses at some T 80-512.

PR Self-Review

Reviewed revision

836f353

Behavior and intent

This PR adds a new op, aiter.ops.moe_nvfp4 (NvFp4MoeWeights, moe_nvfp4), and a fused_moe path that is selected only when the weights are fp4x2 and the new w1_global_scale / w2_global_scale arguments are passed. Existing ops and all existing fused_moe calls (no global scales) behave as before; the only API change is the two new trailing optional fused_moe arguments.

Why the existing behavior is not enough: AITER has no NVFP4 MoE, so NVFP4 checkpoints such as MiniMax-M3.1 have to be re-quantized (for example to MXFP4) to run on MI355X. In our MiniMax-M3.1-Flash PD runs that cost 1.5-1.7 pp AIME26 pass@1 vs MXFP8, while native NVFP4 matched MXFP8 (+0.10 pp); see Motivation.

Validation and unverified scope

Hardware and software: MI355X (gfx950, 256 CUs), ROCm 7.2.3, PyTorch 2.13 (dev build).

Validated:

  • op_tests/test_moe_nvfp4.py on one MI355X GPU: 51 passed, both as python3 op_tests/test_moe_nvfp4.py (the CI entry point) and python3 -m pytest -q, on 836f353.
  • op_tests/test_fhmoe.py on 836f353: 118 passed, including test_clamp_shared_preserves_existing_positional_argument_order; the one local failure, test_fhmoe_aot_cache_is_retrievable_in_run_only_mode, is from our local FlyDSL 0.3.4.1 (JitFunction has no _compile_or_execute, used by aiter/aot/flydsl/replay.py, which this PR does not touch) and passes in CI.
  • Out-of-tree correctness harness vs a dequantized fp32 reference: 10 shapes (M3 TP4/TP8/EP4, GLM-5.3, DeepSeek-V4.1, Kimi-3.1, generic scale group sizes) and 194 per-T TP4 cases (E128/E256/E384, top-4/top-8, edge T), 0 bad. Run on the tree before the power-of-two CSV rows were added; a CPU check shows those rows pick the same kernels for every T from 1 to 20000 on both paths.
  • The readability commits are ISA-identical on all 389 tuned kernels to the code they refactor.
  • Black 26.3.0 and Ruff 0.16.0 clean (CI style checks pass).
  • Per-layer performance vs AITER MXFP4 (section Performance) and AIME26 / gsm8k accuracy in vLLM, both on an earlier revision of these kernels with the same kernel configs as the shipped CSV.

Unverified:

  • Only gfx950. Other archs get a RuntimeError; no gfx942 or gfx1250 run.
  • Shapes other than MiniMax-M3.1 TP4/TP8 run the built-in default rule; they are correctness-checked out of tree, but their performance is not tuned or measured. TP8 T > 1024 also runs the default rule.
  • Outputs are not bitwise deterministic run to run (stage-2 atomics).
  • bf16 activations with |x| > 65504 would overflow to inf in the f16 cast;

PR-specific question

  • Architecture: gfx950 only. prepare() checks the device arch and raises RuntimeError on any other arch before building or launching anything; the JIT modules are built with GPU_ARCHS pinned to gfx950. The op test skips on non-gfx950.
  • Selection in fused_moe: the NVFP4 path is taken only for q_dtype_w == fp4x2 with a global scale passed. Without global scales the existing fp4x2 (MXFP4) path is unchanged. herd_topk with global scales raises ValueError, and the shared-expert (FHMoE) path with global scales raises NotImplementedError.
  • Unsupported fused_moe options raise ValueError instead of falling back: expert_mask (EP), bias, doweight_stage1, a1_scale / a2_scale, num_local_tokens, hidden/intermediate padding, gate mode other than separated, activation other than SwiGLU, swiglu_limit other than 7.0, output dtype different from the input dtype, a missing global scale, unshuffled weights, and scales that are not 1-byte E4M3 in the shuffle_scale_nvfp4_moe layout.
  • Dtypes: weights packed E2M1 with E4M3 per-16 block scales and fp32 per-expert global multipliers; activations bf16 or f16 (anything else raises ValueError), output in the activation dtype.
  • Shapes (checked when the weights are wrapped): H and I multiples of 128, H / 128 even, I / 128 even or exactly 3. Per call: topk <= 127, T * H and T * topk * I below 2^30 elements (32-bit byte offsets), sorted blocks within the grid-y limit; otherwise ValueError.
  • Path: T * topk <= 4096 and E <= 512 use the fused sort; larger calls use AITER opus moe_sorting and the bf16-X stage-1 kernels.
  • Dispatch CSV: each row is validated at load (kernel name syntax and stage prefix; _inbf16 iff bf16 x on the fallback path, _outbf16 iff bf16 output). Kernel names are parsed with a round-trip canonical check, and each kernel config is checked at compile time by a static_assert.

Changed op tests

op_tests/test_moe_nvfp4.py (new): there was no NVFP4 MoE before, so no existing test covers it. It checks moe_nvfp4 and the fused_moe path against a dequantized fp32 reference on the MiniMax-M3.1 TP4 and TP8 shapes, T 1, 8, 64, 1024 (main path) and 2048 (fallback path), bf16 and f16; a dispatch CSV given through AITER_CONFIG_MOE_NVFP4 that names a kernel outside the prebuilt module (per-kernel JIT build); and 15 fused_moe argument combinations that must raise ValueError.

op_tests/test_fhmoe.py: the expected fused_moe parameter tail now includes the two new trailing arguments w1_global_scale and w2_global_scale; the test still checks that the existing positional order is unchanged.

Add moe_nvfp4 (aiter/ops/moe_nvfp4.py, JIT module module_moe_nvfp4):
NVFP4 weights (E2M1 + E4M3 per-16 block scale + per-expert global
multiplier) decoded to f16 in registers, f16 MFMA on bf16 activations
(no activation quant), SwiGLU-OAI.

- Three launches: fused sort + X cast + output zeroing, stage 1
  (gate/up + activation), stage 2 (down, weighted atomic reduce into bf16).
- Fallback for T * topk > 4096 or E > 512: AITER opus moe_sorting and
  stage-1 kernels that read bf16 X directly (same weights and scales).
- Kernel configs are encoded in the kernel name (parse_cfg in
  moe_nvfp4_common.h); per-T dispatch: in-source TP4 table for
  H 6144 / I 768 / E 128 plus aiter/configs/moe_nvfp4_dispatch.csv
  (override: AITER_CONFIG_MOE_NVFP4).
- No host sync, current stream, torch allocator: CUDA-graph capturable.

Signed-off-by: Sergei Shliapnikov <[email protected]>
@github-actions

github-actions Bot commented Nov 7, 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 7606 --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.

@sshlyapn
sshlyapn marked this pull request as ready for review November 10, 2026 14:07
@sshlyapn
sshlyapn requested a review from a team November 10, 2026 14:07
@aiter-bot

aiter-bot commented Nov 10, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 4a1fd85d63fc · 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. Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?
  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.

@sshlyapn
sshlyapn force-pushed the sshliapn/features/cdna4_nvfp4_moe branch 2 times, most recently from 9888684 to 4aed3b3 Compare November 10, 2026 14:34
@zufayu
zufayu requested a review from yzhou103 November 11, 2026 00:54
- Dispatch rows in aiter/configs/moe_nvfp4_dispatch.csv, keyed by cu_num, H, I,
  E, topk and dtypes (M3.1 rows); above the last row or without rows a shared
  default rule (aiter/jit/utils/moe_nvfp4_common.py, default_rows).
- Kernel name = kernel config: kernel_name / parse_kernel in Python;
  gen_instances.py writes the Cfg literals of the shipped CSV and default-rule
  kernels (prebuilt module, parallel build); a CSV kernel outside it is
  JIT-built in its own module on first use. C++ keeps cfg_valid (static_assert).
- fused_moe path for NVFP4 weights (w1/w2_global_scale); raises on options the
  kernels do not implement. Public API re-exported from aiter, private kernel
  ops called through the compile_ops wrappers, pybind in rocm_ops.hpp.
- f16 activations (f16 output) besides bf16; _inbf16 / _outbf16 kernels;
  input checks (dtype, H, topk <= 127).
- Scale preshuffle in shuffle.py (shuffle_scale_nvfp4_moe), weights via
  shuffle_weight; 32-row stage-1 kernel for the GS-4 scale layout; TP4 fallback
  dispatch row (T <= 16384); power-of-two T rows repeat the pair of the tuned
  bucket that covers them.
- Readability: Cfg fields named as the name tokens, named kernel info fields,
  named SwiGLU constants, keyword GEMM launches, refreshed comments.
- op_test vs a dequantized fp32 torch reference (moe_nvfp4, fused_moe, JIT CSV
  kernel, fused_moe errors), also run by `python3 <file>` as in CI; test_fhmoe
  expects the two new trailing fused_moe arguments.

Signed-off-by: Sergei Shliapnikov <[email protected]>
@sshlyapn
sshlyapn force-pushed the sshliapn/features/cdna4_nvfp4_moe branch from 4aed3b3 to 836f353 Compare November 11, 2026 06:37
@yzhou103

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.

a few small things..

ci green.

Comment thread aiter/ops/moe_nvfp4.py Resolved
Comment thread aiter/fused_moe.py Resolved
Comment thread aiter/ops/moe_nvfp4.py Resolved
Comment thread op_tests/test_moe_nvfp4.py Resolved
@yzhou103

Copy link
Copy Markdown
Contributor
  1. I have one question why you use fp16 instead of bf16 here?
  2. The FP16-output path can produce NaN from finite inputs even when the correct final result is representable in FP16.

In s2_epilogue, each expert’s weighted FP32 contribution is converted to FP16 before the cross-expert atomic reduction. Large positive and negative contributions can therefore overflow before they cancel.

I reproduced this on MI350X/gfx950 at head 836f353, using the PR’s unmodified sort, stage1, and stage2 kernels:

  • Shape: T=1, H=6144, I=384, E=2, topk=2.
  • FP16 input activations are all 1. Gate/up weights, block scales, and gate/up global multipliers are all 1.
  • Stage1 produces finite FP16 intermediates of exactly 56.
  • Down weights are +1 and -1 for the two experts, with global multipliers 8 and routing weights 0.5.

The weighted contributions are:

+56 × 384 × 8 × 0.5 = +86016
-56 × 384 × 8 × 0.5 = -86016

FP32 reduction → FP16: 0
Current FP16 conversion → reduction: +Inf + -Inf = NaN

All 6144 outputs were NaN in each of 20 runs. Normal-value controls passed. The existing BF16-output variant returned zero in all 20 runs; it still uses FP16 GEMM, so this isolates the output conversion/reduction issue.

Please accumulate the expert contributions in FP32 and cast once after reduction, and add this cancellation case as a regression.

f16 atomics overflow to inf on partial expert sums that cancel in the
final result (inf - inf = NaN). For f16 x, stage 2 now adds f32 pairs
into a zeroed f32 workspace, cast to the f16 output once. bf16 output
kernels are unchanged (ISA-identical). Adds the cancellation case as a
regression test.

Signed-off-by: Sergei Shliapnikov <[email protected]>
Stage-2 kernels with the new Cfg::reduce (_reduce names, any output dtype)
store each weighted (token, slot) row with plain f32 stores to a [T * topk, H]
workspace (no zeroing, no atomics); moe_nvfp4_reduce sums the topk rows of a
token in slot order and rounds to bf16 / f16 once (deterministic). The sort
zeroes the f32 atomics workspace of f16 output itself (out may be fp32 [T, H])
instead of a separate torch.zeros.

The dispatch CSV selects the sum per row: bf16 keeps atomics on every row
(_reduce 1.02-1.25x of them); new f16 rows (TP4 / TP8, same tiles as bf16)
take _reduce where it is >1% faster (TP8 T >= 256: 0.53-0.91x, TP4 T >= 512:
0.72-0.94x), f32 atomics below. Default rule: f16 output takes _reduce above
T 8.

Signed-off-by: Sergei Shliapnikov <[email protected]>
Comment thread csrc/include/rocm_ops.hpp Resolved
Comment thread aiter/ops/moe_nvfp4_common.py Resolved
Comment thread aiter/configs/moe_nvfp4_dispatch.csv Resolved
…row checks

- Native interface on the ctypes C ABI (ffi_type="ctypes", aiter_tensor_t,
  explicit stream, aiter_get_last_error): sort, reduce and GEMM launches and the
  kernel-table queries (lookup by name). Per-kernel JIT modules bind the same
  entries. Drops moe_nvfp4_pybind.cu, moe_nvfp4.h and the rocm_ops.hpp macro.
- Dispatch policy (uses_fallback, default rule, tuned CSV reader) moves to
  aiter/ops/moe_nvfp4_dispatch.py; moe_nvfp4_common.py keeps kernel names,
  scale layouts and sort limits.
- moe_nvfp4_dispatch.csv: tuned_fmoe column names (token, model_dim, inter_dim,
  expert, dtype, kernelName1/2) and measured us/us1/us2/err1/err2/tflops/bw;
  AITER_CONFIG_MOE_NVFP4 in jit/core.py.
- Tuned rows are checked against their shape (same BM per stage, scale GS of
  the stage K, N group, K fit); arch check via get_gfx_runtime(); fused_moe
  raises ValueError for global scales with non-fp4x2 weights or another gate
  mode.
- Tests: E 640 fallback, bad CSV rows, fp8 w1 with global scales.

Signed-off-by: Sergei Shliapnikov <[email protected]>
PREBUILD_KERNELS with AITER_ENABLE_EXPERIMENTAL=1 and GPU_ARCHS="gfx942;gfx950"
failed on the gfx950-only builtins. The GEMM kernel body is now compiled for
gfx950 only (moe_nvfp4 rejects other archs before any launch); the gfx950 ISA
is unchanged.

Signed-off-by: Sergei Shliapnikov <[email protected]>
@sshlyapn

Copy link
Copy Markdown
Contributor Author

@yzhou103 thank you for the review, all addressed in b03463e, e329514 and 33226e3.

  • FP16: with f16 output, stage 2 now accumulates the expert contributions in f32 and casts to f16 once, after the reduction. It uses either f32 atomics or a deterministic top-k reduce kernel, picked per shape by tuning: for the tuned MiniMax-M3.1 shapes the reduce kernel takes over above T 128 (TP8) and T 256 (TP4); for untuned shapes the default rule uses it above T 8. The internal GEMMs stay f16 and the bf16 path is unchanged. test_cancellation covers two contributions of +-86016 that cancel to 0 (bf16 / f16, main / fallback path, atomics / reduce).
  • ctypes: the op uses the existing ctypes C ABI (ffi_type="ctypes", aiter_tensor_t, aiter_get_last_error). The pybind file, moe_nvfp4.h and the rocm_ops.hpp macro are removed.
  • File organization: the dispatch policy moved to aiter/ops/moe_nvfp4_dispatch.py.
  • CSV: tuned_fmoe column names and measured metrics.
  • Multi-arch build: 6c9f589 limits the GEMM kernel body to #if defined(__gfx950__), so a PREBUILD_KERNELS install with AITER_ENABLE_EXPERIMENTAL=1 and GPU_ARCHS="gfx942;gfx950" now builds the module. Before, the gfx942 pass failed on the gfx950-only builtins. The gfx950 ISA is unchanged.
  • Tests: op_tests/test_moe_nvfp4.py 68 passed. In test_fhmoe.py, 118 passed and 1 failed; the failure (test_fhmoe_aot_cache_is_retrievable_in_run_only_mode) comes from our local FlyDSL version and fails the same way on the previous head.

@sshlyapn
sshlyapn force-pushed the sshliapn/features/cdna4_nvfp4_moe branch from 9dbd390 to 6c9f589 Compare November 13, 2026 08:24
Resolve aiter/jit/core.py: keep both AITER_CONFIG_FMOE_SWIGLU_LIMIT (main)
and AITER_CONFIG_MOE_NVFP4 (this PR).

Signed-off-by: Sergei Shliapnikov <[email protected]>
Lets a caller that owns the output (vLLM modular experts) skip a copy.
Same kernels and buffers; out must be a contiguous [T, H] tensor of the x
dtype and device.

Signed-off-by: Sergei Shliapnikov <[email protected]>
sshlyapn added a commit to sshlyapn/vllm_gpu that referenced this pull request Nov 15, 2026
On gfx950 with AITER moe_nvfp4 (ROCm/aiter#7606), the NVFP4 routed experts
of MiniMax-M3.1 checkpoints run on the AITER HIP kernels when no
--quantization-config.moe is given: the CompressedTensors NVFP4 MoE method
becomes MiniMaxM3NvFp4HipMoEMethod before weight loading (its backend
selection is skipped) and feeds the checkpoint weights to
aiter.ops.moe_nvfp4 for every T (no re-quantized copy, no modular kernel).
--quantization-config.moe mxfp4|mxfp8 keeps the online re-quantization;
other ROCm targets keep the error.

EP, fused shared experts, padded MoE sizes and other SwiGLU-OAI parameters
are rejected. The startup log notes that prefill (large T) may be slower
than with --quantization-config.moe mxfp4.

Signed-off-by: Sergei Shliapnikov <[email protected]>
sshlyapn added a commit to sshlyapn/vllm_gpu that referenced this pull request Nov 15, 2026
On gfx950 with AITER moe_nvfp4 (ROCm/aiter#7606), the NVFP4 routed experts
of MiniMax-M3.1 checkpoints run on the AITER HIP kernels when no
--quantization-config.moe is given: the CompressedTensors NVFP4 MoE method
becomes MiniMaxM3NvFp4HipMoEMethod before weight loading (its backend
selection is skipped) and feeds the checkpoint weights to
aiter.ops.moe_nvfp4 for every T (no re-quantized copy, no modular kernel).
--quantization-config.moe mxfp4|mxfp8 keeps the online re-quantization;
other ROCm targets keep the error.

EP, fused shared experts, padded MoE sizes and other SwiGLU-OAI parameters
are rejected. The startup log notes that prefill (large T) may be slower
than with --quantization-config.moe mxfp4.

Signed-off-by: Sergei Shliapnikov <[email protected]>
Resolve aiter/fused_moe.py and op_tests/test_fhmoe.py: keep both the deterministic argument (main) and w1_global_scale / w2_global_scale (this PR), with deterministic first so main's positional order is unchanged.

Signed-off-by: Andrei Kochin <[email protected]>
Co-authored-by: Cursor <[email protected]>
Comment thread aiter/configs/tuned_moe_nvfp4.csv Resolved
Comment thread aiter/ops/moe_nvfp4_common.py Resolved
@yzhou103

Copy link
Copy Markdown
Contributor
  1. aiter/ops/moe_nvfp4.py — global-scale validation

Please validate the shapes and devices of g13 and g2 before accepting the weights. .float().contiguous() does not enforce their documented [E, 2] / [E] shapes or ensure they are on the weights’ device.

At a24c873, I confirmed that the constructor accepts a one-element g13 or g2 with E=2, and CPU scales alongside GPU weights. The kernels subsequently read g13[2e], g13[2e+1], and g2[e], while the raw GEMM entry only checks contiguous FP32.

Please add the necessary validation at the Python and raw entry points, with negative tests confirming rejection before launch. This reproduction checked constructor acceptance only; malformed buffers were not launched.

  1. op_tests/test_moe_nvfp4.py — architecture gate and op-test structure

Please use get_gfx_runtime() with a GPU-availability guard for this test. get_gfx() follows the build targets in GPU_ARCHS, so their ordering can silently disable coverage on a supported GPU.

On an actual gfx950 device, I ran:

GPU_ARCHS="gfx950;gfx942" python3 op_tests/test_moe_nvfp4.py

The result was 80 skipped, exit code 0. The script already has a working pytest entry point; the architecture gate is what removes the coverage here.

Please also align the numerical/performance tests with the current aiter-op-test conventions: @benchmark, a candidate loop using run_perftest, asserted FP32 checkAllclose or similarly justified per-row/per-element checks, and a summary table containing latency, throughput, and error. The current global relative norm can hide localized errors. Keep the existing negative and cancellation regressions; the full tuner can still be added separately.

Follow the tuned_<op>.csv naming of the other configs. The env var
AITER_CONFIG_MOE_NVFP4 and the CSV columns are unchanged.

Signed-off-by: Sergei Shliapnikov <[email protected]>
Keep the NVFP4 MoE helpers next to the op (moe_nvfp4.py,
moe_nvfp4_dispatch.py). The module stays torch-free; gen_instances.py
loads it and the dispatch module by file path and registers them in
sys.modules (aiter/ops on sys.path would shadow triton with
aiter/ops/triton). Generated instance files are unchanged.

Signed-off-by: Sergei Shliapnikov <[email protected]>
The kernels index the weights, block scales and global scales by expert
id, so tensors of another shape or device read out of bounds.
NvFp4MoeWeights now checks all six tensors (one layer of E experts,
1-byte weights and scales, float g13 [E, 2] / g2 [E], all on the w13
device; shuffled scales by their shuffled size), moe_nvfp4 checks x /
topk_ids / topk_w shapes and device, and the raw ctypes entries check
w / w_sc / inv_gs against w's expert count and the stage, x / out sizes
and that every tensor is on one GPU. fused_moe reuses the weight checks.
Negative tests cover each case.

Signed-off-by: Sergei Shliapnikov <[email protected]>
…rch, add the benchmark

- Gate on get_gfx_runtime() (the live GPU) instead of get_gfx(), which
  follows GPU_ARCHS and skipped every test under GPU_ARCHS="gfx950;gfx942".
- Replace the global relative Frobenius error with an asserted fp32
  checkAllclose of every element, both sides divided by the reference row
  RMS; atol per output dtype, 2x / 5x the measured worst element.
- Add the aiter-op-test benchmark (test_moe_nvfp4_benchmark: moe_nvfp4 and
  fused_moe, us / TFLOPS / TB/s / err) and main(): the tests, then an
  argparse sweep printed as a markdown table.

Signed-off-by: Sergei Shliapnikov <[email protected]>
@sshlyapn

Copy link
Copy Markdown
Contributor Author

@yzhou103 thanks for the comments. Both points are fixed:

1. Global-scale validation (5c79e6c). You were right: g13 / g2 shapes and devices were not checked, and the raw entry only checked contiguous fp32. I extended the check to every tensor the kernels index by expert id, and to the inputs.

  • NvFp4MoeWeights: new _check_layer runs before any derived size is used. It requires w13 [E, 2I, H/2], sc13 [E, 2I, H/16], w2 [E, H, I/2], sc2 [E, H, I/16] (1-byte dtypes), g13 [E, 2] and g2 [E] (floating), all on the w13 device. Shuffled scales (shuffled=True) must have the shuffle_scale_nvfp4_moe size (K/16 padded to 16) with E leading. Any mismatch raises ValueError before launch.
  • moe_nvfp4: x [T, H], topk_ids and topk_w [T, topk], all on the weights device; otherwise ValueError.
  • fused_moe NVFP4 path: requires w1/w2_scale and both global scales, and routes them through the same check (the duplicate scale-size check is gone).
  • Raw ctypes entries (moe_nvfp4.cu): the GEMM entry now checks w [E, ntiles*16, K/2] 1-byte, the w_sc shuffled size for that E, inv_gs contiguous fp32 with E*2 (stage 1) or E (stage 2) elements, and the x / out sizes against T, topk, K and n_out. The sort, reduce and GEMM entries also require every tensor on one GPU (a CPU tensor is rejected). All raise RuntimeError before launch.
  • Negative tests: test_bad_layer (12 malformed layers incl. your one-element g13 / g2 and CPU scales, raw and shuffled scales: 24 cases), test_bad_inputs (6), test_gemm_entry_errors (7 raw-entry cases: wrong-stage w / w_sc, inv_gs [1, 1] and [E] for stage 1, short x / out, CPU inv_gs), plus 2 new fused_moe cases (global scale shape, CPU global scale).

2. Architecture gate and op-test structure (770b6db).

  • Gate: get_gfx_runtime() with a torch.cuda.is_available() guard (_is_gfx950, as in test_gemm_a6w4.py), no more get_gfx(). On our gfx950 with GPU_ARCHS="gfx950;gfx942", get_gfx() returns gfx942 and get_gfx_runtime() returns gfx950, which explains your 80 skips. Your exact command now runs all tests (results below).
  • Accuracy: the global relative norm is gone. Every accuracy test now asserts fp32 checkAllclose(...) == 0 per element. Both the output and the fp32 reference are divided by the reference row RMS first. The rounding error of a row scales with its magnitude, and a single wrong element, row or expert still fails. rtol 1e-2; atol 0.04 for bf16 and 0.004 for f16. I measured the worst element over all TP4 / TP8, T 1..2048 and E 640 cases at 0.019 (bf16: output rounding plus bf16 top-k atomics) and 0.0008 (f16) of the row RMS, so the tolerances are 2x and 5x that.
  • Benchmark: test_moe_nvfp4_benchmark (@benchmark, __test__ = False) times two candidates with run_perftest: moe_nvfp4 (the call vLLM makes) and fused_moe. Each output is checked as above. It reports us / TFLOPS / TB/s / err per candidate plus gfx. flops / bytes use the test_moe_2stage formula (x, out, and the NVFP4 weights + scales of at most T*topk experts).
  • Script entry: python3 op_tests/test_moe_nvfp4.py runs pytest first, then the sweep. Axes are -d, -dim (model_dim,inter_dim), -t, -e, -k; defaults are bf16, TP4 + TP8, T 1..2048, E 128, topk 4. Results print as a markdown table.
  • Kept: the caller-out, E 640, reduce, cancellation, JIT CSV, bad CSV row and fused_moe error regressions are unchanged apart from the accuracy check.
  • Not in this PR: the full tuner, as you suggested.

Tests run (MI355X, gfx950, AITER image of this branch, fresh JIT dir):

  • python3 -m pytest -q op_tests/test_moe_nvfp4.py -k 'bad_layer or bad_inputs or gemm_entry or fused_moe_errors or cancellation' on 5c79e6c: 70 passed.
  • python3 op_tests/test_moe_nvfp4.py on 770b6db: 110 passed, 0 skipped.
  • GPU_ARCHS="gfx950;gfx942" python3 op_tests/test_moe_nvfp4.py on 770b6db (your command): 110 passed, 0 skipped, exit 0, followed by the default sweep below.
  • black and ruff 0.16.0 clean.

andrei-kochin and others added 2 commits November 18, 2026 17:45
Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	aiter/ops/shuffle.py
main (ROCm#8075) routes fused_moe through the kernel plugin interface at
version 1 and records that signature in tests/plugin_contracts.json. This
PR adds w1_global_scale / w2_global_scale to it, so the contract gate
failed after the merge ("signature of fused_moe changed without an
op_version bump").

- fused_moe_ route: version=2. v1 is not superseded: a v1 provider cannot
  bind the two new arguments (the arity check rejects it), and a *args
  forwarder that binds them would serve an NVFP4 call as MXFP4.
- Routed docstring documents the two arguments for providers.
- tests/plugin_contracts.json: fused_moe entry regenerated with the gate's
  own routed_contracts() (new signature, fingerprint, version 2).
- test_plugin_routed_ops.py: _serve declares the version the op is routed
  at instead of 1, so the fused_moe cases are still served under v2.

Signed-off-by: Andrei Kochin <[email protected]>
Co-authored-by: Cursor <[email protected]>
@yzhou103
yzhou103 merged commit a3d077b into ROCm:main Nov 19, 2026
ZLkanyo009 added a commit that referenced this pull request Nov 19, 2026
…r the plan cache

aiter/fused_moe.py conflicted with #7606 (a3d077b, NVFP4 routed-expert
MoE for gfx950), and #8178 (a53213d) changed it too.

- #7606 adds w1_global_scale / w2_global_scale and passes has_global_scale
  to get_2stage_cfgs, which then selects the NVFP4 full_impl. The conflict
  was in that call: this branch records it as cfg_args / cfg_kwargs for the
  plan, so has_global_scale goes into cfg_kwargs. A call with either global
  scale neither reads nor stores a plan: the scales are not in the plan key,
  and a cached fp8 plan would otherwise skip the check that global scales
  need fp4x2 weights. NVFP4 calls return through full_impl before a plan
  could be stored anyway.
- #8178 moves the CK swiglu_limit checks after the gfx942 FlyDSL backend,
  inside get_2stage_cfgs. A plan hit calls get_2stage_cfgs with the recorded
  arguments (swiglu_limit included) every time, and a full_impl stores no
  plan, so the new order applies to every call. Merged without changes.

New op test checks: an fp8 plan does not serve a call with global scales;
NVFP4 calls reach the full_impl (stubbed) on every eager call and store no
plan; swiglu_limit calls resolve every time where a backend takes them, and
an error raised by get_2stage_cfgs reaches a plan hit.
andrei-kochin added a commit to sshlyapn/aiter that referenced this pull request Nov 19, 2026
Conflict in aiter/fused_moe.py (_fused_moe_impl): main (ROCm#7606, NVFP4 MoE) added a w1_global_scale/w2_global_scale validity check inside the inlined quant-dtype resolution, which this branch moved into _resolve_quant_dtypes. Kept the shared _resolve_quant_dtypes call and placed main's NVFP4 check just before it (using w1.dtype), so it still runs ahead of resolve_activation_dtype as on main. fused_moe_router passes no global scales and stays MXFP4-only.

Signed-off-by: Andrei Kochin <[email protected]>
Co-authored-by: Cursor <[email protected]>
sshlyapn added a commit to sshlyapn/vllm_gpu that referenced this pull request Nov 24, 2026
On gfx950 with AITER moe_nvfp4 (ROCm/aiter#7606), the NVFP4 routed experts
of MiniMax-M3.1 checkpoints run on the AITER HIP kernels when no
--quantization-config.moe is given: the CompressedTensors NVFP4 MoE method
becomes MiniMaxM3NvFp4HipMoEMethod before weight loading (its backend
selection is skipped) and feeds the checkpoint weights to
aiter.ops.moe_nvfp4 for every T (no re-quantized copy, no modular kernel).
--quantization-config.moe mxfp4|mxfp8 keeps the online re-quantization;
other ROCm targets keep the error.

EP, fused shared experts, padded MoE sizes and other SwiGLU-OAI parameters
are rejected. The startup log notes that prefill (large T) may be slower
than with --quantization-config.moe mxfp4.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants