Repository navigation
[HIP] [JIT] [MoE] NVFP4 routed-expert MoE for gfx950 - #7606
Conversation
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]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
WAITING ON AUTHORPR Self-ReviewRevision 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
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
9888684 to
4aed3b3
Compare
- 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]>
4aed3b3 to
836f353
Compare
|
@valar-cop review |
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:
The weighted contributions are: +56 × 384 × 8 × 0.5 = +86016 FP32 reduction → FP16: 0 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]>
…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]>
|
@yzhou103 thank you for the review, all addressed in b03463e, e329514 and 33226e3.
|
9dbd390 to
6c9f589
Compare
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]>
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]>
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]>
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.
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]>
|
@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.
2. Architecture gate and op-test structure (770b6db).
Tests run (MI355X, gfx950, AITER image of this branch, fresh JIT dir):
|
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]>
…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.
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]>
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]>
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:
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_fp4and 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:
Large batches. When T * topk > 4096 or E > 512, the op uses AITER opus
moe_sortingand 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_moeMXFP4 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:
Synthetic routing, NVFP4 / MXFP4 per layer:
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.csvships per-T kernel pairs for MiniMax-M3.1 (H 6144, E 128, top-4, bf16, 256 CUs):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.pyparses and canonicalizes it.Building. The prebuilt module
module_moe_nvfp4contains 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:
Through
fused_moe: pass fp4x2w1/w2in theshuffle_weight(w, (16, 32))layout, E4M3w1_scale/w2_scalein theshuffle_scale_nvfp4_moelayout (aiter/ops/shuffle.py), plus the neww1_global_scale/w2_global_scalearguments. Options the kernels do not implement raise aValueErrorinstead of silently falling back: EPexpert_mask, bias,doweight_stage1, prequantized activations, padding, non-SwiGLU activations,swiglu_limitother than 7.0,stage2_scatter, andherd_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:fused_moepath;AITER_CONFIG_MOE_NVFP4;fused_moeerror cases.ruff0.16.0 andblack26.3.0 are clean.Known limits
expert_mask), no bias, no activation quantization, SwiGLU-OAI only.PR Self-Review
Reviewed revision
836f353Behavior and intent
This PR adds a new op,
aiter.ops.moe_nvfp4(NvFp4MoeWeights,moe_nvfp4), and afused_moepath that is selected only when the weights are fp4x2 and the neww1_global_scale/w2_global_scalearguments are passed. Existing ops and all existingfused_moecalls (no global scales) behave as before; the only API change is the two new trailing optionalfused_moearguments.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.pyon one MI355X GPU: 51 passed, both aspython3 op_tests/test_moe_nvfp4.py(the CI entry point) andpython3 -m pytest -q, on836f353.op_tests/test_fhmoe.pyon836f353: 118 passed, includingtest_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 (JitFunctionhas no_compile_or_execute, used byaiter/aot/flydsl/replay.py, which this PR does not touch) and passes in CI.Unverified:
RuntimeError; no gfx942 or gfx1250 run.PR-specific question
prepare()checks the device arch and raisesRuntimeErroron any other arch before building or launching anything; the JIT modules are built withGPU_ARCHSpinned to gfx950. The op test skips on non-gfx950.fused_moe: the NVFP4 path is taken only forq_dtype_w == fp4x2with a global scale passed. Without global scales the existing fp4x2 (MXFP4) path is unchanged.herd_topkwith global scales raisesValueError, and the shared-expert (FHMoE) path with global scales raisesNotImplementedError.fused_moeoptions raiseValueErrorinstead 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_limitother 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 theshuffle_scale_nvfp4_moelayout.ValueError), output in the activation dtype.T * HandT * topk * Ibelow 2^30 elements (32-bit byte offsets), sorted blocks within the grid-y limit; otherwiseValueError.moe_sortingand the bf16-X stage-1 kernels._inbf16iff bf16 x on the fallback path,_outbf16iff bf16 output). Kernel names are parsed with a round-trip canonical check, and each kernel config is checked at compile time by astatic_assert.Changed op tests
op_tests/test_moe_nvfp4.py(new): there was no NVFP4 MoE before, so no existing test covers it. It checksmoe_nvfp4and thefused_moepath 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 throughAITER_CONFIG_MOE_NVFP4that names a kernel outside the prebuilt module (per-kernel JIT build); and 15fused_moeargument combinations that must raiseValueError.op_tests/test_fhmoe.py: the expectedfused_moeparameter tail now includes the two new trailing argumentsw1_global_scaleandw2_global_scale; the test still checks that the existing positional order is unchanged.