Unit 8 of 11 · about 4 hours · implement, measure

Load-balancing losses, router z-loss, dropped tokens and expert collapse

A router is trained only through the gate values, so nothing in the language-model loss asks it to use every expert. Imbalance wastes capacity and drops tokens silently, and the fixes (a balancing loss, a z-loss, a capacity factor) each add a coefficient that you have to justify with measurements.

You'll be able to

  • Implement the Switch load-balancing loss and the router z-loss, and derive their values and gradients on a small example.
  • Instrument a small MoE decoder with per-layer expert load, dropped fraction and router statistics, and recognize imbalance and expert collapse from them.
  • Run a balance, capacity and z-loss campaign with several seeds and report which effects exceed the seed spread.

Covers

Auxiliary load balancing, router z-loss, dropped tokens and expert collapse
1

Read

In this order, only the parts listed

0 of 4 done

  1. Switch Transformers (arXiv:2101.03961v3, JMLR version)Switch Transformers

    Section 2.2: Equations 4 to 6 (the differentiable load-balancing loss, the sweep and the dropped-token rate), Figure 3 (capacity factors); Section 2.4 with Table 2 (selective precision) and Table 3 (smaller initialization); Appendix B (No-Token-Left-Behind) as depth

  2. ST-MoE: Designing Stable and Transferable Sparse Expert Models (arXiv:2202.08906v2)ST-MoE: Designing Stable and Transferable Sparse Expert Models (Zoph et al., 2022)

    Section 3.3 (Equations 5 and 6, the router z-loss and , Table 4), Section 3.4 and Figure 2 (precision and roundoff), Section 5.2 and Table 8 (capacity factor and routing), Appendix A (token load balance) and Appendix B (z-loss dynamics, Figure 7)

    The setting is a T5 encoder-decoder trained with Adafactor. Skip Sections 4, 6 and 7 (fine-tuning, the 269B model, expert specialization).

  3. CS336 Spring 2026, Lecture 4 slidesCS336 2026 - Architectures and Attention Alternatives

    Slides 36 to 43 (training the router: reinforcement learning, stochastic jitter, balancing losses, DeepSeek's per-expert bias, what happens without balancing) and slides 47 to 49 (token-dropping stochasticity, router stability and z-loss)

  4. Modern LLM Notebook: From Dense to MoE ArchitecturesModern LLM Notebook - Architecture Frontiers

    Section 4 and Section 4.1 (load balancing, the bias update, and the table of metrics to print every few steps)

    Its simplified loss in Section 4 is not the Switch loss; see the traps.

2

Focus on

  • The Switch loss is , with the fraction of tokens whose top choice is expert and the mean router probability. comes from an argmax and carries no gradient; all of the gradient reaches the router through , with size proportional to (slide 40: more frequent use means a stronger push down). The factor keeps the uniform value at for any number of experts.
  • The router z-loss is on the router logits, added with weight (ST-MoE Equations 5 and 6). It keeps router logits small, which matters because large numbers have large roundoff in bfloat16 (ST-MoE Figure 2 gives up to 65,536 times worse than float32). In their Table 4, tightening Adafactor's update clipping stabilized 3 of 3 runs but cost about 2.5 points of quality (-4.206 against -1.755), while the z-loss stabilized 3 of 3 at no loss in quality (baseline: 4 of 6 stable).
  • Imbalance has three symptoms to log per layer: the load histogram (maximum load against ), the dropped fraction at your capacity factor, and the router entropy or the share of experts below a small fraction of the ideal load. Total loss can fall while a layer routes most tokens to a few experts, and averaging across layers hides a collapsed layer.
  • The three controls interact. A balancing loss moves load toward uniform at the cost of the router's freedom, a higher capacity factor trades wasted compute and memory for fewer drops, and the z-loss shapes logit scale, not balance. ST-MoE recommends top-2 routing with capacity factor 1.25 in its setting. Sweep one control at a time, with seeds.
Common mistakes · 3
  • Using the notebook's simplified balancing loss, the sum over experts of . Loads are counts of discrete choices, so this has no gradient path to the router and adds nothing to training. The Switch loss gets its gradient through the differentiable .
  • Reading one summary number as 'collapsed' or 'fine'. In the run above the unbalanced router did not kill any expert but sent the largest expert about three times its ideal share (0.37 against 0.125) and dropped 32% to 45% of assignments; only a per-layer histogram and the dropped fraction show that. A mean over layers can hide one collapsed layer.
  • Carrying a coefficient from one setting to another. The values and come from T5-style encoder-decoder models, and the router z-loss is a different term from OLMo 2's z-loss on the output logits (whose weight is given as in the text and in Table 1). Sweep your own, with the seed spread beside the result.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive for 8 tokens, 4 experts and top-1 counts that and that the Switch loss is when the mean router probability is uniform and when ; with the loss is , which is smallest, , at uniform load. Show that the gradient with respect to is . For router logits show , and at . Then implement both losses in a small MoE decoder and measure. Labeled example, not a target: 4 layers, width 128, 8 SwiGLU experts of width 128, top-2 routing with softmax over all experts and renormalized gates, router in float32, byte-level text (2 MB of JSON files, 90/10 split), 600 steps of 16 sequences of 128 tokens, AdamW with betas 0.9 and 0.95, learning rate 3e-3 with 30 warmup steps, no weight decay, 2 seeds, PyTorch 2.14.1 on CPU. Validation cross-entropy (seed 0, seed 1), dropped fraction and mean over layers of the largest expert load (ideal 0.125), over the last 50 steps: no balancing loss, capacity factor 1.0: 1.450, 1.479, 0.450, 0.373; , 1.0: 1.398, 1.370, 0.105, 0.176; no balancing loss, 1.25: 1.485, 1.477, 0.325, 0.369; , 1.25: 1.379, 1.338, 0.042, 0.193; with , 1.25: 1.369, 1.302, 0.037, 0.186; , 1.25: 1.385, 1.322, 0.031, 0.183. Paired by seed at capacity factor 1.25, the balancing loss lowered validation loss by 0.106 and 0.139, but the z-loss effect (0.010 and 0.036) and the against 0.01 effect (+0.006, -0.016) are smaller than the gap between the two seeds within a configuration (0.04 to 0.07 in the balanced runs), so two seeds cannot resolve them.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.For 8 tokens and 4 experts with top-1 counts , what is the Switch loss divided by if the mean router probabilities are uniform, and if they equal the load fractions?Answer

    with : uniform gives ; gives . With the value is , whose minimum, 1.0, is reached at uniform load. Over all batches it is not a strict minimum, because argmax counts and mean probabilities can disagree and give less than 1.0.

  2. 2.Why does the balancing loss push down the probability of overloaded experts and not touch the counts directly?Answer

    The counts come from an argmax, which has no gradient. The gradient with respect to the router probability is , so experts with a larger load fraction receive a larger push to lower their probability.

  3. 3.Compute the router z-loss contribution for one token with logits and , and say which direction its gradient pushes.Answer

    , so . The gradient on logit is , positive for every logit, so it pulls all logits down in proportion to their probability.

  4. 4.A layer drops 30% of its assignments, but validation loss looks normal. What do you check and change?Answer

    Check whether the loss is better with a larger capacity factor or a stronger balancing loss at the same tokens, and check per-layer loads. Dropped tokens still flow through the residual path, so the loss can look normal while the layer wastes capacity. The remedy trades compute and memory (capacity factor) against router freedom (balancing).

  5. 5.Why is a router softmax usually computed in float32 even in a bfloat16 model, and what does the z-loss add?Answer

    The exponential amplifies rounding error in large logits, and bfloat16 numbers of large magnitude have large roundoff (ST-MoE Figure 2). Float32 gives a precise softmax, and the z-loss keeps the logits small so the same error matters less.

5

Practice

  • TensorTonic: Top-k MoE Router with Load Statistics

    Free problem cs336-l04-topk-moe-router: the returned token_fraction () and probability_mass () are the two vectors of the Switch loss

    The public cases check these vectors on small inputs. For the first case the expected token_fraction is [0.5, 0.5, 1] and probability_mass is [0.288841, 0.288841, 0.422319]. Build the Switch loss and the router z-loss on top of your solution, and add your own gradient tests: the loss equals at uniform load, and no gradient reaches the router through .

  • A balance, capacity and z-loss campaign on a small MoE decoder

    ST-MoE Section 3.3 and Appendix B (z-loss coefficient sweep, Figure 7) as the template; vary the balancing coefficient, the capacity factor and the z-loss one at a time

    Use at least 3 seeds with paired data order, log per-layer load histograms, dropped fraction and router entropy, and report each effect next to the seed spread. The section mini-project reuses the router and the logging.

You're done when

Your balancing loss equals at uniform routing and on the hand example, its gradient reaches the router only through the probabilities, and your campaign table shows each effect next to the seed spread.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 14 more in the section
  • CS336 2026 - Architectures and Attention AlternativesStanford University · primary

    Study the Lecture 3 slides (lecture_03.pdf, architectures and hyperparameters) and Lecture 4 slides (lecture_04.pdf, attention alternatives and mixture of experts) in stanford-cs336/lectures, then implement the Assignment 1 Section 3.3 to 3.5 pieces (RMSNorm, SwiGLU, RoPE, causal attention, the pre-norm block) against its tests. Reconstruct every parameter and state equation before you change one mechanism. Keep GPUs, kernels and parallelism (Lectures 5 to 8) for their own tracks.

  • Modern LLM Notebook - Architecture FrontiersWalking Labs · support

    Use notebooks-en/part2-training/08-gpt2-to-modern-models.ipynb, 11-mla-kv-cache.ipynb and 13-moe.ipynb, and notebooks-en/part4-frontiers/27-long-context.ipynb and 30-efficient-attention.ipynb. Implement only the one variant selected for the checkpoint.

  • Switch TransformersGoogle Research · depth

    Use Equations 4 to 6 (the load-balancing loss), Figure 3 (capacity factors), Table 3 (smaller initialization for stability) and the Appendix F pseudocode as the deeper MoE reference. Reproduce only a tiny router experiment; full sparse pretraining belongs to later systems work.

  • ST-MoE: Designing Stable and Transferable Sparse Expert Models (Zoph et al., 2022)Google · depth

    Read Section 3 and Appendix B: the router z-loss in Equation 5, its coefficient 0.001 and the load-balance weight in Equation 6, and why update clipping stabilizes runs at a quality cost. Its setting is encoder-decoder T5.

Also in this section

  • OLMo 2 Open Model and Training RecipeAllen Institute for AI · required

    Read Section 2.1 (architecture), Section 3.2 (initialization) and Sections 3.3.1 to 3.3.3 (non-parametric norm to RMSNorm, reordered norm with QK-norm, z-loss) and Table 1, then find the same settings in a released configuration. The changes were adopted as a package, so the report cannot attribute stability to any single one.

  • Build a Large Language Model (From Scratch), Chapters 3 and 4Sebastian Raschka / Manning · support

    Use Chapter 3 (causal multi-head attention, pp. 50-91) and Chapter 4 (the GPT model, pp. 92-127) as the smallest runnable decoder, then the companion bonus folders ch04/04_gqa and ch04/07_moe for one bounded variant. The printed chapters use GPT-2 parts (LayerNorm, GELU, absolute positions); the modern pieces live only in the bonus folders.

  • On Layer Normalization in the Transformer Architecture (Xiong et al., 2020)Microsoft Research Asia · support

    Read Figure 1 and Sections 3 and 4: why Post-LN gradients near the output are large at initialization and need warmup, and why Pre-LN does not. The analysis holds at initialization only and assumes uniform attention weights and Gaussian inputs there.

  • GLU Variants Improve Transformer (Shazeer, 2020)Google · support

    Read Section 2 (the GLU family and SwiGLU) and Section 3.1 (hidden width cut from 3072 to 2048 so parameters match), then Table 1, where GEGLU edges out SwiGLU on the longest run. Check the matching arithmetic yourself.

  • GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023) with Fast Transformer Decoding: One Write-Head is All You Need (Shazeer, 2019)Google Research · support

    Read MQA Sections 2 and 3 (one shared key and value head to cut decoding memory traffic), then GQA Section 2 (grouped heads as the interpolation, mean-pooled uptraining with 5% of pretraining compute) and Table 1. Both report encoder-decoder results. MQA is at https://arxiv.org/abs/1911.02150.

  • RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021)Zhuiyi Technology · required

    Read Section 3: the rotation-matrix form of RoPE, why the attention score depends only on relative position, and the long-distance decay property. Base 10000 is the original choice; later models raise it.

  • Extending Context Window of Large Language Models via Positional Interpolation (Chen et al., 2023) and YaRN (Peng et al., 2023)Meta AI; Nous Research · support

    Read Position Interpolation Sections 2 and 3 (scale positions by the length ratio instead of extrapolating), then YaRN Section 3 (frequency-dependent interpolation and the attention temperature). Both still fine-tune. YaRN is at https://arxiv.org/abs/2309.00071.

  • Small-Scale Proxies for Large-Scale Transformer Training Instabilities (Wortsman et al., 2023)Google DeepMind · support

    Read Section 3.1: attention-logit growth and output-logit divergence reproduced in small models at high learning rates, and the QK-layernorm and z-loss fixes (Figures 1 to 4). It explains two of the OLMo 2 choices; transfer to a specific large run is argued, not proven.

  • TensorTonic - Architecture and Attention AlternativesTensorTonic · support

    Solve RMSNorm Forward Pass (cs336-l03-rmsnorm-forward), Parameter-Matched SwiGLU Block (cs336-l03-parameter-matched-swiglu), Rotary Query and Key Embeddings (cs336-l03-rotary-query-key-embeddings), Causal Grouped-Query Attention (cs336-l03-causal-grouped-query-attention), Top-k MoE Router with Load Statistics (cs336-l04-topk-moe-router) and one of cs336-l04-linear-attention-duality or cs336-l04-mamba2-gated-state-scan. Add capacity and token-drop cases the router tests lack. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution.

  • Decoder-Only Transformer StackRoadmap-Final · support

    Extend the already-tested decoder with the chosen mechanism. Preserve its slow oracle, causal and position tests, generation behavior and model arithmetic.

  • DeepSeek-V2, Section 2.1 (Multi-head Latent Attention)DeepSeek-AI · optional

    Read Sections 2.1.1 to 2.1.4: low-rank joint key-value compression, decoupled RoPE and the cache comparison. The 93.3% cache reduction is against their own 67B model, not a portable ratio.

  • Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Dao and Gu, 2024)Princeton and CMU · optional

    Read Section 1 and Sections 5 and 6, including Listing 1 (the segsum reference), for a state-space alternative. Skip the full duality theory; compare against a linear-attention baseline in your own harness.

  • Modern LLM Notebook, Appendix B: From Parameters to MemoryWalking Labs · support

    Appendix B Section 1 (parameters per block and per model, GQA and SwiGLU) and Section 2 (activation memory). Recount the activation tables with autograd hooks; the notebook lists produced tensors, not saved ones. Pin commit 979eecf.

  • Deep Learning Tuning PlaybookGoogle Research · support

    Read 'Identifying scientific, nuisance, and fixed hyperparameters' and 'Determining whether to adopt a training pipeline change or hyperparameter configuration' as the protocol for comparing architecture variants (per-arm learning rate, trial variance). Skip the batch-norm material. Last commit 2024; pin commit 7554a51.