Skip to content

The Ultimate MoE Training Handbook

Skip →DeepSeek-V3.2
RL stage 2 #5Pretraining stage 2 #10corefrontierblogrubric 11/122026 · Hugging Face Space (5 Nov 2026) · ~480 min

Nouamane Tazi, Leandro von Werra, Thomas Wolf

Read first: DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models · Auxiliary-Loss-Free Load Balancing Strategy for Mixture-of-Experts · DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models

Status

TL;DR. This is a long, hands-on handbook from Hugging Face. It converts a dense Megatron-LM run into a 64-expert, top-8 MoE on AWS P5 H100 nodes. Then it takes the MoE layer apart setting by setting: router scoring, routing strategy, load balancing, expert shape, block layout, training, and systems. Each part ends with a symptom, a signal to watch and a recommendation. Chapter 4 follows the model into serving and RL. The central lesson: an MoE adds three new things to manage (a router, a load that must stay balanced, and a token exchange between GPUs in every layer). Most of the hard failures are slow steps or quiet quality loss, not loss spikes.

Why it matters now. The handbook opens with the claim that 18 of the 20 highest-scoring open-weights models on Artificial Analysis are MoEs. The papers on this site (Switch, DeepSeekMoE, aux-loss-free balancing) each introduce one idea. This handbook shows how those ideas interact in a real run, which flags implement them (Megatron-LM pinned at commit d6316eb45), and what each one costs in TFLOP/s. If you fine-tune or RL-train an open MoE as a retriever, reranker or search agent, the router, balancer and train/inference routing mismatch described here will be your problems too.

Reading plan. The handbook says it takes 1–2 days to read, and the 480 minutes here budget for that. For a shorter selected route of about four hours, read chapter 2 (the first MoE), 3.1 (router), 3.3 (load balancing), 3.7 (systems) and the RL part of chapter 4. That route covers the questions below except the expert-shape material, but it is not the whole handbook.

1. The first MoE: same active FFN parameters, 8× the stored FFN parameters

Section titled “1. The first MoE: same active FFN parameters, 8× the stored FFN parameters”

A bias-free SwiGLU expert has three matrices. With hidden size d=2048d = 2048 and expert width 10241024, top-8 of 64 experts uses exactly the parameters of the dense FFN it replaces:

8×3⋅2048⋅1024⏟6,291,456=50,331,648=3⋅2048⋅8192.8 \times \underbrace{3 \cdot 2048 \cdot 1024}_{6{,}291{,}456} = 50{,}331{,}648 = 3 \cdot 2048 \cdot 8192 .

Each layer stores 8× the dense FFN’s parameters, but attention and embeddings are unchanged. Across 16 layers the model has 6.86B parameters, with 1.221B active per token (dense: 1.219B). That is about 5.6× the total at nearly the same active count. The handbook then insists on a dense reference. A 1-expert, top-1 MoE upcycled from the dense checkpoint stayed within 0.00087 of the dense loss over 15 aligned steps. Without deterministic mode, two runs of the same MoE already differed by up to 0.00063 in loss. So you cannot compare configurations until runs are repeatable.

2. Router scoring: four choices, only one changes the winners

Section titled “2. Router scoring: four choices, only one changes the winners”

For token xx, the router produces logits z=Wrxz = W_r x, keeps the top-k, and mixes the chosen experts:

