Skip to content

[FlyDSL] perf(flydsl): route the gfx1250 TP prefill MoE in one launch - #7547

Open
lirui927 wants to merge 20 commits into
ROCm:mainfrom
lirui927:fuse/f7-prefill-moe-route
Open

lirui927 wants to merge 20 commits into
ROCm:mainfrom
lirui927:fuse/f7-prefill-moe-route

Conversation

@lirui927

@lirui927 lirui927 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

What it does

On gfx1250, a TP MoE batch too large for the single-workgroup route (_fused_tp_route) runs three launches before the A1 quant: a zero fill of the per-expert counter, moe_route_lds and moe_contiguous_psum_remap. When the A1 quant is the token-multidest launch, this PR replaces the three with one launch, moe_route_lds_psum_sc.

  • One route launch. The kernel lives in its own module, kernels/moe_route_lds_psum.py, and is an aot_factory with its own declared sources, so kernels/moe_route_maps.py and the AOT caches built from it are unchanged. It routes as moe_route_lds does. Each workgroup then draws a ticket, and the last one sees every final count. That workgroup writes masked_m, the tile-aligned starts and psum, then zeroes the counter for the next call.

  • The quant places the rows. Each route's row is written as (slot << expert_bits) | expert. The token-multidest quant gets a third route mode next to [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's tp_route_slots: route_expert_bits > 0 decodes the row to starts[expert] + slot before the shared quant context and writes the final rows for the gather-reduce.

    • It is the same kernel: the two extra pointers are a tuple operand, route_rows=() (row_starts, final_rows), empty without the mode, and the route build adds only its launcher.
    • The wrapper takes the encoded rows as route_rows with route_starts and writes topids_to_rows, as it does for [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's tp_route_params. The expert bits follow from the length of route_starts.
    • The default token-multidest kernel keeps its name, arguments and ISA.
  • Gate. It is one bool:

    • not the single-workgroup route, HERD, the compact plan, EP or the compact-scale pair;
    • bf16 activations;
    • moe_kernels.token_multidest_quant_used() is true (no A-preshuffle, not prequantized). The quant dispatch uses the same predicate;
    • tp_route_rows_fit(E, routes): E <= 256 and the encoded row fits in int32. tp_prefill_route_psum checks the same function.

    Every other case keeps the old launches. AITER_FLYDSL_TOKEN_MULTIDEST_QUANT=0 turns this route off together with the token-multidest quant.

  • Default scope. By default the route serves TP batches with more than 2048 routes and fewer than 1024 tokens (top-5: 410–1023 tokens). At 2048 routes or fewer the single-workgroup route runs; from 1024 tokens (2048 on wmma_rep 1 rows) the compact-scale quant pair keeps the old launches. The other cases in the test run under an override that forces it: a raised AITER_FLYDSL_COMPACT_SCALE_MIN_TOKENS and a masked A-preshuffle on the tuned row.

  • Counter. It is a zeroed (E + 1,) buffer from graph_alloc.capture_scoped_cache + persistent_alloc, keyed by (E, device) and shared by eager calls and captures. Calls that use it must not overlap: two in flight at once (e.g. on two streams of one device) mix their counts.

    • A capture that runs before any eager call builds its own buffer, which needs torch >= 2.10.

Benefit

Whole fused_moe call, this head, on one idle MI455X (gfx1250), rocm/fw-bringup:gfx1250-minimax-m3-20261112 with FlyDSL 0.5.3: python3 op_tests/test_moe_prefill_route_in_quant.py (exit 0, one run). The baseline is the three launches this PR replaces, on the same tree. The output is bitwise equal in every row (err 0), and the pytest cases (check_moe) check from the kernel names that the one-launch route ran (the benchmark itself asserts only err 0). All five rows run under the test's override (Default scope).

tokens E topk dim inter format split (µs) one launch (µs) change
4536 129 5 6144 768 a4w4 233.0 227.2 -2.5%
9000 129 5 6144 768 a4w4 361.0 358.3 -0.7%
2048 129 5 6144 768 a8w4 139.3 138.4 -0.7%
1024 64 8 7168 2048 a4w4 215.1 211.3 -1.8%
700 256 6 4096 2048 a8w4 242.9 237.5 -2.2%

The gain is small: 0.7% to 2.5% of the call in this run (0.2% to 2.0% in a second run). The default window (MiniMax-M3 at 410–1023 tokens) was not timed at this head. The route + quant stage table of earlier heads is dropped: the quant builds changed since.

Host time per grouped-MoE call (CPU, launches stubbed, one pinned core, 10 interleaved rounds against #7543's branch with an A/A control). Measured at an earlier revision of this branch and not repeated.

call #7543 µs A/A this PR − #7543 bytecodes per call
TP decode M3, 1 tok 108.3 +0.17 (-0.53..+0.62) +0.44 (+0.03..+0.93) +40 of 13286
TP decode M3, 16 tok 109.0 -0.28 (-0.62..+0.70) +0.02 (-0.27..+0.75) +40
single-workgroup route, M3, 128 tok 109.1 -0.12 (-0.48..+0.17) +0.03 (-0.26..+1.03)
this route, M3, 512 tok 137.7 -0.20 (-1.24..+0.91) -7.65 (-7.78..-5.98)
compact pair, M3, 2048 tok 161.8 +1.38 (-1.11..+1.70) +0.43 (-1.09..+2.23)
A-preshuffle prefill, M3, 4096 tok 159.3 -0.19 (-1.73..+1.13) +0.25 (-1.23..+2.47) +105
prefill dsv41 E=384, 1024 tok 160.3 +0.01 (-1.45..+0.94) +0.20 (-1.05..+2.41)
TP decode Kimi-K2 E=384, 32 tok 121.6 +0.22 (-0.82..+1.80) +0.47 (+0.00..+0.87) +41
prequantized EP, 512 tok 152.1 -0.18 (-1.04..+1.30) +0.87 (-0.93..+1.99) +55
EP, 512 tok 149.5 +0.48 (-1.76..+2.26) +0.81 (-1.77..+1.03) +55

Deltas are same-round differences in µs (median, interquartile range). Calls that do not take the route run 40 to 105 more Python bytecodes (0.3-0.7%) and are inside the A/A spread.

Testing

On one idle MI455X (gfx1250), this head, rocm/fw-bringup:gfx1250-minimax-m3-20261112, FlyDSL 0.5.3:

  • python3 -m pytest -q -s op_tests/test_moe_prefill_route_in_quant.py: 8 passed.
  • python3 -m pytest -q -s op_tests/test_moe_tp_route_quant_fused.py ([FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's test): 8 passed.
  • python3 op_tests/test_moe_prefill_route_in_quant.py: exit 0 (the table above).
  • python3 -m pytest -q op_tests/flydsl_tests/test_flydsl_grouped_gemm.py, at the parent commit 86a18b08: 56 passed, 7 failed. See Unverified.

On CPU:

  • black --check and ruff check are clean on the 8 changed files at this head.
  • The rest ran at 86a18b08, whose tree is identical to this head's (the two commits after it cancel out).
    • ISA (FlyDSL compile-only, aiter.aot.flydsl.dry_run("gfx1250") with COMPILE_ONLY=1, final ISA compared with cmp): the 81 kernels without a route mode, the default token-multidest builds among them, are byte-identical to main ea578b41. [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's 12 route kernels are byte-identical to [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's head. Against b871d56b, this branch before [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's rework was merged in, moe_route_lds_psum_sc is byte-identical and the 21 row-decode quant builds are not: the row and start loads now sit ahead of the kernel's "block owns a token" guard (0 to 6 instructions fewer on 286-1809).
    • AOT declared sources (aot_cache._undeclared_imports): clean for the 7 caches around the route and the quant.
    • AOT replay of the MiniMax-M3 rows, python -m aiter.aot.flydsl.moe: 96 ok, and 48 ok with --row-tokens-only; --check passes for both. launch_route_psum and launch_token_multidest_route_rows are among the launchers.
    • Dry-run checks:
      • the quant refuses route_starts with too few tokens, row_to_token, tp_route_params, missing or short route_rows, int64 or strided buffers, and accepts the 512-token call;
      • tp_route_rows_fit is false past 256 experts and where the encoded row leaves int32;
      • of the tuned MiniMax-M3 calls only the 512-token TP call takes the route; decode, the single-workgroup route, the compact pair, A-preshuffle and EP do not.
    • CPU pytest of the neighbouring tests gives the same outcomes as [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's head.

Not covered

  • CI does not run the test: it needs gfx1250, so validation is local.
  • No timing inside the default window, no whole-model or serving run.
  • Archs other than gfx1250, EP, HERD and A-preshuffled batches do not take this path.
  • No test runs MoE calls on two streams of one device (see Counter).
  • Size: +1586/-58 in 8 files against main; +710/-13 in 6 files on top of [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543.

Dependencies

Stacks on #7543 (TP route inside the activation quant): the branch contains #7543's head 5689d664 and main ea578b41 by merge, and it merges after #7543.

PR Self-Review

Reviewed revision

99359c2

Behavior and intent

  • On gfx1250 TP batches past the single-workgroup route, the counter fill, moe_route_lds and moe_contiguous_psum_remap become one moe_route_lds_psum_sc launch when the A1 quant is the token-multidest kernel. The quant decodes (slot << bits) | expert to starts[expert] + slot.
  • Default scope: more than 2048 routes and fewer than 1024 tokens (top-5: 410–1023 tokens). Larger batches take the compact-scale pair and keep the old launches unless env moves that threshold.
  • Built as a third route mode of the token-multidest builder, in the one kernel: route_rows=() is a tuple operand next to [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's tp_route=(). The default kernel is unchanged (ISA-identical to main). The route kernel has its own module and AOT cache.
  • The gate is a plain bool. It shares _compact_ascale and token_multidest_quant_used() with the quant dispatch and tp_route_rows_fit() with the route launcher, and the quant rejects encoded rows before any launch if the two ever disagree.
  • Why: two launches fewer per call. Measured on the whole fused_moe call: 0.7% to 2.5% faster in the five benchmark cases (table above; one run a row).

Validation and unverified scope

  • This revision against the previously published head f5a0231b:
  • GPU, one idle MI455X (gfx1250), this revision, rocm/fw-bringup:gfx1250-minimax-m3-20261112, FlyDSL 0.5.3:
    • python3 -m pytest -q -s op_tests/test_moe_prefill_route_in_quant.py: 8 passed.
    • python3 -m pytest -q -s op_tests/test_moe_tp_route_quant_fused.py: 8 passed.
    • python3 op_tests/test_moe_prefill_route_in_quant.py: exit 0; 5 rows, err 0.
    • python3 -m pytest -q op_tests/flydsl_tests/test_flydsl_grouped_gemm.py at 86a18b08: 56 passed, 7 failed.
  • CPU:
  • Unverified:
    • test_flydsl_grouped_gemm.py is not a usable regression signal in that image: its 7 failures are all "FLYDSL_RUNTIME_RUN_ONLY=1 but no usable AOT cache", and main ea578b41 in the same container fails the same first 5 and then aborts (rc 134); this PR does not change that file beyond [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543;
    • timing inside the default window (410–1023 tokens) and the host-time table at this revision;
    • the CPU ISA, AOT and dry-run checks were not repeated after the last commit;
    • the route launch through a prebuilt AOT cache on a device (only the prebuild and --check ran);
    • a capture on torch < 2.10 (the image has torch >= 2.10), and MoE calls overlapping on two streams of one device (not supported, see Counter);
    • whole-model and serving runs; CI has no gfx1250 runner.

PR-specific question

What behavior would each changed op test fail on before this PR, and why is that coverage not already provided by an existing canonical test?

Changed op tests

@lirui927
lirui927 force-pushed the xiaobingsuper/m3-mi455-perf-stack branch from 2c8902d to 3499407 Compare November 10, 2026 07:46
lirui927 pushed a commit to lirui927/aiter that referenced this pull request Nov 10, 2026
The decode MoE gate of the route fused into the activation quant
(_fuse_tp_route_quant_enabled) read AITER_TDM_FUSE_TP_ROUTE_QUANT from
os.environ on every call, and the fused branch of
flydsl_moe_fused_quant_preshuffle read AITER_FLYDSL_TOKEN_MULTIDEST_QUANT.
The first is now functools.cache'd. The second goes through
token_multidest_quant_enabled(), which the quant dispatch uses as well, so
both see one value. Same defaults and accepted values (1/true/True). Tests
that flip AITER_TDM_FUSE_TP_ROUTE_QUANT between calls clear the cache after
each setenv and around each test; the placeholder test clears the other.

token_multidest_quant_enabled() and its placeholder-test fixture are
byte-identical to the ones ROCm#7547 adds at the same place, so the
two PRs merge cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lirui927 pushed a commit to lirui927/aiter that referenced this pull request Nov 10, 2026
The decode gate of the route-in-quant fusion and the A1 quant dispatch
(_compact_ascale) each called _use_fused_quant_preshuffle with the same
arguments. _grouped_a8w4_tdm_moe now evaluates it at most once per call and
hands the answer to both; same result, same order of evaluation.

CPU (MiniMax-M3 TP4: E=129, topk 5, dim 6144, fp4 activations), gate plus
dispatch question per decode MoE call (4-256 tokens), with the env commit:
1.17-1.20 -> 0.86-0.89 us.

The memo block and the _compact_ascale line are byte-identical to the ones
ROCm#7547 adds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lirui927
lirui927 force-pushed the fuse/f7-prefill-moe-route branch from d0fd64c to 0067b65 Compare November 10, 2026 08:21
lirui927 pushed a commit that referenced this pull request Nov 10, 2026
The decode MoE gate of the route fused into the activation quant
(_fuse_tp_route_quant_enabled) read AITER_TDM_FUSE_TP_ROUTE_QUANT from
os.environ on every call, and the fused branch of
flydsl_moe_fused_quant_preshuffle read AITER_FLYDSL_TOKEN_MULTIDEST_QUANT.
The first is now functools.cache'd. The second goes through
token_multidest_quant_enabled(), which the quant dispatch uses as well, so
both see one value. Same defaults and accepted values (1/true/True). Tests
that flip AITER_TDM_FUSE_TP_ROUTE_QUANT between calls clear the cache after
each setenv and around each test; the placeholder test clears the other.

token_multidest_quant_enabled() and its placeholder-test fixture are
byte-identical to the ones #7547 adds at the same place, so the
two PRs merge cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lirui927 pushed a commit that referenced this pull request Nov 10, 2026
The decode gate of the route-in-quant fusion and the A1 quant dispatch
(_compact_ascale) each called _use_fused_quant_preshuffle with the same
arguments. _grouped_a8w4_tdm_moe now evaluates it at most once per call and
hands the answer to both; same result, same order of evaluation.

CPU (MiniMax-M3 TP4: E=129, topk 5, dim 6144, fp4 activations), gate plus
dispatch question per decode MoE call (4-256 tokens), with the env commit:
1.17-1.20 -> 0.86-0.89 us.

The memo block and the _compact_ascale line are byte-identical to the ones
#7547 adds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lirui927
lirui927 force-pushed the fuse/f7-prefill-moe-route branch from 0067b65 to 5f6b55e Compare November 12, 2026 04:47
@lirui927
lirui927 changed the base branch from xiaobingsuper/m3-mi455-perf-stack to main November 12, 2026 04:47
@lirui927
lirui927 force-pushed the fuse/f7-prefill-moe-route branch 2 times, most recently from 0fa193d to 07cf264 Compare November 16, 2026 08:27
@lirui927
lirui927 marked this pull request as ready for review November 16, 2026 08:28
@lirui927
lirui927 requested a review from a team November 16, 2026 08:28
@github-actions github-actions Bot changed the title perf(flydsl): route the gfx1250 TP prefill MoE in one launch [FlyDSL] perf(flydsl): route the gfx1250 TP prefill MoE in one launch Nov 16, 2026
@aiter-bot

aiter-bot commented Nov 16, 2026 •

Copy link
Copy Markdown

NOT READY FOR HUMAN REVIEW

PR Self-Review

Revision 99359c2465a2 · 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

- On gfx1250 TP batches past the single-workgroup route, the counter fill, `moe_route_lds` and `moe_contiguous_psum_remap` become one `moe_route_lds_psum_sc` launch when the A1 quant is the token-multidest kernel. The quant decodes `(slot << bits) | expert` to `starts[expert] + slot`.
- Default scope: more than 2048 routes and fewer than 1024 tokens (top-5: 410–1023 tokens). Larger batches take the compact-scale pair and keep the old launches unless env moves that threshold.
- Built as a third route mode of the token-multidest builder, in the one kernel: `route_rows=()` is a tuple operand next to #7543's `tp_route=()`. The default kernel is unchanged (ISA-identical to main). The route kernel has its own module and AOT cache.
- The gate is a plain bool. It shares `_compact_ascale` and `token_multidest_quant_used()` with the quant dispatch and `tp_route_rows_fit()` with the route launcher, and the quant rejects encoded rows before any launch if the two ever disagree.
- Why: two launches fewer per call. Measured on the whole `fused_moe` call: 0.2% to 2.0% faster in the five benchmark cases (table above).

Validation and unverified scope

- This revision against the previously published head `f5a0231b`:
  - Merges of #7543's reworked head and of main `ea578b41`.
  - The route kernel moves, unchanged, to `kernels/moe_route_lds_psum.py` as an `aot_factory`; `moe_route_maps.py` is main's again.
  - `flydsl_moe_fused_quant_preshuffle` takes `route_rows` and `route_starts` and writes `topids_to_rows`; `route_expert_bits` and `route_rows_out` are gone, and the three refusals are one.
  - The row decode is a tuple operand of the one token-multidest kernel (`moe_fused_route_quant_scatter.py` adds 76 lines over #7543).
  - `tp_route_rows_fit()` is the one statement of what the route kernel serves. `grouped_moe_gfx1250.py` adds 96 lines over #7543.
  - `_tp_route_state` is keyed by (E, device), as the 11-19 review asked; a per-stream key was tried and reverted (same tree as `86a18b08`).
  - `op_tests/test_moe_prefill_route_in_quant.py`: 224 lines, every case through `fused_moe`; its benchmark times the whole call.
- GPU, one idle MI455X (gfx1250), this revision, `rocm/fw-bringup:gfx1250-minimax-m3-20261112`, FlyDSL 0.5.3:
  - `python3 -m pytest -q -s op_tests/test_moe_prefill_route_in_quant.py`: 8 passed.
  - `python3 -m pytest -q -s op_tests/test_moe_tp_route_quant_fused.py`: 8 passed.
  - `python3 op_tests/test_moe_prefill_route_in_quant.py`: exit 0; 5 rows, err 0.
  - `python3 -m pytest -q op_tests/flydsl_tests/test_flydsl_grouped_gemm.py` at `86a18b08`: 56 passed, 7 failed.
- CPU:
  - This revision: `black --check`, `ruff check`: clean.
  - At `86a18b08` (same tree as this head):
    - ISA, `aiter.aot.flydsl.dry_run("gfx1250")` with `COMPILE_ONLY=1`, `cmp` on the final ISA: 81/81 kernels without a route mode equal to main `ea578b41`; 12/12 of #7543's route kernels equal to #7543's head.
    - Declared sources, `aot_cache._undeclared_imports`: clean.
    - `python -m aiter.aot.flydsl.moe` on the MiniMax-M3 rows: 96 ok, `--row-tokens-only` 48 ok; `--check` passes for both.
    - Dry-run contract, gate and path checks (Testing above). CPU `pytest` of the neighbouring tests: same outcomes as #7543's head.
- Unverified:
  - `test_flydsl_grouped_gemm.py` is not a usable regression signal in that image: its 7 failures are all "FLYDSL_RUNTIME_RUN_ONLY=1 but no usable AOT cache", and main `ea578b41` in the same container fails the same first 5 and then aborts (rc 134); this PR does not change that file beyond #7543;
  - timing inside the default window (410–1023 tokens) and the host-time table at this revision;
  - the CPU ISA, AOT and dry-run checks were not repeated after the last commit;
  - the route launch through a prebuilt AOT cache on a device (only the prebuild and `--check` ran);
  - a capture on torch < 2.10 (the image has torch >= 2.10), and MoE calls overlapping on two streams of one device (not supported, see Counter);
  - whole-model and serving runs; CI has no gfx1250 runner.

PR-specific question

What behavior would each changed op test fail on before this PR, and why is that coverage not already provided by an existing canonical test?
- `test_moe_prefill_route_in_quant.py` is new. It asserts that `fused_moe` launches `moe_route_lds_psum_sc` and two fewer kernels than the split route, with the same output; before this PR that kernel does not exist.
- `test_capture_route_state` checks the shared and capture-scoped counter, and that replays match the eager output; only the new route has this counter.
- The existing `test_moe_route_rows.py` and `test_route_psum_fused.py` cover the split route and the single-workgroup route. Neither covers a ticketed last-workgroup psum or slot-encoded rows.
- The two files below that come from #7543 are answered in #7543.

Changed op tests

- `op_tests/test_moe_prefill_route_in_quant.py` (new, 226 lines, 8 cases)
  - Covers, all through `fused_moe`:
    - output bitwise equal to the split route, with `moe_route_lds_psum_sc` and two fewer kernels: MiniMax-M3 fp4 with and without K-split (4536 and 9000 tokens), fp8 activations, E = 64 top-8 and E = 256 top-6, with dropped routes, eager and in a two-layer graph replayed with new routes;
    - MiniMax-M3 at 410 tokens on the shipped config, without any override;
    - the counter across capture, with and without an earlier eager call.
  - Before this PR: fails, because the one-launch route does not exist.
  - Not redundant: no existing test exercises the one-launch route or its counter.
- `op_tests/test_moe_tp_route_quant_fused.py` (new, from #7543; this PR does not change it)
  - Covers: #7543's route folded into the quant: `fused_moe` bitwise equal with the fold on and off, and the kernel limits against a CPU reference.
  - Before this PR: unchanged by this PR; before #7543 its API does not exist.
  - Not redundant: it is the only test of #7543's path; it is in this diff only until #7543 merges.
- `op_tests/flydsl_tests/test_flydsl_grouped_gemm.py` (modified by #7543; this PR does not change it)
  - Covers: the pad-row test with the separate route, with the route in the quant, and with compact scales at the default switch.
  - Before this PR: unchanged by this PR; before #7543 the `fuse_route=1` case fails its path assertion.
  - Not redundant: it extends the canonical pad-row test; it is in this diff only until #7543 merges.

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
  • FAIL — Aiter Test Gate: failed
  • Required CI failed; fix it before requesting human review.

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

@lirui927
lirui927 requested review from coderfeli and zufayu November 16, 2026 14:52
@zufayu

zufayu commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Review routing reminder: @yadaish is the primary reviewer for this FlyDSL MoE scope. Please route the next technical review/action there; the direct request to @zufayu does not replace the component-owner review.

@zufayu
zufayu requested a review from yadaish November 17, 2026 07:49

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (8)

  1. Remove the host work this PR adds to every grouped-MoE call. aiter/ops/flydsl/grouped_moe_gfx1250.py:863-871 builds a functools.cache(lambda) on every path, EP included; :947 calls tp_route_state_buffer on every eager TP call; :948-955 runs the gate (two imports and an env read) on every non-fused TP call. CPU A/B against main (base-vs-base ±0.14 µs): decode +5.3 µs, fused small route +5.2, compact-pair prefill +11, E=384 +8.3, fp8 prequant +8.9, A-preshuffle +8.1, EP +3.6. AITER_FLYDSL_TOKEN_MULTIDEST_QUANT=0 removes none of it. Use a plain bool, run the cheap checks (E bound, A-preshuffle, dtype, env, eligibility) first and only when not _fused_tp_route, reuse the bool at _compact_ascale, and hoist the imports. Please post eager decode and non-route prefill numbers before and after.
  2. Use aiter/utility/graph_alloc.py for the counter instead of a new cache. capture_scoped_cache + persistent_alloc (:28/:76, used by gemm_kernels.py:464-474 and others) already give a zeroed buffer that is shared across eager calls and captures. Replace _TP_ROUTE_STATE_CACHE/tp_route_state_buffer (:2258-2295), the scratch counter (:2364-2367), the eager pre-allocation (:941-947) and the self_clean=False kernel variant with @capture_scoped_cache _tp_route_state(E, device) and always launch _sc. Key it by (E, device), not by stream: captures run on a side stream. Today a capture with no earlier eager call records one zero-fill per layer, and AOT never builds the non-_sc variant.
  3. Don't mirror the quant dispatch in the gate. _tp_route_quant_takes_route (:2306-2344, "Mirrors the quant dispatch") re-derives use_token_multidest + row_to_token is None from moe_kernels.py:3723-3732; if they drift, moe_kernels.py:3735 raises on default TP prefill. Export one predicate from moe_kernels and use it in both places.
  4. Show that the default token-multidest kernel is unchanged, or keep its signature. The non-route kernel and launcher now take row_starts/final_rows (moe_fused_route_quant_scatter.py:2251-2252, 2475-2486), and every default launch passes topids_to_rows_i32 twice (moe_kernels.py:3801-3808). The kernarg segment goes from 36 to 56 B, the user-SGPR count changes, and the module name stays the same. Post a disassembly diff (user_sgpr_count, kernarg_size, prologue s_loads) plus timing, or give the route build its own launcher.
  5. Fix the docstrings that describe behaviour wrongly. :2317-2319: the compact pair writes row_to_token itself (moe_fused_route_quant_scatter.py:2704-2709); it is excluded because it has no route_starts decode. :2357-2359: every call during such a capture uses a scratch counter, not only the first. :945 "one dict lookup" (1.1 µs measured).

Nits (also required):
6. Test the shapes the route takes by default. op_tests/test_moe_prefill_route_in_quant.py runs only fp4, E=129, wmma_rep 2/8, and its autouse fixture forces compact off. Shipped rows also route E256/k6/dim4096 fp8 (342-1023 and 16385-32768, wmma_rep 16) and dim7168/E96 fp4/fp8. Add fp8, E∈{64,256}, and one default-config case without the override.
7. tp_route_state_buffer docstring (:2276-2283): one overlap of two same-E calls leaves the counter corrupted for every later call until restart, not only the overlapping pair. Say so. moe_route_maps.py:333: use get_warp_size(), as moe_g2l_lut.py:43 does, instead of hard-coding wave_size = 32.
8. kernel_bench_callable "quant_a1" (:1532-1554) times the non-route multidest build and never the new route. Pass the encoded rows with route_starts/route_expert_bits.

Also: #7543 changes the same build_moe_token_multidest_quant_module with a different route-in-quant design (tp_route_slots, row_starts reused as expert ids), and the two conflict in all three files. Please pick one design or say how they fit together.


Reviewed at 07cf264 (Deep; 2 kernel/host hunters + independent pass B + 2 verifiers + miss pass). The ticket/last-block protocol, row encode/decode, self-clean across graph replays and the gather-reduce row handoff checked out in CPU models. Serving only reaches this route at 410-1023 tokens for MiniMax-M3 while the compact pair starts at 1024. CI green.

@lirui927

Copy link
Copy Markdown
Contributor Author

Thanks @valarLip. On how this fits with #7543: the two cover different batch ranges of the same token-multidest quant. #7543 folds the single-workgroup TP route into the quant (token_num x topk <= 2048, so up to 409 tokens for MiniMax-M3 and every decode). This PR replaces the three-launch route that larger batches take (410-1023 tokens for M3 today). Plan: #7543 lands first, split as you asked: the default-kernel quant refactor first, with ISA-equality evidence, and then the route-in-quant fusion. This PR will then be rebased onto #7543's builder, with route_expert_bits added as a second route mode on the shared quant setup instead of a parallel signature. The eight items here will be fixed in that rework, including keeping the default token-multidest kernel's signature and compile key unchanged. I'll re-request review once that is pushed.

@lirui927

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All eight items are addressed. The branch is now rebuilt on #7543's reworked builder, so this PR depends on #7543 and on its first half, #8496 (see the last section). Line numbers below refer to the new head 3e2a90e0.

1. Host work on every grouped-MoE call

  • The functools.cache(lambda), the per-call tp_route_state_buffer call and the gate function are gone.
  • _route_in_quant (grouped_moe_gfx1250.py:1012-1028) is one plain bool. Its first term is not _fused_tp_route, so decode and small batches stop there. The cheap tests come next: HERD, compact plan, EP, compact pair, dtype and E bound. Only after those does it call the shared predicate (item 3), which reads the env last, and then the int32 bound.
  • _compact_ascale moved above the routing (:959-967), so the gate and the quant use the same bool, and _use_fused_quant_preshuffle is still asked once per call. Its EP term is now not _is_ep, which is what _ep_nvr is None meant there: every EP branch sets _ep_nvr.
  • No per-call imports were added. TP_ROUTE_PSUM_MAX_EXPERTS and tp_route_expert_bits are imported at module level. token_multidest_quant_used joins the existing from aiter.ops.flydsl.moe_kernels import (...) at the top of _grouped_a8w4_tdm_moe.
  • CPU A/B, measured with the method you used: FlyDSL launches stubbed, CPU tensors, the call pinned to one core with ASLR off. Main, [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543 PR B, this head and main again were interleaved over 8 rounds; each value is the median of 9 x 400 calls.
call (CPU host time) main µs A/A: main − main #7543 B − main this − main this − #7543 B
TP decode M3, 1 tok (fused route) 105.6 -0.96 +0.40 +0.11 -0.09
TP decode M3, 16 tok 105.7 -1.74 -0.29 -0.24 -0.01
TP M3, 128 tok (fused small route) 104.2 -1.11 +0.85 +0.52 -0.33
TP prefill M3, 512 tok (this route) 129.9 -1.03 +0.91 -5.52 -6.46
TP prefill M3, 2048 tok (compact pair) 154.2 -0.33 -0.12 +0.22 +0.82
TP prefill M3, 4096 tok (A-preshuffle) 810.7 +0.80 +4.34 +1.11 -1.43
TP prefill dsv41 E=384, 1024 tok 148.0 -1.29 +3.95 +4.63 +1.00
TP decode Kimi-K2 E=384, 32 tok 115.1 -0.25 +0.44 +2.49 +1.81
prequantized fp8/fp4 EP, M3 512 tok 147.9 -0.17 +0.52 +1.16 +1.48
EP, M3 512 tok 145.1 -0.30 -0.73 +0.78 +0.60

Same-round deltas in µs, median over 8 rounds, at 5342a7ed; the review fixes after that only added checks on the route path.

Focused re-run, this head vs #7543 B on the paths that showed a gap (16 interleaved rounds, median and interquartile range):

call #7543 B µs A/A: B − B this − B
TP decode M3, 1 tok 105.2 +0.07 (-0.38..+0.97) -0.19 (-0.39..+0.51)
TP prefill dsv41 E=384, 1024 tok 151.9 -0.18 (-1.17..+1.39) +2.11 (+1.35..+2.60)
TP decode Kimi-K2 E=384, 32 tok 115.6 +0.19 (-0.43..+0.56) +1.74 (+1.16..+2.29)
prequantized EP, M3 512 tok 147.1 +0.34 (-0.63..+0.95) +1.01 (+0.04..+1.69)
EP, M3 512 tok 143.7 -0.08 (-1.25..+0.57) +1.68 (+0.56..+2.01)
  • Python call counts per grouped call (sys.setprofile), this head vs PR B:
    • EP, prequantized EP and decode: one more call (token_multidest_quant_used, which replaces the inline chain inside the quant).
    • E=384 decode: two more calls (the predicate and token_multidest_eligible).
    • A-preshuffle prefill: two more calls (the predicate, once in the gate and once in the quant).
    • The new route itself: 32 fewer calls.
  • A micro-benchmark of that predicate call costs 0.1 µs.
  • So the gate adds nothing to decode or the fused small route; the new route's own call is about 6 µs cheaper than the split route it replaces. On E=384 and EP calls this head is still +1.0 to +2.1 µs over [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543 B (about 1%), above the A/A spread. A per-function cProfile of those calls (2000 calls each tree) puts +0.2 to +0.5 µs of self time in the two changed functions (_grouped_a8w4_tdm_moe, flydsl_moe_fused_quant_preshuffle), consistent with the one or two extra calls above; the rest is spread over unchanged functions with mixed signs (e.g. ptr_arg -2.6 µs, _select_cluster_m -2.1 µs on the Kimi-K2 call), which I read as layout effects between the trees rather than added work. The remaining real cost is the shared predicate being a function call inside the quant, which item 3 asks for.

2. Counter via graph_alloc

  • _tp_route_state(experts, device) (:2355-2369) is @capture_scoped_cache + persistent_alloc + torch.zeros, keyed by (E, device).
  • These are gone:
    • _TP_ROUTE_STATE_CACHE and tp_route_state_buffer;
    • the scratch counter and the eager pre-allocation;
    • the self_clean builder flag. build_moe_topids_to_rows_lds_psum_module(n_buckets) builds only moe_route_lds_psum_sc, and every launch uses it.
  • A capture that runs before any eager call builds its own buffer for that capture, and every replay zeroes it, as capture_scoped_cache documents. Eager calls and later captures share the eager buffer.
  • AOT replay (aiter.aot.flydsl.moe --row-tokens-only, then --check) on the MiniMax-M3 rows: 48 ok, and the check passes.

3. One predicate

  • moe_kernels.token_multidest_quant_used(token_num, topk, *, prequantized, payload_preshuffled, remap_rows, fuse_ep_psum, valid_routes_bound) (moe_kernels.py:3468). It is now the dispatch's use_token_multidest (:3957), and the grouped gate calls it with its own _prequantized / a_preshuffled.
  • The row_to_token is None half is the gate's not _compact_ascale and not a_preshuffled: those are the only two cases in which the grouped MoE passes row_to_token.
  • The quant still rejects route_starts before any launch when the call would not take the route build (:3966-3991; since this round it also checks that route_starts / route_rows_out are contiguous int32 of the right size). A drift therefore raises; it cannot misplace rows.

4. Default token-multidest kernel unchanged

  • The route build has its own kernel and launcher. token_multidest_route_rows_kernel / launch_token_multidest_route_rows (moe_fused_route_quant_scatter.py:3002-3048) append row_starts, final_rows after token_num, following [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's tp_route_slots entry. The module name gains _rr{bits}.
  • The default kernel keeps its 5 arguments. Both kernels call one @flyc.jit body (_token_multidest_entry, :2676), and the decode step is compiled in only when route_expert_bits > 0. The default launch passes no extra operands.
  • The builder rejects tp_route_slots and route_expert_bits together.
  • ISA (FlyDSL compile-only for gfx1250 on CPU, final ISA dumps):
    • 81/81 kernels without a route mode are byte-identical to main (bf59948) and to [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543 (6c179fe). They include every token-multidest build (TDM-staged and K-split, fp4/fp8, wmma_rep 1/2, K 1024/6144), routeks, prequantized, the compact pair and row-indexed quant. Example: moe_token_multidest_quant_k5_fd6144_r1_fp4_pk8_scpk_hidtdm4 has .amdhsa_kernarg_size 36 and .amdhsa_user_sgpr_count 11, as on main. The previous head (07cf264) built the same kernels with 56 and 16, and 18 of the 81 differed.
    • The 21 route-mode quant builds and moe_route_lds_psum_sc are byte-identical to 07cf264 (22/22). The kernels whose time the description reports have not changed.

5. Docstrings

  • The gate comment now says the compact pair is excluded because it has no row decode.
  • The scratch-counter and "one dict lookup" text went away with the code it described.

6. Tests

  • test_route_and_quant_place_every_route now runs six shapes, padded (whole tokens and single routes dropped) and unpadded, and checks nothing is written past the last expert's tiles:
    • MiniMax-M3 fp4 at wmma_rep 2 and 8;
    • MiniMax-M3 fp8 (2048 tokens, wmma_rep 8);
    • E=64 topk 8 dim 7168 fp4;
    • E=256 topk 6 dim 4096 fp8 at wmma_rep 16;
    • MiniMax-M3 fp4 at 9000 tokens, where the quant does not split K (the TDM-staged build); test_stage_cases_cover_both_builds asserts the cases hit both builds.
  • test_moe_matches_split_route covers MiniMax-M3 fp4 at 2048/4536 tokens, fp8 at 2048 and E=64 topk 8 at 1024.
  • test_moe_default_config_takes_route runs MiniMax-M3 at 410 tokens on the shipped config, with no override. The fixture is no longer autouse.

7. Counter docstring, get_warp_size()

  • _tp_route_state now says that an overlap mixes counts, misplaces rows, and leaves nonzero counts behind that misplace the rows of every later call until the process restarts.
  • moe_route_maps.py:333 uses get_warp_size().

8. kernel_bench_callable "quant_a1"

  • It now passes the encoded rows (_tp_route.rows) plus route_starts / route_expert_bits / route_rows_out (:1615-1640). The arguments come from the same _route_rows_kw dict that the real call uses.

How it fits with #7543
This is the design from #7543's reply: one builder with orthogonal route modes on the shared _quant_ctx (PR A).

Validation

  • CPU:
    • black and ruff are clean;
    • the ISA comparison above;
    • AOT replay and --check;
    • a dry-run contract check: the quant rejects route_starts below 64 tokens, with row_to_token, without route_rows_out, with zero bits and with tp_route_params, and the builder rejects both modes at once.
  • GPU (MI455X, this head):
    • python3 op_tests/test_moe_prefill_route_in_quant.py -t 410 1024 2048 4536: 20 passed. The stage table in the description was measured at a9cc75ab (the same commits before the rebase onto [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543; the kernels are ISA-identical). Split → one launch: 410 tokens -20% to -39% across the five shapes, 1024 tokens -12% to -25%, 2048 tokens -7% to -13%, 4536 tokens -7% to +1.8%. Payload and scale bytes are equal to the split route in every row.
    • Neighbours, identical on [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543 PR B and this branch: test_moe_route_rows.py 98 passed, test_route_psum_fused.py 34 passed, test_moe_tp_route_quant_fused.py 51 passed, test_flydsl_grouped_gemm.py 55 passed / 6 failed. The same 6 fail on both, from a FlyDSL run-only AOT-cache error in the container.
    • The timed path of the test now checks its bytes on an untimed call made after the timing: run_perftest times on copies of the buffers, and rows within an expert follow atomic order, so checking the timed result against the original buffers compared different placements (it failed once at E=256, 2048 tokens).

@lirui927
lirui927 requested a review from valarLip November 25, 2026 06:29
@lirui927
lirui927 force-pushed the fuse/f7-prefill-moe-route branch from 3e2a90e to 28384ab Compare November 25, 2026 07:46
@lirui927

Copy link
Copy Markdown
Contributor Author

Restacked: this branch is now 28384ab0, on #7543's a6fd1de8 and #8496's 517e25b6. The only change against 3e2a90e0 is in _quant_ctx of moe_fused_route_quant_scatter.py (+22/-3): the hidden-row staging fields are required keyword-only parameters instead of a **staging catch-all, as asked in the review of #8496, so a misspelled field fails when the kernel is built. All kernels are byte-identical to 3e2a90e0 (81 default, 12 route and 22 prefill-route builds, compile-only). The line numbers in my reply above refer to 3e2a90e0.

lirui927 and others added 8 commits November 25, 2026 11:20
Move the per-warp _emit_quant_block_loop context of the token-multidest
quant into a _quant_ctx closure in its builder. The kernel now only loads
its routes' rows and hands them over with the hidden-row staging. Pull the
pk8 hidden-row load of _emit_quant_block_loop into _hidden_pk8_load.

No behaviour change: every quant build that goes through
_emit_quant_block_loop compiles to the same gfx1250 ISA as before.

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

_quant_ctx took the fields that say how the hidden row arrives through a
**staging catch-all, and _emit_quant_block_loop reads hidden_chunks,
chunk_prefetch, hidden_lds_load and mx_group_base back with getattr
defaults. A misspelled keyword at a call site would take the default
without an error: with hidden_lds_load set and hidden_chunks misspelled,
every chunk would be read from LDS slot 0.

They are now seven required keyword-only parameters, so a missing or
misspelled name raises TypeError when the kernel is built.

No behaviour change: the call site already passes all seven, and every
quant build that goes through _emit_quant_block_loop compiles to the same
gfx1250 ISA as before.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Add tp_route_params to flydsl_moe_fused_quant_preshuffle. With it, the
quant launch does the work of moe_route_psum_fused itself: every quant
workgroup loads all expert ids, counts them in LDS (all routes, and the
routes before its own), scans the tile-aligned counts, and gives its own
routes their rows. It writes topids_to_rows, and block 0 writes masked_m
and psum, so gemm1, gemm2 and the gather-reduce read what they read
before. No workgroup waits on another, and nothing is left in global
memory between calls.

Both quant kernels the route batches use take it, as a tp_route_slots
build option (0 = off): the route-indexed kernel, and the K-split build
of the token-multidest kernel (from 64 tokens). The token-multidest
route build is a second entry point next to the default one and shares
its quant context. The wrapper keeps one token-multidest branch: the
route adds its operands and needs a K-split build, else the batch takes
the route-indexed kernel, whose route build is K-split too. The id loads
and the lane's hidden-row loads are issued before the first barrier, so
the route work hides under them. Each thread loads 8 id slots, enough
for the 2048 routes the fused TP route serves, and skips the slots a
smaller call does not use, so one build serves every batch.

Rows within an expert follow route order, the same in every block.
moe_route_psum_fused assigns them with LDS atomics, so its order varies
from call to call; each route's quantized row, masked_m and psum are
bitwise those of the split path, and the MoE output too, because no GEMM
row or gather-reduce result depends on where a row sits.

The wrapper refuses buffers the kernel cannot write in place (non-int32,
strided or other-device topids_to_rows, masked_m or psum, too few
grouped rows), tile_m <= 0, a route count that is 0, above
TP_ROUTE_MAX_NUMEL (2048) or not a multiple of topk, an expert count
outside 1..TP_ROUTE_MAX_EXPERTS, and the modes the fused route does not
cover (prequantized, A-preshuffle, remap, EP psum, row-major scales,
num_valid_routes, row_to_token). topk_ids must not share storage with
the outputs. The quant kernels without the route compile to the same ISA
as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Small TP batches (token_num * topk <= 2048) build their routes with
moe_route_psum_fused, one workgroup that counts, scans and remaps every
route, and then quantize the bf16 hidden rows into expert order in a
second launch. On MiniMax-M3 TP4 decode (E = 129, top-5 with the shared
expert on every token) that route launch runs once per MoE layer.

The grouped MoE now hands those batches to the quant launch with
tp_route_params, so a MoE call runs 4 kernels instead of 5. It is taken
for the fused TP route batches with topk <= E <= TP_ROUTE_MAX_EXPERTS,
bf16 input, at most TP_ROUTE_MAX_NUMEL routes, no a1_scale, no
A-preshuffle and not the compact-scale quant pair; every other batch
keeps its launches. AITER_TDM_FUSE_TP_ROUTE_QUANT=0 restores the
separate route launch, like AITER_TDM_FUSE_PSUM_QUANT does for the EP
psum.

_compact_ascale (with _quant_mode and _prequantized) moves above the TP
route gate and keeps its guards, so EP, prequantized and A-preshuffled
calls still skip _use_fused_quant_preshuffle. The kernel-bench quant_a1
callable passes tp_route_params, so it times the launched kernel.

test_grouped_skips_pad_rows_routed_to_minus_one checked that a 128-token
TP batch with pad rows routed to -1 reaches the token-multidest quant;
that batch now takes the route-in-quant build. The test now runs it with
the route in its own launch and in the quant, and the compact-scale case
with the switch at its default, and checks zero pad rows and unchanged
real rows on each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
op_tests/test_moe_tp_route_quant_fused.py compares the fused route +
quant with fused_route_psum_remap followed by the quant, at 1 to 409
tokens with M3 routing (E = 129, top-4 plus a shared expert), padded TP
rows and dropped or out-of-range ids, and at the kernel limits (E = 256,
top-8 uniform ids with repeats within a token, up to 2048 routes):

- masked_m, psum and topids_to_rows equal a CPU reference;
- payload and scales equal the split path's once each route's row is moved,
  with sentinel-filled outputs so an unwritten row fails;
- a HIP graph replayed with new routes rewrites every route output;
- buffers and modes the kernel cannot serve are refused: strided or host
  outputs, too few rows, tile_m 0, 0, 19 or 2050 routes, a negative
  expert count, a compact-scale row_to_token;
- the public fused_moe output (a4w4 and a8w4) is bitwise equal with the
  switch on and off, and only the switch-off call launches the route. At
  model_dim 1024 and 80 tokens that call reaches the token-multidest route
  build.

python3 op_tests/test_moe_tp_route_quant_fused.py runs the split vs
fused check over a token sweep at dim 1024 and 6144 and prints the split
and fused route + quant times.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add moe_route_lds_psum_sc, a TP route kernel that also produces the
tile-aligned expert prefix:

- It routes as moe_route_lds does. After a workgroup's global slot
  reservations return, it draws a ticket on counter[E]; the one that draws
  the last ticket sees every final count and writes masked_m, the
  tile-aligned exclusive starts and psum, then zeroes the counts and the
  ticket, so the counter is zero again for the next launch.
- A route kernel cannot know an expert's start before the whole batch is
  counted, so each route's row is written as (slot << expert_bits) | expert
  instead of a final row.

The token-multidest A1 quant gets a third route mode next to the default
and tp_route_slots: route_expert_bits > 0 decodes the loaded rows to
starts[expert] + slot before the shared quant context, and its K-group-0
blocks write the resolved rows to final_rows for the gather-reduce, so no
psum-remap launch is needed. That build has its own kernel and launcher,
with row_starts and final_rows appended after token_num; the default
kernel keeps its name, arguments and ISA. The two route modes are
exclusive.

flydsl_moe_fused_quant_preshuffle takes route_starts, route_expert_bits
and route_rows_out, and rejects them before any launch unless the call
takes the token-multidest quant without a row_to_token map (otherwise the
encoded rows would be read as final rows), and unless route_starts and
route_rows_out are contiguous int32 and route_rows_out has one element per
route, since both go to the kernel as raw pointers. Whether a routed call takes the
token-multidest quant is now token_multidest_quant_used(), which the
dispatch uses and the grouped MoE can ask before it picks its route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On gfx1250 TP batches too large for the single-workgroup route
(_fused_tp_route), three launches ran before the A1 quant: a zero fill of
the per-expert counter, moe_route_lds and moe_contiguous_psum_remap. When
the A1 quant is the token-multidest launch, they become one
moe_route_lds_psum_sc launch, and the quant places each route at
starts[expert] + slot.

The gate is one bool, evaluated only when _fused_tp_route is off: no HERD,
compact plan or EP, not the compact-scale quant pair (it has no row
decode), bf16 activations, E <= 256, token_multidest_quant_used() for the
call, and token_num * topk < 2^(31 - expert_bits) so the encoded row stays
a positive int32. _compact_ascale moves above the routing to feed it, so
_use_fused_quant_preshuffle is still asked once per call; its EP test is
now written as not _is_ep, which is what _ep_nvr is None meant there.

The route counter is a zeroed (E + 1,) int32 buffer from
capture_scoped_cache + persistent_alloc, keyed by (E, device): eager calls
and captures share it, and a capture that runs before any eager call
builds its own, zeroed on every replay (that case needs torch >= 2.10, as
persistent_alloc does). The route zeroes it behind itself,
so calls that share it must not overlap; _tp_route_state says what an
overlap breaks.

kernel_bench_callable's "quant_a1" times this route's quant with the
encoded rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
op_tests/test_moe_prefill_route_in_quant.py, gfx1250 only:

- route + A1 quant stage, one launch vs the split launches, against a CPU
  reference: exact masked_m/starts/psum, each expert owning rows
  [start, start + count), payload and scale bytes equal to the split
  route's, dropped routes kept at -1, the counter zero afterwards. Cases:
  MiniMax-M3 (E=129, topk 5, dim 6144) fp4 at wmma_rep 2/8 and fp8, E=64
  topk 8 dim 7168 fp4, E=256 topk 6 dim 4096 fp8 at wmma_rep 16, and
  9000 tokens, where the quant does not split K; padded cases also drop
  single routes, and the bytes past the last expert's tiles stay untouched;
- fused_moe bitwise equal to the split route, eager and as a two-layer
  CUDA graph replayed with new routing, with two fewer kernels and no fill
  or psum-remap launch: MiniMax-M3 fp4 at 2048/4536 tokens, fp8 at 2048,
  E=64 topk 8 at 1024, and MiniMax-M3 at 410 tokens on the shipped config;
- graph capture sharing the eager counter, and capture before any eager
  call (skipped on torch < 2.10).

All but the shipped-config case pin the A1 quant to the token-multidest
launch: no A-preshuffle, and AITER_FLYDSL_COMPACT_SCALE_MIN_TOKENS set high
so the compact-scale pair does not replace it.

python3 op_tests/test_moe_prefill_route_in_quant.py runs the tests, then
times the stage both ways and prints a markdown table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lirui927 and others added 11 commits December 2, 2026 06:39
moe_fused_route_quant_scatter.py imports _warp_inclusive_prefix_i32 from
kernels/topk/topk_common.py, which imports kernels/dpp_utils.py. Main
has since put the quant builders of that file behind AOT caches, so
with the import undeclared the five caches built from it
(moe_fused_quant_preshuffle_route_ksplit, moe_token_multidest_quant,
moe_token_multidest_compact_quant, moe_apre_quant, moe_apre_scatter)
fail the declared-sources check, a prebuild raises and every launch
falls back to a JIT trace. Both files join _GFX1250_MOE_ROUTE_QUANT.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
- tp_route_slots() always returned one constant and repeated the route
  limit the quant wrapper already checks; the wrapper passes
  TP_ROUTE_SLOTS.
- The compact-scale decision is made once before the routes are built
  (not _is_ep is what _ep_nvr is None said there: every EP branch sets
  it), where the route choice of a later change can read it too.
- tp_route_params without topids_to_rows is refused in the row-indexed
  branch it would reach, not ahead of every routed call.
- python3 op_tests/test_moe_tp_route_quant_fused.py takes -p/--pattern,
  so "wide" (E = 256, top-8) times the batches at the 2048-route limit.

No kernel changes: the route builds keep their names and ISA.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ll-moe-route

Conflicts: the imports of kernels/moe_route_maps.py (main's aot_factory next
to get_warp_size) and the head of the routed branch of
flydsl_moe_fused_quant_preshuffle (the tp_route_params refusal moved into
the row-indexed branch).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… caches

- The route kernel moves to kernels/moe_route_lds_psum.py and is an
  aot_factory like the routes next to it. In moe_route_maps.py its import
  of topk/topk_common.py made every AOT cache built from that file
  (moe_topids_to_rows, moe_topids_to_rows_lds, moe_contiguous_psum_remap,
  moe_route_psum_fused) fail the declared-sources check after the merge
  with main; that file is unchanged again, and the new cache declares
  its own sources.
- flydsl_moe_fused_quant_preshuffle takes route_rows (the encoded rows)
  and route_starts, and writes topids_to_rows, as it does for
  tp_route_params. route_rows_out and route_expert_bits are gone (the
  bits follow from the length of route_starts), and the three refusals
  are one.
- tp_route_rows_fit(experts, numel) is the one statement of what the
  route kernel serves; the gate and tp_prefill_route_psum both read it.
  tp_prefill_route_psum returns a plain tuple.
- The gate is one negated group plus the three positive conditions.

The kernels are unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
278 -> 215 lines, 51 -> 8 cases.

- fused_moe with the fold off and on, bitwise, is the main check: 4 cases
  (the route-indexed and the token-multidest route build, fp4 and fp8
  activations) instead of 8.
- The kernel-level check keeps the four cases no MoE config reaches: one
  token, out-of-range ids, and the limits (E = 256, top-8, 2048 routes).
  The 42-case tokens x pattern x tile sweep, its graph replay and the
  refusal-by-refusal contract test are gone.
- One id generator and one CPU reference, inlined where it is used.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
301 -> 224 lines.

- Every case goes through fused_moe and compares it, bitwise, with the
  launches the route replaces: eager with dropped routes, and a
  two-layer graph replayed with new routes, with two fewer kernels.
- The stage-level harness (route + quant against a CPU reference, 12
  cases) and the test of its case table are gone. Its two shapes that no
  MoE case had, E = 256 fp8 and the batch that does not split K (9000
  tokens), are MoE cases now; MiniMax-M3 fp4 at 2048 tokens, the same
  build as 4536, is dropped.
- python3 op_tests/test_moe_prefill_route_in_quant.py times the whole
  fused_moe call on the split route and on this one.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The _quant_ctx / _hidden_pk8_load refactor is no longer needed, and the
net diff against main has none of it.

- Token-multidest quant: the route operands are a tuple operand of the
  one kernel, tp_route=() (empty with the route off, so that build, its
  name and its launcher are main's, untouched). The route step and the
  early hidden-row loads sit in the kernel body under a compile-time
  condition; a route build adds only its launcher. There is no second
  kernel and nothing to share between two entries.
- Route-indexed quant: the row load is main's again, and the route
  build replaces its result.
- _emit_quant_block_loop is main's plus the hidden_preloaded hook.

Outside the route additions the file reads as on main: +434/-1 against
main, was +613/-119.

Final ISA (compile-only, gfx1250): the 81 kernels without the route are
byte-identical to main, the six route-indexed route builds to the
previous head. The six token-multidest route builds gain main's
"block owns a token" guard (s_cmp_ge_u32 + s_cbranch_scc1) and split one
s_lshl3_add_u32 into shift + add, 2 or 3 instructions on 926-988; the
rest is the same instructions with other register numbers and order.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ROCm#7543 no longer needs the _quant_ctx refactor: its route is a tuple operand
of main's token-multidest kernel. Conflict in
kernels/moe_fused_route_quant_scatter.py: this PR's row decode sat between
the row loads and _quant_ctx. It is re-expressed the same way, as a second
tuple operand of the one kernel, route_rows=() (row_starts, final_rows),
whose decode feeds the kernel body the rows it would otherwise load. The
_token_multidest_entry shell and the second kernel are gone; the route
build adds only its launcher.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@lirui927

lirui927 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

review-pr scan (aiter skill from main ea578b41: fetch.sh + triage.py, REVIEW_AUTO_VALIDATE=0) at head 50905197fe9a1a1cda5fb7fe07abdb699ceca592: ⚠️ NEEDS WORK, 2 warnings and 1 note. 40 of 68 rules derived, 1644 lines / 8 files (over the review bar: the diff includes #7543), the diff applies to main 0dbaa95c. All 8 Step 8 gates pass; an independent reader upheld the three findings and corrected details, which are folded in. Advisory only; no GPU work was run by the scan.

Card

ROCm/aiter PR #7547 — [FlyDSL] perf(flydsl): route the gfx1250 TP prefill MoE in one launch

On gfx1250 TP MoE batches past the single-workgroup route, this PR replaces the counter fill, moe_route_lds and psum-remap launches with one route launch whose last workgroup builds masked_m/starts/psum, and lets the token-multidest activation quant decode each route's row; the diff also carries all of #7543.

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — auto-validation is disabled (REVIEW_AUTO_VALIDATE=0), and triage found 3 candidate test targets with no unique one, so there is no head-matched report. Environment gap, not a PR defect. The PR body reports 8 + 8 passed on one MI455X at this head; those runs were not reproduced here.
Perf (advisory): NOT RUN — this review ran no GPU work, and the harness is added by this PR, so base has nothing to time. The PR's own table (MI455X, this head, one run) times the split route against the one-launch route on the whole fused_moe call: -0.2% to -2.0% over five shapes, all run under the test's override (a raised compact-scale threshold and a masked A-preshuffle row).
Size: 1644 lines / 8 files — over the review bar
Design (advisory): SPLIT — (1) #7543's part of this diff (925 lines as its own PR: tp_route_slots, op_tests/test_moe_tp_route_quant_fused.py, the pad-row test), already its own PR and gone from this diff once it merges; (2) what this PR adds on top of it (723 changed lines): the ticketed route kernel moe_route_lds_psum_sc, the route_expert_bits row decode in the token-multidest quant, the _route_in_quant gate with its per-stream counter, and op_tests/test_moe_prefill_route_in_quant.py
Human: recommend valarLip review whether a third route mode (route_expert_bits) on build_moe_token_multidest_quant_module plus a cached per-stream counter _tp_route_state is worth two saved launches on batches where the GEMMs dominate, for PR #7547

⚠️ [verified] _tp_route_state(experts, device, stream_id) in aiter/ops/flydsl/grouped_moe_gfx1250.py now has the current stream in its cache key, and capture_scoped_cache looks an eager buffer up as cache.get((None, *args)). torch.cuda.graph captures on torch's shared capture stream unless it is given one, so such a capture no longer finds the counter an eager warm-up call built on the default stream: it builds a capture-scoped one, and persistent_alloc raises RuntimeError inside a capture on torch < 2.10. At the parent commit 86a18b08 the key was (experts, device) and one earlier eager call was enough. This was traced in the code, not run: the PR's GPU image has torch >= 2.10 (the test_capture_route_state[False] case ran), so its 8 passed cannot show it, and test_capture_route_state[True] asserts state_is_zero(129) == eager_first, which holds whether or not the capture shared the eager counter; that case and check_moe's graph capture are not skipped on torch < 2.10 and would raise there. Impact: on torch < 2.10, capturing a TP batch on this route (by default MiniMax-M3 at 410-1023 tokens) fails where the previous revision worked, unless the warm-up ran on the capture stream; on torch >= 2.10 such a graph records its own zero fill of the counter. The PR body states the torch >= 2.10 requirement, but not that it is a change against 86a18b08, and nothing enforces it at the gate. Author must decide the trade-off (a stream-independent eager lookup brings back the cross-stream sharing the last commit removed; otherwise gate the route on torch >= 2.10 under capture or skip those tests below it), and make the eager-first test tell a shared counter from a capture-scoped one.

⚠️ [inferred] The benchmark in op_tests/test_moe_prefill_route_in_quant.py reports -0.2% to -2.0% on the whole fused_moe call from one run with no spread, and all five rows (700 to 9000 tokens) run under the test's override, which raises AITER_FLYDSL_COMPACT_SCALE_MIN_TOKENS and masks a tuned row's A-preshuffle; four of them need it (the 700-token E = 256 row is inside the default window by the gate's terms). Nothing is timed for MiniMax-M3 inside its shipped window (410-1023 tokens), and the host-time table predates the last commit, which adds a current_raw_stream call on this path. Impact: a 1-2% single-run delta is within what run-to-run noise can produce, so the case for a new kernel, a third quant route mode and a cached counter rests on numbers that neither cover the shipped window nor show a spread. Reviewer should ask for repeated timings (several runs, with min-max) at 410, 512 and 1023 tokens on the shipped MiniMax-M3 config, split vs one launch.

📝 [verified] No CI job runs the new path: op_tests/test_moe_prefill_route_in_quant.py skips off gfx1250, it is in neither .github/test-manifests/mi450-gfx1250-p0.txt nor -p1.txt, and .github/workflows/ffm-bringup.yaml, the only workflow that runs tests on gfx1250, does not run it. The PR body's CPU ISA, AOT-replay and dry-run checks were run at 86a18b08, before the last commit (which touches aiter/ops/flydsl/grouped_moe_gfx1250.py and the test, no kernel file). Impact: the green checks say nothing about this route, and the evidence is the author's local MI455X log. Reviewer should ask who reruns the two test files on gfx1250 before merge, or accept the author's log at this head.

Step 8 gates
answers      ANSWERS COMPLETE: 6/6
diagnostic   DIAGNOSTIC COMPLETE: 6/6
corefiles    CORE FILES: none in this diff, declared
ledger       LEDGER COMPLETE: 40/40 rules adjudicated with evidence
card         CARD NAILED DOWN: 3 findings, each traced to an adjudication and anchored in a changed file; every FIRE accounted for
refutations  REFUTATIONS COMPLETE: 3 attempted, 3 survived, 0 killed before reaching the card
independent  INDEPENDENTLY REFUTED: 3 judged, 3 defended, 0 killed by a reader who had not seen the reasoning
design       DESIGN ROUTED: size 1644 lines / 8 files -- over the review bar

@zhuyuhua-v

Copy link
Copy Markdown
Contributor

The review-pr scan (aiter skill, from main) at 5090519 reports ⚠️ NEEDS WORK: 2 warnings and 2 notes; all 8 Step 8 gates pass, and an independent reader upheld all four. At 1644 lines / 8 files the PR is over the review bar, and the design gate suggests a split (#7543's ~925 lines vs this PR's own 723).

  • Warning (test code): test_capture_route_state[True] says the graph shares the eager counter, but it can't show that. torch.cuda.graph with no stream captures on its own side stream, and _tp_route_state is keyed by stream, so the capture builds its own counter. That case and check_moe's graph capture also have no skip for torch < 2.10, where persistent_alloc raises.
  • Warning (evidence): the perf table is one run per row with no spread, all under the test's override, and nothing was timed in the default window (MiniMax-M3, 410–1023 tokens).
  • Note (evidence): no CI job runs this path. MI35X runs the file with python3, and its main() exits 0 off gfx1250 without testing anything.
  • Note (small test fix): the benchmark's "route ran" assert is vacuous after the first row with the same expert count.
  • For valarLip: 7 of the 8 items from his 11-19 review are addressed. Item 2 is reversed: he asked for the counter to be keyed by (E, device), "not by stream", and the last commit keys it by stream.
Card

ROCm/aiter PR #7547 — [FlyDSL] perf(flydsl): route the gfx1250 TP prefill MoE in one launch

On gfx1250 TP MoE batches too large for the single-workgroup route, this PR replaces the counter fill, route and psum-remap launches with one route launch whose last workgroup writes the per-expert counts, starts and psum, and lets the token-multidest activation quant put each route on its final row; the diff also carries all of #7543.

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — auto-validation is off (REVIEW_AUTO_VALIDATE=0) and there is no gfx1250 GPU here; triage also found 3 candidate test targets and no single one. The changed path runs at serving time (it is not data-only), so this is an environment gap, not a PR defect. The PR body reports 8 + 8 passed on one MI455X at this head; not reproduced here.
Perf (advisory): NOT RUN — this review ran no GPU work, and the bench harness is new in this PR, so base has nothing to time. The PR's own table (one MI455X run, this head) times the whole fused_moe call, split vs one launch: -0.2% to -2.0% over five shapes, all under the test's override.
Size: 1644 lines / 8 files — over the review bar
Design (advisory): SPLIT — (1) #7543's part (about 925 changed lines: tp_route_slots, op_tests/test_moe_tp_route_quant_fused.py, the pad-row test) is already its own open PR and leaves this diff once #7543 merges; (2) this PR's own 723 lines in 6 files: the ticketed route kernel kernels/moe_route_lds_psum.py and its AOT cache, the route_expert_bits row decode in the token-multidest quant, the _route_in_quant gate with the per-stream _tp_route_state counter, and op_tests/test_moe_prefill_route_in_quant.py
Human: recommend valarLip review whether keying the _tp_route_state counter by stream is acceptable for PR #7547 (item 2 of his 11-19 review asked for (E, device), "not by stream"; at this head every torch.cuda.graph capture on torch's default side stream builds and zero-fills its own counter, which needs torch >= 2.10), and whether two saved launches justify a third route mode on build_moe_token_multidest_quant_module

⚠️ [verified] test_capture_route_state[True] in op_tests/test_moe_prefill_route_in_quant.py says "A capture shares the eager counter", but it cannot show that. _capture() calls torch.cuda.graph(graph) with no stream=, so torch captures on its own side stream. _tp_route_state in aiter/ops/flydsl/grouped_moe_gfx1250.py is keyed by current_raw_stream(device), so the capture misses the eager counter built on the default stream and builds its own capture-scoped one, exactly as the [False] case does. assert state_is_zero(129) == eager_first passes either way. Impact: no test runs the shared-counter path, which is the path a caller takes when it captures with stream= set to its warm-up stream. Also, the [True] case and every check_moe graph capture lack a skip for torch < 2.10, where persistent_alloc raises RuntimeError inside a capture, so on older torch the suite fails instead of skipping. The author's own 12-02 scan comment flagged this test and the head has not changed since. Author must run the [True] warm-up and capture on one non-default stream s (with torch.cuda.stream(s): expect = moe(...), then torch.cuda.graph(g, stream=s); torch refuses to capture on the default stream) and assert, under s, that the graph reused the eager buffer, or drop the sharing claim. Also skip the capture-first cases, including the graph part of check_moe, when ROUTES_INSIDE_CAPTURE is false.
⚠️ [inferred] The body's perf table comes from bench() in op_tests/test_moe_prefill_route_in_quant.py: one run per row, no spread. All five rows (700 to 9000 tokens) run under token_multidest_a1_quant(), which raises the compact-scale threshold and masks A-preshuffle. The window where the route runs by default (MiniMax-M3 top-5 at 410-1023 tokens) was not timed at this head, and the host-time table predates the last commit. Impact: nothing shows that a 0.2-2.0% whole-call change is larger than run-to-run noise, or what the gain is where the route actually runs. That gain is the whole case for a new kernel, a third quant route mode and a cached counter. Reviewer should ask for whole-call timings, split vs one launch, at 410, 512 and 1023 tokens on the shipped MiniMax-M3 config without the override, with several runs per point and their min/max.
📝 [verified] No CI job runs this path. The MI35X Standard Tests run op_tests/test_moe_prefill_route_in_quant.py as python3 "$file" (.github/scripts/aiter_test.sh), and its main() returns 0 off gfx1250 without testing anything. It is in neither gfx1250 test manifest (mi450-gfx1250-p0.txt, -p1.txt), and .github/workflows/ffm-bringup.yaml, the only workflow that names gfx1250, does not run it. The green checks therefore say nothing about this route; the only evidence is the author's MI455X log. Reviewer should ask who reruns the two new test files on gfx1250 at the final head before merge.
📝 [verified] The body says "the benchmark asserts the one-launch route ran". In bench() (op_tests/test_moe_prefill_route_in_quant.py) that check is assert state_is_zero(experts), which only shows that an eager counter for that expert count exists and is zero. After the first E=129 row (4536 tokens) it passes for the 9000- and 2048-token rows whether or not the route ran. check_moe checks the same shapes with the profiler, so the numbers are probably right, but the bench's own check proves nothing. Reviewer should ask the author to clear gm._tp_route_state before each bench row, or to check kernel names as check_moe does.

Step 8 gates
answers      ANSWERS COMPLETE: 6/6
diagnostic   DIAGNOSTIC COMPLETE: 6/6
corefiles    CORE FILES: none in this diff, declared
ledger       LEDGER COMPLETE: 40/40 rules adjudicated with evidence
card         CARD NAILED DOWN: 4 findings, each traced to an adjudication and anchored in a changed file; every FIRE accounted for
refutations  REFUTATIONS COMPLETE: 4 attempted, 4 survived, 0 killed before reaching the card
independent  INDEPENDENTLY REFUTED: 4 judged, 4 defended, 0 killed by a reader who had not seen the reasoning
design       DESIGN ROUTED: size 1644 lines / 8 files -- over the review bar

The counter stays keyed by (experts, device): a capture runs on a side
stream, so a per-stream key gives every graph its own counter and a zero
fill per replay, which the 11-19 review asked to avoid.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@zhuyuhua-v

Copy link
Copy Markdown
Contributor

The review-pr scan (aiter skill, from main) at 99359c2 reports ⚠️ NEEDS WORK: 1 warning and 3 notes; all 8 Step 8 gates pass, and an independent reader upheld all four. The only new commit reverts 5090519, so the tree equals 86a18b0.

  • Resolved since 5090519: _tp_route_state(experts, device) is keyed by (E, device) again, which was valarLip's 11-19 item 2. With the stream key gone, a capture after an eager call reuses the eager counter by design. Both test_capture_route_state[True] and check_moe make an eager call before capturing, so neither needs a torch < 2.10 skip ([False] keeps its skip).
  • Warning (evidence, not resolved): the perf table is still one run per row with no spread, MiniMax-M3 at 410–1023 tokens is still untimed, and the "Why" line (0.2–2.0%) doesn't match the table (0.7–2.5%). The 700-token E=256 top-6 row does fall in the route's default window, but it isn't MiniMax-M3. Three or more interleaved runs with spread at 410/512/1023 tokens, plus a Why line matching the table, would settle it.
  • Note (test): on torch ≥ 2.10, [True] still passes if the graph used its own counter. One identity assert inside the torch.cuda.graph block would pin it.
  • Note (evidence): no CI runs the path, since MI35X runs the file with python3 and main() exits 0 off gfx1250. A gfx1250 pytest log at this head would cover it.
  • Note (description): the body still says "the benchmark asserts the one-launch route ran", but after the revert bench() asserts only err == 0. Either reword the body or add the _kernels() check check_moe already uses.
  • For valarLip: the shared (E, device) counter has no guard against two calls with the same expert count running at once on two streams, which would leave every later call silently wrong until restart. The PR documents this, and it's the key he asked for.
Card

ROCm/aiter PR #7547 — [FlyDSL] perf(flydsl): route the gfx1250 TP prefill MoE in one launch

On gfx1250 TP MoE batches too large for the single-workgroup route, this PR replaces the counter fill, route and psum-remap launches with one route launch whose last workgroup writes the per-expert counts, starts and psum, and has the token-multidest activation quant put each route on its final row; the diff also carries all of #7543.

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — auto-validation is off (REVIEW_AUTO_VALIDATE=0) and there is no gfx1250 GPU here; triage also found 3 candidate test targets and no single one. The changed path runs at serving time (not data-only), so this is an environment gap, not a PR defect. The PR body reports 8 + 8 pytest passes on one MI455X at a tree identical to this head (86a18b0); not reproduced here.
Perf (advisory): NOT RUN — this review ran no GPU work, and the bench harness is new in this PR, so base has nothing to time. The PR's own table (one MI455X run, whole fused_moe call, split route vs one launch on the same tree) shows -0.7% to -2.5% over five shapes, all under the test's override.
Size: 1644 lines / 8 files — over the review bar
Design (advisory): SPLIT — (1) #7543's share (about 920 changed lines: the tp_route_slots fold, op_tests/test_moe_tp_route_quant_fused.py, the pad-row case), already its own open PR and gone from this diff once #7543 merges; (2) this PR's own 723 lines in 6 files: kernels/moe_route_lds_psum.py and its AOT sources entry, the route_rows decode in the token-multidest quant, the _route_in_quant gate with the shared (E, device) counter, and op_tests/test_moe_prefill_route_in_quant.py
Human: recommend valarLip review whether the (E, device)-keyed counter _tp_route_state, shared by every stream, with its stated restriction that no two same-E MoE calls overlap on one device (otherwise it stays nonzero and corrupts every later call until restart), is acceptable for gfx1250 consumers, and whether a 0.2-2.5% whole-call gain justifies a third route mode (route_rows) on build_moe_token_multidest_quant_module, for PR #7547

⚠️ [verified] The perf claim rests on one run per row with no spread, and MiniMax-M3 has no timed row. MiniMax-M3 at 410–1023 tokens is the default scope the PR names. The Benefit table comes from one run of bench() in op_tests/test_moe_prefill_route_in_quant.py, with every row inside token_multidest_a1_quant()'s override (compact-scale threshold raised, A-preshuffle masked). Three rows (4536, 9000 and 2048 tokens) are at or above the 1024/2048-token compact-scale threshold. By the PR's own Default-scope account, those batches keep the old launches without the override. Only the 700-token E=256 top-6 a8w4 row (-2.2%) is a batch the route takes by default. The body says MiniMax-M3's window "was not timed at this head". The second run's range (0.2–2.0%) sits about 0.5 points below the table's (0.7–2.5%), as large as the smallest gain, and the "Why" line quotes 0.2–2.0% as "(table above)". The host-time table (-7.65 us at 512 tokens) is from an earlier revision. Impact: the gain cannot be told apart from run-to-run noise, and the model the default scope is stated for has no number. Reviewer should ask for at least 3 interleaved runs with median and spread for MiniMax-M3 at 410, 512 and 1023 tokens, and for the Why line to match the table. Those are the M3 rows of python3 op_tests/test_moe_prefill_route_in_quant.py -t 410 512 1023, which runs all five shapes at each count; below 1024 tokens the override does not change the M3 path.
📝 [verified] No CI job runs this path. .github/scripts/aiter_test.sh runs python3 op_tests/test_moe_prefill_route_in_quant.py on MI35X (gfx950), where main() returns 0 at its gfx1250 check without testing anything. The pytest cases skip off gfx1250, and at this head the Standard Tests job was skipped anyway. Impact: a regression in the route kernel or the row decode would pass CI green. Reviewer should ask for the 8-case pytest log at this head on gfx1250 before merge. The PR body already says CI cannot run it.
📝 [verified] The body says "the benchmark asserts the one-launch route ran", but at 99359c2 bench() in op_tests/test_moe_prefill_route_in_quant.py (lines 189–206) asserts only err == 0 against the split route. The revert removed assert state_is_zero(experts), which held trivially after the first row of each expert count. Impact: a -t row whose batch misses the gate would time the same path twice and still pass, so its "gain" would be noise. For example, at 409 tokens or fewer with E=129 top-5, both runs take the single-workgroup route. The five default rows are covered by check_moe's kernel-name assert. Author must drop the sentence, or add the same _kernels() check check_moe uses (assert moe_route_lds_psum_sc ran).
📝 [verified] test_capture_route_state[True] in op_tests/test_moe_prefill_route_in_quant.py still does not pin that the graph shares the eager counter. With the (E, device) key back, an eager-first capture takes the eager buffer by construction, because capture_scoped_cache returns cache[(None, *args)] first. But state_is_zero(129) reads only the eager buffer, which a capture with its own counter also leaves zero. Impact: on torch >= 2.10 a regression back to a per-capture counter would pass. Author must add one identity assert, e.g. inside the torch.cuda.graph block, assert that _tp_route_state(129, device) is _tp_route_state.eager_cached(129, device).

Step 8 gates
answers      ANSWERS COMPLETE: 6/6
diagnostic   DIAGNOSTIC COMPLETE: 6/6
corefiles    CORE FILES: none in this diff, declared
ledger       LEDGER COMPLETE: 40/40 rules adjudicated with evidence
card         CARD NAILED DOWN: 4 findings, each traced to an adjudication and anchored in a changed file; every FIRE accounted for
refutations  REFUTATIONS COMPLETE: 4 attempted, 4 survived, 0 killed before reaching the card
independent  INDEPENDENTLY REFUTED: 4 judged, 4 defended, 0 killed by a reader who had not seen the reasoning
design       DESIGN ROUTED: size 1644 lines / 8 files -- over the review bar

@lirui927

lirui927 commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Reply to the review of 2026-11-19 (valarLip, at 07cf264). Status of the eight items at 99359c24; line numbers are at that head. The branch contains #7543's head 5689d664 and main ea578b41 by merge, so the conflict with main is resolved. The head's tree is identical to 86a18b08: the two commits after it (a per-stream counter key and its revert) cancel out.

  1. Host work on every call: fixed. No per-call functools.cache(lambda), no eager state lookup, imports hoisted (grouped_moe_gfx1250.py:34). The gate is one bool (:1101-1118): a negated group (single-workgroup route, HERD, compact plan, EP, compact-scale pair), then the dtype, then the shared predicate, then tp_route_rows_fit. Host time against [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543's branch with an A/A control (CPU, measured at an earlier revision of this branch and not repeated): decode +0.0..0.4 µs, single-workgroup route +0.0, compact pair +0.4, E=384 +0.2..0.5, A-preshuffle +0.25, EP +0.8..0.9 (A/A -0.3..+1.4); a call that takes the route is 7.7 µs cheaper. Calls that do not take it run 40-105 more Python bytecodes (0.3-0.7%). Table in the description.
  2. graph_alloc for the counter: fixed. _tp_route_state(experts, device) under capture_scoped_cache, allocated with persistent_alloc (grouped_moe_gfx1250.py:2499-2514), keyed by (E, device) as asked, not by stream. Only the _sc kernel exists. The restriction that comes with this key is in the docstring: calls with the same expert count must not overlap on one device (e.g. on two streams), and nothing guards against it.
  3. Gate does not mirror the dispatch: fixed. moe_kernels.token_multidest_quant_used() (moe_kernels.py:3470) is called by the gate (grouped_moe_gfx1250.py:1111) and by the quant dispatch (moe_kernels.py:3957). What the route kernel serves is likewise stated once, tp_route_rows_fit() (kernels/moe_route_lds_psum.py:39), read by the gate (grouped_moe_gfx1250.py:1117) and by the route launcher (:2538).
  4. Default token-multidest kernel unchanged: fixed by keeping its signature. The two route pointers are a tuple operand of the one kernel, route_rows=() (moe_fused_route_quant_scatter.py:2607), empty in the default build, so that build keeps main's arguments, name and launcher; the route build adds only its launcher (:2940). Compile-only on CPU, the final ISA of the 81 kernels without a route mode is byte-identical to main.
  5. Docstrings: fixed. The compact pair is excluded because it has no row decode (grouped_moe_gfx1250.py:1097-1100); the scratch counter and the "one dict lookup" text are gone with item 2.
  6. Shapes the route takes by default: fixed. Every case goes through fused_moe (test_moe_prefill_route_in_quant.py:34-40): MiniMax-M3 fp4 with and without K-split, fp8 activations, E = 64 top-8 at dim 7168, E = 256 top-6 fp8, plus MiniMax-M3 at 410 tokens on the shipped config without any override (:155). Not done: a dim-7168 E = 96 case, left out to keep the file small (dim 7168 runs with E = 64, and 96 lies between the tested expert-bit widths).
  7. Counter docstring and get_warp_size(): fixed (grouped_moe_gfx1250.py:2504-2510; kernels/moe_route_lds_psum.py:68).
  8. kernel_bench_callable "quant_a1" passes the route operands: fixed, **_route_kw at grouped_moe_gfx1250.py:1718.

On #7543: the two are route modes of one builder and are exclusive there (#7543's tp_route_slots for up to 2048 routes, this PR's route_rows past that). This PR is stacked on #7543 and merges after it; on top of #7543 it is +710/-13 in 6 files. #8496 is closed and is not a dependency.

Also in this revision: the route kernel moved, unchanged, to its own module kernels/moe_route_lds_psum.py as an aot_factory with its own declared sources, and moe_route_maps.py is main's again. The wrapper takes route_rows + route_starts and writes topids_to_rows; route_expert_bits and route_rows_out are gone. The test is 224 lines (was 301).

What ran, on one idle MI455X (gfx1250), rocm/fw-bringup:gfx1250-minimax-m3-20261112, FlyDSL 0.5.3, at 86a18b08 (same tree as the head):

Still open:

  • The gain on the whole fused_moe call is small: 0.7% to 2.5% in one run (one run a row, no spread) and 0.2% to 2.0% in a second run. All five rows run under the test's override.
  • MiniMax-M3's default window (410-1023 tokens) is not timed; will post when measured.
  • CI has no gfx1250 runner, and op_tests/flydsl_tests/test_flydsl_grouped_gemm.py gives no regression signal in that image (main fails there in the same way), so the runs above are the only device evidence.

@lirui927

lirui927 commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Reply to the review-pr scan of 2026-12-03 at 99359c24 (zhuyuhua-v), which supersedes the scans at 50905197 and earlier. Thanks.

  1. Counter key: resolved, as the scan says. _tp_route_state(experts, device) is keyed by (E, device) again (item 2 of the 11-19 review); the per-stream key of 50905197 is reverted, and the tree equals 86a18b08. The restriction is documented and has no guard: two calls with the same expert count in flight at once on one device mix their counts. No test runs two streams.
  2. Perf evidence: not resolved, still open. The table is one run a row with no spread: 0.7% to 2.5% of the whole fused_moe call, and 0.2% to 2.0% in a second run, so the smallest gains are within run-to-run difference. All five rows run under the test's override; only the 700-token E = 256 top-6 row is a batch the route takes by default. MiniMax-M3 at 410-1023 tokens is not timed; will post when measured. The "Why" line of the description now quotes the table's range (0.7% to 2.5%, one run a row).
  3. Identity assert in test_capture_route_state[True]: not done; no code changed after the scan. The finding is correct: state_is_zero(129) reads only the eager buffer, so on torch >= 2.10 the case does not pin that the capture shares it.
  4. gfx1250 log: done at 86a18b08 (same tree as this head) on one idle MI455X: python3 -m pytest -q -s op_tests/test_moe_prefill_route_in_quant.py 8 passed, op_tests/test_moe_tp_route_quant_fused.py 8 passed, and the benchmark script exits 0 (5 rows, err 0). CI still does not run the path.
  5. "The benchmark asserts the one-launch route ran": the finding is correct, and that sentence of the description is stale. At this head bench() asserts only err == 0 against the split route; the assert went away with the revert. That the route runs for the five shapes is asserted by the pytest cases (check_moe checks that moe_route_lds_psum_sc ran), not by the benchmark.
  6. Size: +1586/-58 in 8 files against main, of which +710/-13 in 6 files is this PR on top of [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543; the rest leaves the diff when [FlyDSL] perf(flydsl): fold the gfx1250 TP MoE route into the activation quant #7543 merges.

This branch has not been deployed

No deployments
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.

5 participants