Skip to content

[FlyDSL] [CI] [MoonEP] Balance MegaMoE v2 prefill with MoonEP placed inside the compact prepare - #6268

Open
JiaoliangYu wants to merge 24 commits into
ROCm:mainfrom
JiaoliangYu:moonep-mega-fuse
Open

JiaoliangYu wants to merge 24 commits into
ROCm:mainfrom
JiaoliangYu:moonep-mega-fuse

Conversation

@JiaoliangYu

@JiaoliangYu JiaoliangYu commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

MoonEP expert balancing in front of an unchanged MegaMoE v2. No existing file changes; the MegaMoE kernels are main's.

  • MoonEPPlanner (kernels/moonep_plan.py): each rank counts its logical routes per expert, the EP group exchanges the histograms once (mori symmetric buffer, epoch flags), and every rank runs the same placement on the gathered matrix: balance towards the average, keep each destination's top-B remote experts, return the rest to their owners, settle the prefetch slots stickily. Each route is then rewritten to the virtual id dest * (EPR + B) + slot of its replica. Three small kernels; one planner serves every layer, slot tables are per layer.
  • An ordinary MegaMoEV2 over R * (EPR + B) experts runs the virtual ids, so fanout pairs and the aligned-pair Stage2 stay available. Unbalanced passes only map ids to their owner's copy (home_ids).
  • MoonEPWeightPool: one P2P-readable VMM segment per rank and layer holding an [EPR | B] window for each of w1, w1 scale, w2, w2 scale (fd and device exchanged in one socket message), and one prefetch launch for all four that skips slots already holding their expert. Windows above 4 GiB (MegaMoE's 32-bit buffer offsets) are rejected.
  • EP4 and EP8.

Tests

  • op_tests/test_moonep_plan.py (1 GPU): placement and slot tables vs a CPU reference, and the rewrite kernel's per-(source, virtual id) route counts vs a Python split of the same placement; R=8/4 x B=8/48, sticky slots, >32 slots, top-B cut, empty route slots.
  • op_tests/multigpu_tests/test_moonep_mega.py (8 and 4 GPU): outputs bit-identical to plain MegaMoEV2 over steps, layers sharing one instance, balance on/off, B=48, CUDA graph, side stream. Negative controls (no slot fill, layers sharing slot tables) fail as expected.
  • op_tests/test_moonep_slot_cache.py (8 GPU): multi-part prefetch, resident skip, two EP4 groups in one world, no fds kept.

Results

DeepSeek-R1 fp4 on MI355X with ATOM ROCm/ATOM#2499, gsm8k (paired against plain mega, same session):

mega MoonEP paired p
EP4 0.9477 0.9500 0.76
EP8 0.9522 0.9507 0.87

Prefill, DeepSeek-V4-Pro EP8, 1024/2 conc 2048, 1 warm + 2 timed rounds, same session: plain mega 66,687 tok/s, MoonEP 81,643 (+22.4%), mean TTFT 15.7 -> 12.8 s. The earlier prepare-fused version measured 81,711 vs 66,345 (+23.2%). Per MoE layer (EP8, 8k/16k tokens per rank) planning in front is within noise of the fused version except uniform routing at 8k tokens (+3%, ~170 us).

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 6268 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

jiaolyu added 6 commits October 8, 2026 12:10
Port the virtual-id MoonEP meta (balance, top-B, owner rollback) plus a
sticky slot settle into @flyc.jit emitters the prepare owner CTA can call
on the gathered histogram, and split each logical (source, expert) route
range into the virtual count matrix the destination plan consumes.
MegaMoEV2(moonep_slots=B) takes logical topk_ids over an [EPR | B] weight
window.  Prepare counts and exchanges the logical histogram once, places it
with MoonEP on the owner CTA, and runs the unchanged destination plan,
offset derivation and payload on the virtual count matrix it implies, so
MoonEP adds no histogram exchange or barrier of its own.  Fanout pairs and
the aligned-pair Stage2 stay off in this mode; forward(after_prepare=...)
lets the caller enqueue the slot weight copy before Stage1.
One MegaMoEV2 instance serves every shape-identical layer, so the slot
tables move out of the shared workspace: new_moonep_slot_state() gives a
window its own tables behind a dispatch-table copy, and
bind_moonep_slot_state() selects it per call like the weight pointers.
Unplanned passes only need every expert on its owner; write that mapping
directly instead of running the balance, top-B and settle rounds.
The [EPR | B] pool MoonEP fills from peers between prepare and Stage1:
a VMM-stitched row-contiguous window and a prefetch kernel that skips
slots already holding their expert.  The placement helpers now carry
their own wave/LDS helpers and the placement test its own CPU
reference, so the fusion stands alone on main.
@JiaoliangYu JiaoliangYu changed the title [MoonEP] Plan MoonEP placement inside the MegaMoE v2 compact prepare [MoonEP] Balance MegaMoE v2 prefill with MoonEP placed inside the compact prepare Oct 8, 2026
jiaolyu and others added 10 commits October 8, 2026 14:03
- close every VMM shareable fd once imported/exchanged instead of holding
  world_size fds per pool for the model lifetime
- bootstrap the fd exchange over the pool's own process group with its
  leader's global rank, so several EP groups can share one world
- settle up to 64 prefetch slots with a 64-bit bitmap; reject B > 64
- run after_prepare on the stream forward() prepared on, so the slot
  fill stays between prepare and Stage1 for an explicit stream
Tests: EP sub-group pools and fd count, B=48 with >32 slots settled,
explicit-stream forward.
Prepare keeps 8 waves; waves at or above the EP size join the barriers
and store nothing. Reject weight windows above 4 GiB, which GEMM1/GEMM2
cannot address with 32-bit buffer offsets.
Tests: placement R=8/4/2 x B=8/48; 8/4/2-GPU fused runs match plain
MegaMoEV2 bit for bit (EP2 with B=2).
MegaMoEV2 rejects moonep_slots for other EP sizes; tests cover 8 and 4.
MoonEPVmmPool lays a rank's parts (w1, w1 scale, w2, w2 scale) back to back in
one segment, each with its own [epn + B] window, so a layer needs one VMM
allocation, one fd exchange and one prefetch launch instead of four. Only the
segment is padded to the VMM granularity, so pad_experts goes away.
Tests: slot cache with two parts (incl. a segment off the granularity), two
EP4 groups in one world.
MoonEP no longer lives inside the compact prepare. MoonEPPlanner counts each
rank's logical routes, exchanges the histograms once, runs the placement
and rewrites every route to the virtual id of its replica; an ordinary
MegaMoEV2 over R * (EPR + B) experts then runs it, so fanout pairs and the
aligned-pair Stage2 stay on. Unbalanced passes only map ids to their owner.
The MegaMoE files are back to main; the 4 GiB window check moves to
MoonEPWeightPool. Kernels launch through _run_compiled, since
flyc.compile() also runs them.
Tests: planner placement and rewrite vs a CPU reference (R=8/4, B=8/48);
8/4-GPU outputs match plain MegaMoEV2 bit for bit, incl. B=48, CUDA graph,
side stream; slot-cache prefetch.
@JiaoliangYu
JiaoliangYu marked this pull request as ready for review October 12, 2026 03:57
@JiaoliangYu
JiaoliangYu requested a review from a team October 12, 2026 03:57
@github-actions github-actions Bot changed the title [MoonEP] Balance MegaMoE v2 prefill with MoonEP placed inside the compact prepare [FlyDSL] [MoonEP] Balance MegaMoE v2 prefill with MoonEP placed inside the compact prepare Oct 12, 2026
jiaolyu added 2 commits October 12, 2026 11:24
With every block on the same slot the grid read one owner, over one xGMI
link, at a time. DSv4-Pro EP8, 8 slots from 7 owners: 2.74 -> 1.51 ms,
102 -> 186 GB/s per rank. Tests: slot-cache prefetch (multi-part,
resident skip, two EP4 groups).
@zufayu
zufayu requested a review from yadaish October 13, 2026 01:42
@zufayu

zufayu commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

@aiter-bot review

@aiter-bot

Copy link
Copy Markdown

[ROCm/aiter] PR #6268 — [FlyDSL] [MoonEP] Balance MegaMoE v2 prefill with MoonEP placed inside the compact prepare

Adds a MoonEP planning layer in front of an unchanged MegaMoE v2: ranks exchange per-expert route histograms over mori symmetric memory, run one deterministic placement (balance to the all-rank average, top-B remote experts per destination, sticky prefetch slots), rewrite routes to virtual ids over R(EPR+B) experts, and pull the chosen remote experts' weights into local slots through a HIP-VMM pool so the plain MegaMoE runs them locally.*

Review (advisory): 🔴 HIGH RISK
Validation (deterministic): NOT RUN — REVIEW_AUTO_VALIDATE=0 (auto-validation disabled; triage found 3 candidate targets with no unique added one) and no torch-bearing python on this box to hand-run one
Perf (advisory): NOT RUN — the PR ships no benchmark entry point (its +22.4% / 66,687 → 81,643 tok/s prefill numbers are the author's paired same-session ATOM serving runs, not a committed harness) and this box has no torch-bearing python to measure with

🔴 [verified] op_tests/test_moonep_slot_cache.py sits at op_tests/ depth 1, so the standard single-GPU op-test job shards it in and runs it as plain python3, where dist.init_process_group("nccl") (line 47) dies with "environment variable RANK expected, but not set" — the PR's own CI run 38242953083 is red on exactly this file on both MI35X and MI300X (test_moonep_plan.py passed on both; the shard-4 linear-attention failure and shard-7 timeout touch no file of this PR), and op_tests/multigpu_tests/test_moonep_mega.py has the same latent problem in the label-gated multigpu job because it has no torchrun entry in .github/scripts/aiter_test.sh and is not in its skip list. Author must wire both multi-rank tests into the CI runner (a torchrun special case as test_comm_fused_moe.py has, a skip-list entry, or self-set MASTER_ADDR as test_custom_group.py does) so the default op-test job goes green.
⚠️ [verified] MoonEPWeightPool.prefetch (aiter/ops/flydsl/kernels/moonep_weights.py) checks resident for dtype and length but experts_to_copy_row for dtype only, while the prefetch kernel reads slots [0, B) from it through an unbounded buffer descriptor (no num_records_bytes, which defaults to 2^32-1 records) — a shorter tensor silently reads past the allocation and the garbage expert id then drives the owner * segment_bytes source offset, copying arbitrary memory into the prefetch slots with no error; resident is also passed by data_ptr() without .contiguous() (unlike sel one line above), so a strided [B] resident silently reads the wrong slots and skips the wrong copies. Author must give experts_to_copy_row the same length check and both tensors a contiguity assert or .contiguous().
⚠️ [verified] The shipped prefetch kernel and VMM pool are exercised only at toy shapes — test_moonep_slot_cache.py uses 4 experts/rank, 3 slots and parts of 512 KB + 48 bytes, while the production-shape test (test_moonep_mega.py) fills its slots with torch.where/index_select instead of the real pool — so the real prefetch path at production scale (the docstring's 29.4 MB rows) and the body's "bit-identical outputs" claim (the test gates only at max_rel < 2e-2 and prints exact_ranks without asserting it) are in no committed test. Author must state what was actually run for the docstring's 41.6–55.4 GB/s numbers and commit a production-shape run of the real pool, asserting exact_ranks or softening the claim.

@zufayu

zufayu commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Where that review came from — I ran the bot on your PR to show what it does. It is not an automatic hook; nothing reviews your PR unless somebody asks.

Any reviewer on the aiter allowlist can ask for one, on any PR including their own. The trigger is a comment containing the words below — shown quoted here, because quoted lines deliberately do not trigger it:

@aiter-bot review

  • Reviews the PR at its current head. Comment again after pushing fixes for a fresh pass; a repeat on the same commit is deduped.
  • One review runs at a time on one box, roughly 20 minutes. If work is ahead of you the bot replies with your place in the queue, and if the runner is down it says so rather than leaving you waiting for a review that will never start.
  • The card is advisory. It never blocks a merge, 🔴 included — it is there to be argued with.

Feedback on the review itself is welcome; it is how the rules get better.

@@ -0,0 +1,115 @@
# SPDX-License-Identifier: MIT

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

CI is red because of this PR. test_moonep_slot_cache.py is an 8-rank torchrun test sitting in the op_tests/ root, so the single-GPU job runs it with plain python and it dies with RANK expected, but not set. Please move it under multigpu_tests/ with a proper torchrun entry, or skip it when there's no distributed env.

@@ -0,0 +1,268 @@
# SPDX-License-Identifier: MIT

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

test_moonep_mega.py can't catch a regression yet.

  • It fills the slots with torch.where/index_select, so the real MoonEPWeightPool.prefetch kernel is never exercised at production shapes.
  • It never fails: on a mismatch it prints SOME_FAILED but still exits 0, and exact_ranks is printed, not asserted.
  • It goes through _setup_dist() from test_mega_moe_v2.py, which needs torchrun, and that file is on the multigpu skip list for exactly this reason. So adding ci:multi-gpu alone won't run it.

f"expert rows must be positive 16-byte multiples, got {row_bytes}"
)
window = experts_per_rank + prefetch_slots
if any(window * b > 1 << 32 for b in row_bytes):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Off-by-one in the 4 GiB guard (moonep_weights.py:72). MegaMoE reads weights through a buffer descriptor with num_records = 0xFFFFFFFF bytes, so a window of exactly 2^32 bytes is already too big. I checked this on gfx950: at a 2^32-byte window, the last dword reads back as 0 and everything before it is fine. The guard should be >=, same as MegaMoE's own activation checks: if any(window * b >= 1 << 32 for b in row_bytes):

… checks

- CI: move test_moonep_slot_cache.py to multigpu_tests; aiter_test.sh runs
  test_moonep_mega.py and test_moonep_slot_cache.py under torchrun on 8
  gfx950 GPUs and skips elsewhere; test_shuffle_out.py runs under pytest.
- test_moonep_mega.py fills the slots with MoonEPWeightPool.prefetch instead
  of index_select, requires bit-identical outputs on every rank, and exits
  non-zero on failure.
- MoonEPWeightPool: the 4 GiB window guard is >= (MegaMoE's descriptors hold
  2^32 - 1 bytes); prefetch checks experts_to_copy has one entry per slot and
  makes resident contiguous.
- shuffle_scale_a16w4_out_shape(): the padded [rows, ceil8(k)] shape
  shuffle_scale_a16w4 returns, for sizing out= storage; shuffle_scale uses it.
- Prefetch docstring states where its bandwidth table was measured.
@github-actions github-actions Bot changed the title [FlyDSL] [MoonEP] Balance MegaMoE v2 prefill with MoonEP placed inside the compact prepare [FlyDSL] [CI] [MoonEP] Balance MegaMoE v2 prefill with MoonEP placed inside the compact prepare Oct 21, 2026
@github-actions github-actions Bot added the CI label Oct 21, 2026
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Nov 6, 2026
@zufayu
zufayu requested a review from GwilliamHu November 23, 2026 10:18
@zufayu zufayu assigned GwilliamHu and unassigned yadaish Nov 23, 2026
@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Nov 24, 2026

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants