Skip to content

[HIP] Mega-MHC: faster large-M prefill (split tail for any T, ping-pong post tiles) - #7818

Merged
junhaha666 merged 8 commits into
ROCm:mainfrom
cpersson-amd:mega_mhc_large_m
Nov 19, 2026
Merged

junhaha666 merged 8 commits into
ROCm:mainfrom
cpersson-amd:mega_mhc_large_m

Conversation

@cpersson-amd

@cpersson-amd cpersson-amd commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Speeds up the HIP Mega-MHC large-token path (T > 4096) on gfx950. Ragged token counts gain the most: up to 34% with post and up to 24% without. It also removes a correctness hazard: on gfx950, the split-tail collapse could silently drop one stream when a split-tail block shared a CU with a body block.

Motivation

At T > 4096 the large variant runs whole rounds of 256 CUs. A final round with only a few 16-row tiles leaves most CUs idle, which is why T=4097 with post costs 156 us against 96 us at T=4096 (H=5120). The large post tiles were also bound by the barrier between their two wave groups.

Changes

  • _select_stream_variant sends T > 4096 with 1..8 tiles past whole CU rounds to the split-tail variant. Before, only T=4160 went there. The split-tail kernel now takes any such T: the body runs whole rounds, and the leftover tiles are split over H across 256 blocks.
  • Large post tiles use ping-pong LDS buffers and interleave their two wave groups. Collapse columns that are not staged stay in registers.
  • Split-tail post launches stage the body through LDS (2560 columns), with a 4-stream body for single-round tails. No-post runs ping-pong.
  • No-post split-tail collapses use scalar FMAs (collapse_fma). The packed form exposed a gfx950 hazard: a v_pk_{fma,mul,add}_f32 whose low half reads src1's high dword (op_sel[1]) sees zero for that operand in lanes 48..63 while another wave on the same SIMD runs MFMA. A body block next to a split-tail block then intermittently lost stream 1 from one element per 8-element vector. Scalar FMAs avoid the hazard and let the tail overlap the body again, without reserving LDS to keep the two apart. Post launches keep the packed form (see the unverified scope below).
  • op_tests/test_mega_mhc.py defaults now include ragged T (4097, 4224, 6000, 8200, 8320, 9000) and H=7168, so a standard run covers the new split-tail shapes. The default run goes from 30 to 84 cases, about 40 s more on one MI355X.

Performance

MI355X (gfx950, 256 CUs), op_tests/test_mega_mhc.py --backends hip --iters 201, BF16 output. Values are the median of 3 runs in us; "before" is the base commit with its own variant selection.

T post H=5120 post H=7168 no-post H=5120 no-post H=7168
4096 95.8 → 95.4 (-0.4%) 132.2 → 131.9 (-0.2%) 69.1 → 65.1 (-5.7%) 98.7 → 91.0 (-7.8%)
4097 156.2 → 111.5 (-28.6%) 209.9 → 150.0 (-28.6%) 91.9 → 75.7 (-17.6%) 127.0 → 102.4 (-19.4%)
4160 121.6 → 121.2 (-0.3%) 163.6 → 162.3 (-0.8%) 91.0 → 85.1 (-6.5%) 123.4 → 114.4 (-7.2%)
4224 183.5 → 121.4 (-33.8%) 244.7 → 162.5 (-33.6%) 107.5 → 84.7 (-21.3%) 151.0 → 115.3 (-23.6%)
6000 178.1 → 161.7 (-9.2%) 230.7 → 207.0 (-10.2%) 106.3 → 106.6 (+0.3%) 147.3 → 146.4 (-0.6%)
8192 182.4 → 170.4 (-6.6%) 261.8 → 234.8 (-10.3%) 123.1 → 119.8 (-2.7%) 166.1 → 164.0 (-1.3%)
8200 244.9 → 177.8 (-27.4%) 329.7 → 255.7 (-22.5%) 152.6 → 125.7 (-17.7%) 207.9 → 174.0 (-16.3%)
8320 254.8 → 217.1 (-14.8%) 341.9 → 301.4 (-11.8%) 160.4 → 128.5 (-19.9%) 220.8 → 180.8 (-18.1%)
9000 256.9 → 224.4 (-12.7%) 346.8 → 313.9 (-9.5%) 158.7 → 160.6 (+1.2%) 222.8 → 228.1 (+2.4%)
12290 320.0 → 256.9 (-19.7%) 439.9 → 359.5 (-18.3%) 203.9 → 181.5 (-11.0%) 291.8 → 258.4 (-11.4%)
13000 346.1 → 303.4 (-12.4%) 469.7 → 424.7 (-9.6%) 220.7 → 223.6 (+1.3%) 314.2 → 311.7 (-0.8%)
16384 361.6 → 335.5 (-7.2%) 524.2 → 465.2 (-11.2%) 227.8 → 226.9 (-0.4%) 306.4 → 293.1 (-4.4%)

Every post shape among 17 T per H (4096..16384) is faster or within 1%. No-post shapes whose last round is half full or less, at T=9000, 10000 and 13000, are up to 2.4% slower. Every other no-post shape is faster or within 1%.

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X
  • Tested on MI300X

End-to-end accuracy: DeepSeek-V4.1-Flash (H=5120) on MI355X, served by vLLM with TP4, FP8 KV cache and dspark speculative decoding. vLLM #65992 routes the mHC seams through mega_mhc. Only the AITER commit differs between the two runs: base vs this PR.

Task Base This PR
gsm8k, 5-shot, all 1319, strict / flexible 92.65 / 92.57 92.12 / 92.19 (± 0.72)
niah_single_2, 32k / 64k 1.00 / 1.00 1.00 / 1.00

The gsm8k difference is sampling noise: 43 questions are correct only on base and 36 only with this PR (McNemar p ≈ 0.43).

Documentation

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

Kernel-internal tuning and variant selection only; the mega_mhc API is unchanged.

Dependencies

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

Breaking Changes

None.

AI assistance

This change was developed with AI assistance (Claude). I reviewed every change, and ran the tests and benchmarks myself on MI355X.

PR Self-Review

Reviewed revision

d8d77f0337

Behavior and intent

Outputs are unchanged; only the variant selection and the large-M kernel schedules change.

  • T > 4096 with 1..8 tiles past whole CU rounds now uses the split-tail variant, which before took only T=4160.
  • Large post tiles overlap their two wave groups.
  • The no-post split-tail collapse stays scalar, so co-resident blocks cannot hit the gfx950 packed-FP32 op_sel hazard described above.

The existing behavior is insufficient for two reasons:

  • At every other ragged T, the large variant ran a final CU round of a few 16-row tiles on a mostly idle GPU. T=4097 with post cost 156 us against 96 us at T=4096.
  • The large post tiles were bound by the barrier between their two wave groups.

vLLM's chunked prefill produces such ragged T on most steps: a prefill chunk plus the decode rows batched with it.

Validation and unverified scope

