Skip to content

feat(moe): dynamic expert replication for Turbo DeepEP MoE layers - #1508

Draft
boyang-amd wants to merge 6 commits into
mainfrom
dev/boyang/moe-expert-replication
Draft

boyang-amd wants to merge 6 commits into
mainfrom
dev/boyang/moe-expert-replication

Conversation

@boyang-amd

@boyang-amd boyang-amd commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Requires AMD-AGI/Primus-Turbo#675 (grouped_gemm with the weights as a list of segments, one launch per pass). Without it, setting moe_replica_planner raises at startup; with replication off (the default) nothing changes. This PR stays a draft until #675 merges; then it also moves PRIMUS_TURBO_COMMIT in ci.yaml to a Primus-Turbo main commit that has it.

Design and alternatives: #1502. Tracking: #1493.

Why

With expert parallelism every EP rank waits for the busiest one: the dispatch, the expert GEMMs and the combine of a MoE layer finish when the rank with the most routed tokens finishes. On a DeepSeek-V3 4-layer proxy at EP8 (8 x MI355X) the busiest rank gets 1.6-2.3 times the mean load under skewed routing, and 1.11-1.31 times with real DeepSeek-R1 routes; offline, the same real routes reach 1.46 at EP32 and 1.86 at EP64. The aux loss and the expert bias even the load out over many steps, but nothing moves work off the busiest rank within a step.

Replication gives each rank a few replica slots. Before the experts run, a planner copies the hottest experts into slots on lightly loaded ranks and moves part of their tokens there; after the backward, the replicas' weight gradients go back to the owners. A replica is a temporary copy, not a parameter: no optimizer state, nothing new in checkpoints, and the router, aux loss and expert bias only see logical experts.

