Skip to content

[FlyDSL] [gfx1250] Quantize the MoE a1 scale and shuffle. - #5507

Merged
junhaha666 merged 7 commits into
mainfrom
wjx/moe-fused-quant-preshuffle
Sep 18, 2026
Merged

junhaha666 merged 7 commits into
mainfrom
wjx/moe-fused-quant-preshuffle

Conversation

@lalala-sh

@lalala-sh lalala-sh commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Measured on gfx1250, a4w4, 16384 tokens, 7168/768, E=384, topk=6, no bias (device time summed over the layer kernels):

scattered interleaved write 1014 us quant 143.1
compact + rebuild, 1 launch 953 us quant 75.1

The two-launch form is faster on device and the one-launch form on wall time: merging the passes saves two launches but the persistent grid costs the GEMMs after it about 30 us. This ships the single launch; logits_diff is 3.5076e-06 on all three, unchanged from the scattered write.

Motivation

Technical Details

Test Plan

Test Result

Submission Checklist

…n one launch

The stage1 quant pass wrote its e8m0 straight into the 16-row-interleaved WMMA
layout, once per route. That layout spaces a row consecutive blocks wmma_rep*16
dwords apart, so every store landed 4 useful bytes in a 64 B line, and topk
repeated it: at 16384 tokens the scale cost 143 us of a 68 us pass.

#5313 had answered this by letting the quant write row-major and moving the
interleave into gemm1 LDS read. That is the layout #5391 then dropped, because
producer and consumer derived the choice independently and disagreed under EP.
This keeps the single interleaved layout gemm1 reads and fixes the write
instead: one compact row-major row per source token, then a rebuild pass that
walks destination tiles so both its load and its store cover whole lines.

The rebuild cannot run inside the token loop. A cache line of the interleaved
scale spans 16 consecutive grouped rows, which belong to 16 unrelated tokens; no
workgroup owns them, so it needs every token quantized first. A persistent grid
plus a spin barrier buys that ordering without a second launch, reusing the
protocol build_moe_fused_route_psum_quant_scatter_module already uses. Two
blocks per CU: one also works but gives up the cross-block latency hiding, and
measured 93 us against 75.

Falls back to the scattered write when the shape cannot take it -- prequantized
input, EP route counts, a routing the token-multidest quant does not cover, or a
scale row too wide to stage a tile in LDS.

Measured on gfx1250, a4w4, 16384 tokens, 7168/768, E=384, topk=6, no bias
(device time summed over the layer kernels):

  scattered interleaved write   1014 us   quant 143.1
  compact + rebuild, 2 launches  915 us   quant 54.3 + rebuild 7.9 + map 6.1
  compact + rebuild, 1 launch    953 us   quant 75.1

The two-launch form is faster on device and the one-launch form on wall time:
merging the passes saves two launches but the persistent grid costs the GEMMs
after it about 30 us. This ships the single launch; logits_diff is 3.5076e-06 on
all three, unchanged from the scattered write.

Also packs the fallback scattered write into one dword per 4 MX blocks, which
share a destination dword in the interleaved layout too (143.1 -> 142.7 us).
@lalala-sh
lalala-sh requested a review from a team September 14, 2026 14:16
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci: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; main branch always runs both MI35X and MI300X
multigpu 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: 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 5507 --add-label <label>

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 opt this PR out.

Style only, no behaviour change. Four things CI would have caught:

  - black 26.5.1 wants a blank line after two module-level statements the
    branch touched.
  - The LDS-budget environment knob went away with the simplification, and
    took the only use of `os` in this module with it.
  - The fused builder inherited dst_scale_dwords_per_row and its constants
    from the plain one, but its scale destination is the source token row,
    so nothing reads them.
  - Phase 1 closures captured the persistent loop token0, which ruff reports
    as B023 even though the tracer walks the body once. Taking it as a
    parameter binds them to a local and says the same thing more directly.

ruff 0.16.0 and black 26.5.1, the versions pre-checks.yaml pins, are clean on
the five changed files. logits_diff stays 3.5076e-06 and the fused kernel 74.4
us at 16384 tokens; pre- and post-format trees measured 1097.58 us against
1097.58 on the same machine state.
@zufayu
zufayu requested a review from coderfeli September 15, 2026 01:56
…r-reduce

The gather-reduce pass read grouped_out through one buffer descriptor covering
the whole tensor, indexed in dwords. Two 32-bit quantities in that scheme break
once the tensor passes 4 GiB, which contiguous_m * model_dim * 2 does at around
48k tokens with topk=6:

  - The descriptor bound was built as an i32 product of dwords and 4. Landing
    in the negative half is harmless -- create_buffer_resource_from_addr sign
    extends to the i64 num_records field, and the hardware reads that as a huge
    unsigned bound -- so the wrap goes unnoticed until it crosses 2**32 and
    lands on a small positive bound instead. At 301056 rows that bound is 20 MB
    and every row past it reads as zero.

  - The buffer offset itself is 32-bit, so even a correct bound cannot reach
    the far end of the tensor.

Folding the grouped row into the 64-bit descriptor base fixes both: the offset
then only has to span one row. The base is loop-invariant, so the address math
runs once per route instead of once per access -- which is also why this is not
slower. A dropped EP route now takes a zero-length descriptor rather than an
out-of-range row, so switching its loads off no longer depends on the bound the
first hunk just changed.

Measured on gfx1250, 7168/3072, E=96, topk=6, logits_diff against the fp32
reference (gate 0.01):

  tokens   before      after
   16384   4.22e-06    4.22e-06
   48128   9.90e-01    4.23e-06
   49152   9.51e-01    4.23e-06
   65536   nan         4.22e-06

a4w4 moves with it: 47104 tokens 9.50e-01 -> 6.65e-06, 65536 nan -> 6.67e-06.
The route-ksplit quant faulted outright at these sizes (Memory access fault on
a page not present); the multidest one only wrote the zeros, because its stores
go through descriptors whose bounds check drops them silently.

bench_gfx1250_combo.py --dsv4 --ops moe now passes all ten token tiers. The
gather-reduce kernel measures 108.3 us against 113.8 at 16384 tokens, a4w4
7168/768 E=384, interleaved over three pairs.
The compact-scale quant and the WMMA scale rebuild ran as one launch over a
persistent grid of cu_num*2 workgroups, separated by a hand-rolled grid-wide
spin barrier. FlyDSL has no cooperative launch, so nothing makes those
workgroups co-resident, and the barrier deadlocks if even one of them is not:
the others spin forever, the kernel never returns, and the device reads as
100% busy while producing nothing. A serving runtime cannot promise that
residency -- collectives and other streams hold CUs of their own -- so this
only ever held on a benchmark that owned the device.

Launching the two phases back to back on one stream buys the same ordering
from the inter-kernel dependency and assumes nothing about residency. Both
were already grid-stride loops, so a grid that just covers the work leaves
each block one iteration, and each kernel now allocates only the LDS its own
phase uses. The pair is also the faster of the two at prefill sizes, 65.6 us
against 79.4 at 16384 tokens and wmma_rep=2, since the persistent grid slowed
the GEMM behind it.

Below roughly a thousand tokens the pair loses to writing the interleaved
scale inline: the rebuild launch is a fixed cost, while coalescing the scale
write pays off only in proportion to the token count. Gate the compact path on
batch size, with a higher threshold at wmma_rep=1 whose narrower interleave
stride is exactly one cache line:

  inline / pair, us, run_perftest with rotated inputs, fd7168 topk=6 fp4
  wmma_rep=1   512  7.1/11.8   1024  10.7/12.6   2048  18.4/14.4
  wmma_rep=2   512  8.4/12.0   1024  15.3/13.0   2048  23.5/14.8

AITER_FLYDSL_COMPACT_SCALE_MIN_TOKENS overrides the threshold.

Since the two paths fill the same buffer gemm1 reads, they cross-check
bitwise: payload and interleaved scale agree on both sides of the threshold,
at wmma_rep 1 and 2, and with padding tiles exercising the rebuild's
zero-fill. End to end on a4w4 the logits_diff is unchanged at 3.60e-06.
main reverted #5274 in #5581, so its compact-scale and a_gather work is gone
and this branch no longer overlaps it. The only conflict left is the scale
staging in launch_gemm_a8w4_tdm: take main's ceildiv helpers from #5476 while
keeping row_major_ascale dropped, which is what this branch's compact path
replaces.