All runs are on MI355X (gfx950, 256 CUs) in the vllm/vllm-openai-rocm nightly ROCm image.

  • Correctness, H=5120 and 7168: 256/256 pass for each H. That covers 32 T × 4 modes × 2 output dtypes, with python op_tests/test_mega_mhc.py -t 1 7 64 1024 2048 2049 2050 3000 4096 4097 4100 4104 4160 4161 4224 5000 6000 8191 8192 8193 8200 8320 9000 12288 12290 12416 16000 16383 16384 16385 16400 32768 -n {5120,7168} --mode post no_post identity_pre no_post_identity --out-dtype bf16 mxfp8 --backends hip --check-only.
  • Repeat-launch probe: 40 launches each for post and no-post at T=4097, 4224, 8320 and 12416, both H. All 640 launches match the reference.
    • Before the scalar collapse, and without the LDS reservation, no-post T=8320 failed in 33..39 of 40 launches.
    • Disassembly confirms that no no-post split-tail kernel still contains a packed FP32 op with op_sel[1].
  • The hazard reproduces outside Mega-MHC in a standalone gfx950 HIP test. One wave runs MFMAs; another wave on the same SIMD, in another workgroup or the same one, runs v_pk_fma_f32 … op_sel:[0,1,0]. Its low result in lanes 48..63 then uses zero for src1. op_sel on src0 or src2, op_sel_hi only and default operands are unaffected. It reproduces identically on all 8 GPUs of a second MI355X node, so it is not one faulty GPU or node.
  • End-to-end with DeepSeek-V4.1-Flash on vLLM (see Testing): gsm8k and niah_single_2 at 32k and 64k match base. A dense kernel sweep of H=5120, both modes, over 271 values of T between 4097 and 16384 finds no outlier. Post is faster at every T, and no-post is at most 3% slower.
  • Unverified:
    • gfx942 and gfx1250. The selection change is gfx950-only: gfx942 always takes the generic kernel, and gfx1250 has its own selector. The large-tile kernel changes were neither built nor run on those targets.
    • gfx950 with masked CUs (HSA_CU_MASK / ROC_GLOBAL_CU_MASK) or fewer than 256 CUs. The large and tail paths do not depend on CU count for correctness (see the PR-specific question).
    • Packed FP32 ops with op_sel[1] remain outside the no-post split tail. Identity-pre builds have none.
      • Variant 11 no-post, whose loop this PR changes to ping-pong, has 64 such ops (128 with 32-row tiles). Base has the same counts.
      • Variant 11 post has 64 in the 2-stream staged body (16 in base) and 12 in the 4-stream body (12 in base).
      • Variant 12 post bodies have 24..96.
      • Decode variants 0..10 and the generic variant 13 have 12..896. This PR does not change them.
    • These kernels pass a stress of 200 launches per case:
      • Cases: T=3000, 4096, 6000, 9000 and 16000; post and no-post with a non-identity pre mix; both H; with and without a BF16 GEMM on a side stream.
      • Result: 0 of 8000 launches fail, for both base and this PR.
      • Control: the packed no-post split-tail build fails 168/200 launches at T=8320 and 145/200 at T=12416 under the same stress.
      • This is evidence, not proof that the hazard cannot fire.
    • Exposure differs by kernel:
      • Unstaged variant 11 no-post (26 or 52 KiB LDS) runs several workgroups per CU.
      • Every post body takes 148..159 KiB LDS, so one workgroup per CU.
        • The 4-stream variant 11 post (T <= 4096) runs 512 threads, so two of its own waves share each SIMD.
        • The other post bodies run 256 threads, so only a kernel on another stream could share their SIMDs.
    • Making the variant 11 collapse scalar as well would cost 2..4% on no-post and up to 1.2% on post. I'll file that, together with the decode and generic variants, as a follow-up.

PR-specific question

Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?

_prepare_scratch and mega_mhc in aiter/ops/mega_mhc.py select a changed path (variant 11 large or variant 12 tail) only when all of the following hold:

  • The runtime arch is gfx950. gfx942 always takes variant 13 generic, and gfx1250 uses _select_gfx1250_variant.
  • H is 5120 or 7168 (_STREAM_HIDDEN_SIZES). Any other H loads the generic module.
  • The residual is (T, 4, H) BF16, i.e. hc_mult is 4, with packed BF16 fn (mega_mhc_shuffle_fn).
  • sinkhorn_repeat is 20. Any other count switches to generic in mega_mhc.
  • split_k is not given; an explicit split_k selects generic.
  • T: large for T > 2048 (unchanged boundary). tail for T > 4096 with 1 <= ceil(T/16) % 256 <= 8, i.e. 1..8 tiles past whole rounds of 256 16-row tiles.
  • Both modes (post and no post), identity pre, and both output dtypes (BF16 and MXFP8) take these variants. The validation matrix above covers all of them.

The host launcher in csrc/kernels/mega_mhc.cu enforces the same boundaries even if Python is bypassed:

  • The tuned modules check arch == "gfx950".
  • Each module is compiled for one H and checks h == H.
  • The stream variants check sinkhorn_repeat == 20 and the tuned split.
  • (T, 4, H) and the tensor dtypes, contiguity and alignment are checked.
  • Variant 12 checks blocks > 256 && 1 <= blocks % 256 <= 8, so the split-tail kernel cannot run at a token count it does not tile.

The 256 in these boundaries is a performance tuning constant (gfx950 has 256 CUs), not a correctness requirement:

  • large and tail are not distributed variants, so they keep no 256-CU or CU-mask guard, and they need none.
  • Body tiles are independent.
  • The tail's split-K reduction over H is wait-free: each block does an atomic fetch_add on the tile counter, the last one finishes the tile, and the others return. No block waits for another to be resident.
  • With fewer visible CUs only the speed changes. CU-masked runs were not tested.

Changed op tests

op_tests/test_mega_mhc.py: default TOKEN_COUNTS adds 4097, 4224, 6000, 8200, 8320 and 9000; default HIDDEN_SIZES adds 7168. 84/84 pass at 612562b.

cpersson-amd and others added 4 commits November 10, 2026 13:35
…st tiles

The four-wave post path of the large and tail kernels rotated one prefetched
residual tile through register copies (current = next). Those copies read the
load destinations, so the compiler waits on the loads just issued and, since
vmcnt retires in order, on the preceding residual stores. Alternate two tile
and fn buffers instead, so the prefetch covers a full k-step.

With two column groups, alternate 64-column chunks between the groups so each
k-step reads and writes 256 contiguous bytes per row and stream. The staged
RMSNorm pass maps columns the same way.

gfx950, MI355X, POST BF16 (median of 3, us):
  H=5120   8192: 181.9 -> 175.1   12288: 270.4 -> 259.7   16384: 359.0 -> 344.9
  H=7168   8192: 265.5 -> 256.5   12288: 396.0 -> 392.9   16384: 529.2 -> 521.1
T <= 4096 and the T=4160 tail are unchanged.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Carl Persson <[email protected]>
… post tiles

The staged large post kernel holds 3584 collapse columns per row in LDS for
the RMSNorm pass. The remaining columns were stored to layer_input and read
back, about 8% extra DRAM traffic at H=5120. That kernel already runs one
workgroup per CU, so registers past 256 (AGPRs) are free: keep each lane's
last unstaged collapse vectors (up to 20) in a register FIFO. The RMSNorm
pass reads them back with the main loop's row and column ownership.

DRAM traffic at T=16384, H=5120 drops from 1.087x to 1.015x the ideal.

gfx950, MI355X, POST BF16 (median of 3, us), against the previous commit:
  H=5120   8192: 175.3 -> 171.0   12288: 260.2 -> 252.9   16384: 347.2 -> 337.4
  H=7168   8192: 251.8 -> 235.5   12288: 387.8 -> 353.1   16384: 518.6 -> 472.7
Unstaged launches (non-full CU rounds) and T <= 4096 are unchanged.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Carl Persson <[email protected]>
…ing-pong

Generalize the T=4160 tail variant. Whenever one to eight 16-row tiles remain
past whole rounds of 256 CUs, run the whole rounds as the body and split the
remaining tiles 32 ways over H instead of launching a sparse extra round.
Post uses the four-stream body for one round and the two-stream staged body
beyond. Without post, the first CU round also covers the tail; those launches
reserve LDS so blocks do not share a CU. A block running the split tail beside
a no-post body block intermittently corrupted that body's collapse.

Post large tiles now always use LDS staging; it beats the unstaged kernel on
sparse final rounds too. The no-post large tiles use the ping-pong loop.

gfx950, MI355X, BF16, median of 3, us (stock -> this change):
  post    H=5120  4097: 157.4 -> 111.6  8200: 245.1 -> 178.0  13000: 344.9 -> 302.1
  post    H=7168  4097: 214.3 -> 151.6  8200: 333.0 -> 262.1  13000: 478.0 -> 424.3
  no_post H=5120  4097:  92.3 ->  75.0  8320: 160.8 -> 145.3  4096:   69.0 ->  65.1
  no_post H=7168  4097: 127.7 -> 102.9  8320: 223.7 -> 204.2  4096:   99.2 ->  92.2
Other no-post T are within about 1.5%.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Carl Persson <[email protected]>
On gfx950, a packed FP32 VOP3P op (v_pk_fma/mul/add_f32) whose low half
reads src1's high dword (op_sel[1]) sees zero for that operand in lanes
48..63 while another wave on the same SIMD executes MFMA. The no-post
collapse compiled to v_pk_fma_f32 with a broadcast pre weight taken from
the high dword, so a body block sharing a CU with a split-tail block
(and vice versa) intermittently dropped one stream from one element of
an eight-element vector.

Keep the no-post variant-12 collapse FMAs scalar and drop the 80 KiB
dynamic LDS reservation that kept those blocks apart. Post kernels run
one wave per SIMD and are unchanged. Tail and body now overlap again:
no-post T=8320 145.3 -> 128.1 us (H=5120) and 203.8 -> 180.7 us
(H=7168); T=12416 209.7 -> 189.5 and 296.6 -> 271.9 us; post and
single-round no-post unchanged.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Carl Persson <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
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 Radeon R9700 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 7818 --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.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

