Unit 6 of 10 · about 4 hours · derive, implement
Auxiliary load-balancing loss and router z-loss
Without a balancing force the router collapses onto a few experts, overflows their buffers and starves the rest. The auxiliary loss and the z-loss are the two standard counterweights, with different failure modes.
You'll be able to
- Derive the Switch auxiliary load-balancing loss and its gradients at the level needed to spot sign, normalization and detach errors.
- Explain the router z-loss, what it penalizes and why it stabilizes routing precision.
- Contrast auxiliary-loss balancing with auxiliary-loss-free bias routing.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Auxiliary load-balancing lossSwitch Transformers
Section 2.2, Equations 4 to 6: with token fraction and router probability fraction , the non-differentiability of , and
- Earlier auxiliary loss formGShard: Scaling Giant Models with Conditional Computation and Automatic Sharding
Algorithm 1, line 17 (arXiv:2006.16668v1): with counts and mean gates as the differentiable approximation
- Router z-lossST-MoE: Designing Stable and Transferable Sparse Expert Models
Section 3.3, Equations 5 and 6, and Table 4 (arXiv:2202.08906v2): z-loss as mean squared log-sum-exp of router logits, total loss weights with , and stabilization without quality loss versus update clipping
- Auxiliary-loss-free balancingDeepSeek-V3 Technical Report - MoE Sections
Section 2.1.2, Auxiliary-Loss-Free Load Balancing with Equation 16, and Complementary Sequence-Wise Auxiliary Loss, Equations 17 to 20 (arXiv:2412.19437v2): bias-only routing plus a tiny sequence-wise loss; throughput figures are the authors cluster results
Focus on
- The Switch loss multiplies by so uniform routing gives the same value at any expert count. is a non-differentiable count fraction; gradients flow only through .
- The z-loss penalizes large router logits through the squared log-sum-exp. Small logits shrink bfloat16 roundoff inside the router exponentials, which selective float32 precision alone did not fix at scale.
- Auxiliary-loss-free routing adds a per-expert bias for selection only and adapts it from observed load. Gate values still come from unaugmented affinities; the bias is updated outside backward.
- Loss scales do not transfer: Switch uses ; DeepSeek-V3 keeps only an extremely small sequence-wise coefficient. Copying one into the other over- or under-balances.
Common mistakes · 3
- Letting gradients flow into the count fraction . Detach it: only (or ) is differentiable. Differentiating counts is the standard implementation bug.
- Treating the z-loss as a load balancer. It balances logit magnitudes for numerical stability, not token counts across experts; it complements the auxiliary loss rather than replacing it.
- Tuning the bias as a gradient parameter. The aux-loss-free bias is a control variable updated from load statistics in a pre-hook, not through the loss.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why does the Switch loss multiply by ?Answer
Under uniform routing each , so the sum is . Multiplying by keeps the loss constant as experts are added.
2.Which vector carries gradients in the auxiliary loss, and why?Answer
Only : comes from argmax counts and has no derivative. The loss optimizes the differentiable probability fraction toward the observed counts.
3.Logits give z-loss 6.0731. What are the gradient signs?Answer
All positive, proportional to softmax: about . The loss pushes every logit down, largest first.
4.When would you prefer bias routing over a large auxiliary loss?Answer
When balancing pressure degrades quality: the bias keeps load even without taxing the main objective, at the cost of external load tracking.
Practice
- Deep-ML 389: Mixture of Experts Load Balancing Loss
Implement
moe_load_balancing_loss(gate_logits, num_experts, alpha); the tests check 0.01 for a balanced two-expert batch and 0.02 for a fully collapsed batch atalpha = 0.01Derive the two expected values from the Switch formula before running. The tests check loss values only, not z-loss or bias routing.
You're done when
You derive both auxiliary losses and the z-loss from memory, predict the 0.01 versus 0.02 cases, and pass Deep-ML 389.
Only when you can do this without notes.
Leads to
Notes
Resources · 4 for this unit, 8 more in the section
- GShard: Scaling Giant Models with Conditional Computation and Automatic ShardingLepikhin et al. (ICLR 2021) · support
Read the mixture-of-experts layer: top-2 gating, expert capacity, the auxiliary loss and random routing. Compare its capacity rule with Switch.
- ST-MoE: Designing Stable and Transferable Sparse Expert ModelsZoph et al. (2022) · support
Read the stability section that introduces the router z-loss and compare it with the auxiliary balancing loss.
- DeepSeek-V3 Technical Report - MoE SectionsDeepSeek-AI (2024) · support
Read the DeepSeekMoE architecture (shared and fine-grained experts, auxiliary-loss-free balancing, node-limited routing) and the all-to-all communication design. Its throughput figures are its own cluster's results.
- Switch TransformersGoogle Research · support
Read Section 2 for simplified routing, the capacity factor and the load-balancing loss, and Section 5 for combining data, model and expert parallelism. Reproduce its capacity arithmetic for one batch.
Also in this section
- Ultra-Scale Playbook - Expert ParallelismHugging Face · primary
Read Expert Parallelism and its interaction with DP in the 5D summary. Derive tokens, bytes and expected imbalance for one top-k routing example; use the linked MoE introduction only if the architecture is unfamiliar.
- How to Scale Your Model - Expert Parallelism on GPUsGoogle DeepMind · support
Read the expert-parallelism part of Rooflines for LLM Scaling on GPUs and work its quiz before the answer. Use it for the all-to-all cost half of your MoE accounting.
- TorchFeather - Expert ParallelismTorchFeather · required
Watch the video segments from 16:49:58 (MoE) through 18:36:24 (expert parallelism), 19:01:56 (all-to-all dispatch and combine) and 19:27:38 (expert tensor parallelism), then trace
model/moe/anddistributed/expert_parallel.py. Build a tiny router-dispatch-expert-combine oracle first, then map each group, placement andall_to_all_singlecall to it. - Mixture of Experts ExplainedHugging Face · required
Study routing, capacity, token dropping, auxiliary loss and the expert-parallelism sections. Implement the small routing examples and verify conservation of token contributions through combine; group composition and FSDP interaction come from the papers and TorchTitan.
- TensorTonic - Top-k MoE Router with Load StatisticsTensorTonic · support
Solve Top-k MoE Router with Load Statistics, including its lower-index tie rule, before building dispatch.
- Bumblebee - Router, Dispatcher and Expert PrimitivesBumblebee · depth
Only as a possible capstone target: read
primitive/modules/router.py,dispatcher.py,experts.pyandmoe.pyin a clean checkout. Its own todo lists no multi-GPU correctness test yet, so do not treat it as a reference implementation. - TorchTitan - MoE Model and ParallelismPyTorch · support
Read the MoE model files and their parallelization plan only after the tiny oracle passes, at a pinned commit. Record how a production PyTorch stack composes EP, expert FSDP and the other mesh dimensions.
- PyTorch Distributed - all-to-all collectivePyTorch · reference
Read
all_to_all_singleforinput_split_sizesandoutput_split_sizeson dim 0 and its uneven-split example. Use it for the dispatch and combine calls in the tiny oracle, and check zero splits yourself.