Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Many specialists, only a few called at a time
Instead of one big brain doing everything, a mixture of experts has many smaller specialists and a dispatcher. For each word, the dispatcher picks the one or two most suitable specialists, and only they do any work. So the model can know a lot (many specialists) while staying fast (few working at once). The trick is to stop the dispatcher sending everything to the same favourite specialists while the others sit idle. The demo shows how tokens spread over experts with and without balancing.
MoE models give large-model quality at smaller per-token compute, attractive when inference cost or latency matters, though all experts must still fit in memory.
- 1. In an MoE layer, each token is processed by…
- 2. MoE increases ___ without increasing per-token compute:
- 3. Load balancing prevents…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Router: logits z = x W_r over E experts; gate probabilities p = softmax(z). Top-k routing keeps the k highest and renormalises their weights; the layer output is Σ_(i ∈ top-k) p_i · Expert_i(x).
- Sparsity: total parameters ≈ E · expert + shared; active per token ≈ k · expert + shared (Mixtral: about 47B total, about 13B active with k = 2 of 8). Expert compute per token is a k/E fraction.
- Switch balancing loss: L_aux = α · E · Σ_i f_i · P_i, where f_i is the fraction of tokens routed to expert i and P_i the mean router probability. It equals 1 when perfectly balanced and approaches E under collapse.
- Capacity: each expert accepts at most ⌈c · tokens / E⌉ tokens per batch (capacity factor c ≈ 1.25); overflow tokens are dropped (skip the layer via the residual) or rerouted.
- Expert parallelism: experts live on different devices, and tokens are exchanged with all-to-all communication.
- 1. Balancing loss under perfect balance:
- 2. Expert compute fraction for top-2 of 8:
- 3. Capacity per expert for 4096 tokens, 64 experts, factor 1.25:
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.MoE in code
Exercise 1.
- Implement top-k routing with renormalised weights.
- Implement the Switch load-balancing loss (1 when balanced, near E when collapsed).
- Compute expert capacity.
Practice.
- Libraries: Megablocks, DeepSpeed-MoE, Tutel, and Hugging Face implementations of Mixtral, DBRX, DeepSeek-MoE and Qwen-MoE.
- Monitor per-expert load during training, and tune the auxiliary-loss weight (often 0.01 on the LM loss scale) and the capacity factor.
- Router z-loss (penalising large router logits) improves stability.
- Fine-tuning MoE models can overfit more than dense ones; inference needs memory for all experts even though compute is sparse.
class MoE(nn.Module):
def __init__(self, d, E, k):
super().__init__(); self.router = nn.Linear(d, E, bias=False); self.k = k
self.experts = nn.ModuleList(nn.Sequential(nn.Linear(d, 4 * d), nn.SiLU(), nn.Linear(4 * d, d)) for _ in range(E))
def forward(self, x): # x: (tokens, d)
w, idx = self.router(x).softmax(-1).topk(self.k, dim=-1); w = w / w.sum(-1, keepdim=True)
out = torch.zeros_like(x)
for e, expert in enumerate(self.experts):
tok, slot = (idx == e).nonzero(as_tuple=True)
if len(tok): out[tok] += w[tok, slot, None] * expert(x[tok])
return out- 1. A library for efficient MoE training:
- 2. Router z-loss improves…
- 3. At inference, MoE models need memory for…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Conditional computation. An MoE layer computes a sparse, input-dependent subset of a large model. If experts specialise (different regions of input space, languages, topics), the model’s capacity grows almost linearly in E at fixed compute, which is why MoE models reach a given quality with less training compute (Fedus and colleagues, 2022).
Why routing collapses. Early in training, an expert that happens to be chosen more is trained more, becomes better, and is chosen even more: a rich-get-richer loop. The router’s gradient only reaches selected experts. Balancing losses add a gradient that pushes probability towards under-used experts.
Balance is not accuracy. Balancing guarantees that capacity is used and that load is even across devices (crucial for throughput with expert parallelism). Whether quality improves depends on whether the extra experts have useful work. On a small task with 8 regions, 4–6 experts can already cover the structure.
- 1. Routing collapse is a…
- 2. The router's gradient reaches…
- 3. Balancing guarantees…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.Does a mixture of experts give large-model quality at small-model cost, and what does balancing add?
History.
- R. Jacobs, M. Jordan, S. Nowlan and G. Hinton, “Adaptive mixtures of local experts” (Neural Computation, 1991).
- N. Shazeer et al., “Outrageously large neural networks: the sparsely-gated mixture-of-experts layer” (ICLR 2017).
- W. Fedus, B. Zoph and N. Shazeer, “Switch transformers” (JMLR 2022).
- A. Q. Jiang et al., “Mixtral of experts” (2024).
Exercise 2.
- Task: inputs in the plane, split into 8 angular sectors, each with its own linear rule (target standardised to about unit variance); 4000 training and 2000 test points.
- Models:
- dense ReLU MLP with 4 hidden units (the per-token compute of one expert);
- dense MLP with 32 units (the total size of all experts);
- Switch-style top-1 MoE of 8 experts with 4 hidden units each, without and with the balancing loss (α = 0.1).
- Training: Adam, 1500 steps of 256 points.
| model | test R² | experts used (> 2% of tokens) | largest expert share |
|---|---|---|---|
| dense, 4 units (same per-token compute) | 0.061 | — | — |
| dense, 32 units (same total size) | 0.894 | — | — |
| MoE, no balancing | 0.897 | 4 | 0.326 |
| MoE, balanced | 0.918 | 8 | 0.176 |
- MoE gives big-model quality at small-model compute: each token uses one 4-unit expert, yet R² matches the 32-unit dense network.
- Without balancing the router collapses: only 4 of 8 experts receive tokens.
- Balancing fixes utilisation reliably: all 8 experts are used in every seed.
- But not necessarily accuracy:
| seed | R² (no balancing / balanced) | experts used |
|---|---|---|
| 1 | 0.922 / 0.899 | 6 → 8 |
| 2 | 0.927 / 0.917 | 5 → 8 |
Balancing helped in seed 0 and slightly hurt in seeds 1 and 2.
- A tuning note: with my first setting (α = 0.01 on an unstandardised target) the balancing term was too weak to change anything. α must be set relative to the main loss.
MoE in AI, robotics and aerospace
- Cost-efficient assistants: MoE LLMs give high quality at lower per-token compute on ground servers.
- Multi-domain models: experts can specialise by sensor type, flight phase or language.
- Design lesson: sparse capacity needs active routing management; monitor expert load as closely as the loss.
References
- N. Shazeer et al. (2017). “Outrageously large neural networks: the sparsely-gated mixture-of-experts layer.” Proc. ICLR.
- W. Fedus, B. Zoph and N. Shazeer (2022). “Switch transformers: scaling to trillion parameter models with simple and efficient sparsity.” JMLR 23.
- A. Q. Jiang et al. (2024). “Mixtral of experts.” arXiv:2401.04088.
- B. Zoph et al. (2022). “ST-MoE: designing stable and transferable sparse expert models.” arXiv:2202.08906.