Repository navigation
feat(moe): dynamic expert replication for Turbo DeepEP MoE layers - #1508
Draft
boyang-amd wants to merge 6 commits into
Draft
boyang-amd wants to merge 6 commits into
boyang-amd wants to merge 6 commits into
Conversation
|
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. |
This was referenced Nov 20, 2026
boyang-amd
force-pushed
the
dev/boyang/moe-expert-replication
branch
from
November 20, 2026 13:38
ef2a6ae to
366805a
Compare
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
force-pushed
the
dev/boyang/moe-expert-replication
branch
from
November 21, 2026 03:24
366805a to
a5b8c54
Compare
boyang-amd
force-pushed
the
dev/boyang/moe-expert-replication
branch
3 times, most recently
from
November 24, 2026 06:37
97d0e8e to
5bb041e
Compare
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
force-pushed
the
dev/boyang/moe-expert-replication
branch
from
November 24, 2026 08:44
5bb041e to
b2568ef
Compare
…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.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Requires AMD-AGI/Primus-Turbo#675 (
grouped_gemmwith the weights as a list of segments, one launch per pass). Without it, settingmoe_replica_plannerraises at startup; with replication off (the default) nothing changes. This PR stays a draft until #675 merges; then it also movesPRIMUS_TURBO_COMMITinci.yamlto 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; withmin_rows,min_gain,cost,block) andmoonep(exact balance, from MoonEP);fixedre-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 ownsLexperts followed byBslots, so DeepEP built forR * (L + B)experts sends every route to the rank that computes it, without kernel changes.storage.py:SlotStorage, the slot weights and theirmain_grad(allocated by the transport);LayerwiseStoragekeeps one set per expert linear.transport.py:SlotTransportmoves weights owner -> replica and gradients replica -> owner and returns aPendingto wait on;NcclTransportdoes 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) andReplicaSlots(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_routesturns a dispatcher's logical routes into physical ones andReplicaSlots.weight_segmentsgives 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 onmain.PrimusTurboDeepEPTokenDispatcherbuilds the scheduler, anddispatch_preprocessrewrites the routes withto_physical_routesafter the even force-balancing, then calls Turbo's_pre_dispatchonce 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, beforefinalize_model_gradsreduces 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 outnumberget_num_microbatches()the scheduler raises rather than drop gradients.PrimusTurboGroupedLinear.forward_internalcalls_with_replica_segmentsafterprepare_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 onegrouped_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 amain_gradin 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 withoutmoe_replica_planner.megatron.moe.replica_attachruns once aMoELayeris built. It rejects subclasses ofMoELayer, and a layer whose dispatcher has no replica scheduler (e.g. the Primus-Turbo patches did not apply), so replication never silently stays off.main_gradin the dtype Megatron's DDP gives the owners: fp32 withaccumulate_allreduce_grads_in_fp32, elseparams_dtype. The first forward that uses the slots checks it against the owners'main_grad.megatron.moe.replica_ddpwraps DDP's private_make_backward_post_hook(Megatron4b4acac9a; to be followed when Megatron moves). Withoverlap_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 reachedmain_grad. For weights markedmoe_replica_owner, DDP's hook still adds the gradient intomain_gradbut 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'sforce_all_reduce), so the reduction still overlaps the rest of the backward. Withoverlap_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 inno_syncis not marked (Megatron's pipeline schedules withalign_grad_reducestart a chunk's reduction themselves after its last backward); a step in which the hook never ran raises.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; withper_stepnothing moves. A recompute replays its forward's slot table and leaves the planning state to the latest plan.pp_warmup_patches.pyresets the replica schedulers after Primus's pipeline warmup, which runs one synthetic forward and backward before training.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_replicainrocm_arg_validation.pyrejects 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) andpatch_primus_pipelinealgorithms other than the verified1f1b,1f1b-interleaved,zero-bubbleandzbv-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_trainingabove 1 (the scheduler counts one MoE call per micro-batch), a BF16 grouped GEMM backend other than default or triton (per-precision values such asbf16:triton,fp8:ckare parsed),tensor_parallel_num_weight_shardsabove 1 andnum_distributed_optimizer_instancesabove 1 (DDP paths the replica DDP patch does not cover), andoverlap_param_gatherwithout 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_pathreplays routes recorded by Megatron's router tracer (moe_routing_trace_path) through Megatron'sRouterReplay, so benchmarks can run a real model's routing on mock weights;moe_routing_replay_layerspicks 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_replayrejectsdisable_primus_topk_router(the replay lives inPrimusTopKRouter), 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/04-technical-guides/moe-expert-replication.md(new, linked from the indexes andmoe-training.md) and the new rows inmegatron-parameters.mdsection 10.6.Behavior changes: none with
moe_replica_planner: nullandmoe_routing_replay_path: null(the defaults).Memory. The slots take MoE layers x
moe_replica_slotsx 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.moonepneeds 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_reduceandoverlap_param_gatheroff unless noted, mock weights.ultraepwith the defaults (4 slots,min_rows1024,min_gain0.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 withmoe_routing_replay_path. Primus revisions of this PR: the synthetic-skew row and the recompute run at97d0e8e(after the last change to the replica path), the off-vs-main comparison and the 100-step expert-bias row at13b9074, the EP64-node rows and the second EP8 row ata5b8c54, the other rows at the first revision (2026-11-20); Primus-Turbo #675 at8eadf346throughout.moe_router_force_biased: -0.7)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>.jsonland replayed withmoe_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:
moonepper 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:
ultraepandmoonep(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_stage2 / 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 tomainfor the first 2 steps and then within the spread between runs ofmain(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.
ultraepper step 2.4e-4 and 1.3e-3;ultraepper 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);moonepper micro-batch 2.4e-4 and 2.8e-3; with the expert bias on,moonepper 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,moonepper 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_reduceandoverlap_param_gatheron (Primusb2568ef46plus 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 underoverlap_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
23c7b4d94plus the sixth commit), PP2 x EP4 on the same 8 GPUs (expert data parallel size 1, 8 micro-batches per step), overlap andpp_warmupon, expert bias off, 30-step runs:per_step1453.7 -> 1404.9 ms (-3.4%, median of 6 interleaved rounds),per_microbatch1420.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_pipelinewithcommunication_method: batch_p2p, per step:1f1b1467.0 -> 1421.1 ms (-3.1%),1f1b-interleaved1479.3 -> 1423.5 ms (-3.8%),zero-bubble1437.5 -> 1390.8 ms (-3.2%),zbv-formatted1632.7 -> 1552.9 ms (-4.9%); the defaultasync_p2pdid 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-formattedlogs 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'spp_warmupruns one synthetic micro-batch, which the schedulers counted as part of the first step.Test
tests/unit_tests/backends/megatron/moe_replica/andtest_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' configuredmain_graddtype 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 ofMoELayersubclasses 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 withforce_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.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 samegrouped_gemmcall 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 withoverlap_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 infinish_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), withper_microbatch, overlapped transfers, recompute andper_step, the same comparison holds; without the restore theper_microbatchcases fail (weight gradients off by 1.0). Under DDP as the pipeline schedules run it (every backward inno_sync, then an explicitstart_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 tostate_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'sRouterReplay.moe_routing_trace_pathand replayed while recording again gave the same top-k experts for every token on all 8 ranks (2 steps, 262144 tokens per rank).turbo_sync_free_moe_stage2 / 3 with the overlap on.ci:gpuis 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
SlotTransportandSlotStorage.patch_zero_bubble): it did not start on the pinned Megatron, with or without replicas._pre_dispatchdoes without replicas)._pre_dispatchas a dense[tokens, R * (L + B)]probability matrix; a Primus-Turbo argument taking the[tokens, top-k]probabilities would avoid building it.RouterReplaykeeps 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.PRIMUS_TURBO_COMMITmove inci.yaml, added here once fix(megatron): align tokenizer and dataset path interfaces with upgraded Megatron #675 merges.