y=s∑i∈TopK(z)wi Ei(x),wi=g(zi)∑j∈TopKg(zj) (renormalized),g∈{softmax,σ,softplus}.y = s \sum_{i \in \text{TopK}(z)} w_i \, E_i(x), \qquad w_i = \frac{g(z_i)}{\sum_{j \in \text{TopK}} g(z_j)} \ \text{(renormalized)}, \qquad g \in \{\text{softmax}, \sigma, \sqrt{\text{softplus}}\}.
  • Gating function gg. Softmax, sigmoid and sqrt(softplus) rank experts identically, so they change weights, not winners. The exception is when a selection bias is added to the gated scores. Megatron accepts the aux-loss-free bias only with sigmoid or sqrt(softplus).
  • Output scale ss. With equal weights on kk zero-mean, pairwise uncorrelated experts of RMS rr, the routed output has RMS r/kr/\sqrt{k}, so s≈ks \approx \sqrt{k} restores rr. DeepSeek-V3 uses 2.5 at k=8k=8 and Kimi K2 2.827 (≈8\approx\sqrt 8), but Kimi K3 uses 1.0 at k=16k=16. The value is not settled. Renormalization itself lowered validation loss from 2.219 to 2.183 in Krajewski et al.
  • Sharpness. A linear router sharpens as token norms or router weights grow. Too flat a gate averages its top-k, which shows up as Max1/Max2 → 1.
  • Precision. A bf16 router can round two close logits to the same value and flip the winners. Always run the router in fp32, and add a z-loss (ST-MoE’s 1e-3) to a softmax router whose logits drift upward.

One trap: softmax over a single chosen logit is always 1. So top-1 softmax routing needs --moe-router-pre-softmax, or the router gets zero gradient.

3. Load balancing: what imbalance costs, and four ways to fix it

Section titled “3. Load balancing: what imbalance costs, and four ways to fix it”

Imbalance is measured by MaxVio=(max⁡ici−cˉ)/cˉ\text{MaxVio} = (\max_i c_i - \bar c)/\bar c. With routing forced even (random logits), the model ran at 149.4 TFLOP/s. With routing forced maximally skewed (MaxVio 7, every token on the busiest expert), it ran at 100.5. A freshly initialized learned router ran its first 40 iterations as slowly as the worst forced case. The reason is the all-to-all. Each GPU receives every token routed to its local experts, and the next all-to-all waits for the slowest GPU.

dispatch expert GEMMs combine
tokens ── all-to-all ──► GPU 0 (experts 0-7 ) ── grouped GEMM ──┐
├─► GPU 1 (experts 8-15) ── grouped GEMM ──┼── all-to-all ──► output
├─► ... │ (waits for the
└─► GPU 7 (experts 56-63) ── grouped GEMM ──┘ slowest GPU)
expert imbalance: one expert gets far more than its even share of tokens (MaxVio)
rank imbalance: one GPU's 8 local experts together exceed the mean; this sets step time
(hot experts spread over GPUs partly cancel: MaxVio 7 gave ≈2× mean per GPU)
BalancerHow it actsWhat the handbook reports
Aux loss (Σ f·P)Gradient pulls router probabilities toward even loadCoefficient is a trade-off. Flat probabilities can make it look balanced while loads stay skewed (Sigma-MoE-Tiny)
Scope: sequence / micro-batch / global batchDecides over which tokens “even” is measuredGlobal batch lets domain experts form and lowers perplexity, but the step was 5.8% slower (Qiu et al., 43B)
Loss-free bias (sign update)Bias changes selection only; no gradientFixed step 1e-3 is too coarse for large pools: busiest expert ≈20× mean at 128 experts, ≈50× at 1,024, and LM quality hurt above 128 (Li et al.)
Quantile balancingSolves for the bias from each expert’s score quantileHalved average MaxVio at 768 experts (Jin et al.). Kimi K3 uses it at 896 experts. Global balance can hide local micro-batch imbalance
  • Granularity. At fixed total and active parameters, loss fell from 2.334 to 2.297 as experts were cut finer, up to 128 experts of width d/4d/4 at top-8, and then plateaued (Liew et al.). Every finer cut still means smaller GEMMs and more token copies.
  • LatentMoE. Project each token from dd to ℓ\ell before dispatch, run experts on ℓ\ell, and project back after combine. Each copy shrinks by α=d/ℓ\alpha = d/\ell, which pays for α× more experts and α× larger top-k at the same traffic. Kimi K3 projects 7,168 → 3,584. It reported routed-branch activation blow-ups and fixed them with an RMSNorm before the up-projection.
  • Shared experts. Gains from scratch are small and inconsistent (about 0.01–0.02 lower loss in some studies, nothing or slightly worse in OLMoE). A shared slot also cuts routing combinations (32 choose 4 = 35,960 against 31 choose 3 = 4,495).
  • Variable compute. LongCat-Flash adds 256 identity (“zero-computation”) experts beside 512 FFN experts. It picks 12, and a bias targets 8 real experts per token on average.
  • Rogue experts. In Step 3.5 Flash one or two experts’ output norms exploded while the loss barely moved. In layer 45 the max expert norm went from about 14× to about 5,700× the layer median. Track max/median expert output norm per layer.
  • Layout. Leading dense layers (DeepSeek-V3 keeps its first 3) remove some all-to-alls at little cost in Ling’s models. They do not reliably fix early-layer imbalance. Shortcut-connected MoE rewires the block so the all-to-all overlaps attention. LongCat-Flash’s exposed communication fell from 25.3% to 8.4%.
  • Upcycling vs scratch. Upcycling copies or slices the dense MLP into the experts. In OLMoE, a from-scratch MoE caught up after 500B tokens (25% of the dense model’s 2T). In Komatsuzaki et al. catching up took 120% of the dense compute.
  • Muon. Megatron orthogonalizes each expert’s matrix separately, so a rarely chosen expert moves about as far as a busy one. Start at --muon-extra-scale-factor 0.2, because the default 1.0 diverged on a dense 7B in Mellum2’s tests. The router’s optimizer is a genuine open choice. DeepSeek-V4 keeps it on Muon, while Qwen3.8-Next moved it to AdamW after early instability.
  • MTP. One MTP layer with loss scale 0.1 (DeepSeek-V3 used 0.3 then 0.1). It cost about 37% longer early steps on the handbook’s 256-node runs, because by default it lands on the last pipeline stage.
  • Quiet failures. Routing collapse, dead experts and rogue experts can all leave the loss flat. Watch MaxVio and min/max expert norms, not just loss spikes.