What

  • primus/backends/megatron/core/transformer/moe/replica/
    • planner.py: ultraep (quota placement under a slot budget, from UltraEP; with min_rows, min_gain, cost, block) and moonep (exact balance, from MoonEP); fixed re-splits rows among existing slots. Every rank computes the same plan from the same all-gathered counts, so no plan is communicated.
    • remap.py: logical to physical expert ids. Each rank owns L experts followed by B slots, so DeepEP built for R * (L + B) experts sends every route to the rank that computes it, without kernel changes.
    • storage.py: SlotStorage, the slot weights and their main_grad (allocated by the transport); LayerwiseStorage keeps one set per expert linear.
    • transport.py: SlotTransport moves weights owner -> replica and gradients replica -> owner and returns a Pending to wait on; NcclTransport does it point to point, the owners adding the gradients in source-rank order. Slot tables are [R, B] tensors, so a transport that plans and moves on the device (planned for MI455X) can take them as they are.
    • scheduler.py: ReplicaScheduler (one per MoE layer: count all-gather, planning per step or per micro-batch, remap, activation-recompute replay) and ReplicaSlots (one per expert linear: which expert each slot holds, and the rules for every transport: a slot that gets another expert or is emptied returns its gradients first, every slot returns at the end of the step). ReplicaScheduler.to_physical_routes turns a dispatcher's logical routes into physical ones and ReplicaSlots.weight_segments gives the experts' grouped GEMM operand of the micro-batch; neither depends on the Primus-Turbo integration.
  • primus_turbo.py: one inserted step in each class, each flow otherwise as on main. PrimusTurboDeepEPTokenDispatcher builds the scheduler, and dispatch_preprocess rewrites the routes with to_physical_routes after the even force-balancing, then calls Turbo's _pre_dispatch once with the physical expert ids and their probabilities. Right after the remap, an identity autograd function on the dispatcher's input tokens ends the step in its backward on the last micro-batch: after both expert linears wrote their slot gradients, before finalize_model_grads reduces the expert gradients. Whether its micro-batch is the step's last is recorded in its forward, and its backward raises if a layer's backwards do not come in micro-batch order; if a step's micro-batches outnumber get_num_microbatches() the scheduler raises rather than drop gradients. PrimusTurboGroupedLinear.forward_internal calls _with_replica_segments after prepare_weights, which keeps the Primus-Turbo decisions (BF16 experts only, fused accumulation); the FP8 / FP4 / BF16 branches stay as they are, the BF16 one running the own experts and slots as one grouped_gemm(x, [weights, slots], ...) (two grouped GEMMs over split rows were 3% slower end to end in the prototype), and a micro-batch without replicas issues the same call as without replication. After a GEMM that used the slots, an identity on its output restores, in its backward, the forward's slot table before the GEMM's backward (see pipeline parallelism below). The slots carry a main_grad in the owners' dtype, so the fused wgrad accumulation covers both segments; without fusion a hook adds the slot gradients and frees the copy.
  • patches/moe_patches/moe_replica_patches.py, two hooks, off without moe_replica_planner. megatron.moe.replica_attach runs once a MoELayer is built. It rejects subclasses of MoELayer, and a layer whose dispatcher has no replica scheduler (e.g. the Primus-Turbo patches did not apply), so replication never silently stays off.
    • The dispatcher's scheduler is handed to the layer's two expert linears (no global lookup at run time), which allocate their slots on the GPU with a main_grad in the dtype Megatron's DDP gives the owners: fp32 with accumulate_allreduce_grads_in_fp32, else params_dtype. The first forward that uses the slots checks it against the owners' main_grad.
    • megatron.moe.replica_ddp wraps DDP's private _make_backward_post_hook (Megatron 4b4acac9a; to be followed when Megatron moves). With overlap_grad_reduce, DDP marks a parameter ready in its backward hook on the last micro-batch and scales and reduces a bucket once all its parameters are ready; an owner's weights were ready at the expert GEMM backward, before the replica gradients reached main_grad. For weights marked moe_replica_owner, DDP's hook still adds the gradient into main_grad but runs as if it were an earlier micro-batch, and the end of the step marks the weights ready once, after the replica gradients are in (with DDP's force_all_reduce), so the reduction still overlaps the rest of the backward. With overlap_param_gather, the expert linears' forward pre-hook waits for their parameters' all-gather only after the weights were pushed to the replicas; the push now waits for it first, as the pre-hook would, except while DDP's forward pre-hooks are off (first iteration, evaluation, checkpointing). The replica code reaches DDP only through these two callbacks on the owner parameter; building a MoE layer fails if an overlap is on but this patch was not applied. As in UltraEP's Megatron fork, which does the same for the gradients but does not wait for the all-gather. An owner whose hook ran only in no_sync is not marked (Megatron's pipeline schedules with align_grad_reduce start a chunk's reduction themselves after its last backward); a step in which the hook never ran raises.
  • Pipeline parallelism (also interleaved). A schedule runs the forwards of later micro-batches before the backward of an earlier one, but each MoE layer runs the forwards, and separately the backwards, of a step in micro-batch order, so each backward uses what its own forward saw: the end of the step as above, and with per_microbatch (whose later forwards may reassign the slots) the slot restore: the gradients of the slots that change go back to their owners and the forward's weights are pushed again, as UltraEP restores its replica weights; with per_step nothing moves. A recompute replays its forward's slot table and leaves the planning state to the latest plan. pp_warmup_patches.py resets the replica schedulers after Primus's pipeline warmup, which runs one synthetic forward and backward before training.
  • Arguments in language_model.yaml, all off by default: moe_replica_planner, moe_replica_placement, moe_replica_slots, moe_replica_min_rows, moe_replica_min_gain, moe_replica_cost, moe_replica_block, moe_replica_replan_above, moe_replica_async_comm, moe_replica_log_interval. validate_moe_replica in rocm_arg_validation.py rejects what the replicas do not handle, with the reason in the message: MegaMoE, FP8 / FP4 experts and the fused grouped MLP, TP / expert TP above 1, Primus's zero-bubble runtime (patch_zero_bubble) and patch_primus_pipeline algorithms other than the verified 1f1b, 1f1b-interleaved, zero-bubble and zbv-formatted, token dropping, even force-balanced routing, EP communication overlap, delayed wgrad, FSDP, CUDA graphs, the deprecated MoE layer, moe_router_grad_merge (not tested with the end of the step on the dispatcher input), num_microbatches_with_partial_activation_checkpoints (a forward that is not recomputed would take another micro-batch's replayed routes), mlp_chunks_for_training above 1 (the scheduler counts one MoE call per micro-batch), a BF16 grouped GEMM backend other than default or triton (per-precision values such as bf16:triton,fp8:ck are parsed), tensor_parallel_num_weight_shards above 1 and num_distributed_optimizer_instances above 1 (DDP paths the replica DDP patch does not cover), and overlap_param_gather without the distributed optimizer. It also estimates the slots' memory and logs it, with no CUDA call (it runs before Megatron sets the device); slots that do not fit fail with an out-of-memory error when the MoE layers allocate them.
  • router.py: moe_routing_replay_path replays routes recorded by Megatron's router tracer (moe_routing_trace_path) through Megatron's RouterReplay, so benchmarks can run a real model's routing on mock weights; moe_routing_replay_layers picks the recorded layer of each MoE layer. Evaluation routes by the router's own scores and does not move the recorded position. validate_moe_routing_replay rejects disable_primus_topk_router (the replay lives in PrimusTopKRouter), router paths that do not take replayed routes, recompute of MoE layers, PP above 1 and MTP; the replay needs one trace file per rank.
  • Docs: docs/04-technical-guides/moe-expert-replication.md (new, linked from the indexes and moe-training.md) and the new rows in megatron-parameters.md section 10.6.

