Repository navigation
[HIP] [CK] [FlyDSL] Low-M MXFP4 fused-MoE: padded-row launch bound, SiTUv2 stage1 fusion, BM16 inline-sort - #5300
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags & labels: |
70f4498 to
c3395cd
Compare
1530999 to
05421b2
Compare
There was a problem hiding this comment.
🟡 Changes recommended
The review found a confirmed scale-padding bound bug risk and a new unsafe eval() on CSV data that should be tightened before merge.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
This PR optimizes low-M (decode-shaped) MXFP4 fused-MoE on HIP by reducing wasted frontend work and enabling SiTUv2 + BM16 inline-sort paths through metadata-driven dispatch and new kernel variants.
Changes:
- Add a distribution-independent padded-row upper bound to cap MoE quant/sort launch extent (new bounded entry point; legacy behavior preserved when omitted).
- Fuse SiTUv2 activation into the mxmoe-port stage1 epilogue and thread activation into AOT job keys / kernel compilation.
- Enable BM16 inline-sort two-stage selection via tuned metadata + runtime capability checks; expand tuning candidate space (XCD swizzle sweep) and update Kimi-K3 tuned rows.
File summaries
| File | Description |
|---|---|
| csrc/kernels/quant_kernels.cu | Adds bounded launch variant for fused dynamic MX quant + MoE sort to reduce empty workgroups on low-M. |
| csrc/kernels/mxfp4_moe/moe_mxfp4_aux.cu | Adds internal “is supported” probe for codegen’d aux sort instances. |
| csrc/kernels/mxfp4_moe/moe_aux/codegen/gen_instances.py | Adds Kimi-K3 shape tuple for aux instance generation. |
| csrc/include/rocm_ops.hpp | Exposes new bounded quant+sort op and internal aux-support probe to Python via pybind. |
| csrc/include/quant.h | Adds constexpr padded-rows upper-bound helper and declares new bounded API. |
| csrc/include/moe_mxfp4_aux.h | Declares internal aux sort capability probe. |
| csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py | Sweeps additional stage1 variants (XCD swizzle) and augments candidate reporting (tflops/bw, error formatting). |
| aiter/ops/quant.py | Plumbs num_experts_upper_bound through fused quant+sort wrappers and calls bounded kernel when provided. |
| aiter/ops/moe_mxfp4_aux.py | Adds Python wrapper for the internal aux sort capability probe. |
| aiter/ops/flydsl/mxfp4_gemm1_kernels.py | Threads activation/betas into stage1 wrapper and kernel compilation selection. |
| aiter/ops/flydsl/kernels/mxfp4_gemm1.py | Implements SiTUv2 activation in stage1 epilogue and adds activation to kernel name keying. |
| aiter/ops/flydsl/kernels/mxfp4_gemm_common.py | Fixes scale-stride math to round up (padded scale columns) for non-256-aligned cases. |
| aiter/fused_moe.py | Adds inline-sort dispatch gating, capability checks, and threads expert-count bound to quant+sort. |
| aiter/configs/model_configs/kimik3_a4w4_tuned_fmoe.csv | Updates tuned rows to use mxmoe-port BM16 inline-quant variants for low token counts. |
| aiter/aot/flydsl/mxfp4_moe.py | Adds activation to AOT job keys and compiles stage1 with SiTUv2 support. |
Review details
- Files reviewed: 15/15 changed files
- Comments generated: 4
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
There was a problem hiding this comment.
🟡 Changes recommended
The updated tuner code stores err1/err2 as formatted strings (and also uses eval() for dtype parsing), which breaks later numeric formatting/metrics paths and introduces an avoidable code-execution risk.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (1)
csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py:6302
- Using
eval()on CSV-provided dtype fields allows arbitrary code execution if the tuned CSV is ever untrusted (and it’s unnecessary here). Prefer a safe parse oftorch.<dtype>strings viagetattr(torch, ...)and fall back to the original value when it’s already a dtype object.
key = tuple(
eval(row[col]) if col in self.DTYPE_KEYS else row[col] for col in self.keys
)
- Files reviewed: 15/15 changed files
- Comments generated: 1
- Review effort level: Lite
25cad76 to
b075ab1
Compare
There was a problem hiding this comment.
🟡 Changes recommended
A few new/expanded dispatch paths accept invalid inputs (e.g., zero expert bound or non-positive SiTUv2 betas) that can silently produce wrong results or NaNs unless validated.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
- Files reviewed: 15/15 changed files
- Comments generated: 3
- Review effort level: Lite
There was a problem hiding this comment.
🔵 Needs a closer look
It changes GPU kernel behavior, dispatch/fallback logic, and tuning/AOT keying across multiple layers, which warrants final human review for correctness and performance regression risk.
Review details
- Files reviewed: 15/15 changed files
- Comments generated: 0 new
- Review effort level: Lite
…/sort For R = M * topk route slots over E experts and sort block BM, writing each positive per-expert row count as c_i = 1 + x_i gives sum(ceil(c_i / BM)) = a + sum(floor(x_i / BM)) <= a + floor((R - a) / BM), which is non-decreasing in both a and R. So with A = min(E, R) occupied blocks, BM * (A + floor((R - A) / BM)) upper-bounds the padded sorted rows regardless of how the routing is distributed, and still holds when routes are dropped as invalid. fused_dynamic_mx_quant_moe_sort_hip_bounded launches min(legacy_extent, padded_row_bound) workgroups, so a caller that supplies a trustworthy host-side expert bound can only shrink the grid, never grow it. Callers that omit the bound keep the legacy extent; buffer allocation, layout and ABI are unchanged. At M=1, E=896, BM=32 roughly 98% of the legacy workgroups were empty. Co-Authored-By: Claude Opus 5 <[email protected]>
Decode-shaped fused-MoE calls (M <= 64, one graph replay per token step) are latency bound. The generic MXFP4 two-stage path runs five kernels and pays an E-wide sort at block_m=32 whose cost does not shrink with M. For small M the sort is still worth doing, but at block_m=16 and with activation quantization folded into stage1, which collapses the frontend to a single fused sort/zero kernel: three kernels per call instead of five. At E=896, topk=16 and M=64 the 1024 routes spread over 618 active experts, so ceil(c_i/BM) = 1 for BM=16 and BM=32 alike -- the same block count with half the GEMM row work. Weight re-reads only begin once some expert exceeds BM rows, so whether BM16 wins for a given shape is a tuning question, not a fixed threshold. Selection is driven purely by tuned-config metadata (run_1stage=0, flat=0, output_aux, fuse_quant=fp4, an inline_quant stage1 name, and a stage2 whose sort_block_m matches stage1 BM). There is no path registry, no CSV path column, no model-name dispatch and no M-threshold environment variable. The checks run twice: _is_mxfp4_inline_sort against the tuned metadata in get_2stage_cfgs, and _mxfp4_inline_sort_unsupported against the actual call in _fused_moe_impl for what the lookup key cannot see. Neither ever raises -- an invocation the fast path cannot serve re-resolves metadata with that family disabled and falls back to legacy. Co-Authored-By: Claude Opus 5 <[email protected]>
Mxfp4FlydslTuner now enumerates both stage1 XCD swizzles, which is worth about 1% once the padded rows span enough blocks, and writes err1/err2 as percent strings to match every other tuned config in the tree. It also fills in tflops/bw, which it previously left at 0: the stage1/stage2 pair is timed as one unit, so the whole-fused-MoE estimate calculate() already produces is the right roofline for it. Re-tuned the Kimi-K3 A4W4 SiTUv2 token=1..64 rows in that candidate space; all of them now select the BM16 inline-sort pair. Measured on gfx950 / MI355X against the previous tuned rows, under HIP Graph, 9 alternating AB/BA rounds of 300 replays over 7 route distributions: geomean 1.139x across 77 scenarios, worst 1.026x, no regression. Cosine similarity against a BF16 oracle is unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
Mxfp4FlydslTuner mapped every non-Swiglu act_type to ActivationType.Silu and never passed `act` to _mxfp4_a4w4_stage1_fw, so SiTUv2 rows were timed and validated against the silu stage1 while production dispatches the situv2 one. The recorded us/err then describe a kernel that never runs. Parse Situv2 out of act_type, derive the stage1 `act` from it, and thread it through both _port_e2e call sites -- the correctness check and the perftest lambda must exercise the same variant. The betas are passed explicitly because _mxfp4_a4w4_stage1_fw defaults them to 1.0 while run_torch_moe_stage1 defaults to 4.0/25.0; leaving them out would make every candidate fail the cosine gate. Swiglu keeps mapping to a silu stage1, so such rows still fail the gate rather than tuning a kernel that cannot emit them. Selection is unaffected: situv2's extra epilogue cost scales with padded rows, so it penalises BM32 roughly twice as hard as BM16, and the silu timings were already conservative for the shipped BM16 rows. The tuned CSV keeps its silu-derived numbers until a re-tune. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Reject incompatible tuned metadata before aux dispatch and parse tuner types without evaluating CSV input.
Three input-validation gaps found in review: - fused_dynamic_mx_quant_moe_sort_hip_bounded accepted num_experts_upper_bound == 0, which clamps the launch extent to 0 and leaves the output scale buffer uninitialized instead of erroring. - flydsl_mxfp4_gemm1 accepted non-positive SiTUv2 betas; the stage1 epilogue takes their reciprocals and produces inf/NaN. The three sibling FlyDSL entrypoints already validate this. - _padded_scale_cols floored the group count, under-reporting the expected e8m0 scale width for sizes not divisible by the group size. Now matches the allocator in aiter/ops/quant.py. Co-Authored-By: Claude Opus 5 <[email protected]>
_is_inline_sort_kname only inspects stage1, so the incomplete-metadata discard also fired on tuned rows that pair an inline-quant mxmoe stage1 with a plain mxmoe stage2. Those belong to the mxmoe dispatcher, not to the inline-sort two-stage path, and discarding them dropped 36 shipped GLM5/Kimi-K2 rows onto the heuristic FlyDSL fallback, which has no AOT cache and fails test_moe_2stage under FLYDSL_RUNTIME_RUN_ONLY=1. Match on the kernel pair instead: a row targets this path only when its stage2 also parses as a FlyDSL v2 gemm2. Co-Authored-By: Claude Opus 5 <[email protected]>
Allow ATOM's uint8-backed E8M0 scales to use the validated BM16 fast path without weakening layout checks.
c49768e to
ed1f8a1
Compare
Fall back before dispatch when stage2 bias, expert parallelism, or a mismatched activation makes the tuned inline-sort row unsafe.
Refresh the existing low-token winners and metrics using the production SiTUv2 activation and beta values.
There was a problem hiding this comment.
🔵 Needs a closer look
It changes multiple performance-critical GPU kernel paths and dispatch/fallback logic (including kernel ABI and tuning/config selection), which requires final human review with targeted correctness/perf validation.
Review details
- Files reviewed: 15/15 changed files
- Comments generated: 0 new
- Review effort level: Lite
Preserve the exact-config contract when an inline-sort row is discarded and avoid promising a heuristic fallback in diagnostics.
There was a problem hiding this comment.
🔵 Needs a closer look
The new shared HIP launcher computes topk via division by token_num without validating token_num > 0, which can crash on empty-batch/malformed invocations.
Review details
Suppressed comments (1)
csrc/kernels/quant_kernels.cu:1951
fused_dynamic_mx_quant_moe_sort_hip_implderivestopkviainput.numel() / (cols * token_num)without validatingtoken_num(orcols) first. If an empty batch or malformed call passestoken_num==0, this is a division-by-zero and will crash before any grid-size checks.
int cols = input.size(-1);
int topk = input.numel() / (cols * token_num);
int num_experts = (sorted_ids.size(0) + topk - topk * token_num) / block_m;
- Files reviewed: 15/15 changed files
- Comments generated: 0 new
- Review effort level: Lite
Prints the co-residency inputs and the path actually taken, under AITER_MOE_ROUTING_VERBOSE. The envelope statement wants max_blocks_per_cu, the grid and the LDS request per token count, and whether a call ran fused or split is otherwise only inferable from its timing -- which is exactly the inference that makes an occupancy claim unfalsifiable. This is measurement scaffolding, not a feature. It is the tip commit so it can be dropped with one rebase before anything goes upstream. It is a print only: it selects nothing, so it does not touch ROCm#5300's rule that selection is metadata-driven. Co-Authored-By: Claude Opus 5 <[email protected]>
130 commits, no conflicts. Nine of them touch aiter/fused_moe.py, including the MXFP4 fused-MoE work in ROCm#5300, ROCm#4526 and ROCm#4985, so the three things this guard rests on were re-checked against the merge result: * tuned_fmoe.csv still carries no mxfp4 row with a non-256-aligned inter_dim, so the tuned path cannot hand an affected shape to CK-Tile behind the guard. * The CK-Tile stage-2 scale indexing is still unfixed (ROCm#5233 open), so the host-side guard is still needed. * Dispatch is unchanged: inter_dim 128/384/640 to FlyDSL, 192/320 and the 256-aligned values on CK-Tile, with _fused_moe_impl's validation firing on exactly the re-routed shapes.
Low-M MXFP4 fused-MoE: padded-row launch bound, SiTUv2 stage1 fusion, BM16 inline-sort
Motivation
Decode-shaped fused-MoE calls (
M <= 64, one HIP-Graph replay per token step) arelatency bound, not throughput bound. The generic MXFP4 two-stage path pays a fixed
cost that does not shrink with
M: anE-wide sort whose padded extent is dominatedby
E * block_m, and a quant launch grid sized for that extent.For Kimi-K3 A4W4 SiTUv2 (
E=896,topk=16,H=3584, TP8 localI=384) atM=1roughly 98% of the quant workgroups are empty, and the frontend (sort + zero + quant)
is a fixed ~8 us on top of ~12 us of GEMM.
This PR contains three independent, generic changes. Everything is driven by ordinary
tuned-config metadata: no path registry, no
pathCSV column, no model-name dispatch,no M-threshold environment variable.
1. Padded-row quant launch bound (all paths)
For
R = M * topkroute slots,A = min(E, R)occupied blocks and sort blockBM,writing each positive per-expert row count as
c_i = 1 + x_igiveswhich is non-decreasing in both
aandR, soBM * (A + floor((R - A) / BM))is adistribution-independent upper bound on padded sorted rows.
fused_dynamic_mx_quant_moe_sort_hip_boundedtakesmin(legacy_extent, bound), so acaller supplying a trustworthy host-side expert bound can only shrink the grid, never
grow it. Callers that omit the bound keep the legacy extent. Buffer allocation, layout
and ABI are unchanged.
moe_quant_padded_rows_upper_bound(csrc/include/quant.h), constexpr withstatic_asserts.
routing_num_expertsthreaded throughaiter/fused_moe.pyto the quant call sites.2. SiTUv2 fused into the mxmoe-port stage1 epilogue
The mxmoe-port stage1 (
flydsl_mxmoe_g1_a4w4_*) only implemented SiLU, so a SiTUv2model could only use the generic
flydsl_moe1_*family. Kimi-K3 A4W4 was on thatfamily, which has no BM16 inline-quant variant -- so §3 was unreachable for it, and
more generally for any SiTUv2 model.
Stage1 now takes the activation as a compile-time parameter:
tanhis evaluated assign(x) * (1 - exp2(-2*log2e*|x|)) / (1 + exp2(-2*log2e*|x|)),reusing the
exp2/rcptranscendentals the SiLU epilogue already issued, so it iscomputed in-register on the stage1 accumulators with no extra pass over the
intermediate.
betaandlinear_betaare runtime f32 kernel scalars, not compilekeys, so re-tuning betas does not recompile; the activation itself is a compile key and
is part of both the kernel name suffix and the stage1 AOT job key.
3. BM16 inline-sort two-stage (low
M)For small
Mthe sort is still worth doing, but atblock_m=16rather than 32, withactivation quantization folded into stage1 so the frontend collapses to a single fused
sort/zero kernel. Three kernels per call instead of five: fused sort/zero, BM16 stage1
with inline quant, BM16 atomic stage2.
At
M=64, 1024 routes spread over 618 active experts give a mean of 1.7 rows perexpert, so
ceil(c_i/BM) = 1forBM=16andBM=32alike: the same block count withhalf the GEMM row work. Weight re-reads only begin once some expert exceeds
BMrows.Selection is purely from metadata (
run_1stage=0,flat=0,output_aux,fuse_quant=fp4, aninline_quantstage1 name, and a stage2 whosesort_block_mmatches stage1
BM) —_is_mxfp4_inline_sort, no name allowlist.Stage1 inline quant re-quantizes the
BMrows of every block, so its cost grows withpadded rows while the saving (two frontend launches) is fixed. Whether it wins for a
given shape is a tuning question, not a fixed threshold.
Dispatch and fallback
Validated twice, and neither ever raises:
get_2stage_cfgs:_is_mxfp4_inline_sortinspects the tuned metadata(
run_1stage,flat,output_aux,fuse_quant, the stage1 inline-quant kernel nameand the matching stage2
sort_block_m). An inapplicable tuned row is dropped and thelookup falls through to the default heuristics.
_fused_moe_impl:_mxfp4_inline_sort_unsupportedchecks only whatthe lookup key cannot see -- gate mode, hidden / intermediate padding, EP, bias,
explicit activation scales, stage2 scatter, and whether a codegen'd BM16 aux instance
exists. If the selected fast row cannot run this invocation, metadata is re-resolved
with the fast path disabled.
Tuning
Both are candidates in the existing tuner, so a new model picks them up with no code
change:
Mxfp4FlydslTunernow also sweeps both stage1 XCD swizzles. The Kimi-K3 tuned configrows for
token=1..64were re-tuned in this candidate space; they move from theflydsl_moe1_*family toflydsl_mxmoe_g1_a4w4_16x256x256_f16in_nt[_xcd4].Measured result
Kimi-K3 A4W4 SiTUv2,
E=896,topk=16,H=3584, TP8 localI=384, BF16 in/out,MXFP4 per-1x32, gfx950 / MI355X. Compared against the same tree with the pre-existing
tuned rows, under HIP Graph, 9 alternating AB/BA rounds of 300 replays each, over 7
route distributions.
Overall geomean 1.139x over 77 scenarios, i.e. 12.2% end-to-end latency reduction
across the
M <= 64matrix, with no scenario below 1.026x. Cosine similarity againsta BF16 oracle is unchanged (0.9552 vs 0.9551 at
M=64).Follow-up (not in this PR)
A sortless
M == 1executor: atM == 1every route slot is a distinct(token, expert)pair, so binding one route per workgroup and accumulating into apre-zeroed output with atomics removes the sort entirely. That is a separate change
and will be sent as a stacked PR.
Verification
On gfx950 / MI355X: the bound is exact on small partitions and bounded quant matches
the legacy launch bit-for-bit; activation is part of the stage1 AOT cache key, so silu
and situv2 rows get distinct entries; the SiTUv2 BM16 graph output holds its cosine
similarity against a BF16 oracle; every AOT job for the shipped MXFP4
configs compiles (388/388); EP and unsupported invocations fall back to legacy instead
of raising.