Foundations to Frontier
Tests
E. Deep Learning › E12 Transformer Architectures

Mixture of Experts / Switch Transformer

A mixture-of-experts layer replaces one feed-forward network with many experts and a learned router that sends each token to a few of them. Parameters grow with the number of experts while compute per token stays roughly constant. Shazeer and colleagues' sparsely gated MoE (2017) used top-k routing. The Switch Transformer (Fedus, Zoph and Shazeer, 2022) simplified it to top-1 with a capacity limit and a load-balancing loss, reaching 1.6 trillion parameters and 7× faster pre-training than a dense T5 of equal compute. This page covers routing, capacity, the balancing loss and parameter–compute trade-offs. In the exercises you implement top-k routing, the Switch balancing loss and capacity. You then train a top-1 MoE of 8 linear experts on 8-cluster data. Without balancing the router collapses onto 4–5 experts, keeps only 60–68% of tokens and has test MSE 1.4–1.6. Moderate balancing (weight 0.1–1) uses all experts with MSE as low as 0.02, while very strong balancing (10) hurts again.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Many specialists, each token sees one

Instead of one big feed-forward network that every token passes through, a mixture of experts has many smaller expert networks and a router. The router reads each token and sends it to the expert most likely to handle it well. The model can hold far more knowledge (parameters) while each token still pays for only one expert’s computation. The difficulty is keeping the work spread out: if the router sends everything to one favourite expert, the others sit idle. Try the routing demo.

Transformer lab
Expert capacity 20 tokens (dashed); tokens dropped by overflowing experts: 9 of 128 assignments. A load-balancing loss pushes the router toward even loads.
Why engineers care

Many of today’s largest language models are mixtures of experts. They trade memory for compute: cheap per token, but large to store and tricky to balance across hardware.

📝 Quick check (Level 0)
0/3 answered
  1. 1. The router decides…
  2. 2. MoE grows parameters while keeping…
  3. 3. A failure mode is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Routing:
    • router probabilities p = softmax(xW_r);
    • top-k routing sends the token to the k largest experts, weighting their outputs by the (renormalised) gate values;
    • Switch uses k = 1 with output p_k·E_k(x).
  • Capacity: each expert processes at most c = capacity factor × tokens / E. For 1024 tokens, 8 experts and factor 1.25 that is 160. Overflow tokens are dropped (passed through by the residual connection).
  • Load-balancing loss (Switch):
    • L_aux = α·E·Σᵢ fᵢPᵢ, where fᵢ is the share of tokens routed to expert i and Pᵢ the mean router probability;
    • it equals 1 for perfectly even routing and E when all tokens go to one expert;
    • Switch used α = 0.01.
  • Parameters versus compute:
    • an MoE layer with E experts has about E times the FFN parameters (128 × 4.7 M for BERT-sized FFNs);
    • with top-1, each token uses 1/E of them;
    • Switch-C had 1.6 T parameters.
  • Dropping: with counts (50, 10, 4, 0) and capacity 20, 30 tokens are dropped.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Capacity for 1024 tokens, 8 experts, factor 1.25:
  2. 2. Balance loss for even routing (before α):
  3. 3. Switch Transformer's top-k:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

MoE in code

Exercise 1.

  • Top-2 routing chose the right experts with gates summing to 1.
  • The balancing loss was 1 for even routing and 4 when 4 experts’ traffic collapsed onto one.
  • Capacity for 1024 tokens and 8 experts was 160.

Practice.

  • In practice experts are sharded across devices (expert parallelism), and an all-to-all exchange sends tokens to their experts.
  • Mixtral 8×7B (2023) routes each token to 2 of 8 experts per layer. It holds about 47 B parameters but uses about 13 B per token.
  • Training tips:
    • router z-loss or noise for stability;
    • higher precision for the router;
    • capacity factor 1–1.25 in training, higher at inference.
  • MoE models need more memory than dense models of equal compute, and fine-tuning can overfit.
logits = router(x)                                   # (tokens, E)
p = logits.softmax(-1); gate, k = p.max(-1)          # top-1
f = torch.bincount(k, minlength=E).float() / len(k)
aux = alpha * E * (f * p.mean(0)).sum()              # Switch load-balancing loss
y = torch.zeros_like(x)
for e in range(E):
    sel = (k == e).nonzero().squeeze(-1)[:capacity]
    y[sel] = gate[sel, None] * experts[e](x[sel])