Behavior changes: none with moe_replica_planner: null and moe_routing_replay_path: null (the defaults).

Memory. The slots take MoE layers x moe_replica_slots x one expert's weights and gradients per GPU. DeepSeek-V3 (176 MB per slot and layer in BF16): 2.8 GB for the 4-layer proxy, 40.9 GB for the full 58 MoE layers with the default 4 slots. moonep needs a slot per local expert (32 at EP8), 327 GB on the full model, which does not fit; it is for shallow models until slots can be shared across layers.

Results (8 x MI355X, one node, EP8, BF16, Primus-Turbo #675 at 8eadf346)

Replication helps in proportion to the load imbalance it removes: 1.6-3.2% with real routing at EP8, 5.6-15.8% with EP64-like imbalance inside a node, 21% under heavy synthetic skew, and 0.4% slower when the load is already balanced.

DeepSeek-V3 4-layer proxy: 256 experts, top-8, main_grads_dtype: bf16, sequence 4096, MBS 2, GBS 64 (4 micro-batches per step, 8192 tokens per rank per micro-batch), Turbo DeepEP at 80 CUs, distributed optimizer, overlap_grad_reduce and overlap_param_gather off unless noted, mock weights. ultraep with the defaults (4 slots, min_rows 1024, min_gain 0.1), per_step. The DeepSeek expert bias is off (moe_router_enable_expert_bias: false) unless the row says on. Step time on rank 7: median of 3 interleaved runs per arm (20- or 30-step runs, steps after the 10th), or the mean after the 10th step of one 100-step run where marked. Real routing is replayed with moe_routing_replay_path. Primus revisions of this PR: the synthetic-skew row and the recompute run at 97d0e8e (after the last change to the replica path), the off-vs-main comparison and the 100-step expert-bias row at 13b9074, the EP64-node rows and the second EP8 row at a5b8c54, the other rows at the first revision (2026-11-20); Primus-Turbo #675 at 8eadf346 throughout.

Routing Busiest rank / mean without replicas -> with them No replicas (ms/step) This PR (ms/step) Change
Balanced: EP64 node, late training with the expert bias 1.05 -> 1.05 1002.5 1006.7 +0.4%
Real: EP8, DeepSeek-R1 routes on wikitext, model layers 13 / 33 / 47 / 26, 100-step run 1.11-1.21 1093.8 1075.8 -1.6%
Real: EP8, same routes, model layers 10 / 30 / 44 / 23 1.31 1106.7 1071.1 -3.2%
Real: EP64 node, training without the expert bias 1.31 -> 1.03 1097.2 1036.0 -5.6%
Real: EP64 node, DeepSeek-R1 routes on mixed text (web, math, code, books) 1.44 -> 1.05 1157.5 1048.3 -9.4%
Real: EP64 node, early training 1.71 -> 1.08 1262.2 1067.2 -15.4%
Real: EP64 node, DeepSeek-R1 routes on wikitext 1.68 -> 1.05 1254.0 1056.2 -15.8%
Synthetic skew (moe_router_force_biased: -0.7) 1.6-2.3 -> 1.00-1.01 1342.2 1059.9 -21.0%
Same skew, expert bias on (as in the DeepSeek-V3 recipes) 1240.3 1046.8 -15.6%
Same skew, expert bias on, 100-step run 1131.4 1039.3 -8.1%
  • EP64 node: the real routes are split as in EP64 (64 ranks with 4 experts each, 8 nodes) and the 8 GPUs play the node with the busiest rank, each GPU getting the same routed tokens per layer and micro-batch as its EP64 rank (within 1%). This measures the expert compute inside one node; a real EP64 run also has imbalance between nodes, which replicas confined to a node cannot remove, and inter-node all-to-all, so it gains less (estimates in [MoE Replica Design] Dynamic expert replication for MoE training: planners, scheduling, segmented grouped GEMM, transports #1502). The EP64-node traces are made offline from the recorded routes (the converter is not part of this PR): an EP64 micro-batch is 64 source ranks x 8192 tokens, 4 experts per rank and 8 ranks per node; for each step and layer the node with the busiest rank is kept, proxy GPU s plays source node s and that node's GPU s, its sources' assignments to the node's experts are rescaled to exactly 8192 tokens x top-8, the node's expert j becomes proxy expert 32 (j // 4) + j % 4, and the assignments are packed into tokens of 8 distinct experts, written as router_trace_rank<r>.jsonl and replayed with moe_routing_replay_path. "Early training" and "training without the expert bias" are routes recorded while training an 8-layer DeepSeek-V3-shaped model from scratch on FineWeb-Edu; the R1 routes are DeepSeek-R1-0528's.

  • With the expert bias on, the bias itself evens out a fixed skew during training (layer 0: 2.32, 1.93, 1.58, 1.34 times the mean at steps 1, 26, 51, 76), so replicas save less over a run: -15.6% over 30 steps, -8.1% over 100.

  • Real routing at EP8 starts at 1.11-1.31 and its hot experts change every micro-batch, which leaves little to gain. Planning per micro-batch then moves more weights than it saves: moonep per micro-batch with 32 slots is 5.3% slower on the R1 routes (1093.8 -> 1152.0 ms, 100-step run).

  • Other modes on the synthetic skew, expert bias off: ultraep and moonep (32 slots) per micro-batch -17.4% each (100-step runs, means: 1339.2 ms without replicas, 1105.6 ms with either; two independent runs whose means happen to agree, medians 1104.3 and 1106.7 ms); turbo_sync_free_moe_stage 2 / 3 -20.8% / -20.3% (20-step runs); all 4 layers recomputed, expert bias on, -17.9% (1595.3 -> 1309.1 ms, 20-step run).

  • Off by default, and off it costs nothing: 1342.2 ms against 1342.0 ms on main (a477507) with the same Primus-Turbo, 3 interleaved 30-step rounds (+0.01%). The loss is identical to main for the first 2 steps and then within the spread between runs of main (6.1e-5 against 5.0e-5 relative over 30 steps).

  • Loss and grad norm with replicas stay within the spread between two runs without them (relative, maximum over 100 steps). Two runs without replicas: loss 1.7e-4, grad norm 2.6e-3. ultraep per step 2.4e-4 and 1.3e-3; ultraep per micro-batch 2.0e-4 and 5.7e-3 (one step where the logged grad norm, printed to 3 significant digits, differs in its last digit); moonep per micro-batch 2.4e-4 and 2.8e-3; with the expert bias on, moonep per micro-batch 2.3e-4 and 1.3e-3 against 3.2e-4 and 2.8e-3 between two runs without replicas. With the real routes, moonep per micro-batch differs by 7.5e-4 in loss against 2.3e-4 between two runs without replicas, with the grad norm within the spread. All 4 layers recomputed: 3.2e-5 and 2.1e-4 over 20 steps; sync-free stage 2 / 3: 1.7e-5 / 1.9e-4 and 4.3e-5 / 7.8e-4.

  • overlap_grad_reduce and overlap_param_gather on (Primus b2568ef46 plus the fifth commit; same session, 3 interleaved 30-step rounds per arm, expert bias off): 1327.2 -> 1044.6 ms (-21.3%), against 1341.7 -> 1059.5 ms (-21.0%) with both off; the overlap itself saves 1.1% without replicas and 1.4% with them. Loss and grad norm with replicas within twice the spread between runs without them: loss 9.3e-5 against 6.3e-5, grad norm 9.2e-4 against 7.1e-4. All 4 layers recomputed, expert bias on, 20-step runs: 1577.2 -> 1292.7 ms (-18.0%), loss 1.6e-5 against 2.3e-5. At EP4 (expert data parallel size 2, same 8 GPUs; 2 runs without replicas, 1 with): 1415.0 -> 1358.2 ms (-4.0%), loss 6.0e-5 and grad norm 8.1e-4 against 7.1e-5 and 1.0e-3. Before this commit, the overlapped reduction missed the replica gradients: 1.3e-2 in loss and 68% in grad norm after 20 steps, even at expert data parallel size 1 (the owners' buckets were scaled by 1 / data parallel size and reduced before the replica gradients were added). Stale weights under overlap_param_gather: a one-off debug patch (not in this PR) compared every slot with its owner (sums of the weights) after each step's weight push at expert data parallel size 2: no mismatch in 232 checks with the wait for the all-gather, 112 mismatches without it. The runs are not bitwise reproducible from step 3 even for identical code (two runs of the same code differ by 1.4e-4 in loss), so 'unchanged with the overlap off' is judged by that spread: the first 2 steps are identical to the runs before this commit, then within 1.5e-4.

  • Pipeline parallelism (Primus 23c7b4d94 plus the sixth commit), PP2 x EP4 on the same 8 GPUs (expert data parallel size 1, 8 micro-batches per step), overlap and pp_warmup on, expert bias off, 30-step runs: per_step 1453.7 -> 1404.9 ms (-3.4%, median of 6 interleaved rounds), per_microbatch 1420.5 ms (-2.3%); interleaved with one layer per virtual stage 1412.7 -> 1383.3 ms (-2.1%) per step and 1422.6 ms per micro-batch (0.7% slower); all 4 layers recomputed 1798.1 -> 1720.6 ms (-4.3%) per step and 1733.7 ms (-3.6%) per micro-batch. The gain is smaller than at EP8 because each of 4 EP ranks averages over twice as many experts. patch_primus_pipeline with communication_method: batch_p2p, per step: 1f1b 1467.0 -> 1421.1 ms (-3.1%), 1f1b-interleaved 1479.3 -> 1423.5 ms (-3.8%), zero-bubble 1437.5 -> 1390.8 ms (-3.2%), zbv-formatted 1632.7 -> 1552.9 ms (-4.9%); the default async_p2p did not start on this machine with or without replicas (lazy 2-rank NCCL communicator init). Loss and grad norm with replicas within twice the spread between runs without them in all of these (PP2 per step, 7 runs with replicas and 11 without: loss 1.5e-4 against 1.1e-4, grad norm 1.4e-3 against 1.2e-3); zbv-formatted logs no loss, only the grad norm was compared. A one-off debug patch compared every slot with its owner after each restore (PP2, per micro-batch): no mismatch in 964 checks, 284 of them after the restore moved weights. PP1 at EP8 with the overlap on, re-measured with this commit: 1326.8 -> 1045.3 ms (-21.2%). Before this commit the replica runs stopped in the first step: Primus's pp_warmup runs one synthetic micro-batch, which the schedulers counted as part of the first step.

Test

  • CPU unit tests, tests/unit_tests/backends/megatron/moe_replica/ and test_rocm_arg_validation.py: 183 passed, 27 skipped (GPU-only and an optional comparison with MoonEP's reference planner). They include the slot rules with a recording transport (including a slot emptied mid-step, and a return already posted by the last micro-batch's backward that the step end waits for once without sending it again), the slots' configured main_grad dtype and the check against the owners, the end of the step after the last micro-batch only (and the error when the micro-batch count is missing), the rejection of MoELayer subclasses and of layers without the replica scheduler, the memory estimate (logged without a CUDA call), the replica DDP patch with stand-ins for DDP (an owner's hook skips the grad-ready marking only on the last micro-batch, the end of the step marks it once with force_all_reduce, the push waits for the all-gather only while DDP's forward pre-hooks are on, a missing patch with an overlap on is an error), the routes and operand the replicas hand to the dispatcher and experts (to_physical_routes, weight_segments), and in 1F1B order the end of the step and the slot restores, an out-of-order backward, the planning state across a recompute, and the reset after the pipeline warmup.
  • GPU unit tests on 4 x MI355X, the files below: 30 passed.
    • test_replica_moe_layer_gpu.py: a Megatron MoE layer through the Turbo DeepEP dispatcher and grouped linears, two micro-batches with per-micro-batch planning and the hot experts moving between ranks (slots reassigned and emptied), against the same layer without replicas: outputs, input gradients and expert weight gradients right after the step's backward, with no later forward. Cases: synchronous and overlapped transfers, the layer recomputed, and a last micro-batch without replicas whose step end returns what the first one left. It fails if an emptied slot does not return its gradients, and all cases fail with the end-of-step hook removed. With replication on but no replicas in any micro-batch, every expert GEMM is the same grouped_gemm call as without replication. The inserted step's fused-accumulation decision and its BF16-only error are tested on their own. Wrapped in Megatron's DDP with overlap_grad_reduce (2 GPUs, expert data parallel size 1; 4 GPUs, size 2), over two steps, the reduced expert gradients must match the layer without replicas and the expert buckets must start their reduction in the backward. Without the deferral the gradients are off (relative 1.0 and 1.8); without the marking at the end of the step the buckets fall back to a reduction in finish_grad_sync (a bucket whose parameters never register in the first step keeps reducing there), which the second check catches. In 1F1B order (three micro-batches, F0 F1 B0 F2 B1 B2), with per_microbatch, overlapped transfers, recompute and per_step, the same comparison holds; without the restore the per_microbatch cases fail (weight gradients off by 1.0). Under DDP as the pipeline schedules run it (every backward in no_sync, then an explicit start_grad_sync) the reduced gradients match too.
    • test_replica_gpu.py: one expert layer with replicas against an fp32 reference (fused and unfused wgrad accumulation, synchronous and overlapped transfers); the slots add nothing to state_dict().
    • test_transport_gpu.py: only changed slots are written; returned gradients reach their owners and leave the slots cleared.
    • test_turbo_capability.py: the startup error without segment support.
    • test_routing_replay.py (needs a GPU to import Megatron's training module): reading a trace, handing a router its recorded routes and wrapping around, picking layers, and evaluation neither replaying nor taking recorded tokens, nor routing by the indices the last training forward handed to Megatron's RouterReplay.
  • End to end on the proxy above: the comparisons in Results; routes recorded with moe_routing_trace_path and replayed while recording again gave the same top-k experts for every token on all 8 ranks (2 steps, 262144 tokens per rank).
  • pre-commit on the changed files.
  • gfx942 (the CI GPUs): fix(megatron): align tokenizer and dataset path interfaces with upgraded Megatron #675 has only been run on MI355X.
  • Multi-node and EP above 8 (expert data parallel size 2 is covered on one node with EP4).
  • turbo_sync_free_moe_stage 2 / 3 with the overlap on.
  • CI GPU jobs: ci:gpu is added when the PR is marked ready, after fix(megatron): align tokenizer and dataset path interfaces with upgraded Megatron #675 merges and the Turbo pin moves.

Not in this PR

  • Planning and transfers on the device (no host sync per plan; CUDA IPC) and slot storage shared across layers: kept for MI455X, where weight transfers are much cheaper. Both go in as another SlotTransport and SlotStorage.
  • Planners that keep replicas within a node for multi-node EP.
  • Primus's zero-bubble runtime (patch_zero_bubble): it did not start on the pinned Megatron, with or without replicas.
  • Passing the router's top-k indices to the dispatcher (the logical top-k is read back from the routing map, as Turbo's _pre_dispatch does without replicas).
  • The physical routes reach _pre_dispatch as a dense [tokens, R * (L + B)] probability matrix; a Primus-Turbo argument taking the [tokens, top-k] probabilities would avoid building it.
  • Routing replay with recompute of MoE layers: Megatron's RouterReplay keeps the indices for a recompute (REPLAY_BACKWARD), but nothing in this Megatron or in Primus switches to that mode in the recompute pass, so the replay rejects it for now.
  • Slots that got no rows still return their (zero) gradients at the end of the step; skipping them would save a transfer.
  • The PRIMUS_TURBO_COMMIT move in ci.yaml, added here once fix(megatron): align tokenizer and dataset path interfaces with upgraded Megatron #675 merges.

@github-actions

Copy link
Copy Markdown

Primary maintainers: @wenxie-amd @Xiaoming-AMD

Reach out to the primary maintainers with any questions about this PR.

Outside China Standard Time (UTC+8) working hours, for urgent issues you can also reach out to: vidushi8, lorri-rao, GeneDer, amd-fuyuajin, JohnQin-llm.

Host-side planning for dynamic expert replication: hot experts are copied
into replica slots on lightly loaded EP ranks, and every rank derives the
same plan from the same all-gathered per-expert counts.

- moonep: every rank computes the same number of rows (needs B >= L slots).
- ultraep: quota placement with a per-rank slot budget; options min_rows,
  min_gain, replica_cost and block.
- fixed: re-split rows among the replicas of an existing slot table.
- remap_topk / remap_alloc: logical to physical expert ids, so a DeepEP
  dispatcher built for R * (L + B) experts sends every row to the rank
  that computes it.
- alloc_fractions / resplit_alloc / resplit_if_balanced: keep a plan's
  per-expert shares for later micro-batches of a step.

CPU unit tests cover row conservation, the slot budget, determinism, the
min_gain and replica_cost cut-offs, re-splits and the remap. The
dispatcher integration that calls this code follows in the next commit.
@boyang-amd
boyang-amd force-pushed the dev/boyang/moe-expert-replication branch from 366805a to a5b8c54 Compare November 21, 2026 03:24
@boyang-amd boyang-amd changed the title feat(moe): dynamic expert replication for Turbo DeepEP MoE layers, 15.7% faster steps under skewed routing on 8x MI355X feat(moe): dynamic expert replication for Turbo DeepEP MoE layers, up to 21% faster steps under synthetic skew on 8x MI355X Nov 21, 2026
@boyang-amd boyang-amd changed the title feat(moe): dynamic expert replication for Turbo DeepEP MoE layers, up to 21% faster steps under synthetic skew on 8x MI355X feat(moe): dynamic expert replication for Turbo DeepEP MoE layers, 9-16% faster steps with EP64-like real routing on 8x MI355X Nov 21, 2026
@boyang-amd
boyang-amd force-pushed the dev/boyang/moe-expert-replication branch 3 times, most recently from 97d0e8e to 5bb041e Compare November 24, 2026 06:37
With moe_replica_planner set, every MoE layer's PrimusTurboDeepEPTokenDispatcher
owns a ReplicaScheduler: it all-gathers the routed counts, plans replicas
(ultraep or moonep, once per step or every micro-batch), and remaps the
top-k logical experts to R * (L + B) physical experts, so DeepEP sends every
route to the rank that computes it without kernel changes. The dispatcher
hands Primus-Turbo's _pre_dispatch the physical expert ids and their
probabilities, as for any routing.

PrimusTurboGroupedLinear then runs its L own experts and B replica slots as
one Primus-Turbo grouped_gemm over the weight segments [weights, slots]
(needs AMD-AGI/Primus-Turbo#675; an older Primus-Turbo raises at startup).
The slots carry a main_grad in the owners' dtype, so the fused wgrad
accumulation covers both segments.

The replica code is in three parts, as in the design: the planners (previous
commit), the slot storage (storage.py, one set of slots per expert linear)
and the slot transport (transport.py, NCCL point to point: owners push
weights, replicas return gradients, which the owners add in source-rank
order). ReplicaSlots decides what moves when: a slot that changes or empties
returns its gradients first, and every slot returns at the end of the step.

One patch wires it into Megatron, off without moe_replica_planner:
megatron.moe.replica_attach runs when a MoELayer is built. It hands the
dispatcher's scheduler to the layer's expert linears, which allocate their
slots on the GPU with a main_grad in the dtype Megatron's DDP gives the
owners (fp32 with accumulate_allreduce_grads_in_fp32, else params_dtype;
checked against the owners' main_grad when the slots are first used). It
also ends the step in the backward of the layer's input on the last
micro-batch, after both expert linears wrote their slot gradients and
before finalize_model_grads. Subclasses of MoELayer are rejected, and so is a
MoE layer whose dispatcher has no replica scheduler (it needs the Primus-Turbo
DeepEP dispatcher), so replication never silently stays off.

Slots are plain tensors (not checkpointed, no optimizer state). The new
moe_replica_* arguments default to off, which leaves the MoE path unchanged.

Tests: scheduler bookkeeping, the slot rules and the wiring on CPU; the NCCL
transport on 2 GPUs; a 2-GPU expert layer with replicas against an fp32
reference (fused and unfused wgrad accumulation, synchronous and overlapped
transfers); a Megatron MoE layer on 2 GPUs through the Turbo DeepEP
dispatcher and grouped linears with slots reassigned and emptied mid-step,
against the layer without replicas, with the step ended by its own backward
(synchronous and overlapped transfers, the layer recomputed, a last
micro-batch without replicas); and the startup error without segment
support.
…cation

validate_moe_replica (rocm_arg_validation.py) checks the value ranges and
rejects the combinations the replicas do not handle, with the reason in the
message: MegaMoE, FP8 / FP4 experts and the fused grouped MLP, TP, expert TP
or PP above 1, token dropping, even force-balanced routing, EP communication
overlap, delayed wgrad, FSDP, CUDA graphs, the deprecated MoE layer,
moe_router_grad_merge (its input-gradient join skips a MoE layer with the
replica forward pre-hook), mlp_chunks_for_training above 1 (the scheduler
counts one MoE call per micro-batch), a BF16 grouped GEMM backend other than
default or triton (per-precision values such as bf16:triton,fp8:ck are
parsed), and overlap_grad_reduce. With overlap_grad_reduce the expert
gradient buckets are reduced during the backward, before the replica
gradients reach their owners; on the DeepSeek-V3 proxy (expert data parallel
size 1) that lost them (grad norm off by 68% after 20 steps).

It also estimates the slots' memory per GPU (MoE layers x slots x one
expert's weights and gradients, the gradients in the owners' main_grad
dtype) and logs it. It makes no CUDA call, as it runs before Megatron sets
the device; slots that do not fit fail with an out-of-memory error when the
MoE layers allocate them, e.g. moonep, which needs a slot per local expert,
on a full-depth DeepSeek-V3 (327 GB at EP8).

Docs: the moe_replica_* rows in megatron-parameters.md section 10.6, a user
guide docs/04-technical-guides/moe-expert-replication.md (prerequisites,
design, configuration, memory, results on MI355X, limitations), and links
from the technical-guide indexes and moe-training.md.
moe_routing_replay_path points at the directory Megatron's router tracer
writes with moe_routing_trace_path (one router_trace_rank<r>.jsonl per rank).
Each rank reads its own file once; every MoE layer replays the recorded
decoder layer with the same number, or the one listed for it in
moe_routing_replay_layers, taking the next recorded tokens on every training
forward. Evaluation routes by the router's own scores and does not move the
recorded position, so training stays in step with the recording.
PrimusTopKRouter hands the routes to Megatron's RouterReplay
(REPLAY_FORWARD), so the probabilities still come from the router's scores.

This makes benchmarks with a real model's routing on mock weights
reproducible, e.g. a 4-layer proxy driven by four layers of a full model.

validate_moe_routing_replay rejects disable_primus_topk_router (the replay
lives in PrimusTopKRouter, so it would silently not run), the router paths
that do not take replayed routes (moe_router_fusion, the fused router with
aux score, forced or biased routing), recompute of MoE layers (every forward
takes new tokens), PP above 1 and MTP; the replay itself requires one trace
file per rank, as the files are read by global rank. Docs: two rows in
megatron-parameters.md and a benchmarking section in the expert replication
guide. Tests: reading a trace and handing out its routes, evaluation, and
the validation.
@boyang-amd
boyang-amd force-pushed the dev/boyang/moe-expert-replication branch from 5bb041e to b2568ef Compare November 24, 2026 08:44
@boyang-amd boyang-amd changed the title feat(moe): dynamic expert replication for Turbo DeepEP MoE layers, 9-16% faster steps with EP64-like real routing on 8x MI355X feat(moe): dynamic expert replication for Turbo DeepEP MoE layers Nov 24, 2026
…am_gather

With overlap_grad_reduce, DDP marks a parameter ready for the gradient
reduction in its backward hook on the last micro-batch and scales and
reduces a bucket once all its parameters are ready. A replica owner's
weights were ready at the expert GEMM backward, before end_step added the
replica gradients into their main_grad, so those were neither scaled nor
reduced (grad norm off by 68% on the DeepSeek-V3 proxy).

A second patch, megatron.moe.replica_ddp, wraps DDP's
_make_backward_post_hook (Megatron 4b4acac9a). For weights marked
moe_replica_owner, DDP's hook still adds the gradient into main_grad, but
on the last micro-batch it runs as if it were an earlier one; end_step
marks the weights ready once per step after returning the replica
gradients (moe_replica_grad_ready, with DDP's force_all_reduce), so the
reduction still overlaps the rest of the backward. With
overlap_param_gather the expert linears' forward pre-hook waits for their
parameters' all-gather only after the weights were pushed to the
replicas; the push now waits for it first, as the pre-hook would
(moe_replica_wait_param_gather), except while DDP's forward pre-hooks are
off. The replica code reaches DDP only through these two callbacks on the
owner parameter. Building a MoE layer fails if an overlap is on but the
DDP patch was not applied.

validate_moe_replica no longer rejects overlap_grad_reduce. It rejects
tensor_parallel_num_weight_shards above 1,
num_distributed_optimizer_instances above 1 and overlap_param_gather
without the distributed optimizer, whose paths are not covered.

Tests: the patch with stand-ins for DDP on CPU; the MoE layer with
replicas wrapped in Megatron's DDP with overlap_grad_reduce on 2 GPUs
(expert data parallel size 1) and 4 GPUs (size 2): over two steps, the
reduced expert gradients must match the layer without replicas, and the
expert buckets must start their reduction in the backward.
A pipeline schedule runs the forwards of later micro-batches before the
backward of an earlier one. Replication read the scheduler's latest
micro-batch in the backward, so the step could end early, and with
per_microbatch planning a later forward could reassign the slots that an
earlier micro-batch's backward still needs. A MoE layer still runs the
forwards, and separately the backwards, of a step in micro-batch order,
so each backward now uses what its own forward saw:

- The identity that ends the step moves from a forward pre-hook of the
  MoE layer to the dispatcher's input tokens, right after the routes are
  remapped. It records in its forward whether its micro-batch is the
  step's last, and its backward raises if a layer's backwards do not come
  in micro-batch order.
- An identity on the output of each expert grouped GEMM restores, in its
  backward, the slot table of its forward before the GEMM's backward: the
  gradients of the slots that change go back to their owners and the
  forward's weights are pushed again, as UltraEP restores its replica
  weights. With per_step the slot table does not change within a step and
  nothing moves.
- The planning state (plan, lookup table, version) only follows new
  plans; a recompute replays its forward's slot table (slot_target)
  instead of setting the plan back, which could leave a stale lookup
  table after a later plan equal to the replayed one.
- megatron.moe.replica_ddp: an owner whose DDP hook ran only in no_sync
  (pipeline schedules with align_grad_reduce start a chunk's reduction
  themselves) is not marked; a step in which the hook never ran raises.
- Primus's pp_warmup runs one synthetic forward and backward before
  training; it now resets the replica schedulers, which counted it as a
  micro-batch of the first step.

validate_moe_replica no longer rejects pipeline parallelism. It rejects
Primus's zero-bubble runtime (patch_zero_bubble, which did not run on the
pinned Megatron), patch_primus_pipeline algorithms other than the
verified 1f1b, 1f1b-interleaved, zero-bubble and zbv-formatted, and
num_microbatches_with_partial_activation_checkpoints.

Tests: on CPU, the end of the step and the slot restores in 1F1B order,
an out-of-order backward, the planning state across a recompute, the
reset and the DDP callbacks; on GPUs, the MoE layer with replicas in 1F1B
order (three micro-batches, F0 F1 B0 F2 B1 B2) with per_microbatch,
asynchronous transfers, recompute and per_step against the layer without
replicas, and under DDP with every backward in no_sync and an explicit
start_grad_sync.
ddp_ref = weakref.ref(ddp)
ran = pending = False

def deferred_hook(*args):

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant