Skip to content

[FlyDSL] Fused online Hadamard rotation + MXFP4 quantization for dense and MoE stage-1 inputs (flydsl_rot_quant) - #4549

Merged
yadaish merged 7 commits into
ROCm:mainfrom
jiangyon-amd:flydsl-rot-quant
Nov 17, 2026
Merged

yadaish merged 7 commits into
ROCm:mainfrom
jiangyon-amd:flydsl-rot-quant

Conversation

@jiangyon-amd

@jiangyon-amd jiangyon-amd commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Update (2026-11-14): rebased onto current main (edf58c67a), which has the FlyDSL 0.5.0 pin and the #7653 fix. Seven commits:

  1. The op rewritten for the pinned FlyDSL and the in-repo review contract.
  2. One MXFP4 group per lane, which leaves the output unchanged and makes RS=64/128 faster.
  3. The MoE stage-1 variant.
  4. Fixes from a pre-review: API aligned with fused_dynamic_mxfp4_quant_moe_sort, padding slots of num_local_tokens sorts skipped, a device guard, and the mxfp4_moe_sort_fwd zeroes the last token's final scales when K // 32 is not a multiple of 4 (e.g. K=2880) #7646 workaround.
  5. Review follow-ups: the MoE scale padding columns follow fused_dynamic_mxfp4_quant_moe_sort (undefined), and the test runs in less time.
  6. The MoE fused/two-pass switch accounts for the mxfp4_moe_sort_fwd zeroes the last token's final scales when K // 32 is not a multiple of 4 (e.g. K=2880) #7646 padding: 1.27-1.68x faster at K=2880 for mid-size batches.
  7. [HIP] [Bugfix] mxfp4_moe_sort: keep the last row's tail scales when model_dim / 32 is not a multiple of 4 #7653 is in main, so the mxfp4_moe_sort_fwd zeroes the last token's final scales when K // 32 is not a multiple of 4 (e.g. K=2880) #7646 padding and its separate threshold are removed; one switch serves every K.

Kernel numbers are re-measured on this head and are unchanged under FlyDSL 0.5.0 (within 1.5%). End-to-end vLLM results for dense and MoE models are new.

Summary

Adds two gfx950 FlyDSL ops that rotate a bf16 activation by a block-diagonal normalized Sylvester Hadamard matrix (rotation_size ∈ {32, 64, 128}) and quantize it to MXFP4 in one pass. Scales use aiter's default RoundUp e8m0. The output equals per_1x32_f4_quant applied to the bf16-rounded rotated tensor.

  • aiter.ops.flydsl.flydsl_rot_quant(x, *, rotation_size=64, shuffle=False) covers the dense case. Its returns match per_1x32_f4_quant_hip (fp4x2, e8m0). With shuffle=True the scales are written straight into the CK layout that gemm_a4w4 consumes.
  • aiter.ops.flydsl.flydsl_rot_quant_moe_sort(x, sorted_ids, num_valid_ids, token_num, topk, block_size, *, rotation_size=64) produces the MoE stage-1 input. Its scales are already sorted by moe_sorting's sorted_ids. The leading arguments and the contract are those of fused_dynamic_mxfp4_quant_moe_sort on the rotated tensor, so the output can be passed as prequantized_a1 / prequantized_a1_scale to fused_moe_2stages.
from aiter.ops.flydsl import flydsl_rot_quant

xq, xs = flydsl_rot_quant(x, rotation_size=64, shuffle=True)
y = gemm_a4w4(xq, shuffle_weight(wq, layout=(16, 16)), xs, shuffle_scale(ws), dtype=torch.bfloat16)

Motivation