🐍 Exercise 1: routing
Implement top-k routing, the Switch load-balancing loss and expert capacity.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Tokens reach experts on other devices by…
  2. 2. Mixtral routes each token to…
  3. 3. MoE models need more…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why balancing is needed.

  • Routing is a rich-get-richer process: an expert chosen more often gets more gradient, improves on its tokens and is chosen even more.
  • Without a counterweight, a few experts take most tokens, others never train, and capacity limits drop the overflow.
  • The auxiliary loss pushes the router’s probability mass towards experts with fewer tokens. Since fᵢ is not differentiable, the gradient flows through Pᵢ.

Too much balancing. Balancing and specialisation conflict. A very strong auxiliary loss forces even routing even when the data’s structure calls for something else, so tokens go to the wrong experts. Exercise 2 finds a middle range that works best.

Scaling. At fixed compute per token, more experts mean more parameters and lower loss. Fedus et al. found Switch-Base reached T5-Base’s quality up to 7× faster. Gains diminish, and memory, communication and instability grow.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Routing without balancing tends to…
  2. 2. The aux loss gradient flows through…
  3. 3. Switch-Base reached T5-Base's quality…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much balancing does a router need?

History.

  • R. Jacobs, M. Jordan, S. Nowlan and G. Hinton introduced adaptive mixtures of local experts (1991).
  • N. Shazeer et al. introduced the sparsely gated MoE layer (ICLR 2017). GShard (Lepikhin et al., 2020) scaled top-2 MoE to 600 B parameters.
  • W. Fedus, B. Zoph and N. Shazeer’s Switch Transformers (JMLR 2022) used top-1 routing up to 1.6 T parameters. Mixtral 8×7B followed in 2023.

Exercise 2.

  • Task: inputs from 8 clusters, each with its own linear target map, so 8 experts would be ideal.
  • Model: a top-1 MoE of 8 linear experts with output p_k·W_k x, capacity factor 1.25 and the Switch balancing loss at different weights.
  • Training: 600 Adam steps, 2 seeds.
balance weight test MSE (2 seeds) experts used (of 8) busiest expert’s share tokens kept
0 1.624, 1.411 5, 4 0.38, 0.38 0.68, 0.60
0.01 1.246, 0.838 6, 5 0.27, 0.25 0.79, 0.77
0.1 0.552, 0.020 7, 8 0.27, 0.14 0.89, 1.00
1 0.075, 0.458 8, 8 0.16, 0.21 0.99, 0.93
10 0.830, 0.325 8, 8 0.28, 0.19 0.87, 0.94
  • Without balancing the router collapses. Only 4–5 experts receive tokens, the busiest takes 38%, a third of tokens are dropped by capacity, and the error is high.
  • Moderate balancing (0.1–1) fixes it: all experts are used, almost no tokens are dropped, and the error falls by 3 to 80 times.
  • Too much balancing (10) hurts again, because forcing even routing overrides the clusters, though all experts are used.
  • Results vary between seeds, typical of router training. Switch’s α = 0.01 assumes their loss scaling and token counts, so the best weight must be tuned per setup.
🐍 Exercise 2 (research): how much balancing does a router need?
Train a top-1 mixture of linear experts on clustered data with different load-balancing weights.

MoE in AI, robotics and aerospace

  • Large shared models: MoE lets one model hold specialised knowledge for many domains (maintenance, operations, design) at modest per-query compute.
  • Deployment cost: all experts must be stored and often spread across devices; plan memory and communication, not just FLOPs.
  • Robot skill libraries: gating networks that choose among skill experts follow the same routing and balancing principles.

References

  1. N. Shazeer et al. (2017). “Outrageously large neural networks: the sparsely-gated mixture-of-experts layer.” Proc. ICLR.
  2. W. Fedus, B. Zoph, N. Shazeer (2022). “Switch Transformers: scaling to trillion parameter models with simple and efficient sparsity.” JMLR 23.
  3. D. Lepikhin et al. (2021). “GShard: scaling giant models with conditional computation and automatic sharding.” Proc. ICLR.
  4. R. A. Jacobs, M. I. Jordan, S. J. Nowlan, G. E. Hinton (1991). “Adaptive mixtures of local experts.” Neural Computation 3(1).