Repository navigation
[FlyDSL] [Perf] MegaMoE: shorten EP8 prepare chain, coalesce MXFP8 quant (gfx950) - #6900
Conversation
…ant (gfx950) The compact prepare kernel's critical path is the cross-rank protocol chain (count, histogram exchange over XGMI, plan, pair-order fill), not the activation quant. This change shortens that chain for EP8 layouts with at most 64 experts per rank and top-k <= 8 (DeepSeek-V4-Pro, R1, GLM-5.2) and keeps main's kernel for every other layout. Protocol: - Publish plan data and flags with relaxed system/agent-scope or write-through (sc0|sc1) stores drained by s_waitcnt vmcnt(0) plus a barrier, instead of a release fence per flag. On gfx950 each agent or system release lowers to buffer_wbl2, which writes back the whole dirty L2 of the XCD, including the concurrent quant output. - Prepare CTAs reduce their own histogram rows and derive their bases with an LDS prefix; the owner pushes each reduced segment to the peers as soon as it is ready. Pushed counts carry the launch tag, so consumers poll exactly the words they need. - For P <= 16 (decode and small prefill) the owner CTA counts, plans and fills alone; group CTAs retire at once and, at decode, the role is the block index (no ticket atomic). All roles on this path are self-contained and the grid is co-resident. - Host-constant dispatch and peer tables are read with scalar loads so descriptors stay in SGPRs. - The top-k index buffer views are bounded to the live rows (tokens * top-k * 4 B), so the clamped and speculative index loads of a rank with zero tokens are out-of-bounds zero-fills, not faults. Quant (FP8, tile_m >= 128, and the m64 P32 bucket from 2048 tokens): 16 B per lane, 1x32 amax across a lane quad with DPP, packed cvt_pk_fp8, a software-pipelined stream with work stealing on the last two rounds, and a larger per-compile-key quant CTA count. Output is bit-identical to quant.emit_per_1x32_mx_fp8_group. FP4 keeps the existing per-group quant. Layouts outside the guard (Kimi-K3, EP2/EP4, epr > 64) compile the previous kernel unchanged. No new environment variable. Fast-path kernel names contain _v14. The FlyDSL AOT cache must be regenerated, since the prepare cache keys change. Signed-off-by: Chushi Chen <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
- Owner fallback prefix (more than 7 rounds of 64 segments, e.g. EP8 epr 56-63) no longer overwrites the raw BLOCK_HIST counts when the group CTAs self-prefix: a group that is still reading them after GROUP_DONE could otherwise take offsets for counts. - The quant work-steal counter moves to PREP_EPOCH_GATE row 0 (slot P), which is never an epoch gate (P >= 1), so a launch with Q == quant_cu_capacity can no longer leave its epoch value in the counter. Signed-off-by: Chushi Chen <[email protected]>
…ile in place The fast path is only compiled for EP8 with epr <= 64 and top-k <= 8 (_fast_prepare_supported). Remove code no compile on that path reaches: - 16 helpers that are never executed (alternate count/fill/offset variants and copies of dispatch.py helpers); - branches the guard makes impossible (not ll / not split_meta / epr > 64 ...) and the always-true ll, split_meta, own_ll, fused_pairs and fused_regs flags; - the non-merged section-ready init: Stage1 already requires payload_chunk_rows % sort_block_m == 0 for compact dispatch. Keep main's compile_mega_moe_prepare where it was instead of moving it; it now hands supported layouts to _compile_fast_mega_moe_prepare. Generated code is unchanged: final ISA of all production prepare kernels matches the previous revision up to compiler run-to-run noise, and test_mega_moe_v2 outputs are bit-identical. Signed-off-by: Chushi Chen <[email protected]>
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
The tile_m word pushed to every peer is fz_tile_m | (launch tag << tag_shift) with tag_shift = bit_length(mtpr * topk). When a plan's tile_m (32, or 64 for fp4 small buckets) is >= 2^tag_shift, i.e. mtpr * topk < 64 on a non-fixed-slot EP8 layout (e.g. R1/GLM at mtpr 1-2, V4 EPLB epr 52/56 at mtpr <= 8), tile_m bits land in the tag: the peer either never sees the expected tag (hang) or decodes tile_m as 0. Start the tag at bit 8 at least (tile_m <= 128). The shift still depends only on mtpr and topk, so it stays identical on all ranks even when they pick different tile_m. For mtpr * topk >= 128 (every served and AOT config) tag_shift and the generated code are unchanged. Signed-off-by: Chushi Chen <[email protected]>
Signed-off-by: Chushi Chen <[email protected]>
… APIs - Scalar-cache warm-up: keep the s_buffer_load results alive with llvm.fake.use (same idiom as mla_gfx1250 keep_alive) plus an explicit s_waitcnt lgkmcnt(0), instead of an empty side-effecting inline asm. - Quant work steal: index the in-loop grab address by tid (only tid 0 issues it, so the address is unchanged) instead of an opaque-zero v_mov_b32 asm; the divergent address still keeps the AMDGPU atomic optimizer off the grab. - Use fx.inttoptr instead of the private comm_ops._to_ptr_global, and dpp_utils.update_dpp_i32 instead of raw rocdl.update_dpp + ir_value(). gfx950 ISA of all 667 compiled prepare kernels is unchanged except the work-steal kernels' prologue (v_mov_b32 + v_ashrrev_i32 -> v_lshlrev_b32, same waitcnt/atomic sequence); outputs bit-identical to main. Signed-off-by: Chushi Chen <[email protected]>
Signed-off-by: Chushi Chen <[email protected]>
- Drop the always-true `if const_expr(True):` in _emit_plan. - arith.unwrap -> .ir_value(); drop the raw `arith` import; use fx.rocdl / fx.math instead of the module aliases. - Keep-alive of the scalar-cache warm-up loads uses the typed LLVM-dialect op llvm.intr_fake_use instead of call_intrinsic by name (FlyDSL has no fx wrapper for an operand-only keep-alive). - Remove unused parameters, always-true/alias flags, dead stores, a duplicate tid, and stale comments; remove misplaced `# fmt: off/on` markers (the `# fmt: on` sat inside a function body, so black skipped the rest of the file). The black reformat follows in the next commit. gfx950 ISA is byte-identical for all 667 compiled prepare kernels (flydsl 0.5.0). Signed-off-by: Chushi Chen <[email protected]>
Formatting only (black 26.10.1); the AST is unchanged. Signed-off-by: Chushi Chen <[email protected]>
A/B on main 075695e (flydsl 0.5.0, 8x MI355X, 8 paired rounds) shows no measurable gain from warming the peer tables (decode prepare ratio 0.998, 95% CI 0.983-1.014), so remove it: 9 fewer scalar loads, a branch and 2 waits per decode kernel; outputs bit-exact. The dispatch-table warm-up stays (removing it costs ~3% of decode prepare at bs 1/42). Signed-off-by: Chushi Chen <[email protected]>
The warm-up loads have no consumer, so keeping them alive needed a raw llvm.intr.fake.use (FlyDSL has no fx wrapper for it). Remove the warm-up and with it the last raw MLIR dialect use in the file. Cost: about 3% (~0.5 us) of decode prepare at bs 1/42; prefill kernels are unaffected. Outputs bit-exact. Signed-off-by: Chushi Chen <[email protected]>
Merge duplicated code in the MegaMoE prepare fast path (-300 lines): - fold _group_count_held into _group_count_regs (route_segment=None) - fold _next_pair_packed_top2 into _next_pair_packed(top2=) - _emit_mx_fp8_quad_chunk reuses _mx_fp8_quad_convert - new helpers: _pack/_unpack_route_segment, _pair_mask/_pair_member, _tok_idx_buffers, _lds_round_carry, a local _offsets_pairs closure and quant-loop _load/_convert closures - _emit_plan: drop defer_plan_ready and dead fused/non-fused arms - drop unreachable guards and the split>1 select chain (the fast path is always npes==8, topk<=8), the unused prefetch fallback in _emit_fused_count_tok, and a dead non-fused fence The stock compile_mega_moe_prepare path is unchanged. gfx950 ISA is unchanged (3273/3328 kernel instances byte-identical; the other 55 have identical LLVM IR and differ only by backend operand-order nondeterminism, also seen when rebuilding the same file). EP8 outputs are bit-exact against main and the previous revision; AOT 192/192. Signed-off-by: Chushi Chen <[email protected]>
Summary
This PR rewrites the fast path of the MegaMoE compact-dispatch prepare kernel (
mega_moe_prepare.py) for EP8 layouts on gfx95x (validated on gfx950 only).Everything outside the guard (EP ≠ 8, more than 64 experts per rank, top-k > 8) compiles main's kernel unchanged (see "Stock path" below).
Updates after review (86e5ba0, 371eb60, 500523c, 8995b51, c2ad464, 216870d, f362cd8, b760aca, 5e30506, 2d66a0c, e6e42c7):
quant_cu_capacity. The counter now has a dedicated slot.llvm.fake.usekeep-alive, a tid-indexed steal address,fx.inttoptr,update_dpp_i32. ISA of 667 prepare kernels is unchanged, except one fewer prologue instruction in the work-steal kernels.const_expr(True), replacedarith.unwrapwith.ir_value(), and removed dead params, flags and comments.# fmtmarkers and black-formatted the fast path. The formatting is its own commit, b760aca, with the AST unchanged.llvm.intr.fake.use, and FlyDSL has no fx wrapper for it. No raw MLIR dialect use is left in the file. A paired A/B gave the cost: none for the peer-table part, and ~3% (~0.5 us) of decode prepare at bs 1/42 for the dispatch-table part. Prefill is unaffected and outputs are bit-exact.compile_mega_moe_preparestays in place.Review layout. This is one file (+3.9k lines; main's code is unchanged apart from a guard and one kwarg). If you prefer, I can restructure before review, either way with a GPU re-validation:
mega_moe_prepare_ep8.py, with main'smega_moe_prepare.pyuntouched except a ~10-line guard. The diff becomes a pure addition.Motivation
On an earlier build (an older aiter with FlyDSL 0.3.4.1, before this change was rebased on main) I timed the prepare kernel's phases with in-kernel timestamps. The critical path was the cross-rank protocol chain, not the activation quant, even for 8192-token prefill. The chain: count routes, exchange per-rank histograms with the 7 peers over XGMI, plan the tile layout, fill the pair order. On that build the chain took about 65 µs at decode and 100-119 µs with 32 prepare CTAs (P=32). I did not repeat the timestamp breakdown on main; the main kernel times are under Performance.
The kernel runs once per MoE layer per step, so this latency shows up in every decode and prefill step.
Changes
All changes are in
aiter/ops/flydsl/kernels/mega_moe/mega_moe_prepare.py. Call sites, the API, the workspace layout and the plan contract with Stage1/Stage2 are unchanged.Shorter protocol chain
buffer_wbl2, which writes back the whole dirty L2 of the XCD (during prefill mostly the concurrent quant output). Plan data and counts are now written with relaxed system/agent-scope or write-through (sc0|sc1) stores, drained withs_waitcnt vmcnt(0)plus a barrier. Only the flag the consumer acquires is published after that.Faster MXFP8 quant (FP8 only; buckets with tile_m ≥ 128, and the m64 P32 bucket from 2048 tokens)
cvt_pk_fp8.prepare_quant_cu).quant.emit_per_1x32_mx_fp8_group. FP4 keeps the existing per-group quant.Why private plan/group emitters instead of extending
dispatch.py. The fast path does not calldispatch.emit_dispatch_plan/emit_dispatch_group; it has its own_emit_plan/_emit_group(it reusesdispatch._classify_fanout_wave_route,_wave_inclusive_scan_i32and the slot table as is). Relative todispatch.pythey change:dispatch.py: one release per flag);Only main's prepare kernel calls the shared emitters. Turning these differences into parameters of
dispatch.pywould mean editing the code main runs for every other layout and for the stock fallback here, which this PR keeps byte-identical on purpose. Drift risk: a fix to the shared emitters (e.g. from the #6127 Stage1 work) has to be checked against both copies until they are merged. I offer as a follow-up moving the private emitters into their own module; it needs a GPU re-validation.Stock path. Main's
compile_mega_moe_preparestays where it is and is unchanged except for two additions:m64_qdppkwarg;if _fast_prepare_supported(...): return _compile_fast_mega_moe_prepare(...).Every other line of that function shows as unchanged context in the diff:
Guard and rollback.
_fast_prepare_supported(npes, epr, topk)sits next to the dispatch incompile_mega_moe_prepare: EP8, epr ≤ 64, top-k ≤ 8. That covers DeepSeek-V4-Pro (epr 48), R1 and GLM-5.2 (epr 32), and also layouts with redundant experts such as V4-Pro with 32 or 64 extra experts (epr 52/56; the open MoonEP PR [FlyDSL] [CI] [MoonEP] Balance MegaMoE v2 prefill with MoonEP placed inside the compact prepare #6268 with 8 extra experts per rank gives epr 56). Correctness was checked with the repo test across the guard: epr 16/32/48/52/56/64 and top-k 2/4/6/8, including the epr 64 boundary (see Testing). Perf data exists only for V4-Pro, R1 and GLM-5.2._v13). Fast-path kernel names contain_v14, so traces show which path ran. The gfx95x arch check is unchanged.Performance
Setup. 8x MI355X (gfx950), ROCm 7.2.0. Docker image built from aiter main a29547a and sglang main d0a7565436 (plus a one-line import fix needed for sglang main to serve DeepSeek-V4 on gfx950, unrelated to MoE), FlyDSL 0.4.0. Stock and PR arms use the same image and differ only in
mega_moe_prepare.pyand its regenerated AOT cache. These numbers predate the merge of main a0c4b69 (FlyDSL 0.4.2, #7127). On that merged head I re-measured prepare against main (see Testing, "Merge with main"): V4-Pro 5.2-6.2x at decode and 2.1x at 8192, consistent with the table below.Microbench: prepare kernel time (µs), DeepSeek-V4-Pro a8w4, EP8, MTPR 8192
Method. My own 8-rank harness, not in the repo: a real
MegaMoEV2forward per measurement, prepare kernel time from the torch profiler, slowest rank's median over 50 iterations, 1 GiB L2 flush before every forward. Decode is timed under CUDA graph (as served), prefill eager. Each sweep runs in a fresh 8-rank process; stock (3 processes) and PR (4 processes) are interleaved (a4w4 rows: 30 iterations, 4 vs 4 processes; MTPR 16384 eager rows: 4 vs 4; GLM-5.2 / R1 / Kimi checks below: 20 iterations, 1 process per arm). Medians over processes, range in brackets; "worst" = slowest PR process vs fastest stock process. I did not usebench_mega_moe_v2.py --mega-onlyfor these numbers (it replays warm, without an L2 flush); I can add the harness as a test-only change if that helps.kimi_k3_route, epr 112, top-k 16): the same_v13stock kernel runs, 0.99-1.00x.End to end: DeepSeek-V4-Pro, TP8 / DP-attention 8 / EP8, MegaMoE a8w4, DSPARK MTP, c128
Setup. Agentic trace replay with aiperf (InferenceX
dsv4/sglang/mi355x-fp4-mtp/agentic.yaml, variantoverride_tp8_c128_dp_ep8_megamoe_hicache, seed 42, simulated accept length 3.77). One node, fresh container and caches per arm; the PR arm ships only the new file plus the cache written bypython -m aiter.aot.flydsl.mega_moe --quant a8w4. 1422 warm-up requests are dropped, then a 35-min profile. "[10,35]" scores requests that start after minute 10 and end by minute 35; "full" is the whole profile. Interactivity = 1/ITL (tok/s/user). Flag sets:SGLANG_AMD_FLYDSL_MEGA_MOE_MTPR=8192, chunked prefill 65536, prefill-decode interval 20). Every step runs the compact path, so prepare runs in every decode and prefill step.SGLANG_AMD_FLYDSL_MEGA_MOE_DECODE_MTPR=512,AITER_MEGA_FIXED_SLOT_MAX_MTPR=1023, chunked prefill 131072, interval 40. Pure-decode steps use the fixed-slot decode instance, which does not call this kernel.Accuracy
kimi_k3_route, Zipf routing, mixed and zero-token ranks).test_mega_moe_v2.pyvs the fp32 reference: all configurations listed under Testing pass, with per-bs rel-L2 identical to stock (a8w4 0.0591-0.0592, a4w4 0.2110-0.2121).kimi_k3_routeruns the stock_v13kernel and is bit-exact vs stock.FlyDSL AOT cache
The prepare cache keys change, so the shipped FlyDSL AOT cache has to be regenerated.
PREBUILD_KERNELS=1does that automatically.preload_mega_moe_preparealso compiles the second (qdpp) variant of the m64 P32 bucket.python -m aiter.aot.flydsl.mega_moe --quant a8w4and--quant a4w4. Each printsCompiled: 192 ok, 0 failedon main.--quant a8w4alone,test_mega_moe_v2.py(MTPR 8192 and 16384, mixed and zero-token ranks) had 0 runtime cache misses, also withFLYDSL_RUNTIME_RUN_ONLY=1, and the e2e PR arms compiled no prepare kernel at runtime.How to reproduce
E2E. sglang d0a7565436, server and router flags exactly as in the InferenceX recipe above (CI flag set = the 2026-10-07 CI job of that recipe; cookbook = the recipe after #4315), aiperf agentic replay at concurrency 128, 35-min profile after warm-up. Both arms use the same container image; the PR arm bind-mounts the new
mega_moe_prepare.pyand the AOT cache from the command above.Known gaps
num_quant_cu(fromMegaMoEConfig.prepare_quant_cu, 64-192) to 216 (m128) / 80 (m64 P32), clamped toquant_cu_capacity − 1 − P. 216 assumes a 256-CU part for co-residency (grid 1+P+Q ≤ 249). Follow-up offered: move the values intoprepare_quant_cuper bucket or derive them from the CU count.--rank-tokenscovers mixed tokens, but the fields are still unified.Testing
test_mega_moe_v2.pyandbench_mega_moe_v2.pyare inskip_testsof.github/scripts/aiter_test.sh, which also applies withci:multi-gpu. aiter CI therefore does not run any test of this kernel; all correctness and perf runs were manual on 8x MI355X with main a29547a.test_mega_moe_v2.py: every command under "How to reproduce" passes (rc 0, graph replay PASS) with rel-L2 identical to stock: 22 configurations, including MTPR 512/1024/8192/16384, a8w4 and a4w4, mixed and zero-token per-rank tokens, the all-zero step, R1, GLM-5.2,kimi_k3_routewith fanout/invalid-route/padding boundaries, pad-tail, concentrated experts, Zipf 1.2 and burst 16.0,1,1,1,1,1,1,1ranks), all with 0 runtime cache misses and also passing withFLYDSL_RUNTIME_RUN_ONLY=1, rel-L2 identical to stock and to that revision; plus 29 a8w4 harness points: outputs bit-identical to that revision, prepare time ratio 1.002 (0.974-1.057). The e2e runs used the final file.NETWORKSentries (test-side only, not in this PR; I can add them) at epr 52/56/64 with top-k 6, epr 64 with top-k 8, epr 16 with top-k 4 and epr 32 with top-k 2, bs 1/42/452/2394/8192 at MTPR 8192, plus the zero-token mixed ranks at epr 56 and 64. All take the fast path, pass, and give rel-L2 identical to stock main (6 digits) at every bs.s_sleepin each group CTA between the GROUP_DONE spin and the BLOCK_HIST read. Before the fix this faults on all 8 GPUs; after the fix it passes and is bit-stable.FLYDSL_RUNTIME_RUN_ONLY=1passes._pf1_pg1_qfo1kernel.--check(RUN_ONLY) finds all 192. One test-only workaround was needed: in this image, torch 2.9.1 cannot run the hidden-GPU replay'sbuild_p2p_table, so the harness returned a zero table. The same failure happens with main's unmodified file.topk_ids) faulted on the speculative top-k index load, so all top-k index buffers are now bounded to tokens × top-k; and the FP8 DPP quant stream was not restricted to its buckets, so a4w4 output was wrong and the m32/m64 FP8 buckets quantized twice. The zero-token--rank-tokenscases and the a4w4 runs fail on that revision and pass now.op_tests/multigpu_tests/test_mega_moe_v2.py(8 GPU, manual, see above)Documentation
Dependencies
Breaking Changes
None. The API and workspace layout are unchanged;
compile_mega_moe_preparegains one new internal optional kwarg (m64_qdpp, default False), set by the host-side bucket gate. Layouts outside the guard run the previous kernel.PR Self-Review
Reviewed revision
e6e42c7
Behavior and intent
compile_mega_moe_prepareunchanged.Validation and unverified scope
op_tests/multigpu_tests/test_mega_moe_v2.py, 22 configurations: a8w4/a4w4, MTPR 512-16384, mixed and zero-token ranks, R1, GLM-5.2, kimi_k3_route. Rel-L2 is identical to stock.python -m aiter.aot.flydsl.mega_moe --quant a8w4|a4w4: 192/192 compiled, and runs withFLYDSL_RUNTIME_RUN_ONLY=1hit the cache with 0 misses.--checkpasses.--checkpasses.test_mega_moe_v2.py, so all of the above was run manually.PR-specific question
_fast_prepare_supportedlimits the blast radius, and rollback is a revert of one file.Changed op tests
None.