In the one step traced on a single node, half the step was exposed all-to-all, and part of that was ranks waiting for an overloaded peer. The same iteration ran 40% faster with forced balance. Across nodes, first confirm that NCCL actually uses the fabric. A socket fallback ran at 1.7 TFLOP/s against 42.0 on EFA. The all-to-all bus bandwidth fell from 77.14 GB/s on 2 nodes to 39.25 on 4 and 30.91 on 8, so baselines must be per node count. The handbook suggests accepting an allocation at about 90% of its baseline. The levers it then tests are listed below. Its advice is to try them one at a time, because the gains do not simply add:

  • 1F1B overlap of one micro-batch’s all-to-all with another’s compute (up to 35% faster on two nodes).
  • Fine-grained recompute or offload instead of full recompute.
  • Group-limited routing, which only saves traffic with a per-node dispatcher such as DeepEP.
  • A capacity factor or replicas of hot experts. The handbook keeps dropless as the default.
  • Blockwise FP8 on Hopper and MXFP8 on Blackwell, which the Megatron Core report puts at about 10–25% end to end.
Measurement (handbook’s own runs unless noted)Value
First MoE total / active parameters6.86B / 1.221B (dense 1.219B)
Forced-even vs most-skewed routing149.4 vs 100.5 TFLOP/s
Router configs, median of last 20 of 120 iters (one seed)quantile 139, aux loss 125, quantile + EMA 0.9 121, bias-only 99 TFLOP/s
Traced single-node step≈50% exposed all-to-all; 40% faster with forced balance
NCCL socket fallback vs EFA (EP16 proxy)1.7 vs 42.0 TFLOP/s
All-to-all busbw, 2 / 4 / 8 nodes77.14 / 39.25 / 30.91 GB/s
EP16 across 2 nodes vs EP8 in one node59% lower (nodes and accumulation also differ)
--moe-permute-fusionpermute/copy kernels 11.45% → 7.14% of step; step −3.3%
Full recompute at micro-batch 2−24% throughput

Chapter 4, serving a different k. Qwen3.6-35B-A3B (256 experts, trained at top-8) scores 81.65% on MMLU. Served at top-4, the result depends on what the four surviving weights are divided by:

Top-4 denominatorMMLU change
Sum of the 4 survivors (usual renormalization)−4.65
Trained top-8 mass−3.10
Top-16 mass−0.35 (not significant, p = 0.66)

