Skip to content

5.6 MoE and long context

ready≈ 14 hoursNeeds: 4.5
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (MoE router)
  4. 4 Do
  5. 5 Check

Sparse experts. An MoE layer replaces the MLP with E expert MLPs and a router, a linear layer giving each token one score per expert. Each token goes to its top k experts and their outputs are mixed with the softmax weights (Shazeer et al. 2017). Parameters grow with E while compute per token stays that of k experts. Mixtral 8x7B has 46.7 B parameters but uses 12.9 B per token (Jiang et al. 2024); you will count both.

Balance. Hardware processes each expert’s tokens as a fixed-size batch, so every expert has a capacity: capacity factor × T k / E slots. Tokens beyond it are dropped and pass through on the residual stream. Left alone, a router sends most tokens to the few experts that got ahead early. Switch Transformer adds E Σ fi Pi to the loss, with fi the fraction of tokens routed to expert i and Pi its mean router probability (Fedus et al. 2021). A z-loss on the router logits keeps them small and stable (Zoph et al. 2022).

Long context. Attention costs O(T²), and the KV cache grows with T (5.1). Sliding-window attention lets each token see only the last w tokens; stacked layers still pass information further (Beltagy et al. 2020; Mistral 7B, Jiang et al. 2023). RoPE models fail beyond their training length because they meet rotation angles they never saw. Position interpolation divides positions by the extension factor, a little fine-tuning recovers quality (Chen et al. 2023), and NTK-aware scaling instead raises the RoPE base, which keeps the high frequencies that resolve neighbouring tokens (Peng et al. 2023, YaRN).

What the balancing loss pushes onstep 1 of 4
  1. Lbal=E∑i=1EfiPi,Pi=1T∑tpti,pt=softmax⁡(zt)\mathcal{L}_{\text{bal}} = E \sum_{i=1}^{E} f_i P_i, \qquad P_i = \frac{1}{T}\sum_t p_{ti}, \quad p_t = \operatorname{softmax}(z_t)

MoE router

Load balancing and dropped tokens

Static view on small screens. Open this page on a laptop to interact.

experts E: top-k:
0 steps applied
token 0: expert 0, weights 1.00token 1: expert 0, weights 1.00token 2: expert 0, weights 1.00token 3: expert 0, weights 1.00token 4: expert 1, weights 1.00token 5: expert 0, weights 1.00token 6: expert 0, weights 1.00token 7: expert 0, weights 1.00token 8: expert 0, weights 1.00token 9: expert 0, weights 1.00token 10: expert 0, weights 1.00token 11: expert 0, weights 1.00token 12: expert 0, weights 1.00token 13: expert 0, weights 1.00token 14: expert 0, weights 1.00 (some choices dropped)token 15: expert 0, weights 1.00 (some choices dropped)token 16: expert 0, weights 1.00 (some choices dropped)token 17: expert 0, weights 1.00 (some choices dropped)token 18: expert 1, weights 1.00token 19: expert 1, weights 1.00token 20: expert 1, weights 1.00token 21: expert 2, weights 1.00token 22: expert 1, weights 1.00token 23: expert 1, weights 1.00token 24: expert 1, weights 1.00token 25: expert 2, weights 1.00token 26: expert 1, weights 1.00token 27: expert 1, weights 1.00token 28: expert 2, weights 1.00token 29: expert 3, weights 1.00token 30: expert 2, weights 1.00token 31: expert 3, weights 1.00token 32: expert 3, weights 1.00token 33: expert 2, weights 1.00token 34: expert 2, weights 1.00token 35: expert 3, weights 1.00token 36: expert 3, weights 1.00token 37: expert 3, weights 1.00token 38: expert 3, weights 1.00token 39: expert 3, weights 1.00colour: first-choice expert
0: 171: 92: 63: 8capacity 13choices per expert (dashed: dropped)
balancing loss E·Σ fiPi = 1.151 (about 1 when even, 4 at total collapse) dropped choices: 4 of 40; capacity 13 slots per expert router z-loss: 7.95; routing fractions f: 0.42, 0.23, 0.15, 0.20

Each dot is a token; the router is a linear map from the embedding to one score per expert, so the experts split the plane into wedges. The tokens come from four topics of unequal size, so equal wedges already overload some experts, and pushing the bias toward expert 0 makes it worse: tokens beyond an expert's capacity are dropped (crossed) and skip the layer. The balancing-loss button follows its gradient, which lowers the scores of experts that get more than their share and raises the rest, until the wedges carve the tokens up evenly. A higher capacity factor drops fewer tokens but wastes compute on padding.

Left: 40 tokens in a two-dimensional embedding space, from four topics of unequal size, coloured by the expert the router picks first, over a background showing which expert wins in each region; tokens dropped for lack of capacity are crossed. Right: a bar per expert with the number of routing choices it received against a capacity line, with overflow dashed. Buttons set the number of experts and k, and apply 20 gradient steps of the balancing loss to the router or reset it; sliders set the capacity factor and a bias toward expert 0. The readout gives the balancing loss, dropped choices, the z-loss and the routing fractions. Keyboard: Tab to the buttons and press Enter; Tab to the sliders and use the arrow keys.
Top-k routing, load balancing, capacity, and RoPE context extension stubs/m5_6_moe.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m5_6_moe.py and run mlc check 5.6. The tests are identical; import the results on the progress page.

Hints · dispatch 0/3 revealed
Hints · moe_forward 0/3 revealed
Hints · moe_param_count 0/3 revealed

Then train one. Open notebooks/5.6-moe-gpt.ipynb on Kaggle with a GPU and paste in your 4.6 GPT and your 5.6 file. It checks a PyTorch MoE layer against your moe_forward, then trains three models on TinyStories for the same steps: your dense GPT; an MoE with 8 half-width experts and top-2 routing, so the same compute per token; and that MoE without the balancing loss. Compare validation loss, parameter counts and how evenly each layer uses its experts. The gain from experts is modest at this size and grows with scale.

1. An MoE layer with 8 experts and top-2 routing, each expert the size of the dense MLP, costs per token roughly…
2. Why is a load-balancing loss needed?
3. Raising the capacity factor from 1.0 to 2.0…
4. Position interpolation and NTK-aware scaling both let a RoPE model run past its training length. How do they differ?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.