@cpersson-amd
cpersson-amd marked this pull request as ready for review November 11, 2026 12:42
@cpersson-amd
cpersson-amd requested a review from a team November 11, 2026 12:42
@github-actions github-actions Bot added the HIP label Nov 11, 2026
@aiter-bot

aiter-bot commented Nov 11, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 4c7e357593d7 · mode shadow

Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision.

Questions to answer in the PR description

  1. What behavior does this PR change, and why is the existing behavior insufficient?
  2. What did you validate, and what remains unverified? Include commands, hardware/configuration and results.
  3. Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?
  4. For every changed op_tests/ file, what behavior does it cover and why is it not redundant? Write None if no op test changed.

Edit the PR Self-Review section in the PR description. Include the current revision SHA; this comment refreshes automatically.

Missing or invalid answers

  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA

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

@junhaha666

Copy link
Copy Markdown
Contributor

@aiter-bot review

@aiter-bot

Copy link
Copy Markdown

aiter-bot — queued behind 2 review(s); expect to start in about 68 min. The box reviews one PR at a time.

@aiter-bot aiter-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ROCm/aiter PR #7818 — [HIP] Mega-MHC: faster large-M prefill (split tail for any T, ping-pong post tiles)

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — triage: the PR changes runtime code but ships no test target (auto-validation also disabled, REVIEW_AUTO_VALIDATE=0); the changed path is executed at run time (gfx950 variant-11/12 kernels), so the missing target is a coverage gap, not a data-only diff
Perf (advisory): NOT RUN — the harness exists (op_tests/test_mega_mhc.py --iters 201) but this box is 8x gfx942 (MI300X) and the changed variant-11/12 paths never execute on gfx942, so a local run would time the unchanged generic kernel; the only timing evidence is the PR's own base-vs-head table
Size: 477 lines / 2 files
Design (advisory): split-tail-for-any-ragged-T dispatch plus register-resident unstaged collapse columns — routed to the Human line
Human: recommend la review whether PR #7818's split-tail-for-any-ragged-T boundary is the right trade — the up-to-2.4% no-post regression at half-full final rounds (T=9000/10000/13000) against the 9-34% post gains — and whether the register-resident kept columns are the right substitute for LDS staging on gfx950

