Maps to: CMU 11-711 Spring 2026, Lecture 21 (04/02), “Mixture of Experts”, Sean Welleck; slides
anlp-s2026-21-moe.pdf(acknowledging Stanford CS336, Spring 2025, Lecture 4); no course code. Readings: W. Fedus, J. Dean, B. Zoph, A Review of Sparse Expert Models in Deep Learning (2022); N. Muennighoff et al., OLMoE: Open Mixture-of-Experts Language Models (2024). Additional: D. Dai et al., DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models (2024). Sources: the public slides, the readings, and the papers cited in each section. Numbers quoted from papers or slides are attributed to them. Every number labelled “measured” comes fromcode/lecture21/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code:code/lecture21/— five demos, each under a minute once the models are cached. Reading time: ~80 minutes for the prose; ~15 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Write down an MoE layer: experts, router scores, top-k gating, and how it replaces a Transformer’s FFN.
- Distinguish total from active parameters, and explain why MoEs scale parameters at fixed FLOPs per token.
- Compare expert designs: expert count, fine-grained experts, shared experts.
- Compare routing functions: top-k token choice, expert choice, hashing. Explain capacity and token dropping.
- Explain the load-balancing loss and the router z-loss: what each optimizes and why it is needed.
- Describe expert parallelism (all-to-all dispatch and combine) and sparse upcycling.
- Say when an MoE pays off, and what experts specialize in, with evidence.
0.2 Prerequisites and scope
- Prerequisites:
- Lecture 5: the Transformer block and its FFN.
- Lecture 7: scaling laws, and Fact World.
- Lecture 20: the collectives, especially all-to-all, and data/tensor parallelism.
- Scope: the slides’ outline (what MoEs are, expert design, routing functions, loss functions, systems, case studies), with the readings’ details.
- Not in scope:
- MoE in attention layers, beyond a sentence.
- Kernel-level MoE implementations (grouped GEMMs, MegaBlocks).
- MoE scaling-law fits.
0.3 Section → code map
| Section | Idea | Demo in code/lecture21/ |
|---|---|---|
| §1.4, §2 | the layer by hand; total vs active parameters | 01_moe_layer.py Parts A–B (+ moe.py) |
| §3 | expert combinations (fine-grained) | 01_moe_layer.py Part C |
| §4 | capacity, dropping; token choice vs expert choice vs hashing | 01_moe_layer.py Parts D–E; 03_routing_balance.py Part D |
| §5 | balance loss, capacity, z-loss, trained | 03_routing_balance.py Parts A–C |
| §6 | expert parallelism; upcycling | 05_upcycling_expert_parallel.py |
| §7 | does the MoE pay? two regimes | 02_more_params_same_flops.py; 04_specialization.py Part A |
| §8 | what experts specialize in | 04_specialization.py Parts B–D |
0.4 Notation
| Symbol | Meaning |
|---|---|
| hidden state of token entering the FFN position | |
| (or ) | number of routed experts; the -th expert |
| router vector of expert | |
| router score (probability) of expert for token | |
| gate: the weight of expert in token ‘s output (0 if not chosen) | |
| (or ) | experts per token |
| share of tokens routed to expert ; average router probability of expert |
1. Why mixtures of experts?
1.1 The idea: sparsity
The slides’ key idea: replace the Transformer’s feed-forward layer with a new layer that holds many FFNs (“experts”) and a router that picks a few of them for each token. The model then has many total parameters, but only a relatively small number are active for any one token, in training and in inference. A token passes through attention as usual. At the FFN position it visits, say, 2 of 8 experts instead of one big FFN.
Why the FFN? It holds about two thirds of a Transformer’s parameters (Lecture 20: 70–81% for Llama 3) and is applied to each token independently. That makes it easy to route tokens to different FFNs without changing anything else.
1.2 A new dimension of scaling
Lecture 7’s scaling laws tie quality to parameters and data, with compute . MoEs break the link between parameters and compute: scale the parameter count while keeping the FLOPs per token fixed (Fedus et al., 2022). The slides list the payoffs reported in the literature:
- More efficient training: fewer FLOPs to reach a given quality than a dense model (OLMoE, AI2 2025).
- Faster wall-clock training (Switch Transformer).
- A better inference-cost vs performance trade-off (DeepSeek, Mixtral, OLMoE).
- Wide adoption: Gemini, gpt-oss and Qwen3 are MoEs (the slides’ examples).
1.3 The costs
The slides’ potential downsides:
- System complexity. Experts’ usage must be coordinated, and a very large total parameter count must be hosted on many devices.
- New losses and hyperparameters: load balancing, capacity, z-loss, expert count, top-k.
- Instability. MoEs can be unstable and tricky to train.
1.4 Total vs active parameters
Computed (demo 01 Part B) from published configurations:
| model | total | active per token | active / total |
|---|---|---|---|
| Mixtral 8x7B (8 experts, top-2) | 46.7B | 12.9B | 0.28 |
| OLMoE-1B-7B (64 experts, top-8) | 6.92B | 1.28B | 0.19 |
| DeepSeekMoE 16B (2 shared + 64 routed, 6 routed active; slides) | 16.4B | 2.8B | 0.17 |
| ours: MoE, 8 experts × 128, top-2 | 987,712 | 397,888 | 0.40 |
| ours: dense with FFN 256 (same active size) | 395,840 | 395,840 | 1.00 |
Mixtral’s name says “8 × 7B”, but the experts share attention and embeddings, and only the FFNs are replicated. The result is 46.7B parameters, not 56B, and each token uses 12.9B, about as much compute as a 13B dense model.
2. The MoE layer
2.1 Formulas
A standard pre-norm Transformer layer (slides’ notation, norms omitted):
The MoE layer replaces with . Inside it:
- experts with parameters ;
- a parameterized router that chooses 1 or more FFNs for each input.
With top-K token-choice routing (slides):
The router is “surprisingly simple” (slides): one vector per expert, dot products with the token’s hidden state, a softmax. Many models (Mixtral, OLMoE) renormalize the chosen gates to sum to 1. Switch Transformer uses and keeps the raw probability. There is a reason (moe.py handles it): a renormalized top-1 gate is always 1, and then the router would receive no gradient from the language-model loss.
2.2 Worked example
Demo 01 Part A routes 3 tokens over 4 experts with top-2:
| scores | softmax | top-2 | gates (renormalized) | |
|---|---|---|---|---|
| token 0 | +0.14 −2.37 −0.37 −0.30 | 0.43 0.04 0.26 0.28 | experts 0, 3 | 0.61 0.39 |
| token 1 | −0.16 +0.15 +0.08 −0.52 | 0.23 0.31 0.29 0.16 | experts 1, 2 | 0.52 0.48 |
| token 2 | −0.18 +1.45 −0.14 +1.23 | 0.09 0.45 0.09 0.36 | experts 1, 3 | 0.55 0.45 |
The layer’s output equals the hand-computed to . Two more sanity checks from moe.py:
- an MoE with one expert and is exactly a dense FFN;
- an MoE whose experts are all copies of one FFN, with renormalized gates, also computes that FFN, whatever the router does (§6.3).
2.3 Where to put the experts
Nowadays experts typically sit in every FFN layer. Some models put MoEs only in every other layer, and DeepSeekMoE keeps the first layer dense. Attention-layer experts exist but are less common, and can be unstable (slides).
3. Expert design
3.1 How many experts?
Strategy 1: more experts, more parameters. Go to 2N, 4N, 8N, 16N, … experts at a fixed . More is better, but with diminishing returns, and more parameters need more devices to hold them (slides).
3.2 Fine-grained experts
Strategy 2: more, smaller experts at fixed parameters (“fine-grained expert segmentation”, DeepSeekMoE). Split each expert’s hidden dimension into pieces and activate times as many. The slides’ example:
- baseline: 8 experts of width , 2 active;
- fine-grained: 16 experts of width , 4 active.
Same parameters, same FLOPs, but far more ways to combine experts (demo 01 Part C):
| design | combinations per layer |
|---|---|
| 8 experts, top-2 | 28 |
| 16 half-size experts, top-4 | 1,820 |
| DeepSeekMoE: 64 routed, top-6 | 74,974,368 |
| OLMoE: 64, top-8 | 4,426,165,368 |
More combinations means more flexibility: each token gets a closer-to-tailored FFN. The slides note diminishing returns beyond some granularity (Krajewski et al., 2024, fit scaling laws for it) and more communication if it is not managed well.
3.3 Shared experts
Always keep a fixed set of experts active, route to the rest. For example, 1 shared expert plus 3 routed experts chosen from 31. The intuition (DeepSeekMoE): the shared expert learns common knowledge, so the routed experts need not each relearn it, and redundancy among experts drops. The evidence is mixed across studies, and always-on experts reduce routing flexibility (slides). OLMoE, for one, uses no shared expert.
4. Routing
4.1 Three ways to match tokens and experts
All routers compute a score for each (token, expert) pair, then choose by some strategy (slides):
- token choice: each token chooses its top- experts;
- expert choice: each expert chooses its top- tokens;
- global choice: a joint assignment over all tokens and experts, e.g. as a linear assignment or optimal-transport problem (BASE layers, Lewis et al., 2021).
4.2 Load, capacity and token dropping
Token choice has two failure modes (slides): an expert gets too many tokens, or too few (wasted parameters). Real systems run each expert as one batched matrix multiplication with a fixed buffer. The capacity of an expert is
Tokens beyond an expert’s capacity are dropped for that expert. They keep only their other experts and the residual connection.
Measured (demo 01 Part D, the first MoE layer of an untrained model on 18,630 Mix World tokens): even random routing loads the busiest expert to 1.52× the mean.
| router | capacity factor 1.0 | 1.25 | 1.5 | 2.0 |
|---|---|---|---|---|
| untrained | 13.6% dropped | 3.8% | 0.3% | 0.0% |
| skewed towards one expert | 22.9% | 19.8% | 16.7% | 10.4% |
Two remedies follow: balance the routing (§5), or go dropless, so that every token reaches its experts however uneven the load. OLMoE and DeepSeekMoE train dropless; DeepSeekMoE gets there by avoiding expert parallelism.
4.3 Expert choice, hashing, and others
- Expert choice (Zhou et al., 2022):
- Pros: load balance is solved at training time, since every expert takes exactly tokens. The model can give some tokens more capacity than others, because a token may be picked by several experts.
- Cons: at generation time only one token is processed at a time, so the selection needs a different mechanism. A token can also be picked by no expert (dropped).
- Measured (demo 01 Part E, untrained router): 1.8% of tokens get no expert, and 23.8% get three or more. After training (demo 03), 33% get one and 30% three or more. Its routing also depends on the other tokens in the batch, later tokens of the same sentence included, which generation cannot reproduce.
- Hashing (Roller et al., 2021): the expert is a fixed function of the token id. There is nothing to learn, and it is a surprisingly strong baseline. Measured (demo 03): hash routing reaches dev loss 1.495 vs 1.490 for a learned top-2 router at this scale. Its load is only as even as token frequencies allow (1.64×: every ”.” goes to the same expert).
- Reinforcement learning treats the discrete choice as an action (Bengio et al., 2016; Clark et al., 2022). It is principled for the non-differentiability, but expensive and less stable, and it has not shown much benefit over simpler methods (slides).
The slides’ bottom line: every major MoE LLM nowadays uses top-k token-choice routing.
5. Training MoEs: balancing and stability
5.1 The problem
We want a good model (perplexity, task metrics) and good hardware utilization. But the routing decision is discrete and not differentiable: the top- selection gives no gradient to the experts not chosen. The options (slides):
- reinforcement learning (§4.3);
- noise for exploration (Shazeer et al., 2017, noisy top-k);
- heuristic balancing losses: the current standard (Fedus et al., 2022, and since).
5.2 The load-balancing loss
The auxiliary loss (Switch Transformer; slides “Expert balancing loss”):
- counts where tokens actually went. It is not differentiable.
- is the average router probability. It is differentiable, and the gradient flows through it.
- The product penalizes an expert that receives many tokens and much probability. The gradient pushes probability away from overloaded experts.
- Its minimum, , is reached when every expert gets of both. The factor makes the value independent of the expert count.
The slides call it “heuristic, but surprisingly effective and widely used”. Typical weights: 0.01 (Switch, OLMoE), 0.001 (DeepSeekMoE, which adds a device-level loss).
Measured (demo 03, 8 experts top-2, 600 steps, real tokens only):
| balance-loss weight | busiest expert / mean (average over layers) | worst layer | dev loss |
|---|---|---|---|
| 0 | 1.77 | 2.53 | 1.493 |
| 0.01 | 1.15 | 1.20 | 1.490 |
| 0.1 | 1.26 | 1.39 | 1.491 |
Without the loss, one expert of layer 3 got 3,021 tokens and another 69. With it, every expert gets between 1,033 and 1,323. In this dropless setting the language-model loss barely moves: imbalance costs hardware (§6), not quality.
With a capacity limit (factor 1.25), imbalance turns into lost computation:
| setting | assignments dropped | dev loss | arithmetic loss |
|---|---|---|---|
| dropless, no balancing | 0% | 1.493 | 2.124 |
| capacity 1.25, no balancing | 4.4% | 1.499 | 2.248 |
| capacity 1.25, balance 0.01 | 0.2% | 1.494 | 2.182 |
A pitfall we fell into. The first version of
moe.pyrouted every position of a padded batch, and about two thirds of the positions were<pad>. Pad tokens all look alike, so they all went to the same experts. The balance loss spent its effort balancing padding: the busiest expert’s share seemed to drop from 3.09× to 1.23×. On real tokens the change was 1.66× → 1.65×: nothing. Production systems pack sequences without padding; masking padding out of routing, capacity and the auxiliary losses is the equivalent. Check your routing statistics on real tokens.
Per-device balancing (slides): experts are grouped on devices (§6), and what matters for speed is the load per device. DeepSeekMoE adds a loss on groups of experts in addition to the expert-level loss.
5.3 Stability: fp32 routing and the z-loss
Routers are numerically delicate:
- small changes in logits flip the top- choice;
- softmaxes of large logits in bf16 round badly.
Two standard measures (slides):
- Compute the router in fp32, even when everything else is bf16.
- The router z-loss (Zoph et al., 2022, ST-MoE). It penalizes large logits through the log of the softmax denominator:
Its minimum is at , i.e. a softmax denominator of 1 (the slides: “make the denominator in the softmax smaller”). Note what that implies: with 8 experts, the minimizing logits sit near , not near 0.
Measured: with weight 0.001 (OLMoE’s), mean falls from 2.31 to 1.20, while the largest logit grows from 3.14 to 3.70. That looked like a bug until we read the formula. At this scale the logits never grow large without the loss, so it has nothing to fix (dev loss 1.495 with it, 1.490 without). Its value is in long, large bf16 runs, where unchecked logits grow and destabilize training.
6. Systems
6.1 Expert parallelism
Experts can reside on different accelerators; the input data is dynamically dispatched to them and fetched back (slides; Fedus et al., 2022). With experts on devices ( each), and tokens sharded across the same devices:
- Route: each device computes its tokens’ top- experts.
- Dispatch: an all-to-all sends each (token, expert) row to the device holding that expert (Lecture 20, §3.1). The amounts differ per pair of devices, so it is an all-to-all with uneven splits, preceded by an all-to-all of the counts.
- Compute: each device runs its experts on what it received.
- Combine: a second all-to-all returns the results, and each device sums them with its gates.
Measured (demo 05 Part B, 4 real processes, torch.distributed with gloo; 8 experts, 2 per process; 18,630 tokens × top-2 per layer):
- The outputs are identical to the single-device layer (difference 0: the same arithmetic in the same order).
- 74.9% of all token rows cross to another device. With experts spread evenly, a random token’s expert is remote 3 times in 4: the network is on the critical path twice per MoE layer.
- Load: the busiest device processes up to 1.14× the average with the balance loss, and up to 1.85× without. Every all-to-all waits for the slowest device.
6.2 Sparse upcycling
Upcycling (Komatsuzaki et al., 2023) turns a trained dense model into an MoE (slides):
- clone the dense MLP into every expert;
- introduce router parameters;
- continue pretraining.
It is useful if, at a fixed number of FLOPs, dense pretraining + sparse upcycling beats sparse pretraining from scratch. But it can bias the optimization: a well-trained dense model may sit somewhere the MoE cannot easily leave. It also inherits some of the original model’s hyperparameters. The evidence is mixed. In OLMoE, an MoE trained from scratch caught up quickly, after about 25% of the dense model’s budget (slides).
Measured (demo 05 Part A; the dense model after 1,000 steps, then 500 more steps of each option):
- The upcycled MoE starts exactly at the dense model (logits within ). Identical experts with gates summing to 1 compute the same function.
- The copies diverge slowly: mean cosine similarity between experts goes from 1.0000 to 0.9880 after 500 steps, against 0.0012 for experts trained from scratch. Only the different tokens each copy receives break the symmetry.
- After 500 steps: upcycled 1.388, dense continued 1.391, MoE from scratch 1.396 dev loss. Upcycling is a safe start but no shortcut at this budget. Note also that copying a full-width FFN into top-2 experts doubles the FFN compute per token.
7. Does it pay? Parameters at fixed FLOPs, in two regimes
An MoE adds parameters, not compute. That helps exactly when parameters are what limits the model. We tested both sides.
7.1 Capacity-limited: memorizing facts
Measured (demo 02): facts only (2,700 facts), a tiny 1-layer model (d = 32), 4,000 steps, so ~47 exposures per fact. The models differ only in the FFN:
| model | FFN FLOPs / token | recall, seeds 0 / 1 / 2 | mean recall | mean value loss |
|---|---|---|---|---|
| dense, FFN 128 | 1× | 39.7 / 48.9 / 39.8% | 42.8% | 1.88 |
| MoE, 8 × 64, top-2 | 1× | 58.7 / 58.4 / 57.9% | 58.4% | 1.42 |
| dense, FFN 512 (same parameters as the MoE) | 4× | 58.3 / 50.0 / 49.8% | 52.7% | 1.56 |
- At the same FLOPs per token, the MoE recalls 16 points more facts. Its 4× FFN parameters are what memorization needs.
- It matches the dense model with as many parameters, at a quarter of the FFN compute: “scale parameters at fixed FLOPs” in miniature.
- Seeds matter. A 5-seed check (seeds 0–4) found the MoE ahead of the same-FLOPs dense model in 4 of 5 seeds (mean +10 points; seed 3 went the other way). It was equal on average to the same-parameter dense model (52.8% vs 52.4%). A single run would have supported either conclusion.
7.2 Exposure-limited: the full Mix World
Measured (demo 04 Part A): six domains, 1,000 steps, each fact seen only ~6 times:
| model | parameters | active | dev loss | fact recall |
|---|---|---|---|---|
| dense, FFN 256 | 395,840 | 395,840 | 1.410 | 16.7% |
| dense, FFN 1024 | 985,664 | 985,664 | 1.404 | 18.4% |
| MoE 8 × 128, top-2 | 987,712 | 397,888 | 1.415 | 14.1% |
| fine-grained 16 × 64, top-4 | 989,760 | 399,936 | 1.411 | 14.3% |
| shared 1 + 8 × 128, top-1 | 1,086,016 | 397,888 | 1.416 | 16.6% |
Nothing beats the small dense model, not even a dense model with 2.5× its parameters. When data, not capacity, is the bottleneck, extra parameters are idle, and an MoE’s extra experts additionally see fewer tokens each.
7.3 The lesson
MoEs are a way to buy capacity cheaply. Large-scale pretraining is the setting where capacity binds: trillions of tokens, more knowledge than any feasible dense model can hold. That is why MoEs dominate there, and why small-scale experiments often fail to reproduce their benefit.
8. What do experts specialize in?
The slides: some experts in some layers activate frequently for particular domains. The literature’s picture is nuanced:
- OLMoE finds clear domain specialization for distinctive domains (e.g. code, arXiv) and also vocabulary specialization.
- Mixtral’s analysis finds little topic specialization and more syntactic, token-level patterns.
Measured (demo 04; the 8-expert MoE; each real token’s top expert on 18,630 dev tokens; mutual information in bits, estimated by counting):
| layer | shuffled baseline | |||
|---|---|---|---|---|
| 0 | 2.565 | 0.121 | 0.212 | 0.007 |
| 1 | 2.601 | 0.152 | 0.123 | 0.009 |
| 2 | 2.382 | 0.255 | 0.478 | 0.014 |
| 3 | 2.485 | 0.178 | 0.269 | 0.019 |
bits.
- Experts follow tokens far more than domains. The expert choice carries 2.4–2.6 bits about the token but only 0.12–0.25 bits about the domain. (Counting estimates of are biased upward by ~0.3 bits with ~1,000 token types; the gap is far larger.)
- For shared tokens, context matters. A third of the tokens (’.’, ‘a’, ‘in’, numbers) occur in several domains. For them, knowing the domain adds up to 0.48 bits about the expert, far above the 0.01–0.02 bits a shuffled baseline gives. The router reads context, because the hidden state of ’.’ after a Zorbian review differs from ’.’ after a sum. With hash routing this quantity is exactly 0.
- Design changes the picture somewhat. In the last layer, normalized is 0.22 for the fine-grained MoE, 0.18 for the shared-expert MoE and 0.07 for the plain one. Sixteen experts can carry more bits than eight, which favours fine-grained routing in this measure.
9. Case studies
DeepSeekMoE 16B (Dai et al., 2024; the slides):
- 16B total, 2.8B active;
- 66 experts with 8 activated: 2 shared plus 6 of 64 routed (fine-grained);
- MoE in all FFNs (the first layer excepted);
- per-token routing; pipeline parallelism and no expert parallelism, hence no token dropping;
- expert balance loss with weight 0.001, plus a device-level balance loss;
- with 40% of the pretraining compute, it reaches the performance of the dense DeepSeek 7B.
OLMoE-1B-7B (Muennighoff et al., 2024; the slides):
- 6.9B total, 1.3B active;
- 64 small experts (FFN width 1,024) with 8 active, no shared expert;
- per-token, dropless routing;
- balance loss 0.01 and router z-loss 0.001;
- pretraining throughput of 23,600 tokens/s/GPU vs 37,500 for a dense model of the same active size, yet it reaches the dense model’s performance 2× faster;
- fully open: data, code, checkpoints.
Others the slides list: DeepSeek-V3, Mixtral, Qwen3, gpt-oss. They span fine-grained and coarse experts, with and without shared experts; all use top- token choice.
10. Summary
- An MoE layer replaces the FFN with expert FFNs and a router. A token’s output is over its top- experts.
- Computed: Mixtral 8x7B has 46.7B parameters and uses 12.9B per token.
- Expert design. More experts means more parameters at the same FLOPs.
- Fine-grained experts multiply the routing combinations (28 → 1,820) at constant cost.
- Shared experts take common knowledge; the evidence for them is mixed.
- Routing. Top- token choice is the standard. Capacity limits drop tokens when load is uneven.
- Expert choice balances by construction but cannot run token by token.
- Hashing is a strong no-learning baseline. Measured: dev loss 1.495 vs 1.490.
- Losses. The balance loss evens out the load.
- Measured on real tokens: busiest expert 1.77× → 1.15× the mean.
- Under capacity limits it prevents drops (4.4% → 0.2%).
- The z-loss keeps near 0 for stability.
- Mask padding, or the losses balance pads.
- Systems. Expert parallelism routes tokens with two all-to-alls per layer.
- Measured: exact; 75% of rows cross devices; the busiest device sets the pace (1.14× vs 1.85×).
- Upcycling starts from a dense model exactly, and its copies diverge slowly.
- When it pays. MoEs buy capacity at fixed FLOPs.
- Measured, when capacity binds: 58.4% vs 42.8% recall.
- When data binds, nothing is gained. Seeds can flip small-scale comparisons.
- Specialization. Experts follow tokens far more than domains (2.4–2.6 vs 0.12–0.25 bits). For shared tokens the router uses context.
Common pitfalls
- Comparing an MoE with a dense model of the same total size and calling it a loss. The fair baselines are the same active FLOPs, and the same parameters; report both.
- Routing padding. Pad positions take capacity and dominate the balance loss; mask them or pack sequences.
- Normalizing a top-1 gate. It becomes 1 and the router gets no gradient from the main loss.
- Judging balance by expert counts alone. Devices hold groups of experts; measure per-device load (and consider a device-level loss).
- Capacity factors set too tight. Dropped tokens silently skip computation; monitor the drop rate per layer.
- Evaluating expert-choice routing on whole batches. Its routing uses other tokens, later ones included; generation cannot.
- Single-seed conclusions at small scale. Memorization “clicks” differently per seed; use several.
- Expecting MoE gains when data is the bottleneck. Extra parameters need enough tokens to fill them.
Exercises
-
Parameters. A model has layers, , attention with parameters per layer, and SwiGLU experts of width 1,408 ( parameters each); 64 routed experts with top-6, plus 2 shared experts. Ignoring embeddings and norms, compute total and active parameters.
Answer
Attention: 4 × 2048² = 16.8M per layer. One expert: 3 × 2048 × 1408 = 8.65M. Total per layer: 16.8M + 66 × 8.65M = 587.7M; × 24 = 14.1B. Active per layer: 16.8M + 8 × 8.65M = 86.0M; × 24 = 2.06B. Active/total ≈ 0.15 (DeepSeekMoE-like proportions). -
Combinations. How many expert combinations per layer do (a) 8 experts top-1, (b) 32 experts top-4, (c) 128 experts top-8 allow? Which of (b) and (c) has more parameters per expert if both have the same total FFN parameters?
Answer
(a) C(8,1) = 8. (b) C(32,4) = 35,960. (c) C(128,8) ≈ 1.43 × 10¹². With equal total FFN parameters, (b)'s experts are 4× larger than (c)'s (128/32), and both activate the same share of the FFN (4/32 = 8/128 = 1/8). -
Capacity. A batch has 4,096 tokens, 16 experts, top-2, capacity factor 1.25. What is each expert’s capacity? If one expert is chosen by 1,000 tokens, how many of its assignments are dropped? What happens to those tokens?
Answer
C = ⌈1.25 × 4096 × 2 / 16⌉ = 640. 1,000 − 640 = 360 assignments dropped (the last 360 in the order the system processes them). Those tokens get only their other expert's output (and the residual): they lose half of their FFN computation in this layer. -
The balance loss. With experts, compute for (a) ; (b) , . Which direction does the gradient push ?
Answer
(a) 4 × 4 × 0.0625 = 1.0 (the minimum). (b) 4 × (0.42 + 0.015 + 0.015 + 0.01) = 4 × 0.46 = 1.84. The derivative with respect to $P_1$ is $N f_1 = 2.8$, the largest of all experts, so the gradient lowers $P_1$ most: probability moves away from the overloaded expert (and, through the softmax, towards the others). -
The z-loss. Show that with experts and all logits equal to , the z-loss is , minimized at . Why does that not change which experts are chosen?
Answer
$\log \sum_j e^{c} = \log(N e^c) = c + \log N$; squared, minimized at $c = -\log N$. The z-loss acts on the *level* of the logits (adding a constant to all of them changes $\log Z$ but not the softmax), so it pushes the shared offset towards $-\log N$ and penalizes large spreads only through $\log Z$; the ranking, and hence the top-k choice, is governed by the differences between logits. -
Expert parallelism traffic. 64 experts on 16 devices, top-8 routing, tokens spread evenly, routing uniform. What share of (token, expert) rows leave their device? How many bytes per token does one MoE layer send (forward pass) with in bf16?
Answer
A row stays only if its expert is on the token's own device: 4 of 64 experts, so 1/16; 15/16 ≈ 94% leave. Each token sends 8 rows × 4096 × 2 bytes = 64 KB to experts (≈ 60 KB remote) and receives as much back in the combine step: ~120 KB of network traffic per token per MoE layer, in the forward pass alone. -
Which regime? You train an MoE and a dense model with the same active parameters on 1B tokens, and they reach the same loss. Give two explanations and an experiment to tell them apart.
Answer
(1) Data-limited: the dense model is not capacity-bound at 1B tokens, so extra parameters cannot help; test by training a dense model with the MoE's total parameters: if it also does not improve, capacity is not the bottleneck (demo 04). (2) The MoE is under-trained per expert (each expert sees a fraction of the tokens) or poorly balanced; test by training longer, checking the load per expert, and comparing several seeds. If the larger dense model does improve but the MoE does not, look at routing (collapse, drops, z-loss). -
Upcycling. Explain why an upcycled MoE with identical experts and renormalized top-2 gates computes exactly the dense model’s function, and why the experts nevertheless become different. What changes if you use top-1 with raw probabilities?
Answer
With identical experts, $\sum_i g_i \mathrm{FFN}_i(h) = (\sum_i g_i)\,\mathrm{FFN}(h) = \mathrm{FFN}(h)$ because the gates sum to 1. During training each copy receives gradients only from the tokens routed to it, and those differ, so the copies drift apart, slowly at first: demo 05 measured 0.988 similarity after 500 steps. With top-1 and a raw probability gate $s < 1$, the output is $s\,\mathrm{FFN}(h)$, so the upcycled model no longer matches the dense one at the start; renormalizing a top-1 gate makes it 1 but removes the router's gradient from the language-model loss.
Related assignment (concepts only)
- Assignments 3–4: when reproducing or extending an MoE paper:
- fix the comparison first: equal active FLOPs, and equal total parameters;
- log per-layer load, drop rates and router statistics on real tokens;
- run several seeds;
- check whether your data budget lets capacity matter at all.
- These notes do not provide assignment code.
Further reading
- W. Fedus, J. Dean, B. Zoph, “A Review of Sparse Expert Models in Deep Learning”, 2022 (course reading); N. Muennighoff et al., “OLMoE: Open Mixture-of-Experts Language Models”, 2024 (course reading); D. Dai et al., “DeepSeekMoE”, 2024.
- N. Shazeer et al., “Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer”, ICLR 2017; D. Lepikhin et al., “GShard”, ICLR 2021; W. Fedus, B. Zoph, N. Shazeer, “Switch Transformers”, JMLR 2022; B. Zoph et al., “ST-MoE: Designing Stable and Transferable Sparse Expert Models”, 2022.
- Y. Zhou et al., “Mixture-of-Experts with Expert Choice Routing”, NeurIPS 2022; S. Roller et al., “Hash Layers For Large Sparse Models”, NeurIPS 2021; M. Lewis et al., “BASE Layers”, ICML 2021; A. Clark et al., “Unified Scaling Laws for Routed Language Models”, ICML 2022; J. Krajewski et al., “Scaling Laws for Fine-Grained Mixture of Experts”, 2024.
- A. Komatsuzaki et al., “Sparse Upcycling: Training Mixture-of-Experts from Dense Checkpoints”, ICLR 2023; A. Jiang et al., “Mixtral of Experts”, 2024; S. Rajbhandari et al., “DeepSpeed-MoE”, ICML 2022; T. Gale et al., “MegaBlocks: Efficient Sparse Training with Mixture-of-Experts”, MLSys 2023.
Preview of Lecture 22 — Scaling sequence length
MoEs scale parameters at fixed compute. The next lecture scales the other axis that costs memory: sequence length. Attention’s scores dominated Lecture 20’s activation formula. Lecture 22 covers:
- computing attention without materializing them: online softmax, FlashAttention, ring attention across devices;
- why trained models fail beyond their training length, and how RoPE scaling and continued training fix it;
- state-space models (S4, Mamba), which drop attention altogether.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| mixture of experts (MoE) | 混合专家 |
| expert / router / gate | 专家 / 路由器 / 门控(权重) |
| sparse activation / sparsity | 稀疏激活 / 稀疏性 |
| total parameters / active parameters | 总参数 / 激活参数 |
| top-k token-choice routing | 前 k 词元选择路由 |
| expert-choice routing / global choice | 专家选择路由 / 全局选择 |
| hash routing / linear assignment | 哈希路由 / 线性分配 |
| router score / renormalized gates | 路由分数 / 重新归一化的门控 |
| capacity / capacity factor | 容量 / 容量因子 |
| token dropping / dropless | 丢弃词元 / 无丢弃 |
| load balancing / load-balancing (auxiliary) loss | 负载均衡 / 负载均衡(辅助)损失 |
| per-device balancing | 设备级均衡 |
| router z-loss / softmax denominator (partition function) | 路由 z 损失 / softmax 分母(配分函数) |
| routing collapse | 路由坍缩 |
| fine-grained expert segmentation | 细粒度专家切分 |
| shared expert | 共享专家 |
| expert parallelism / dispatch / combine / all-to-all | 专家并行 / 分发 / 合并 / 全交换 |
| straggler | 掉队者 |
| sparse upcycling / symmetry breaking | 稀疏升级 / 打破对称 |
| domain specialization / vocabulary specialization | 领域专门化 / 词表专门化 |
| mutual information / estimation bias | 互信息 / 估计偏差 |
| capacity-limited / data-limited (exposure-limited) | 容量受限 / 数据受限(曝光受限) |
| padding / sequence packing | 填充 / 序列打包 |