Also drops AS_ROW. It was defined as (K // 128) * wmma_m_rep * 16, which is
exactly the AS_FULL_INNER that already existed a few lines above, and the merge
had already moved its uses over to that name.
@zufayu

zufayu commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Advisory review (static + hand-run; not a merge gate). Validation/Perf ran no GPU stage — reasons are on their lines below. Findings tagged [verified] are traced to code/repro.

On the gfx1250 grouped MoE, the a1 e8m0 scale is now written as one compact row per source token and a second kernel rebuilds the 16-row-interleaved layout gemm1 reads (replacing the row-major-ascale path), while the gather-reduce epilogue switches to per-route 64-bit-based descriptors so grouped outputs past 4 GiB still address correctly.

Review (advisory): 🔴 HIGH RISK
Validation (deterministic): NOT RUN — the PR changes runtime code but ships no test target (triage: required, target=null); auto-validation disabled (REVIEW_AUTO_VALIDATE=0) and no gfx1250 GPU on this box, so the new kernels were checked by static layout analysis and an index-math simulation only.
Perf (advisory): NOT RUN — no gfx1250 GPU here and the PR ships no benchmark entry point as a test target; the claimed 1014→953 us layer / 143.1→75.1 us quant (gfx1250, a4w4, 16384 tokens, 7168/768, E=384, topk=6) is unverified.

🔴 [verified] The new compact-path gate _use_fused_quant_preshuffle (grouped_moe_gfx1250.py:301) checks token count, topk and geometry but not the pre-existing AITER_FLYDSL_TOKEN_MULTIDEST_QUANT kill-switch that the actual dispatch inside flydsl_moe_fused_quant_preshuffle checks (moe_kernels.py:3229). With that env var set to 0 on a ≥1024-token (2048 when wmma_rep=1) non-EP gfx1250 a4w4 batch, the caller sizes out_scale as a compact (token_num, model_dim//32) buffer (grouped_moe_gfx1250.py:698) but the dispatch silently falls back to the route-indexed kernel, which writes the full 16-row-interleaved scale for all token_numtopk routed rows through an unbounded byte view (moe_fused_route_quant_scatter.py:1691) — contiguous_m ≈ topktoken_num + E*tile_m, so at topk=6 the stores land ~6x past the allocation: silent heap corruption with no crash, on exactly the rollback path an operator reaches for when the quant path misbehaves. Author must make the gate and the dispatch agree — check the env var in _use_fused_quant_preshuffle, or assert fused_preshuffle_out is None on every branch that did not take the compact path.

⚠️ [verified] The compact-quant + scale-rebuild pair ships with no collectible test and no CI path that can execute it: no test file is touched, the pk8 requirement keeps it off the gfx942/gfx950 default CI, and the PR carries no ci:* label — the only correctness evidence is a self-reported logits_diff 3.5076e-06 with no harness named, and the gate additionally accepts quant_mode="fp8" (a8w4 activations) that the body's a4w4-only measurement never covered. Author must add a test pinning the compact+rebuild scale buffer against the scattered path (or a torch reference) and name the harness that produced the logits_diff; Reviewer should ask which ci:* label actually runs gfx1250 hardware.

⚠️ [verified] The PR body says "This ships the single launch" and labels the 953 us row "compact + rebuild, 1 launch", but the shipped code launches two kernels (compact quant, then scale rebuild — moe_kernels.py:3245-3270), and the rebuild docstring explicitly rules out fusing them ("it cannot start until every token is quantized", moe_fused_route_quant_scatter.py:2470). The 953 us / 75.1 us numbers therefore cannot be mapped unambiguously to the shipped implementation. Author must reconcile the body's launch-count wording with the code and state which form the measured numbers describe.

⚠️ [verified] The new "quant_a1" bench hook (grouped_moe_gfx1250.py:857) re-launches flydsl_moe_fused_quant_preshuffle without row_to_token/fused_preshuffle_out, so when the compact path is active the hook times the old scattered kernel instead — a tuning run would report ~143 us for a production path that costs ~75 us, with nothing flagging the mismatch. Author must thread the compact buffers through the bench partial (or add a separate entry) so the label matches the kernel actually measured.

⚠️ [verified] build_moe_token_multidest_compact_quant_module and build_moe_scale_rebuild_module (moe_fused_route_quant_scatter.py:2176, 2459) are newly public in a module aiter/aot/flydsl/grouped_moe.py imports, but no AOT hunk teaches the pre-compiler the pair, so every (feat_dim, wmma_rep, topk) combination JIT-compiles on first invocation — mitigated by the sibling token-multidest builder already sitting outside AOT's enumeration, but the ≥1024-token default path now routes through the unenumerated pair. Reviewer should ask whether AOT should pre-compile the compact pair now that the large-batch default depends on it.

lalala-sh and others added 2 commits September 17, 2026 02:27
…build

The compact scale path had its own rebuild kernel, but
build_moe_scatter_copy_preshuffle_scale_module already turned a compact
per-token scale plus a grouped-row -> token map into the interleaved layout the
GEMM reads, with the same index math and the same -1 padding rule. Two copies of
one pass, and only ours was outside the oracle test in test_flydsl_moe_aux.

What ours had that the shared one lacked was LDS staging. Written straight out,
adjacent lanes read adjacent grouped rows, so the source side moves one dword
per line; going through LDS lets the load walk a row instead and leaves both
sides on whole lines. Port that over, keeping the direct path for a tile too wide
to stage, since this module also serves gather=False and wider scale rows.

The shared kernel then beats the one it replaces -- 7.9 us against 9.4 at 16384
tokens wmma_rep=2, 7.5 against 8.6 at wmma_rep=1 -- because it takes one tile per
workgroup off a 2D grid rather than a grid-stride loop. Output is bitwise equal
on every shape tried.

Net effect on the layer is a wash, which is expected at 12% of the pair: r1/2048
13.9 us against 14.4, r2/1024 12.8 against 13.0, 16384 unchanged either way.
gemm1/gemm2 stay at 1945/1024 us and logits_diff at 3.6030e-06.

Drops 139 lines: build_moe_scale_rebuild_module, its compile cache, and the
fused_preshuffle_out parameter that selected it. row_to_token now selects the
compact scale on its own, and the caller does the rebuild -- one launch each,
which is what the pair always was.
@junhaha666
junhaha666 merged commit 2b94918 into main Sep 18, 2026
92 checks passed
@junhaha666
junhaha666 deleted the wjx/moe-fused-quant-preshuffle branch September 18, 2026 11:00
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.

3 participants