2 finding(s) posted inline, on the lines they are about:

  • aiter/ops/mega_mhc.py:95 — The new dispatch branch at aiter/ops/mega_mhc.py:95 (tail for any T>4096 with 1..8 tiles past whole CU…
  • csrc/kernels/mega_mhc.cu:1680 — The gfx950 packed-FP32 op_sel[1] hazard this PR reproduces is fixed only for variant 12 without post…

Comment thread aiter/ops/mega_mhc.py Resolved
Comment thread csrc/kernels/mega_mhc.cu Resolved
@junhaha666

Copy link
Copy Markdown
Contributor

@cpersson-amd Please review whether the suggestions made for the aiter-bot modification are reasonable.

Default runs now cover the split tail at non-power-of-two token counts and
both stream hidden sizes.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Carl Persson <[email protected]>
@cpersson-amd

Copy link
Copy Markdown
Contributor Author

Thanks, @junhaha666. Both findings are reasonable:

  • Test coverage: fixed in 612562b. The default run now covers the ragged split-tail shapes and H=7168.
  • Variant 11 hazard: disassembly and stress data are inline. The same packed pattern is in base, and variant 11 never failed under stress, with or without this PR.

@junhaha666
junhaha666 merged commit d83d011 into ROCm:main Nov 19, 2026
GwilliamHu added a commit that referenced this pull request Nov 26, 2026
…50 packed high-dword read

The combine tail of a route_i8 large-input kernel subtracts 128 x the scale
sum from each unit's four accumulators. Written as a vector product, the
compiler packed two units' offsets into one register pair and subtracted the
second one with v_pk_add_f32 op_sel:[0,1]: the low half reads src1's high
dword, the pattern that reads 0 in lanes 48-63 on gfx950 while another wave of
the SIMD runs MFMA (#7818). Each unit's offset is now one scalar
product subtracted value by value, so it sits in the low dword of its own
register and the packed subtract broadcasts it with op_sel_hi only.

Same operations in the same order: bitwise identical results. Offline gfx950
ISA of the V4.1-Flash EP8 (1024, 16384), EP4 and EP2 (16384) large-input
kernels, A8W4 and A4W4: 4 -> 0 op_sel:[x,1] packed-f32 instructions each,
same VGPR/SGPR counts, 3-5 fewer instructions. Found in BinDing's
0055824 (AITER_MEGA_LARGE_V3=qf), which used inline v_sub_f32 instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
GwilliamHu added a commit that referenced this pull request Nov 26, 2026
…50 packed high-dword read

The combine tail of a route_i8 large-input kernel subtracts 128 x the scale
sum from each unit's four accumulators. Written as a vector product, the
compiler packed two units' offsets into one register pair and subtracted the
second one with v_pk_add_f32 op_sel:[0,1]: the low half reads src1's high
dword, the pattern that reads 0 in lanes 48-63 on gfx950 while another wave of
the SIMD runs MFMA (#7818). Each unit's offset is now one scalar
product subtracted value by value, so it sits in the low dword of its own
register and the packed subtract broadcasts it with op_sel_hi only.

Same operations in the same order: bitwise identical results. Offline gfx950
ISA of the V4.1-Flash EP8 (1024, 16384), EP4 and EP2 (16384) large-input
kernels, A8W4 and A4W4: 4 -> 0 op_sel:[x,1] packed-f32 instructions each,
same VGPR/SGPR counts, 3-5 fewer instructions. Found in BinDing's
0055824 (AITER_MEGA_LARGE_V3=qf), which used inline v_sub_f32 instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
GwilliamHu added a commit that referenced this pull request Nov 27, 2026
…50 packed high-dword read

The combine tail of a route_i8 large-input kernel subtracts 128 x the scale
sum from each unit's four accumulators. Written as a vector product, the
compiler packed two units' offsets into one register pair and subtracted the
second one with v_pk_add_f32 op_sel:[0,1]: the low half reads src1's high
dword, the pattern that reads 0 in lanes 48-63 on gfx950 while another wave of
the SIMD runs MFMA (#7818). Each unit's offset is now one scalar
product subtracted value by value, so it sits in the low dword of its own
register and the packed subtract broadcasts it with op_sel_hi only.

Same operations in the same order: bitwise identical results. Offline gfx950
ISA of the V4.1-Flash EP8 (1024, 16384), EP4 and EP2 (16384) large-input
kernels, A8W4 and A4W4: 4 -> 0 op_sel:[x,1] packed-f32 instructions each,
same VGPR/SGPR counts, 3-5 fewer instructions. Found in BinDing's
0055824 (AITER_MEGA_LARGE_V3=qf), which used inline v_sub_f32 instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
coderfeli pushed a commit that referenced this pull request Nov 29, 2026
…nce optimizations, capacity 32768, rank-shared AOT (#8623)

* tune(mega_moe): 256-wide small-input GEMM1/GEMM2 tiles for EP8 V4.1-Flash at 16 and 32 tokens

Half the GEMM1 tiles and GEMM2 blocks, each streaming a longer weight slab.
Measured on 8x MI355X (EP8 V4.1-Flash a8w4, MTPR 1024, one CUDA graph per
distinct input, max over ranks): -2..-8% per call at 16-32 rows a rank
under uniform, zipf and hot routing. Bitwise identical outputs (asmval, 142
points). The EP8 fused-config digest follows.

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

* perf(mega_moe): send a dedup row before its expert-counter atomic

A deduplicated token row goes to its destination's token-row region, whose
place does not depend on the expert offset the counter atomic returns, so the
row push is issued first and overlaps the atomic's remote round trip.
Bitwise identical outputs (asmval, 142 points: decode MTPR 128 and prefill
MTPR 16384, uniform / zipf / hot / invalid-slot routing, uneven and idle
ranks). Measured with the next three commits: 1-8% per call at 16-512 rows a
rank (EP8 V4.1-Flash a8w4, MTPR 1024; e.g. 512 rows 355.9 -> 344.4 us
uniform, 618.0 -> 587.9 zipf, 1487.4 -> 1417.6 hot).

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

* perf(mega_moe): quantize each token row once in the small-input dispatch

With dedup_rows a producer wave takes a token instead of a route: it loads
and quantizes the row once and pushes it to each distinct destination rank
of its top-k (one lane a route; v_readlane keeps the remote pointers
scalar), and the top-k counter atomics go out from one instruction. Before,
each route's wave quantized the row again. Bitwise identical outputs
(asmval, 142 points); part of the 1-8% measured with the neighbouring
dispatch and entry changes.

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

* perf(mega_moe): interleave an expert's slots over its small-input m-tiles

m-tile t of an expert with nt m-tiles takes its slots t, t + nt, ..., so the
rows of a GEMM2 tile come from many source ranks and its returns spread over
their links instead of one. A row's GEMM math and the combine's fixed top-k
order are unchanged, and the slot order within an expert was already decided
by racing atomics: bitwise identical outputs (asmval, 142 points); part of
the 1-8% measured with the neighbouring dispatch and entry changes.

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

* perf(mega_moe): small-input entry without the ticket atomic and epoch gate

Protocol change: a launch no longer takes an entry ticket (one atomic per
CTA) or waits at an epoch gate. Roles go by block id (owner, producers,
consumers), and every CTA reads the entry state past L2: the previous
launch's epoch (DispatchSlot.LAUNCH_EPOCH), parity and expected source
value, and advances them itself. The last WG of a launch (the combine's last
ticket, when every CTA is past its reads) zeroes the work and producer
counters and stores this launch's epoch, parity and expected value for the
next one; stream order puts those stores before the next launch's loads.
Cross-rank buffers written before the plan stay parity double-buffered, so
no handshake is needed. The names follow (launch_epoch, cta).

The op test's epoch-wrap case now presets the runtime's launch-epoch word
(the entry ticket counter it preset is gone); the next launches still cross
the 32-bit wrap. Bitwise identical outputs (asmval, 142 points); part of the
1-8% measured with the dispatch changes before it.

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

* feat(mega_moe): EP8 small-input GEMM1 pairs an expert's 32-row m-tiles into 64-row units

On a rank that reads W1 through the cache (a hot expert or many routed rows), each GEMM1 unit of an expert
with more than one m-tile runs a pair of its interleaved m-tiles (2j, 2j + 1) as one 64-row tile, so its W1
slab is read once per 64 rows instead of once per 32. The local plan keeps a per-expert unit-group table
next to its m-tile table; a unit's plan comes from one ballot lookup over it (shared with the m-tile lookup).
The XCD slices of the GEMM1 unit space stay equal in m-tile units (a pair's units weigh two m-tiles'), so an
XCD holding a paired hot expert does not take more rows than the others; a rank that does not pair skips
those lookups. GEMM2 keeps its m-tile units and slices.

V4.1-Flash EP8 configs: pair_tiles at 64 and 128 tokens. Measured on 8x MI355X (a8w4, MTPR 1024, 3 ABBA
rounds against the parent): hot -11.7% at 64 rows a rank and -17.3% at 128, zipf -1.0% / -4.2%, uniform and
the other sizes within +-0.2%. Bitwise identical outputs (asmval, 142 points; MFMA order per accumulator
unchanged).

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

* feat(mega_moe): EP8 V4.1-Flash large-input route at every capacity

V41_FLASH_EP8_LARGE_M_MTPRS lists every large-input capacity (1024..16384).
The fault that kept capacities 1024-4096 on the staged route came from
another process's kernels sharing the GPUs, not from the kernel: on exclusive
GPUs the large-input route at 1024, 2048 and 4096 passes the asmval large
points three times each without a fault. An EP8 instance below 8192 now
serves prefill through the fused route (768 rows a rank at capacity 1024:
354 us vs 518 us staged, uniform). The config docstring and the AOT README
follow.

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

* feat(mega_moe): serve A4W4 decode calls through the fused small-input route

An A4W4 MegaMoEV2(routed=True) on a FUSED_LAYOUTS layout (EP8 DeepSeek-V4-Pro,
EP8 / EP4 / EP2 DeepSeek-V4.1-Flash) now builds the small-input runtimes and
sends calls of up to 512 rows a rank through the fused dispatch + GEMM1 +
GEMM2 + combine kernel; above that A4W4 takes the staged route. The
large-input route stays A8W4 (LARGE_M_QUANTS).

- The producers quantize each bf16 row to MXFP4 (E2M1 + E8M0 per 32 values),
  bit-identical to per_1x32_mx_quant(quant_mode="fp4") of the staged route,
  with the MXFP8 lane mapping (16 values a lane, a scale group per lane pair):
  a lane stores 8 payload bytes per 1024-value chunk, so rows of 5120 / 7168
  values tile exactly. The dedup_rows producers (one quantization a token)
  take the same path.
- GEMM1 reads FP4 A (128-byte K-steps), also through the dedup_rows srcmap.
- The GEMM1 output stays FP8, so GEMM2 and the combine are unchanged; the
  shared GEMM1-output arena is sized per route dtype.
- Kernel names gain _afp4 for A4W4 only; the A8W4 kernels are unchanged.
- The V4.1-Flash AOT profiles ship A4W4 as well.

The A4W4 small-input kernels use the A8W4 small-input tunes unchanged.

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

* test(mega_moe): run the routes suite with --quant a4w4

The routes suite builds the instance with --quant (A4W4: small-input and
staged routes, gated at relL2 0.25 against the fp32 reference and the staged
route).

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

* refactor(mega_moe): share the MX quant helpers with the fused small-input producers

Review follow-ups on the A4W4 small-input route:
- The E8M0 scale comes from quant_utils.emit_mx_e8m0_scale (RoundUp) in
  per_1x32_mx_quant and in the fused producers' _quantize_row_mx; quant.py
  gains pack_mx_fp4_words, which both use for the FP4 words.
- The payload store derives a lane's word count from the quantized row; the dead
  fz_n_i32 argument of emit_direct_fixed_slot_payload and TILE_K_BYTES go.
- SmallMRuntime / LargeMRuntime gate on FUSED_QUANTS / LARGE_M_QUANTS; the
  small-input payload capacity takes the A dtype (MegaMoEV2 drops _quant).
- The route-plan test covers MTPR 128 and 8192, pins the payload-arena size, the
  staged A4W4 row bytes and the FP8 GEMM1 output, and reuses the shape dicts.
- README: fused small-input route a8w4 or a4w4, large-input a8w4 only; the
  V4.1-Flash defaults build both quants.

ISA: the small-input kernels (a8w4 and a4w4) are byte-identical to the parent's
(offline gfx950 build of every token bucket).

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

* refactor(mega_moe): let the fused GEMM1 short and fold tiles read FP4 A

Prepares the A4W4 large-input route, whose GEMM1 runs the short, mid and
fold tiles (dedup_rows srcmap, async A copies) on packed FP4 rows:

- ATileLoader: an async A copy may end on a partial round (an FP4 fold tile
  of 128 + 32 rows is 1280 16-byte chunks, 2.5 rounds of 512 threads); the
  round runs on its leading waves, and load_row_map points the idle threads'
  rows past the tile at its last row, so the row-arrival wait never spins on
  another tile's rows. Every existing tile copies whole rounds and keeps
  its code.
- build_fused_gemm1: the short / fold tile loaders and MFMAs take the A
  dtype and its row bytes; the row_map path no longer requires 256-byte
  K-steps.

No kernel changes: the A8W4 tiles pass the same values.

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

* feat(mega_moe): serve A4W4 prefill calls through the fused large-input route

An A4W4 MegaMoEV2(routed=True) on a FUSED_LAYOUTS layout now also builds the
large-input persistent kernel at the capacities large_m_mtprs_for() gives the
layout (1024..16384 for EP8 DeepSeek-V4-Pro and EP8 DeepSeek-V4.1-Flash, 8192
and 16384 for EP4 / EP2 DeepSeek-V4.1-Flash), so a call of 513 rows a rank up
to the capacity is fused like A8W4 instead of taking the staged route.
LARGE_M_QUANTS goes: both fused routes take FUSED_QUANTS.

- The input quant kernel writes MXFP4 rows (model_dim / 2 bytes, the same
  E8M0 scales); the dispatch moves them in 64-lane column blocks of 1024
  values, a dwordx2 a lane (dwordx4 for FP8), in the presend and batched
  payload copies; the route-major copy takes any dwordx4-aligned row.
- GEMM1 reads FP4 A (128-byte K-steps) in every tile shape: main, short,
  mid and fold, also through the dedup_rows srcmap (x_bytes from the FP4
  row size).
- The GEMM1 output stays FP8, so GEMM2 and the combine are unchanged; the
  shared GEMM1-output arena is sized for the large-input route's FP8 rows.
- LargeMRuntime sizes its payload, quant buffers, input checks and AOT
  preload by the A dtype; _dispatch_dtype moves to mega_moe_stage1 for both
  fused runtimes.
- Kernel names gain _afp4 for A4W4 only; the A8W4 kernels are unchanged.

The A4W4 large-input kernels use the A8W4 large-input tunes unchanged. The
route-plan test follows: A4W4 routed instances of the four fused layouts take
the large-input route at MTPR 8192 and 16384 (FP4 payload rows, uint8 quant
buffer, FP8 GEMM1 output held by the shared arena), the large-input buffers
fit 32-bit offsets for both quants, and the A4W4 large-input kernel runs the
A8W4 config and Stage2 spec with row copies and GEMM1 tiles of whole column
blocks and waves.

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

* test(mega_moe): cover the A4W4 large-input route

- AOT: the V4.1-Flash EP4 / EP2 / EP8 A4W4 jobs include the large-input
  MTPRs (8192, 16384).
- Multi-GPU: the A4W4 large-input route is compared with the staged route
  to --rtol (FP8 vs FP4 GEMM1 output), in the main comparison, layer-slot
  stress and skewed route switch; the SiLU gate checks the instance's quant.
  The fused-vs-staged gates of the size suite's main comparison and the
  routes suite also fail on any row off by more than half its norm (a
  corrupted row the tensor's relative L2 would hide).

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

* feat(mega_moe): per-quant fused configs for A4W4 tuning

select_fused_config takes the quant: A4W4 starts from a layout's A8W4
config and goes through _tune_a4w4_small / _tune_a4w4_large (identity for
now), so the A4W4 small- and large-input routes can take tunes of their own.
The runtimes select their configs with their quant, and the payload-sharing
classmethods (indexed_payload, payload_capacity, ends_all_ranks) take the
activation dtype, since a tune may change the protocol knobs they read.
No kernel changes.

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

* feat(mega_moe): per-bucket large-input configs and a small-input split-tail knob for A4W4 tuning

Large-input route: a call launches the config of its EP-wide max_tokens
(MegaMoEV2.forward / forward_prequant pass it through; None keeps the
capacity's config), so _tune_a4w4_large takes the token bucket and can
change the launch geometry per row count, as the staged path does. The
knobs that size the runtime's buffers or set what the routes share
(large_m_runtime_knobs: P2P quant, dedup rows, bucket pairs, combine token
wait, row alignment, scale staging) must agree across the buckets of a
capacity; LargeMRuntime checks it, sizes the scale staging buffer for the
largest bucket config and preloads every distinct bucket config. A8W4
still runs one config per capacity.

Small-input route, FusedStage1Knobs.g1_split_tail (off by default): with
tile_n 256, up to N units of an XCD slice's partial last GEMM1 round run as
two tile_n / 2 halves, as many as that round leaves CTAs idle; GEMM2
readiness counts half units. It enters the small-input kernel name only when
set (not with pair_tiles). The kernel's GEMM1 builds share one argument list.
The small-input kernels are byte-identical to the parent's (offline gfx950
build); on 8x MI355X per-bucket large configs (V4-Pro EP8) and g1_split_tail
(V4-Pro EP8 small-input kernel) run correctly (--check-time-acc).

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

* feat(mega_moe): A4W4 tune for EP8 DeepSeek-V4-Pro fused routes

A4W4 on EP8 V4-Pro now takes its own small- and large-input tunes instead of
the A8W4 ones (A8W4 configs and every other layout are unchanged).

Large input (routes suite, MTPR 16384, speedup = staged / fused):
  rows      513   1024  2048  4096  8192  16384
  before   0.871 0.935 0.995 0.953 1.013 0.982
  after    1.307 1.365 1.384 1.283 1.246 1.182
The EP4 V4.1-Flash knob set without the parts V4-Pro's dims cannot take
(fold_tail / mid_tail_rows, GEMM2 fold_tail / nt_single / ascale_lds /
early_p_mid), cached W1, payload_min_blocks 4, and early_p 2 from the
8192-row bucket.

Small input (MTPR 512):
  tokens     1     16    64    128   256   512
  before   1.538 1.584 1.614 1.628 1.295 1.083
  after    1.749 1.621 1.637 1.646 1.304 1.124
The EP8 V4.1-Flash small tune (with its 256-wide GEMM1/GEMM2 n-tiles at 16
tokens) without the parts measured on V4.1-Flash only (its 256-wide GEMM2
tiles at 32 tokens and its GEMM1 m-tile pairs), cached W1 at 1 token, and
256-wide GEMM1 n-tiles with g1_split_tail 64 at 256/512.

The A4W4 large-input test now checks the A4W4 config and compares the payload
geometry with A8W4 only while the runtime-sizing knobs agree (the V4-Pro A4W4
tune dedups dispatch rows).

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

* feat(mega_moe): A4W4 tune for EP8 DeepSeek-V4.1-Flash fused routes

A4W4 on the EP8 V4.1-Flash layout takes its own small- and large-input
tunes (_tune_v41_flash_ep8_a4w4_small / _large) on top of the A8W4 ones,
selected from the A4W4 hooks; A8W4 configs are unchanged.

Small input: bucket 1 cached W1; bucket 16 256-wide GEMM1/GEMM2 tiles with
g1_split_tail 64; buckets 256/512 256-wide GEMM1 tiles; the A8W4 tune's
GEMM1 m-tile pairs at 64 / 128 tokens and 256-wide GEMM2 tiles at 32 carry
over. Large input: buckets >= 2048 payload_min_blocks 4; 512/1024 keep the
A8W4 tune.

Measured on gfx950, 8 ranks, routes suite, MTPR 16384 (staged/routed,
uniform; measured before this series carried the A8W4 small-input
changes): small 1.31-2.37x -> 1.37-2.49x, large 1.22-1.66x ->
1.25-1.68x; zipf 1.0 and all-to-rank-0 routing do not regress.

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

* tune(mega_moe): A4W4 EP4 V4.1-Flash fused small/large configs

Small: tile_n 256 + g1_split_tail 64 at 64/256 tokens, stream_w + early_p 6
at 512. Large: cached W1, 64 producer CTAs and early_p 2 from 4096 tokens.
Measured on gfx950 (4 ranks, routes suite, MTPR 16384); A8W4 unchanged.

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

* tune(mega_moe): A4W4 EP2 DeepSeek-V4.1-Flash fused small- and large-input configs

Small-input: cached W1 at 1 token, 256-wide GEMM1 tiles at 64 tokens.
Large-input: presend over 16 local experts. A8W4 configs unchanged.

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

* test(mega_moe): A4W4 fused-config digests and quant-parametrized protocol checks

- A4W4 fused-config digests for EP8 DeepSeek-V4-Pro and EP8 / EP4 / EP2
  DeepSeek-V4.1-Flash: every small-input bucket at MTPR 256 and 512 and every
  large-input capacity of the layout at each of its token buckets.
- The *_small_m_buckets_share_one_protocol tests run for a8w4 and a4w4.
- EP8 V4.1-Flash pairs an expert's 32-row m-tiles at 64 and 128 tokens for
  either quant (the A4W4 tune keeps the A8W4 one there), on the interleaved
  local plan the pairing needs.
- The A4W4 large-input config geometry is checked at every capacity a layout's
  large-input route serves (1024..16384 on EP8).

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

* feat(mega_moe): V4.1-Flash EP4 / EP2 large-input route at every capacity

Every fused layout now builds the large-input kernel at every capacity in
LARGE_M_MTPRS (1024..16384), as EP8 V4.1-Flash already did since 6420f64;
large_m_mtprs_for() and the per-layout V41_FLASH_EP*_LARGE_M_MTPRS lists go.
EP4 and EP2 reuse their existing large-input tunes unchanged: the tunes do not
depend on the capacity (A4W4 varies by token bucket only), so a capacity below
8192 launches, at each bucket, the config the 16384 capacity launches there.

The EP4 fault once seen at 1024-4096 is believed to be the same co-residency
misdiagnosis as EP8's (another process's kernels sharing the GPUs); GPU
revalidation of EP4 / EP2 at 1024, 2048 and 4096 is pending.

Offline: the AOT replay builds EP4 and EP2 at MTPR 1024 / 2048 / 4096 for a8w4
and a4w4 (36 jobs ok, --check 36 ok). Rank-0 large-input kernel spills vs the
16384 kernels: a8w4 keeps sgpr 47 / vgpr 50 / scratch 188 everywhere; a4w4
keeps sgpr 47 / vgpr 31 / scratch 112 at EP4 2048 / 4096, but EP4 1024 and EP2
1024 / 2048 / 4096 spill one more vgpr (vgpr 32, scratch 116 vs 31 / 112).
The shipped AOT MTPR list is unchanged; its comment and the README follow.

Tests: the capacity tests run every layout over LARGE_M_MTPRS, a new test pins
that each capacity's configs equal 16384's, the A4W4 digests stay over the
capacities they pinned, and the offline routed instance adds MTPR 1024 / 4096.

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

* feat(mega_moe): send every call the small-input route cannot take to the large-input route

MegaMoEBundlePlan.route_for drops the max_tokens >= LARGE_M_MIN_TOKENS bound
of the large-input route: on an instance that builds it, a call the
small-input route does not take (forward_prequant, a part without 256 CUs, a
max_tokens above the reduced small_m_mtprs) runs fused instead of staged. With
the large-input route at every capacity of every fused layout, a routed
instance at a power-of-two MTPR up to 16384 now stages no call that passes
max_tokens.

Such a call of fewer than LARGE_M_MIN_TOKENS rows launches the
LARGE_M_MIN_TOKENS config, which large_m_buckets() already builds, so no new
kernel is compiled; every large-input tune keeps that config up to 1024 rows
(a test pins it), so it is also the config of the call's own bucket. Calls of
513 rows or more take the same route and config as before.

Tests: an exhaustive sweep (4 fused layouts x a8w4 / a4w4 x MTPR 1..16384 x
every max_tokens) asserts no routed call stages and every large-input call
launches a built bucket, and that without the small-input route the
large-input route takes every call from MTPR 1024; the route-exclusion and
routed-instance tests cover prequant and reduced small capacities.

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

* fix(mega_moe): keep the large-input 8-bit combine offset off the gfx950 packed high-dword read

The combine tail of a route_i8 large-input kernel subtracts 128 x the scale
sum from each unit's four accumulators. Written as a vector product, the
compiler packed two units' offsets into one register pair and subtracted the
second one with v_pk_add_f32 op_sel:[0,1]: the low half reads src1's high
dword, the pattern that reads 0 in lanes 48-63 on gfx950 while another wave of
the SIMD runs MFMA (#7818). Each unit's offset is now one scalar
product subtracted value by value, so it sits in the low dword of its own
register and the packed subtract broadcasts it with op_sel_hi only.

Same operations in the same order: bitwise identical results. Offline gfx950
ISA of the V4.1-Flash EP8 (1024, 16384), EP4 and EP2 (16384) large-input
kernels, A8W4 and A4W4: 4 -> 0 op_sel:[x,1] packed-f32 instructions each,
same VGPR/SGPR counts, 3-5 fewer instructions. Found in BinDing's
0055824 (AITER_MEGA_LARGE_V3=qf), which used inline v_sub_f32 instead.

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

* perf(mega_moe): spread a few-token launch's dedup sends over each producer's waves

With dedup_rows one producer wave takes a token: it quantizes the row once and sends it to every destination
of its top-k. At 1-4 tokens a rank that leaves the other waves of each producer CTA idle and puts all of a
token's remote rows behind one wave. A launch of at most _SPREAD_MAX_TOKENS (4) tokens a rank now has every
wave of the token's producer CTA quantize it and send, count and publish the routes of its own top-k slots
(slot j: wave j % num_waves). The writes each destination sees, and the protocol (one producer CTA a token,
the same done counts), are unchanged; the choice is rank-local.

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

* perf(mega_moe): fused small-input GEMM2 stores BF16 P2P rows with every lane of the workgroup

The fused small-input kernel's GEMM2 epilogue scattered one weighted BF16 row per wave store with
BN // 8 lanes active (32 of 64 at BN 256), each row behind a readfirstlane chain for its route,
weight and peer base. On BF16 launches (fp8_rows == 0) every lane now stores 16 bytes of one row,
64 // (BN // 8) rows per store (as amd-kernels PR #12's fused EP8 return path), through a global
store at its own peer address; the route/weight/peer/value LDS reads of all passes are issued
before the first store. FP8 launches (with their BF16 head rows) keep the per-wave rows.

Each element is still f32(acc) * f32(weight) rounded once to BF16 at the same destination byte,
so the P2P rows and the combine output are bitwise unchanged. Lean / tok_done epilogues are
untouched (wide_bf16 is off for them).

V4.1-Flash EP8 decode (MTPR 512, ABBA, 1-512 rows x uniform/zipf/hot): 0 points slower;
8 rows uniform/zipf 1.7-2.2% faster and 192/256 rows uniform 1.1-2.4% faster, both quants.

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

* tune(mega_moe): EP8 V4.1-Flash 8-column GEMM1 epilogue from 16 small-input tokens

Both quants, from the 16-token bucket: the per-tile output resource with the 8-column GEMM1 quantize/store pass
(epi_evec 8) and its no-serial-wait form (epi_lean 1; the IEEE SiLU stays, so outputs are bitwise-identical).
ATT of the hot rank at 128 zipf tokens: the 2-column pass costs 49k cycles a wave, 16k of them on its 2-byte
stores. Applied in _tune_v41_flash_ep8_small_both after the A8W4 / A4W4 tunes of the V4.1-Flash EP8 layout only.
Offline gfx950 ISA: 236-248 VGPRs; the a8w4 pair-tile body (64 / 128 tokens) spills 4 SGPRs.

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

* perf(mega_moe): small-input 64-row GEMM2 issues its B loads ahead of the barrier and the A copy

The fused small-input kernel's BM64 / BN256 GEMM2 tiles (256 and 512 tokens) take gemm2_compute_v2's
early_b_load with a_dma_uniform: each K-step's W2 and scale loads go before the barrier and an unconditional
A copy, so the first MFMA waits for them with vmcnt(4) (the copy stays in flight). Before, the A copy was issued
first and the MFMAs waited vmcnt(2) behind it. ATT at 192 uniform tokens: that wait (gemm2.py:92) is
41.1k / 40.5k cycles a wave (9.7% / 9.4%, A8W4 / A4W4). Both quants (GEMM2 reads FP8 A for either).
Offline gfx950 ISA: no new spills; the 32-row tiles (and EP2) compile byte-identical.

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

* refactor(mega_moe): clamp-SwiGLU of the GEMM1 epilogue as a module function

SiluQuantEpilogue's silu(gate) * up with the swiglu_limit clamps becomes gemm_util.silu_mul_f32, so a GEMM1
body with its own epilogue computes the same values. Same operations in the same order: every offline gfx950
small-input kernel (EP8 / EP4 / EP2 V4.1-Flash, EP8 V4-Pro, A8W4 / A4W4, 1-512 tokens) compiles byte-identical.

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

* perf(mega_moe): ring GEMM cores for the fused small-input kernel (ring_core knob, off)

The small-input GEMM1 / GEMM2 K-loops wait on loads they just issued: at 192 uniform tokens ATT shows 66.2k
(GEMM1) and 45.1k (GEMM2) cycles a wave of vmcnt waits against 10.8k / 5.6k in amd-kernels PR #12, whose
loops are issue-bound instead. The new gemm_ring module ports that PR's GEMM core as one unit:

- the K loop is unrolled at trace time (no back-edge register copies), the FP4 weights are the scaled MFMA's
  operand A, and step k + pf's weight loads are spread over step k's MFMAs in the order they are emitted;
- the activation rows reach LDS by async DMA (BufferLoadAsyncLDS128b, asyncmark groups) through an nbuf-stage
  ring of 128-K steps in MFMA fragment order, nbuf - 2 >= pf steps ahead, so a weight wait never drains it;
- GEMM1 runs clamp-SwiGLU and the 1x32 MXFP8 quant in registers (no C-shuffle) and stores its output in the
  fragment order GEMM2's ring copies, with one scale dword per row and K step;
- GEMM2 reads its first pf weight steps and its rows' route ids before the m-tile's ready wait (the first read
  of the ready word goes ahead of them), and drops the CU's L1 at the unit claim, before any of its loads.

FusedStage1Knobs.ring_core = (pf1, nbuf1, pf2, nbuf2) turns it on (kernel name _rc...). It needs 64-row
interleaved m-tiles, 64 GEMM1 columns a wave (tile_n 256) and 256-wide GEMM2 tiles; each wave owns 64 rows x 32
intermediate / 64 hidden columns. Dispatch, plan, unit claims, ready epochs and combine are unchanged; GEMM2
takes its m-tile's expert and rows from the CTA's own plan. The GEMM2 scatter epilogue gains acc_t (transposed
accumulators, 16-byte LDS writes, rows BN + 4 floats apart). Both quants share the code: only GEMM1's activation
differs (FP4 rows: one slot a row tile and step).

No config sets ring_core yet: every offline gfx950 small-input kernel compiles byte-identical.

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

* tune(mega_moe): EP8 V4.1-Flash small-input ring GEMM cores from 64 tokens

Both quants, buckets 64-512 (_tune_v41_flash_ep8_small_both): ring_core (2, 4, 2, 6) on 64-row m-tiles,
256-wide GEMM1 units and 256-wide GEMM2 tiles; 64 and 128 tokens leave their 32-row m-tile pairs (amd-kernels
PR #12 runs its 64-row tier from 49 tokens). GEMM2 weights go 2 steps ahead: with 4 weight loads a step and wave
that is more bytes in flight per CU than the PR's 3 steps of 2 (3 steps spill 12 VGPRs).

Offline gfx950 ISA (FlyDSL 0.5.3), A8W4 / A4W4: 252-256 VGPRs (128 arch + AGPRs), no scratch, LDS 67728 B
(2 CTAs a CU: 135 KiB of 160), 1856 MFMAs (2 x 640 GEMM1 + 2 x 288 GEMM2, unrolled), steady K-loop waits
vmcnt(7-16) where the 64-row bodies they replace wait vmcnt(0-2). Every other layout and bucket compiles
byte-identical. Config digests updated for EP8 V4.1-Flash.

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

* perf(mega_moe): half-height ring GEMM bodies for m-tiles of at most 32 rows

With interleaved m-tiles an m-tile of at most half the 64 rows is its expert's only one. Its GEMM1 unit and GEMM2
tiles run 32-row ring bodies (streamed weights) instead of the 64-row ones: half the MFMAs, activation DMA slots and
epilogue rows. The GEMM2 epilogue takes zero accumulators for the masked upper rows.

EP8 V4.1-Flash on MI350X against the parent of the ring commits (ABBA x2, MTPR 512): 142/142 asmval points bitwise
for both quants; 1-32 tokens within noise; 64-512 tokens zipf / hot -2~-17%. Uniform routing loses at 64-128 tokens
(A4W4 +1.7~2.4%, A8W4 +0.6~1.3%) and wins from 192. Bucket rule: a bucket keeps the ring core when its zipf / hot
gain exceeds its uniform loss (serving routing is skewed, the hot expert takes ~49% of the tokens); that holds for
every bucket of both quants (worst: A4W4 64 tokens, uniform +2.4% against zipf -12.5% / hot -4.0%), so both quants
share the 64-512 ring buckets.

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

* perf(mega_moe): large-input GEMM2 claims ahead and reads m-block classes from LDS

The large-input kernel's GEMM2 loop paid two serial thread-0 chains per
(m, n) unit between its barriers: the claim RMW and, with g2_skip_pad, a
chain of dependent srcmap / tile-row / expert loads that classifies the
claimed m-block (skip, fold its tail, single m-block).

- Every CTA classifies all m-blocks once at GEMM2 entry, one m-block per
  thread, into one LDS byte each in the A-scale bytes GEMM2 leaves unused;
  a claim then reads its m-block's byte. The class reads only plan-final
  rows, so it equals the per-claim result.
- A unit's publish takes the CTA's next claim before its drain, so the
  claim RMW returns while the peer stores retire; the loop head uses it
  (or claims itself after a skipped unit).

Each unit is still claimed once and run by its claimer with unchanged
per-row math, scatter and close protocol, so outputs stay bitwise equal.

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

* refactor(mega_moe): drop the large-input on/off API; max_tokens is the route switch

Remove MegaMoEV2.set_large_m_enabled(), the large_m_enabled constructor argument and the _large_m_choice state.
forward(max_tokens=...) already picks the route of every call (MegaMoEBundlePlan.route_for): on a routed instance
a call with max_tokens takes a fused route on every fused layout, and a call without it keeps main's staged route
(fixed-slot or compact), as it did while set_large_m_enabled() had not been called. routed=True builds the
large-input route wherever the layout and capacity support it; routed=False keeps the staged instance of main.
A second switch could only send a call with max_tokens to the staged route; MegaMoEBundlePlan.route_for drops its
large_m exclusion with it.

The only external user was the unmerged SGLang PR sgl-project/sglang#47065, written against an older interface.
The multi-GPU tests take their staged reference from a call without max_tokens, and the size suite and the
benchmark pin their plan through routed / small_m_mtprs.

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

* fix(mega_moe): small-input co-residency check covers the whole LDS and the pair tiles

The small-input fused kernel needs its whole grid resident (2 CTAs a CU): the combine
reducers spin until every CTA took its ticket. The LDS check counted only the pool, not
the A scales, the work word and the plan tables, and pair_tiles at 64-row m-tiles
(128-row pairs) needs 87440 bytes of LDS and 264 registers (one CTA a CU, a hang).
Check the whole SharedStorage at compile time and reject pair_tiles off 32-row m-tiles
in the config. The check equals the compiled LDS size of every offline gfx950 small-input kernel
(V4.1-Flash EP8 / EP4 / EP2, V4-Pro EP8, both quants, 1-512 tokens, 30608-81040 bytes) except the ring-core
kernels, which it bounds 16 bytes high (67744 vs 67728: their A-scale words are unused). No kernel changes
(the 72 kernels compile byte-identical).

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

* perf(mega_moe): ring GEMM cores for every small-input layout and bucket

Every small-input config (EP8 V4-Pro and EP8 / EP4 / EP2 V4.1-Flash, A8W4 and
A4W4, token buckets 1..512) runs the gemm_ring GEMM1 / GEMM2 cores on 64-row
interleaved m-tiles of the local plan, 256-wide GEMM1 units and 256-wide GEMM2
tiles; an m-tile of at most 32 rows (most of them at the small buckets) runs
the half-height bodies. V4-Pro A8W4 takes the dedup rows and local plan the
ring reads; at V4-Pro's dims the GEMM2 weights go one step ahead (two spill).

To fit every layout without scratch: the kernel allocates no AGPRs (with them
the registers split 128 / 128 and the K loops spill VGPRs or copy operands
between the halves), the pointers and epoch the consumer loops hold across
the GEMMs are SGPRs and GEMM2's other dispatch-table pointers and the combine
peer base are loaded past GEMM1 (held through it as VGPRs, they spill the K
loops), grids of one CTA a CU hint one wave a SIMD (the EP4 4-token kernel
spilled), and the 16-token grids of two CTAs a CU no longer hint one.

Offline gfx950 ISA (FlyDSL 0.5.3), all 144 small kernels (4 layouts x 2 quants
x 9 buckets x MTPR 256 / 512): no scratch, at most 256 VGPRs, at most 68.7 KiB
LDS a CTA (two CTAs a CU fit).

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

* refactor(mega_moe): the small-input kernel keeps only the ring GEMM cores

Every small-input config runs the ring cores (previous commit), so the old
GEMM bodies of compile_mega_moe_stage1 go: the streamed / cached / paired /
split-tail GEMM1 builds, the gemm2_compute_v2 tile runner, their LDS (A-scale
tile, C-shuffle) and resources, the m-tile pair plan and the split-tail work
encoding. What the ring requires becomes the kernel itself: dedup token rows
(the per-route payload dispatch goes) and the CTA-local interleaved plan.

Knobs that no config reads any more go with them: FusedStage1Knobs plan_local,
g2_uniform, g1_lookahead, g1_a_ahead, g1_split_tail, pair_tiles and ring_core
(the ring depths are the kernel's: GEMM2 weights one step ahead at V4-Pro's
model dim), and the small kernel's tile_k, pipe_weights, mfma_amajor,
swizzle_a, async_a_copy, use_tile_resource, epi_evec, epi_lean and
ascale_packed (large-input only now). The small-input tunes keep what still
changes a kernel; the protocol tuple is direct_done, tok_counters,
bf16_head_tokens. The launch drops the unused sorted-id / expert-id / token
count / input-scale arguments, and the fixed slots are 64 rows (the m-tile).

Offline gfx950 ISA, all 144 small kernels vs the previous commit: the same
MFMA and memory instructions (kernel-argument loads and register allocation
differ), no scratch, LDS <= 68.7 KiB a CTA. Math order unchanged.

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

* refactor(mega_moe): drop the shared GEMM helpers' small-input-only paths

With the small-input kernel on the ring cores, the staged Stage1 and the
large-input kernel are the only users of build_fused_gemm1 and its helpers,
and both run do_tile. do_tile_la, the paired-tile runner and _PairEpilogue
go, with build_fused_gemm1's rows_rsrc / lookahead / plan_lookup / a_ahead /
pair_tiles; the A loaders' paired / tx modes, their row_stride and valid-rows
clamps, the epilogue's valid-rows / store-policy overrides, the B-scale load
cache policy and gemm2's valid_rows. _LA_CM moves to gemm_ring, its last user.

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

* perf(mega_moe): 32-row ring m-tiles for the small-input buckets up to 128 tokens an EP group

Up to 128 tokens an EP group (EP8 16, EP4 32, EP2 64 tokens a rank) the
small-input kernel plans 32-row m-tiles and runs only the 32-row ring bodies
(the 64-row kernels carry both heights). The kernel is half the size, and the
experts that hold every token of a skewed launch get twice the GEMM1 / GEMM2
units while those still fit one round of the grid. Per-row math order is
unchanged. The plan CTA's m-tile metadata, sized by 64-row m-tiles, holds the
32-row m-tiles of these buckets too (asserted).

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

* refactor(mega_moe): drop the ring cores' fixed knobs and stale small-input notes

What: make_ring_gemm1 takes no sw_cm / q_cm (every caller passed the same
sc0|nt policy, now gemm_ring's _G1_CM) and _lane_ids no unused wave count;
the small-input finalize drops interleave / keep_running (its only caller
passes True for both) and the non-interleaved metadata branch;
SiluQuantEpilogue's fused vec8 store reads its own cache policy instead of
a pass-through argument; comments that named the removed la2 bodies or
64-row-only tiles are corrected.

Why: dead parameters and branches left by the ring-core switch.

Effect: no code generation change: the small-input final ISA of 42 kernels
(EP8 / EP4 / EP2 V4.1-Flash and EP8 V4-Pro, a8w4 and a4w4, 1..512 tokens)
is byte-identical to the previous commit's (FlyDSL 0.5.3, gfx950).

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

* refactor(mega_moe): small-input plan CTA publishes only the plan flag

What: the small-input finalize keeps the source wait, the expert counts and
the plan-flag store, and drops the per-m-tile metadata it wrote (sorted
expert ids, tile row bases, tile rows, num_valid / overflow words), the
plan_wt knob that only set those stores' cache policy and the release
before the flag, and the dispatch-table slots and workspace that only the
removed bodies read (SORTED_EXPERT, TILE_ROW_BASE, NUM_VALID, TILE_ROWS,
G2_EIDS, G2_TRB, G2_MAX_M_BLOCKS, XCD_ACQ). The remaining slots keep their
indices. Fused-config digests move only by the removed plan_wt field (the
old tables without it hash to the new digests).

Why: every CTA builds the plan in its own LDS since the ring cores
replaced the old GEMM bodies; nothing reads the plan CTA's metadata.

Effect: the 42 small-input kernels checked (EP8 / EP4 / EP2 V4.1-Flash and
EP8 V4-Pro, a8w4 and a4w4, 1..512 tokens) keep their VGPR / SGPR / LDS
and have no scratch; the plan CTA's code is about 600 ISA lines shorter.

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

* [CI] Run the MegaMoE V2 routes suite in the multi-GPU job

op_tests/multigpu_tests/test_mega_moe_v2.py has been in skip_tests since
MegaMoE landed (#4439), so no automated flow runs MegaMoE: changes to its
kernels or launch path merge without a single GPU run. #8600, which moved
every MegaMoE launcher onto the FlyDSL AOT cache, is an example: it was
only validated by hand afterwards.

Run the routes suite (staged, small-input and large-input routes as
production builds them; accuracy against the fp32 reference and the
staged route, per-layer rebinding, epoch wrap, CUDA graph replay) for
DeepSeek-V4-Pro and DeepSeek-V4.1-Flash EP8 on 8 ranks. Like
test_mega_moe_tp.py it skips unless the job has 8 gfx950 GPUs, and it
also skips without mori. Under the job's AITER_FLYDSL_AOT_CACHE=verify it
re-traces each MegaMoE launcher the wheel's AOT prebuild covers and
compares it with the cached object.

Measured on 8x MI355X: 182 s for both networks, with an empty FlyDSL
cache and with the AOT cache in verify mode alike. The suite's timing
section is informational only; pass/fail comes from the accuracy gates
with fixed seeds.

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

* ci: run the MegaMoE V2 routes suite for V4.1-Flash EP8 A4W4 too

The multi-GPU case added in the previous commit runs the routes suite for
DeepSeek-V4-Pro and V4.1-Flash EP8 with the default A8W4; this PR adds the
fused A4W4 routes, so the case also runs --network v41_flash --quant a4w4
(about 1.5 min on 8x MI355X).

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

* feat(mega_moe): large-input route at MTPR 32768 on every fused layout

Add 32768 to LARGE_M_MTPRS, so a 32768-capacity instance (ATOM's prefill
max_num_batched_tokens) builds the large-input route and every call that
passes max_tokens takes a fused route (small-input up to 512 rows a rank,
large-input above) instead of staging 513..32768 rows.

At 32768 every layout's large-input config sends a token row to a
destination once (dedup_rows, indexed payload). The V4.1-Flash tunes and
the V4-Pro A4W4 tune already do; V4-Pro A8W4 (all fused knobs off,
route-major payload: a 15.29 GiB/GPU symmetric heap) takes the V4-Pro
A4W4 large-input tune at 32768 only, renamed _tune_v4_pro_large
(8.04 GiB/GPU). Its 1024..16384 configs are unchanged. 65536 stays out
of reach: the tagged count words hold 16-bit counts.

The AOT default V4.1-Flash MTPRs gain 32768 (+28 jobs per quant set);
V4-Pro's 32768 jobs build the large-input kernel through LARGE_M_MTPRS.
Tests: the never-staged exhaustive check covers pow2 capacities up to
32768, the 32-bit offset test also bounds the GEMM1 out-scale view and
the GEMM1 output (per-tile resources past 2^31), every 32768 config is
checked to use dedup_rows, and the A4W4 digests stay pinned to the
pre-existing capacities.

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

* MegaMoE gfx950: map global expert IDs to W1/W2 indices without the rank

The GEMM1 tile scheduler and GEMM2 subtracted a compile-time rank * experts
offset from the global expert IDs the dispatch plan writes. A rank's IDs
modulo its expert count are the same indices, so the GEMMs no longer need
the rank: expert_offset becomes experts_per_rank. The aligned-pair Stage2
passes its pair's local experts directly.

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

* MegaMoE gfx950: pass the rank to the staged kernels at launch

The staged Stage1 bundle, prepare, Stage2 and aligned-pair Stage2 kernels
took the rank as a compile-time constant, so the AOT cache built every
kernel once per rank. They now take it as an i32 kernel argument: the
compile functions and their AOT keys drop rank, and the run/preload
helpers pass it at launch. Rank-dependent index math becomes a few scalar
ops; the source < rank prefix sums become select chains over the running
sums. Outputs are unchanged.

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

* FlyDSL intranode combine: take the rank as a kernel argument

make_combine_kernel baked the rank into its P2P slot offsets, its
cross-device barrier word and the invalid-slot peer, so MegaMoE's fused
combine (mega_moe_combine) was compiled once per rank. The kernel now
takes an i32 rank argument, which the op passes on every launch; the
generic dispatch/combine path shares the same kernel.

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

* MegaMoE gfx950: pass the rank to the small-input kernel at launch

The small-input persistent kernel takes the rank as an i32 kernel
argument instead of a compile-time constant, so one AOT entry serves
every rank. The fused combine publishes its flag at a byte offset
(rank * 8) read from the runtime's dispatch table where it is used,
rather than keeping the rank live across the GEMMs.

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

* MegaMoE gfx950: pass the rank to the large-input kernel at launch

The large-input persistent kernel takes the rank as an i32 kernel
argument. large_m_kernel_specs drops ("rank", rank) from the fused Stage2
spec, so the kernel name hash (S2_KEY) and the AOT key no longer depend on
the rank; the skew boost of the payload geometry tests the destination
against the rank at run time, and the plan writes its counts through the
base of its own row in each destination's count matrix.

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

* AOT MegaMoE: build one job per profile instead of one per rank

Every MegaMoE kernel now takes the rank at launch and no AOT key holds
it, so rank 0's replay builds the kernels of every rank. default_jobs
yields one job per (MTPR, experts per rank, quant): the default build
drops from 276 jobs and 8898 AOT entries to 42 jobs and 1333 entries.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

3 participants