Top-4 halves the activated routed parameters, from 1.006B to 0.503B, about 17% of all parameters each token uses. The router is flat: its top 8 hold only 0.182 of the softmax mass. That is why the choice of denominator matters so much here. On Gemma-4-26B-A4B (top-8 mass 0.302), dropping renormalization at top-6 raised perplexity by 0.7%, against 356% on the Qwen model.

Chapter 4, RL routing. Ma et al. generated with SGLang and recomputed in Megatron on Qwen3-30B-A3B. About 10% of routers chose differently, and 94% of tokens differed in at least one layer. Routing replay (R3) cut the train-inference KL from 1.5e-3 to 7.5e-4, close to dense Qwen3-8B’s 6.4e-4.

  • Many results are toy simulations or single seeds. Most figures in chapter 3 are scripted toys. The handbook’s own throughput comparisons are short runs from init, so a ranking describes the first 120 iterations, not training to a fixed quality.
  • Confounded comparisons, flagged by the authors themselves. For example: the bias-only run used sigmoid, the others softmax, on an older commit. EP8 vs EP16 also differ in nodes and accumulation. The default vs tuned NCCL runs used different node pairs.
  • Evidence is borrowed from other papers. Granularity (Liew et al.), scaling the bias (Li et al.), quantile balancing (Jin et al.) and upcycling catch-up (OLMoE) are cited, not reproduced. The Muon scale-factor advice comes from a dense 7B.
  • Pinned to one stack. Flags, defaults and the two local fixes upcycling needs are specific to Megatron at d6316eb45 on P5/EFA. The router opt-out flag --moe-router-skip-muon and SiTU-GLU require Megatron Core v0.20+; shortcut blocks are upstream-main features.
  • Open questions it leaves open. These include the routed scaling factor, whether to use a shared expert, the router’s optimizer under Muon, and whether routing replay improves RL reward. The handbook presents both sides rather than a verdict.
  • Foundations it builds on. Switch Transformers supplies the f·P aux loss, capacity factor and fp32 router. Mixtral is the coarse top-2-of-8 end of the granularity ladder. DeepSeekMoE supplies fine-grained and shared experts and the device-level loss whose logic (only the per-GPU sum sets step time) the handbook measures directly.
  • Balancing. Aux-loss-free balancing is the sign-update bias the handbook stress-tests. In the cited sweep, its fixed sign-update rate of 1e-3 became too coarse above 128 experts (not a universal expert-count limit), and the handbook compares it against quantile balancing.
  • Training tricks. Multi-token prediction is the MTP layer and its pipeline cost. Muon gets an MoE-specific view: orthogonalizing each expert means rare experts move as far as busy ones. FP8-LM is the precision lever in 3.7, here with blockwise and MXFP8 recipes and the router kept in fp32.
  • Frontier reports it reads from. DeepSeek-V3 is the reference recipe: sigmoid router, scale 2.5, bias plus 1e-4 sequence loss, group-limited routing, FP8, MTP. Kimi K3 shows where that recipe broke at 896 experts: quantile balancing, LatentMoE with a norm, scale 1.0, SiTU-GLU.
  • RL. GRPO assumes the trainer recomputes the rollout’s log-probs faithfully. Chapter 4 shows MoE routing breaks that assumption, and that the remedies (replay, sequence-level ratios, batch-invariant kernels) trade off differently.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    The handbook's first MoE has 16 layers and hidden size 2,048. It replaces each dense SwiGLU FFN of width 8,192 with 64 bias-free SwiGLU experts of width 1,024, routes top-8, and adds a 64 × 2,048 router per layer. The dense model has 1.219B parameters. (a) Compute the parameters of one expert, the active FFN parameters per token per layer, and the stored expert parameters per layer. (b) From the dense total, infer the non-FFN parameters, then derive the MoE's total and active counts. (c) Why does the matched active count not imply a matched step time?

    What a strong answer covers
    • (a) One expert: 3 × 2,048 × 1,024 = 6,291,456. Top-8 active: 50,331,648, exactly the dense FFN's 3 × 2,048 × 8,192. Stored: 64 × 6.29M ≈ 402.7M per layer, 8× the dense FFN.
    • (b) Dense FFNs total 16 × 50.3M ≈ 0.805B, so non-FFN (attention, embeddings, norms) ≈ 1.219 − 0.805 ≈ 0.414B. Routers add 16 × 131,072 ≈ 2.1M.
    • MoE total ≈ 0.414 + 16 × 0.4027 + 0.002 ≈ 6.86B. Active ≈ 0.414 + 0.805 + 0.002 ≈ 1.221B. That is about 5.6× the parameters at nearly the same per-token compute.
    • (c) Each token is copied to 8 experts and moved by an all-to-all, twice per layer in the forward pass, with corresponding backward communication. The expert GEMMs are smaller and grouped. Uneven loads make one GPU finish last. None of this exists in the dense run.
  2. Derive / compute

    A router renormalizes its top-k weights to sum to 1, and the experts' outputs are zero-mean, pairwise uncorrelated, with equal RMS r. (a) Derive the RMS of the routed output when all weight is on one expert and when the k weights are equal, and from this the routed scaling factor that restores r. (b) Compare DeepSeek-V3's 2.5 and Kimi K2's 2.827 at k = 8 with that value, and say what Kimi K3's 1.0 at k = 16 implies under equal weights. (c) In Megatron an ungated shared expert is added at weight 1. What share of a token's output weight does it get at a routed factor of 2.5?

    What a strong answer covers
    • (a) One expert: RMS r. Equal weights 1/k: the variance is k × (r/k)² = r²/k, so the RMS is r/√k. Renormalized outputs therefore lie between r/√k and r, and a factor of √k restores r in the equal-weight case.
    • (b) √8 ≈ 2.83. Kimi K2's 2.827 is essentially √8, while DeepSeek-V3's 2.5 sits a little below. At k = 16, √k = 4, so a factor of 1.0 leaves an equal-weight routed output at about r/4.
    • The handbook stresses that √k is a heuristic: real weights are not equal and experts are not uncorrelated, and shipped models disagree on the factor.
    • (c) The routed weights sum to 2.5 and the shared expert has weight 1, so its share is 1/(1 + 2.5) ≈ 29%. A larger factor shrinks the shared expert's share; a factor of 1 gives it half.
  3. Mechanism

    In the handbook's single-node runs, forced-even routing reached 149.4 TFLOP/s, the most skewed forced routing (MaxVio 7) reached 100.5, and a freshly initialized learned router ran as slowly as the worst case. Explain the mechanism that turns uneven expert loads into a slower step, why the busiest GPU in the MaxVio-7 replay held only about 2× the mean load, and why a profiler can over-attribute this cost to communication.

    What a strong answer covers
    • With expert parallelism the all-to-all hands each GPU every token routed to its local experts. The GPU holding the busiest experts does the most expert compute, and the next all-to-all waits for it, so the slowest rank sets the step.
    • MaxVio = (max load − mean)/mean. MaxVio 7 at top-8 of 64 means the busiest expert got every token. GPU load sums 8 local experts, and in the replay the hot experts were spread over several GPUs, so the busiest GPU was only about 2× the mean.
    • This is why device-level balance (DeepSeekMoE) can be looser than expert-level balance: only the per-GPU sum sets step time.
    • In the traced step, half the time was exposed all-to-all while the load-balancing loss was 3.2. Part of that all-to-all time is waiting for the late rank, not moving bytes: the same iteration ran 40% faster with routing forced even.
    • Diagnostic: re-trace with forced balancing. If the all-to-all shrinks, fix balancing first; if not, work on interconnect and overlap.
  4. Critique

    The fixed-step sign-update expert bias (rate 1e-3) is the default aux-loss-free balancer in Megatron. Using the handbook's evidence, critique its use in pools of 128 to 1,000 experts, and also critique the handbook's own five-router throughput comparison. Propose one experiment that would settle whether the bias or quantile balancing should be the default at 512 experts.

    What a strong answer covers
    • Li et al.: with rate 1e-3, the busiest expert reached about 20× the mean load at 128 experts and about 50× at 1,024, while an aux loss of 1e-2 stayed under about 7×. Above 128 experts the bias also hurt LM quality, plausibly because one fixed step is too coarse.
    • The step size does not scale with the size of the imbalance or the expert count. Quantile balancing solves for the bias instead and halved average MaxVio at 768 experts (Jin et al.); Kimi K3 switched to it at 896 experts.
    • Quantile has its own gap: a globally balanced batch hid a local micro-batch MaxVio of 5.96 against a global 0.92 in Neitemeier et al. It also costs a per-expert top-k each micro-batch.
    • The five-router comparison (quantile 139, aux 125, bias-only 99 TFLOP/s) is one seed and 120 iterations from init. The bias run used sigmoid while the others used softmax, and an older commit that counted tokens in bf16. Quantile also ended with the highest LM loss.
    • Experiment: at 512 experts, sweep the bias rate (for example 1e-4 to 1e-2, plus a proportional update) against quantile balancing, several seeds, long enough to reach steady state. Report loss at matched tokens, global and micro-batch MaxVio, and step time.
  5. Design

    You will train a 2,048-hidden, 64-expert, top-8 MoE with EP8 per node on 4 nodes of 8 H100s over EFA, and you have one week. Design the monitoring and gating you put in place before and during training so that you catch slow or misconfigured nodes, routing collapse, rogue experts and router precision drift. For each signal, say where it comes from and what threshold or comparison you would act on.

    What a strong answer covers
    • Before launch: nccl-tests alltoall busbw per node count. The handbook measured 77.14 GB/s on 2 nodes, 39.25 on 4 and 30.91 on 8, so compare each allocation with its own node count and require about 90% of baseline plus #wrong = 0.
    • At startup: NCCL_DEBUG=INFO must show the EFA transport in the "Using network" line; Socket means fallback, which ran 1.7 against 42.0 TFLOP/s. During training: --gpu-sniff-test-interval flags slow ranks.
    • Routing: MaxVio per layer from saved tokens-per-expert, read alongside the LM loss. Do not read balance from the aux loss alone, because flat router probabilities can make it look balanced while loads stay skewed.
    • Rogue and dead experts: max/median and min/median expert output norm per layer from sparse activation dumps. Step 3.5 Flash's layer 45 went from about 14× to about 5,700× the median while the loss stayed flat.
    • Router precision: use an fp32 router. Megatron already logs z-loss with its coefficient divided out; the square root of the logged value gives RMS logsumexp. Thus sqrt(20.9) ≈ 4.6. Also TFLOP/s against a forced-even control run, and a deterministic-mode rerun before comparing two configs.
  6. Connect

    Connect the handbook's RL routing section to GRPO-style policy optimization. Explain precisely how an MoE adds a train/inference mismatch on top of the usual numerical one, what routing replay (R3) changes in the importance ratio and the gradient, and why its benefit is contested. Use the measurements on Qwen3-30B-A3B.

    What a strong answer covers
    • The rollout engine samples with its own kernels and possibly stale weights. The trainer recomputes log-probs to form the ratio π_θ/π_old. In an MoE, small numeric differences can flip top-k choices, so the trainer differentiates an expert path the sample never took.
    • Measured: about 10% of routers chose differently between SGLang and Megatron, and 94% of tokens differed in at least one layer. Separately, about 10% of activated experts changed after one gradient update.
    • R3 records the rollout's expert indices and replays them in the trainer. Megatron gathers the router's current scores at those indices, so the router still gets a gradient, but through the rollout's experts. The train-inference KL fell from 1.5e-3 to 7.5e-4, near dense Qwen3-8B's 6.4e-4.
    • Contested: Ma et al. saw no crashes with replay, while GRPO without it crashed in all three settings. A Qwen on-policy study saw no gain, and He et al. saw replay score below plain GRPO on Moonlight-16B-A3B. The GSPO authors dropped replay for sequence-level ratios.
    • Alternatives: batch-invariant kernels for the numeric share, importance-ratio masking, or a frozen router matrix. None of these removes the drift from stale weights or from a still-moving balancing bias.

Done with this page?

Status