Rotated MXFP4 checkpoints, such as Quark's online R1 rotation (QuaRot/SpinQuant style), fold a Hadamard rotation into the weights of the attention qkv and MLP gate/up projections, including MoE experts. The activation of every rotated projection must therefore be rotated online before it is quantized. Without fusion that is a bf16 Hadamard matmul over HBM followed by a quant pass, which costs about +8% TPOT in serving (see End-to-end below). Which rotation size recovers the most accuracy depends on the model: in our runs Qwen3-8B does best with 64 and Qwen3-30B-A3B with 32. All three sizes come from one kernel template, so all three are kept.

Relation to the existing ops:

op sizes scale layout difference
per_1x32_f4_quant_hip(hadamard_rotate=True) (#6734) 32 row-major or CK Byte-identical to this op except in groups under its amax floor (it writes 0x5C for zero groups; this op and the torch reference write 0). This op is 1.14–1.15× faster (table below).
rotate_activation(out_fp4, x.view(-1, 128), scale) (DSv4, #3035) 128–1024, whole row row-major or a DSv4 head layout, not CK Rotates in fp32 without the bf16 rounding, so bytes differ slightly. Row-major at RS=128 it is 7–14% faster than this op for M ≤ 256 and 1.3–1.5× slower for M ≥ 1024. For gemm_a4w4 it needs a separate shuffle_scale.
fused_dynamic_mxfp4_quant_moe_sort no rotation sorted MoE layout The unrotated MoE quant-and-sort. flydsl_rot_quant_moe_sort keeps its contract and adds the rotation.
fused_quant_transpose_hadamard_mxfp4 (Triton, #6476) signed H16 — Training side; a different transform.

Changes

  • aiter/ops/flydsl/kernels/rot_quant.py (new): the dense op.
    • One thread owns one 32-element MXFP4 group. It runs the first five FWHT stages in registers, and the RS/32 adjacent lanes of a block finish the remaining stages with xor shuffles, so each scale stays local to its thread.
    • The scale is the shared quant_utils.emit_mx_e8m0_scale in RoundUp mode. At RS=64 the 1/8 normalization is applied to each group's amax and to the conversion exponent instead of to every element. This is exact for a power of two, and a NaN group still gets scale 255.
    • The CK scale scatter uses the same index split as the e8m0 write in silu_and_mul_fq.py. Its padding columns get 0x7F, as shuffle_scale writes them.
    • One wave per CTA and LLVM SLP vectorization off, both from sweeps on MI350X (see the comments in the code).
    • 49–60 VGPRs and no spills at every RS, for both ops.
  • MoE stage 1 (flydsl_rot_quant_moe_sort):
    • For small batches it is one kernel with a thread per (sorted row, group). Valid routes rotate and quantize their token's group and scatter the scale to the sorted row. As in fused_dynamic_mxfp4_quant_moe_sort, only the first K // 32 columns of valid-route rows are defined.
    • A route is valid when its token is below token_num and its slot below topk. This is the same rule as the HIP kernels: a sort with num_local_tokens pads with topk << 24 | count, which names a real token.
    • A token is quantized once per route, so past M * topk * K = 2^21 the op instead runs flydsl_rot_quant once followed by mxfp4_moe_sort_fwd. Over 600 measured points (K 2048-7168, every rotation size, topk 4 and 8) this switch picks a path within 5% of the faster one on 567, and is 0.9% slower than the faster path on average.
  • Both ops launch under the input's device.
  • aiter/ops/flydsl/__init__.py: lazy exports.
  • op_tests/test_flydsl_rot_quant.py (new): see Changed op tests.
  • No existing op, default or config changes behavior.

Performance (if applicable)

Kernel timings are on MI350X (gfx950) with CUDA graphs: 50 launches per replay, median of 30 replays.

Dense. K=4096, CK-layout scales. Before is the fastest existing aiter path for that size. For RS=64/128 that is a bf16 blockwise Hadamard matmul followed by per_1x32_f4_quant_hip(shuffle=True). For RS=32 it is the fused per_1x32_f4_quant_hip(hadamard_rotate=True, shuffle=True) from #6734.

Hardware Workload/configuration Before After Change
MI350X RS=64, M=1 5.65 µs 2.56 µs 2.21×
MI350X RS=64, M=32 5.96 µs 2.65 µs 2.25×
MI350X RS=64, M=256 7.73 µs 2.84 µs 2.72×
MI350X RS=64, M=1024 12.85 µs 3.73 µs 3.45×
MI350X RS=64, M=4096 30.14 µs 8.45 µs 3.57×
MI350X RS=64, M=16384 91.87 µs 28.50 µs (5.96 TB/s) 3.22×
MI350X RS=32 vs #6734, M=1 2.62 µs 2.29 µs 1.14×
MI350X RS=32 vs #6734, M=16384 31.83 µs 27.57 µs 1.15×
MI350X RS=128, M=1 5.82 µs 2.89 µs 2.01×
MI350X RS=128, M=16384 86.87 µs 31.33 µs 2.77×

MoE stage 1. E=128, topk=8, block 32. Before is a Hadamard matmul followed by fused_dynamic_mxfp4_quant_moe_sort. The unrotated quant-and-sort is listed for reference.

Hardware Workload/configuration Before After Change No rotation
MI350X K=2048 RS=128, M=1 6.04 µs 3.07 µs 1.97× 2.57 µs
MI350X K=2048 RS=128, M=32 7.62 µs 3.81 µs 2.00× 3.89 µs
MI350X K=2048 RS=128, M=256 11.17 µs 5.40 µs 2.07× 6.13 µs
MI350X K=2048 RS=128, M=4096 25.10 µs 8.79 µs 2.86× 7.82 µs
MI350X K=2048 RS=32, M=1 / 32 / 4096 5.80 / 7.28 / 21.29 µs 2.53 / 3.19 / 8.10 µs 2.29× / 2.28× / 2.63× 2.58 / 3.88 / 7.90 µs
MI350X K=4096 RS=64, M=1 / 64 / 4096 5.98 / 8.86 / 33.60 µs 2.82 / 6.33 / 12.68 µs 2.12× / 1.40× / 2.65× 2.60 / 4.44 / 12.06 µs

Across K ∈ {2048, 4096}, RS ∈ {32, 64, 128} and M from 1 to 4096, the MoE ratio is 1.29–2.86×. The weakest region is K=4096 around M=64.

End-to-end (vLLM serving, MI350X, TP=1)

These end-to-end numbers come from a local integration that is not part of this PR:

Protocol:

  • Load: random ISL=1024 / OSL=256, 200 prompts × 3 runs, median TPOT.
  • Baseline: each GPU measures its own RTN baseline (same model, no rotation).

Measured on the head before commit 4. Commit 4 does not change kernel timings: the MoE geomean is 1.00× and dense is within ±1%.

Each cell is the extra TPOT over RTN, in ms.

Qwen3-8B, c=4 / c=8 (RTN 3.96–3.97 / 4.29–4.34 ms) RS=32 RS=64 RS=128
separated: matmul + quant +0.33 / +0.37 +0.35 / +0.36 +0.38 / +0.40
this op +0.03 / +0.06 +0.06 / +0.04 +0.10 / +0.12
#6734 HIP fused rotation +0.05 / +0.09 — —
Gluon kernel from the ROCm fused-rotation blog no RS=32 +0.09 / +0.09 +0.27 / +0.28
Qwen3-30B-A3B, c=1 / c=8 / c=32 (RTN 4.44–4.47 / 5.24–5.28 / 6.86–6.98 ms) RS=32 RS=64 RS=128
separated +0.38 / +0.33 / +0.27 +0.42 / +0.42 / +0.30 +0.45 / +0.46 / +0.42
this op on dense layers only +0.16 / +0.17 / +0.10 +0.20 / +0.22 / +0.12 +0.23 / +0.30 / +0.25
this op on dense + MoE stage 1 +0.04 / −0.09 / −0.17 +0.07 / +0.03 / −0.11 +0.06 / +0.09 / −0.03

Notes on the MoE table:

  • The run-to-run spread is about ±0.03 ms at c=8 and up to ±0.1 ms at c=32.
  • The rotated MoE stage 1 is no slower than aiter's unrotated quant-and-sort (3.19 vs 3.88 µs at M=32, RS=32), which is why some cells are at or below RTN.

Accuracy: the fused and separated paths are statistically indistinguishable at every RS on both models. On wikitext-2 token-level PPL (145 windows of 2048 tokens, paired per-window NLL), every difference is under 1.1σ and the largest |ΔPPL| is 0.014.

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X — not applicable: gfx950-only (v_cvt_scalef32_pk_fp4_f32); the test skips other cards in main()
  • Tested on MI300X — not applicable, same reason

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

These are new ops, and there is no user-guide page for FlyDSL quant ops. Their contracts (math, layouts, padding, which rows are defined) are in the docstrings.

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

None.

PR Self-Review

Reviewed revision

9c7ae54

Behavior and intent

This adds two new ops and changes no existing behavior. Today a rotated MXFP4 linear or MoE stage 1 needs a separate Hadamard matmul over HBM before the quant, unless the rotation size is 32 and the layer is dense (#6734). flydsl_rot_quant does the rotation, MXFP4 quantization and the CK scale layout in one pass for rotation sizes 32/64/128, with the rounding contract of per_1x32_f4_quant. flydsl_rot_quant_moe_sort does the same for the MoE stage-1 input with the scale layout of fused_dynamic_mxfp4_quant_moe_sort. Rotated weights and the existing gemm_a4w4 / fused_moe kernels therefore work unchanged.

Validation and unverified scope

On MI350X with flydsl==0.5.0 at this head:

  • python op_tests/test_flydsl_rot_quant.py (defaults): 752 checks passed, 0 failed, exit 0, 34 s. fp4 bytes and e8m0 scales are compared with rtol=atol=0 against per_1x32_f4_quant, over:
    • rotation sizes 32/64/128 and both scale layouts, padding columns included;
    • M ∈ {1, 32, 300, 1024, 4096, 16384} and K ∈ {2880, 4096, 7168};
    • inputs with outlier channels, a zero row, a 1e-30 row and a NaN row.
  • Further checks in that run:
    • RS=32 against per_1x32_f4_quant_hip(hadamard_rotate=True);
    • gemm_a4w4 end to end at N ∈ {256, 4096};
    • the MoE op's fp4 bytes and sorted scales against the torch reference sorted in torch, for E=128, topk=8, every RS and K, and M up to 16384; block_m ∈ {16, 64} and sorts with num_local_tokens for M ≤ 1024. This exercises both the fused and the two-pass dispatch, including K=2880, where K // 32 is not a multiple of 4. A separate run at M=32768, K=2880 covers the scatter store of mxfp4_moe_sort_fwd.
  • By hand:
    • A cross-device call (input on the second GPU, current device the first) matches a same-device call byte for byte for both ops.
    • The dense output is byte-identical (0 of 396 cases differ) to the August revision of this PR.
    • black and ruff==0.16.0 are clean.
    • No VGPR spills at any rotation size.

Unverified or not covered:

  • gfx942/gfx1250 only reach the skip in main(); the ops raise there by design.
  • gemm_a4w4 is not used as a reference below N=256 (it is wrong there for any quantizer, rel. err 0.68 at N=128) or for K not a multiple of 256 (it reads past K).
  • The fp4 bytes of a NaN group are not compared, since e2m1 has no NaN.
  • The MoE op was not run with expert_mask (expert parallelism), and it does not zero the rows of zero-weight top-1 routes as the HIP kernel does.
  • The test cannot see the topk-slot check itself: without it, padding slots would write only rows that are undefined by contract. Its effect was confirmed by timing instead: M=64 with 40 local tokens takes 5.8 µs, against 8.6 µs without the check.
  • The end-to-end numbers come from the local vLLM integration described above: TP=1 only, and not re-run after commit 4.
  • Inputs of 2^31 bytes or more are rejected rather than supported.

PR-specific question

Before this PR, the test fails at import because neither op exists. Afterwards it fails on:

  • any fp4 or e8m0 byte that differs from per_1x32_f4_quant of the rotated input;
  • an RS=64 NaN group whose scale is not 255;
  • an RS=32 byte that differs from the HIP hadamard_rotate path outside its amax floor;
  • a CK scale layout that gemm_a4w4 reads differently;
  • any sorted scale of the MoE op that differs from the torch reference sorted by sorted_ids, for any block size, with or without num_local_tokens, on either dispatch path;
  • an input the ops should reject: fp16/fp32, strided, 3D, K not a multiple of the rotation size, an unsupported size, or a stage-2 sized MoE input.

op_tests/test_quant_mxfp4_hadamard.py (#6734) tests the HIP path at RS=32 only. test_quant.py and test_moe_sorting_mxfp4.py do not rotate. None of them covers these ops or rotation sizes 64 and 128.

Changed op tests

op_tests/test_flydsl_rot_quant.py is new. It follows the test_flydsl_<op>.py convention for FlyDSL ops rather than extending op_tests/test_quant_mxfp4_hadamard.py, which tests a different (HIP) op at a single size.

  • test_rot_quant is the exact-byte check against the shared torch reference. It also checks RS=32 parity with the HIP path, so the two independent implementations check each other.
  • test_rot_quant_gemm_a4w4 is the model call: CK scale layout into gemm_a4w4, the one consumer that layout exists for.
  • test_rot_quant_moe_sort covers the MoE op. Nothing else exercises its sorted-scale scatter, its route validity under num_local_tokens, or its fused/two-pass dispatch.
  • test_rot_quant_rejects_bad_input covers the input guards. An fp16 or strided input would otherwise be read as contiguous bf16 and give plausible garbage, and a stage-2 input would quantize the wrong rows.

🤖 Generated with Claude Code

@jiangyon-amd
jiangyon-amd requested a review from a team August 4, 2026 08:42
@github-actions

github-actions Bot commented Aug 4, 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: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 4549 --add-label <label>

@zufayu
zufayu requested a review from yadaish August 5, 2026 01:40
@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
@zufayu

zufayu commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Closing due to inactivity: no pushes, reviews, or comments for 65 days. This is housekeeping, not a judgement on the change — if you want to continue this work, comment here and we'll reopen, or open a fresh PR rebased on the latest main.

@github-actions

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

@aiter-bot

aiter-bot commented Nov 6, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision 0ffc56cf6c5a · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

This adds two new ops and changes no existing behavior. Today a rotated MXFP4 linear or MoE stage 1 needs a separate Hadamard matmul over HBM before the quant, unless the rotation size is 32 and the layer is dense (#6734). `flydsl_rot_quant` does the rotation, MXFP4 quantization and the CK scale layout in one pass for rotation sizes 32/64/128, with the rounding contract of `per_1x32_f4_quant`. `flydsl_rot_quant_moe_sort` does the same for the MoE stage-1 input with the scale layout of `fused_dynamic_mxfp4_quant_moe_sort`. Rotated weights and the existing `gemm_a4w4` / `fused_moe` kernels therefore work unchanged.

Validation and unverified scope

On MI350X with `flydsl==0.4.2` at this head:
- `python op_tests/test_flydsl_rot_quant.py` (defaults): 752 checks passed, 0 failed, exit 0, 34 s. fp4 bytes and e8m0 scales are compared with `rtol=atol=0` against `per_1x32_f4_quant`, over:
  - rotation sizes 32/64/128 and both scale layouts, padding columns included;
  - M ∈ {1, 32, 300, 1024, 4096, 16384} and K ∈ {2880, 4096, 7168};
  - inputs with outlier channels, a zero row, a 1e-30 row and a NaN row.
- Further checks in that run:
  - RS=32 against `per_1x32_f4_quant_hip(hadamard_rotate=True)`;
  - `gemm_a4w4` end to end at N ∈ {256, 4096};
  - the MoE op's fp4 bytes and sorted scales against the torch reference sorted in torch, for E=128, topk=8, every RS and K, and M up to 16384; block_m ∈ {16, 64} and sorts with `num_local_tokens` for M ≤ 1024. This exercises both the fused and the two-pass dispatch, including the K=2880 padding path. A separate run at M=32768, K=2880 covers the scatter store of `mxfp4_moe_sort_fwd`.
- By hand:
  - A cross-device call (input on the second GPU, current device the first) matches a same-device call byte for byte for both ops.
  - The dense output is byte-identical (0 of 396 cases differ) to the August revision of this PR.
  - `black` and `ruff==0.16.0` are clean.
  - No VGPR spills at any rotation size.

Unverified or not covered:
- gfx942/gfx1250 only reach the skip in `main()`; the ops raise there by design.
- `gemm_a4w4` is not used as a reference below N=256 (it is wrong there for any quantizer, rel. err 0.68 at N=128) or for K not a multiple of 256 (it reads past K).
- The fp4 bytes of a NaN group are not compared, since e2m1 has no NaN.
- The MoE op was not run with `expert_mask` (expert parallelism), and it does not zero the rows of zero-weight top-1 routes as the HIP kernel does.
- The test cannot see the topk-slot check itself: without it, padding slots would write only rows that are undefined by contract. Its effect was confirmed by timing instead: M=64 with 40 local tokens takes 5.8 µs, against 8.6 µs without the check.
- The end-to-end numbers come from the local vLLM integration described above: TP=1 only, and not re-run after commit 4.
- Inputs of 2^31 bytes or more are rejected rather than supported.

PR-specific question

Before this PR, the test fails at import because neither op exists. Afterwards it fails on:
- any fp4 or e8m0 byte that differs from `per_1x32_f4_quant` of the rotated input;
- an RS=64 NaN group whose scale is not 255;
- an RS=32 byte that differs from the HIP `hadamard_rotate` path outside its amax floor;
- a CK scale layout that `gemm_a4w4` reads differently;
- any sorted scale of the MoE op that differs from the torch reference sorted by `sorted_ids`, for any block size, with or without `num_local_tokens`, on either dispatch path;
- an input the ops should reject: fp16/fp32, strided, 3D, K not a multiple of the rotation size, an unsupported size, or a stage-2 sized MoE input.

`op_tests/test_quant_mxfp4_hadamard.py` (#6734) tests the HIP path at RS=32 only. `test_quant.py` and `test_moe_sorting_mxfp4.py` do not rotate. None of them covers these ops or rotation sizes 64 and 128.

Changed op tests

`op_tests/test_flydsl_rot_quant.py` is new. It follows the `test_flydsl_<op>.py` convention for FlyDSL ops rather than extending `op_tests/test_quant_mxfp4_hadamard.py`, which tests a different (HIP) op at a single size.
- `test_rot_quant` is the exact-byte check against the shared torch reference. It also checks RS=32 parity with the HIP path, so the two independent implementations check each other.
- `test_rot_quant_gemm_a4w4` is the model call: CK scale layout into `gemm_a4w4`, the one consumer that layout exists for.
- `test_rot_quant_moe_sort` covers the MoE op. Nothing else exercises its sorted-scale scatter, its route validity under `num_local_tokens`, or its fused/two-pass dispatch.
- `test_rot_quant_rejects_bad_input` covers the input guards. An fp16 or strided input would otherwise be read as contiguous bf16 and give plausible garbage, and a stage-2 input would quantize the wrong rows.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot did not review the current head SHA

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • PASS — Aiter Test Gate: passed

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@jiangyon-amd

Copy link
Copy Markdown
Contributor Author

Reopened and updated after the inactivity close. The branch is rebased onto current main (e1763ad) and the kernel is rewritten for the pinned FlyDSL 0.4.2 following the in-repo flydsl-kernel-code-cleanup and aiter-op-test skills (typed fx, buffer tensors + fx.copy, no inline asm, get_gfx_runtime(), the test on the op-test template). The description now compares against the fused rotations that landed in the meantime (#6734 at RS=32, the DSv4 rotate_activation at 128), and the performance table is re-measured on this head. Ready for review.

@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Nov 7, 2026
@jiangyon-amd jiangyon-amd changed the title [FlyDSL] Fused online Hadamard rotation + MXFP4 quantization (flydsl_rot_quant) [FlyDSL] Fused online Hadamard rotation + MXFP4 quantization for dense and MoE stage-1 inputs (flydsl_rot_quant) Nov 9, 2026
@jiangyon-amd
jiangyon-amd force-pushed the flydsl-rot-quant branch 3 times, most recently from c26dcd6 to 816eb03 Compare November 9, 2026 11:24
@jiangyon-amd

Copy link
Copy Markdown
Contributor Author

@coderfeli @yadaish this is ready for review. Since the reopen on 11-06 it gained the MoE stage-1 variant (flydsl_rot_quant_moe_sort) and a pre-review round. CI is green on 816eb03, and the description has kernel and end-to-end vLLM numbers (Qwen3-8B, Qwen3-30B-A3B) for rotation sizes 32/64/128. The scale-sort bug it works around is filed as #7646 and fixed separately in #7653.

jiangyon-amd and others added 7 commits November 14, 2026 06:34
Add aiter.ops.flydsl.flydsl_rot_quant(x, RS, shuffle_scales=): one gfx950
kernel that rotates each RS-wide block of a bf16 activation by a normalized
Sylvester Hadamard matrix (RS in {32, 64, 128}), quantizes the result to
MXFP4 with the default RoundUp e8m0 scale, and optionally writes the scales
in the CK layout that gemm_a4w4 consumes. The output equals
per_1x32_f4_quant applied to the bf16-rounded rotated tensor.

Rotated MXFP4 checkpoints fold the rotation into the weights, so the
activation of every rotated projection needs it online. Unfused, that is a
Hadamard matmul followed by a quant pass. The HIP per-1x32 quant fuses a
32-point rotation since ROCm#6734; this op adds 64 and 128 in the same single
pass and agrees with the HIP path byte for byte at 32, apart from groups
under its amax floor.

One thread owns one RS-wide block, so the FWHT runs in registers without
cross-lane traffic. At RS=64 the 1/8 normalization is applied to each
group's amax and to the conversion exponent instead of to every element.

MI350X, K=4096, RS=64, CK-layout scales, CUDA graph: 1.8x (M=32) to 2.9x
(M>=1024) over a bf16 Hadamard matmul plus per_1x32_f4_quant_hip.

op_tests/test_flydsl_rot_quant.py checks the fp4 bytes and e8m0 scales
exactly against per_1x32_f4_quant (RS 32/64/128, both scale layouts, M
1..16384, K 2880/4096/7168, zero, tiny and NaN rows), parity with the HIP
path at RS=32, and the CK scale layout end to end through gemm_a4w4.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split each RS-wide block across RS/32 adjacent lanes. Every lane runs the
first five FWHT stages on its 32 values in registers, and the lanes finish
the remaining log2(RS/32) stages with xor shuffles in the same stage order,
so the output is unchanged byte for byte. A lane now owns exactly one MXFP4
group: its scale stays thread-local, VGPRs drop from 101/228 to 60 at
RS=64/128, and small M spreads over 2-4x more lanes.

MI350X, K=4096, CK-layout scales, CUDA graph: RS=64 is 1.13-1.26x and
RS=128 1.15-1.77x faster than the previous revision; RS=32 is unchanged.
CTA size and the SLP setting were re-swept for the new mapping and kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add flydsl_rot_quant_moe_sort(x, sorted_ids, num_valid_ids, topk,
block_size, RS): the rotated MXFP4 quantization of the MoE stage-1 input
with its scales already sorted for the MoE GEMMs, i.e.
fused_dynamic_mxfp4_quant_moe_sort applied to the rotated tensor (without
that op's amax floor). Without it a rotated MoE layer runs a rotation pass
before the quant-and-sort kernel.

For small batches one kernel takes a thread per (sorted row, group):
valid routes rotate and quantize their token's group and scatter the scale
to the sorted row in the mxfp4_moe_sort_fwd layout, padding rows exit.
1024-thread CTAs keep the cost of the exiting threads down. Because a
token is quantized once per route, past M * topk * K = 2^21 the op instead
runs flydsl_rot_quant once and mxfp4_moe_sort_fwd. mxfp4_moe_sort_fwd loses
the last token's final scales when K // 32 is not a multiple of 4, so
those K always take the fused kernel.

MI350X, E=128, topk=8, CUDA graph: 1.3-2.8x faster than a Hadamard matmul
followed by fused_dynamic_mxfp4_quant_moe_sort; at K=2048 within ~0.5 us
of the unrotated quant-and-sort.

The op test gains test_rot_quant_moe_sort: fp4 bytes and sorted scales
compared exactly with the torch reference for K 2880/4096/7168, RS
32/64/128 and M 1..16384.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- flydsl_rot_quant_moe_sort takes token_num in the position
  fused_dynamic_mxfp4_quant_moe_sort has it and rejects a stage-2 input;
  rotation_size and shuffle (were RS and shuffle_scales) are keyword-only.
- Skip the padding slots of a num_local_tokens sort (topk << 24 | count,
  a real token): M=64 with 40 local tokens 8.6 -> 5.8 us.
- Write 0 to the MoE scale padding columns, as mxfp4_moe_sort_fwd does.
- K // 32 not a multiple of 4 now takes the two-pass path as well, with
  zero-padded scale columns to avoid ROCm#7646: K=2880 M=16384 141.6 -> 42.4 us.
- Launch under the input's device.
- Set the no-SLP compile hint directly; one helper for the CK padded
  scale columns.
- Test: block_m 16/32/64 and counted sorts in the MoE check, padding
  columns compared, per-candidate column names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- MoE: stop writing the scale padding columns. As for
  fused_dynamic_mxfp4_quant_moe_sort, only the first K // 32 columns of
  valid-route rows are defined; mxfp4_moe_sort_fwd's scatter store leaves the
  padding columns unwritten, so the two-pass path never matched a "0" claim.
- Merge the no-SLP hint into existing llvm_options instead of replacing them.
- Module docstring shows the keyword API; note that the ROCm#7646 padding goes
  away with ROCm#7653.
- Test: extra block sizes and counted sorts only for M <= 1024 (48 -> 34 s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When K // 32 is not a multiple of 4 the two-pass path also pads the scales
for ROCm#7646, which moves its crossover with the fused kernel about 8x higher.
Switch at M * topk * K > 2^24 for those K and keep 2^21 otherwise.
K=2880, rotation size 64, MI350X: 1.27-1.68x faster for M * topk from 768 to
4096; other K are unchanged. Over 544 measured points (K 2048-7168, every
rotation size, topk 4 and 8) the dispatch is within 0.7% of the faster path
on average, against 2.4% before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in main

mxfp4_moe_sort_fwd keeps the last row's tail scales since ROCm#7653, so the
MoE two-pass path no longer pads the scale rows, and the 2^24 threshold
that compensated for the padding goes too. With the fixed sort the
padded-K dims cross over where the others do: one 2^21 switch for every K
is within 5% of the faster path on 567 of 600 measured points (MI350X,
K 2048-7168, every rotation size, topk 4 and 8), 0.9% off on average.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@yadaish yadaish 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.

LGTM

@yadaish
yadaish merged commit 45cd3d7 into ROCm:main Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants