Mixture of experts: routing, load balancing and capacity
Before this lesson: lesson 04 (the SwiGLU feed-forward network), lesson 05 (the residual path, which carries dropped tokens), lesson 09 (the softmax and its Jacobian), lesson 11 (the feed-forward sublayer and parameter counting) and lesson 12 (bf16 and the z-loss). The all-to-all collective is covered in the ML-systems track. Time: about 75 minutes, plus the notebook.
Why this matters #
A dense transformer uses every parameter for every token: a forward pass costs about FLOPs per token for parameters (lesson 11). An MoE layer breaks this link. Parameters grow with the number of experts ; compute per token grows only with the number of experts each token uses.
The gains are large. With 64 experts, Switch-Base reached the quality of the FLOP-matched dense T5-Base in one seventh of the training time (Fedus et al. 2021). Mixtral 8×7B has about 47B parameters but uses about 13B per token, and matches or beats Llama 2 70B on most benchmarks. DeepSeek-V3 has 671B parameters and uses about 37B per token. Interviews ask about each part: "count the active parameters", "why does the router collapse?", "what is the capacity factor?".
1. Predict first #
2. The picture #
One token, two experts. Take a token vector and two experts , each a small feed-forward network. The router is a linear map: logits and probabilities . Top-1 routing picks and outputs . Only one expert runs. The layer has twice the parameters of one network but the same compute, plus a tiny router.
From soft to sparse. The classic mixture of experts (Jacobs et al. 1991) runs every expert and mixes the outputs: . A sparse MoE keeps only the largest terms of this sum, so the other experts never run for this token.
Why multiply by ? The choice is a step function of : it has zero gradient almost everywhere. The factor is smooth in . Through it, the loss can tell the router "this expert helped, give it more weight". Without it, the router would get no gradient from the main loss.
Where it sits. In a transformer the feed-forward sublayer acts on each token separately (lesson 11). So an MoE layer can replace it with no other change: each token in the batch picks its own experts. Attention stays dense. Mixtral replaces every feed-forward sublayer; GShard and most Switch models replace every other one; DeepSeek-V3 replaces all but the first three.
Drag the router vectors. Here the colors name the four experts: blue, orange, aqua and violet. Each dot is a token, colored by its first choice; the shaded regions show where each expert wins. The bars are the loads, with the capacity as a dashed line. Assignments above the capacity are dropped and shown in magenta. Try one expert wins: one expert gets most tokens and many are dropped. Then set (rings show the second choice) and raise the capacity factor.
Four new problems, one per part of section 3:
- balance: the router can send most tokens to a few experts (3.3);
- fixed buffers: an expert can receive more tokens than it has room for (3.4);
- stability: the router's exponentials amplify bf16 rounding (3.5);
- communication: experts live on different GPUs, so tokens must travel (3.6).
A top-1 MoE layer outputs , with . Why is the expert output multiplied by instead of being used alone?
Without the factor, the router's only effect is the choice , a step function of the logits, so the router would learn nothing from the main loss. With , the derivative of the loss with respect to the logits is not zero, so the router learns to give more weight to an expert that lowers the loss.
3. Definitions and main results #
3.1 The top-k MoE layer #
Notation, used in the rest of the lesson:
- tokens in the batch (batch × sequence, flattened), model width , experts, experts per token;
- expert is a function (with an index; without one, is the number of experts);
- is the normalized residual stream of token (pre-LN, lesson 05);
- the router has a weight and no bias; logits ; probabilities with entries ;
- is the set of the largest ;
- gate weights for ; the output is , and the block outputs .
Two choices of gate weights are common:
- Switch (): , the raw probability.
- Renormalized (GShard top-2, Mixtral): , so the weights sum to 1.
Renormalized top- = softmax over the top- logits. This is Mixtral's , with the logits outside the top set to . Proof: , because the full softmax denominator cancels. The softmax is monotone, so ranking the logits or the probabilities selects the same .
Parameter count. Let each expert be a SwiGLU network with hidden width : three matrices, weights (lesson 04). Per MoE layer:
- total expert parameters: ;
- active expert parameters per token: ;
- router: ;
- forward FLOPs per token: about for the experts and for the router.
Everything else (attention, norms, embeddings) is shared and always active. So total parameters = shared + all experts, and active parameters = shared + experts per MoE layer.
Pick a model, then move and . The top bar is all parameters, the bottom bar the parameters one token uses. Blue is shared (always active), violet the experts that work on the token, faint violet the experts that are stored but idle. Notice that changes only the top bar: memory grows, compute per token does not.
Mixtral 8×7B has 32 layers. Each layer has 8 SwiGLU experts of about 176M parameters each, and top-2 routing. The shared parameters (attention, norms, embeddings, routers) are about 1.6B. About how many parameters are active per token?
Each token uses 2 experts in each of the 32 layers: $64 \times 176\text{M} \approx 11.3$B, plus the 1.6B shared parameters, gives about 12.9B. The total is $1.6 + 32 \cdot 8 \cdot 0.176 \approx 46.7$B, not 56B, because only the feed-forward sublayers are replicated.
3.2 How the router learns from the main loss #
Let be the main loss and , a number: how fast the loss changes when the weight of expert grows. The softmax Jacobian is , where is 1 if the condition holds and 0 otherwise (lesson 09).
- Switch (, raw gate), with the chosen expert: . If the chosen expert helped (), gradient descent raises and lowers the other logits. Shazeer et al. (2017) thought that was needed for useful router gradients; Switch showed that works.
- Top-1 with renormalization. Then for every . The main loss sends no gradient to the router at all.
- Top-2, renormalized. (with the logistic sigmoid) and . The gradient with respect to the logit difference is : the router learns which of the two chosen experts is better. It learns nothing about the experts it did not choose.
3.3 Collapse and the Switch load-balancing loss #
Collapse. Shazeer et al. (2017) observed that the router "tends to converge to a state where it always produces large weights for the same few experts. This imbalance is self-reinforcing": the favored experts get more tokens, so more gradient updates, so they improve and are chosen even more. Unused experts are wasted parameters. On many GPUs the busiest expert also sets the step time.
Definition (Switch load-balancing loss). For a batch of tokens and top-1 routing,
is the share of tokens dispatched to expert : a count. is the mean router probability of expert . Switch uses , chosen from a sweep over to : large enough to balance quickly, small enough not to disturb the main loss.
Top- version. is the share of the assignments that go to expert , so
again. Conventions differ by a factor : the Hugging Face transformers Mixtral code counts all
choices and divides by , so its uniform value is .
Facts.
- Uniform routing gives . With : . The factor makes this value independent of the number of experts.
- A collapsed router gives . If every token has , then and the loss is .
- Why both and . always, so a loss linear in alone would be constant. And alone has no gradient: it counts argmax decisions. The product weights each expert's mean probability by its real load, and the gradient flows through only.
Theorem (gradient of the load-balancing loss). Treat as a constant (it has zero gradient almost everywhere). Then
Proof.
- Only depends on , and only through token : .
- Softmax Jacobian: .
- Sum over : .
- Factor out .
Reading the formula.
- is the load that token "sees", averaged with its own probabilities. A descent step lowers when expert is busier than that () and raises it when expert is less busy. Probability moves from overloaded to underloaded experts.
- The factor means that a token mainly changes the logits of experts it already likes.
- , as for any loss of a softmax. For the router weights (row convention, ): , where row of is .
Press "1 descent step" a few times. The left chart shows the dispatch shares and the mean probabilities ; the aqua line is the uniform share . The right chart shows one token's probabilities and the orange gradient on its logits: positive (pushed down) for the busy expert 1, negative for the idle ones. Watch the loss fall to about 1 as the loads become equal.
It is a surrogate. Switch says the loss "is minimized under a uniform distribution", but this is not exactly true: a few very confident tokens on an underused expert can push it below . In practice the gradient above still drives the routing toward balance. (Shazeer et al. 2017 used noisy top- gating and two separate balancing losses; Switch merged them into this one.)
A router with experts sends every token to expert 1 with probability 1. What is (with ), and what is its value for perfectly uniform routing?
Collapsed: and all other terms are 0, so the loss is . Uniform: , so . The factor makes the uniform value 1 for every number of experts.
3.4 Expert capacity and token dropping #
Why a fixed capacity. Switch was built for TPUs, which need static tensor shapes. Each expert gets a buffer of token slots, fixed before the batch is routed. The expert capacity is
where cf is the capacity factor: gives exactly enough slots for perfectly balanced routing.
Dropping. When an expert's buffer is full, further assignments to it are dropped: that expert's computation is skipped for the token. If all its assignments are dropped, the token reaches the next layer unchanged, through the residual connection (). For top-, a common priority order (GShard-style) is: all first choices in token order, then all second choices.
The trade-off. The layer computes slots, filled or not, so compute, activation memory and communication all grow with cf. A larger cf drops fewer tokens but pays for padding. Switch found the best speed–quality trade-off at cf 1.0 and 1.25, and with its auxiliary loss it typically dropped less than 1% of the tokens.
Balanced on average is not enough. The load of one expert is random. For and it has mean 512 and standard deviation , and the busiest of 8 experts is about 1.5 standard deviations above the mean. So cf drops tokens even then.
Dropless MoE. MegaBlocks (Gale et al. 2022) writes the expert computation as block-sparse matrix products that accept any number of tokens per expert, so no token is dropped. DeepSeek-V3 reports no dropped tokens in training or inference, thanks to its balancing (section 3.7).
Top-1 routing, tokens, experts, capacity factor 1.25. Expert 3 receives 200 tokens. What happens?
. The first 160 assignments in priority order are processed; the last 40 are dropped. A dropped token is not removed from the sequence: its MoE output is 0, so the block outputs . Plain top-1 routing does not reroute to a second expert.
3.5 The router z-loss: stability in low precision #
The problem. bf16 has 7 stored fraction bits, so neighboring bf16 numbers in are apart: 0.0078 in , but 0.5 in (lesson 12). A rounding error in a logit multiplies the probability ratio of two experts by . In exact arithmetic the softmax ignores a common shift of the logits, but not after rounding: large logits carry large errors. ST-MoE (Zoph et al. 2022) links the instabilities of large sparse models to these extra exponentials in the router.
Definition (router z-loss, ST-MoE). For tokens with router logits ,
The total loss is , where is the cross-entropy and plays the role of ; ST-MoE uses .
What it does.
- Gradient: , because .
- It fixes the free shift of the softmax. Since , keeping near 0 keeps the largest logit in , where bf16 is precise.
- When a descent step lowers all logits, most for the most likely expert. It also makes the router a little less confident.
In ST-MoE the z-loss made all runs stable and slightly improved quality; tighter update clipping also stabilized training, but hurt quality. Earlier, Switch used selective precision (the router in float32, cast back to bf16 before the dispatch) and a 10 times smaller initialization scale. ST-MoE found selective precision alone not enough at its largest scale.
Move the shift . All three logits get the same , so the aqua exact softmax never changes. The blue bars use the logits rounded to bf16. Try : rounds to (the bf16 spacing there is 0.5) and the probabilities change by about 0.05. The z-loss is the only quantity that sees ; it is 0 at the preset lse = 0.
Which quantity does the router z-loss push toward 0, and why does that help?
The softmax and the other losses do not change when the same number is added to all logits of a token, so nothing else controls that shift. grows exactly by the shift, so penalizes it. Small logits have small bf16 spacing, so the probabilities computed from rounded logits stay accurate.
3.6 Expert parallelism #
Layout. GPUs form an expert-parallel group. Each GPU holds experts and its own tokens. The other layers (attention, norms, router) are copies on every GPU (data parallelism).
One MoE layer, forward pass:
- Route. Each GPU runs the router and the top- on its own tokens.
- Dispatch (all-to-all 1). Each GPU sends every token copy to the GPU that holds its expert. An all-to-all is a collective in which every GPU sends a different piece of data to every other GPU. With a capacity, the buffers have the static shape .
- Expert compute. Each GPU runs its experts, each on the batch of tokens it received.
- Combine (all-to-all 2). The outputs go back to the tokens' home GPUs, where they are multiplied by the gates, summed over the copies and added to the residual.
The backward pass runs the same two all-to-alls in reverse (output gradients to the experts, input gradients back). So a training step has four all-to-alls per MoE layer.
Volume. In one all-to-all a GPU sends about bytes ( bytes per value). With uniform routing, the fraction leaves the GPU. Example: , , , , bf16 (): MB per GPU, of which MB go to other GPUs, per all-to-all. This traffic scales with tokens and (activations), not with parameters, unlike the gradient all-reduce of data parallelism.
What makes it slow. Stragglers: all GPUs wait for the busiest one, so imbalance costs time even without dropping. Slow links: the all-to-all crosses nodes (InfiniBand instead of NVLink). DeepSeek-V3 limits each token to at most 4 nodes ("node-limited routing") and overlaps communication with computation.
3.7 Balancing without an auxiliary loss, and other routers #
DeepSeek-V3. Each MoE layer has shared expert, used by every token, and routed experts, of which are active. The router computes affinities , with the input of token and a learned vector per expert. Then:
- selection uses biased scores: the top of ;
- gate values use the unbiased scores: ;
- after each step, if expert was overloaded in the batch, and if it was underloaded ( for most of training, then 0).
Why: an auxiliary loss sends gradients into the router that compete with the language-model loss (a large hurts quality, a small one leaves imbalance). The bias has no gradient. It acts like a feedback controller on the load: it changes which experts are picked, and the mixture weights stay undistorted. DeepSeek-V3 keeps only a sequence-wise balance loss with a tiny , against extreme imbalance inside one sequence.
Fine-grained and shared experts (DeepSeekMoE). Split each expert into smaller ones and activate of them: the same parameters and FLOPs, but many more combinations. Top-2 of 16 experts gives combinations; after a 4-way split, top-8 of 64 gives . Shared experts hold common knowledge, so the routed experts can specialize.
Expert-choice routing (Zhou et al. 2022). Each expert picks its top- tokens from the batch: perfect balance, and a token can get zero or several experts. But the choice uses later tokens of the batch, so it does not directly apply to autoregressive generation.
3.8 MoE against dense #
| Dense FFN | MoE FFN ( experts of the same size, top-) | |
|---|---|---|
| Parameters | (+ router ) | |
| Forward FLOPs per token | ||
| Weights to store | : all experts, always | |
| Extra communication | none | 4 all-to-alls per layer per training step |
| Weights read per decoding step, batch | about | |
| New failure modes | none | imbalance, drops, router instability, overfitting when fine-tuning |
- Quality: better per FLOP (the Switch and Mixtral numbers above), worse per parameter: a dense model with the same total parameters is an upper bound for an MoE (DeepSeekMoE).
- Fine-tuning: sparse models overfit small tasks more; Switch used dropout 0.4 inside the experts and 0.1 elsewhere ("expert dropout").
- Decoding: is the expected number of distinct experts that tokens touch under uniform routing: at batch 1, nearly all at a large batch. Decoding is limited by reading weights from memory, so a small batch reads far fewer bytes per step than a dense model of the same total size.
- Rule of thumb (Hugging Face blog): MoE for high throughput on many accelerators; dense when memory is the limit.
Answers to section 1. (1) The router collapses onto a few experts, and the effect feeds itself (3.3); every MoE needs a balancing mechanism (3.3, 3.7). (2) About 2%: a simulation (section 5) gives 1.65%, because the busiest expert gets about 544 tokens on average. With capacity factor 1.25 (640 slots) the drops almost vanish; with at cf 1.0 they are about 5%.
4. Worked example #
Setup. experts, numbered 0, 1, 2, and tokens. To make the arithmetic simple, the logits are , so the router probabilities are:
| token | top-1 | |||
|---|---|---|---|---|
| 1 | 0.7 | 0.2 | 0.1 | 0 |
| 2 | 0.6 | 0.3 | 0.1 | 0 |
| 3 | 0.5 | 0.1 | 0.4 | 0 |
| 4 | 0.2 | 0.5 | 0.3 | 1 |
(a) Gates. Switch (top-1, raw): token 1 uses , and token 4 uses . Top-2 renormalized, token 3: experts 0 and 2, with weights and . These equal and : the softmax over the two chosen logits.
(b) Load-balancing loss ().
- Top-1 counts: expert 0 gets 3 tokens, expert 1 gets 1, expert 2 gets 0. So .
- Column means: .
- .
- . Compare: 1 for uniform routing, 3 for a fully collapsed router.
(c) Gradient for token 1.
- .
- , and .
The entries sum to 0. A descent step lowers token 1's logit for the overloaded expert 0 and raises the other two. Token 4 () gets : it is pushed away from expert 0 as well, and mostly toward the unused expert 2.
(d) Capacity (top-1).
- cf : . Expert 0 receives tokens 1, 2, 3 in order, so token 3 is dropped: its MoE output is 0 and only its residual goes on. Slots: , of which 3 are used and 3 are padding (50%).
- cf : . Nothing is dropped, but 5 of the 9 slots (56%) are padding. A larger capacity factor is an expensive fix for imbalance.
(e) Router z-loss. Here for every token, so . Now add 10 to every logit. The probabilities, the main loss and do not change, but and . Its gradient for token 1 is : it pulls the logits back down, most for expert 0.
(f) Counting DeepSeek-V3. From its configuration: , expert width 2048 (SwiGLU), 256 routed experts and 1 shared expert, top-8, MoE in 58 of 61 layers.
- One expert: $3 \cdot 7168 \cdot 2048 = 44{,}040{,}192 \approx 44.0$M.
- All routed experts: $58 \cdot 256 \cdot 44.04\text{M} \approx 653.9$B.
- Active expert parameters per token: $58 \cdot (8 + 1) \cdot 44.04\text{M} \approx 23.0$B.
- The rest (attention, the 3 dense layers, embeddings, routers) is about 14.6B, used by every token. Total $\approx 671$B, and active about 37B, as reported. Only of the expert parameters work on any one token.
5. In code #
PyTorch's autograd checks the two gradient formulas on the worked example, and NumPy reproduces the drop rate and the counts:
import numpy as np
import torch
p = torch.tensor([[0.7, 0.2, 0.1], [0.6, 0.3, 0.1],
[0.5, 0.1, 0.4], [0.2, 0.5, 0.3]], dtype=torch.float64)
T, E = p.shape
# (b), (c) the Switch loss and its gradient; f is a count, so it carries no gradient
z = p.log().requires_grad_()
probs = z.softmax(-1)
f = torch.bincount(probs.argmax(-1), minlength=E).double() / T
aux = E * (f * probs.mean(0)).sum()
aux.backward()
fbar = (p * f).sum(1, keepdim=True)
print(round(aux.item(), 4), z.grad[0].numpy().round(4))
print(torch.allclose(z.grad, (E / T) * p * (f - fbar)))
# 1.3312 [ 0.0919 -0.0488 -0.0431]
# True
# (e) the router z-loss after a shift of +10
z = (p.log() + 10).requires_grad_()
z_loss = (torch.logsumexp(z, dim=1) ** 2).mean()
z_loss.backward()
print(round(z_loss.item(), 6), z.grad[0].numpy().round(6))
# 100.0 [3.5 1. 0.5]
# large router logits in bf16: same softmax in exact arithmetic, different after rounding
big = torch.tensor([100.3, 100.0, 99.0])
for zz in (big, big - 99.0):
zb = zz.to(torch.bfloat16).float()
print(zb.tolist(), torch.softmax(zb, 0).numpy().round(3))
# [100.5, 100.0, 99.0] [0.547 0.331 0.122]
# [1.296875, 1.0, 0.0] [0.496 0.369 0.136] (exact: [0.497 0.368 0.135])
# token drops of a router that is balanced on average (T = 4096, E = 8, top-1)
rng = np.random.default_rng(0)
for C in [512, 640]: # capacity factor 1.0 and 1.25
loads = np.stack([np.bincount(rng.integers(0, 8, 4096), minlength=8) for _ in range(2000)])
dropped = np.maximum(loads - C, 0).sum(axis=1) / 4096
print(f"C={C}: mean busiest load {loads.max(axis=1).mean():.0f}, dropped {100 * dropped.mean():.2f}%")
# C=512: mean busiest load 544, dropped 1.65%
# C=640: mean busiest load 544, dropped 0.00%
# (f) DeepSeek-V3 expert parameters
D, d_e, n_moe = 7168, 2048, 58
expert = 3 * D * d_e # SwiGLU expert: three matrices
print(expert, round(n_moe * 256 * expert / 1e9, 1), round(n_moe * (8 + 1) * expert / 1e9, 1))
# 44040192 653.9 23.0
The notebook builds the full layer and checks these formulas with exercises.
6. Where it shows up #
- Language models. Sparse MoE layers in Switch (up to 1.6T parameters and 2,048 experts), ST-MoE, Mixtral, DeepSeek-V2 and V3, and many other recent models. Vision MoE (V-MoE, Riquelme et al. 2021) applies the same layer to the tokens of a vision transformer. Hybrid models such as Jamba combine MoE layers with state-space layers (lesson 16).
- ML for science. Physical fields mix regimes (ocean and land, tropics and poles). Spatial Mixture-of-Experts (Dryden and Hoefler, NeurIPS 2022) routes each grid location to experts and was applied to medium-range weather prediction. In an Earth-system foundation model, MoE adds capacity for many variables and regimes at a fixed FLOP cost. But a per-batch balancing loss pushes all experts to the same load, even when the regimes are not equally frequent.
- Practice. Log per layer: the busiest expert's load divided by the mean load, the fraction of dropped tokens, the auxiliary loss and the z-loss (or the mean ). In a bf16 MoE run with loss spikes, check the router logits, the router precision and the z-loss first.
7. Common mistakes #
- "Mixtral 8×7B has 56B parameters." Attention, norms and embeddings are shared. It has about 46.7B parameters, and 12.9B are active per token.
- Renormalizing a top-1 gate. The gate becomes exactly 1, and the main loss no longer trains the router.
- Mixing conventions for top-. normalized by gives 1 for uniform routing; normalized by it gives . Check the uniform value of your implementation.
- "cf = 1 is enough when routing is balanced on average." Random fluctuations alone drop about 2% of the tokens at , , and more with more experts. Raising cf to fix imbalance pays for padding; fix the balance instead.
- "MoE saves memory." It saves FLOPs. All experts must be stored.
- A bf16 router with no protection. Use a float32 router, a z-loss, or both.
- A balancing coefficient that is too large. It competes with the main loss and hurts quality.
8. Check yourself #
- A Switch-style layer with top-1 routing renormalizes its gate. What gradient does the main loss send
to the router, and what does the router learn?
Answer
None. The gate is for all logits, and the argmax is piecewise constant. Only the auxiliary loss trains the router, so it learns balance but not which expert is good for which token. Switch uses the raw for this reason. - With experts, what is for uniform routing, and for a router that gives every
token the probability vector ?
Answer
Uniform: . Collapsed: , so . - tokens, experts, top-2, capacity factor 1.25. Give the capacity, the total number
of slots, and the smallest possible fraction of empty slots.
Answer
. Slots: for assignments. Even with perfect balance, 1024 slots (20%) are empty. - Derive for . Why does the z-loss fix the free
shift of the softmax?
Answer
, so the gradient is . Adding to all logits of token leaves and the other losses unchanged but turns into . The z-loss prefers , which keeps the largest logit in , where bf16 rounding is small. - DeepSeek-V3-style balancing with 4 experts. In one step the loads are 40%, 30%, 20% and 10% of the
assignments, and . How do the biases change, and why is the bias not used in the gate
value?
Answer
The mean load is 25%. Experts 1 and 2 are overloaded: . Experts 3 and 4 are underloaded: . The bias only changes which experts are selected; the gate uses the original affinity, so the mixture weights are not distorted and no balancing gradient competes with the main loss. - A Mixtral-style layer (, top-2) decodes with batch 1 and with batch 16. How many experts per
layer are read on average (uniform routing)? What does that mean for memory bandwidth?
Answer
Batch 1: 2 experts, a quarter of the expert weights. Batch 16: , nearly all of them. Decoding is limited by reading weights, so at batch 1 the MoE reads far fewer bytes per step than a dense model of the same total size; at batch 16 it reads almost all of its weights, but this cost is shared by 16 tokens.
Write the output of a top- MoE layer for token .
, with the largest router probabilities and the gate weights; the block outputs .
Why is an expert's output multiplied by its gate value?
The top- choice is piecewise constant (zero gradient); the smooth gate value is the path through which the main loss trains the router.
Mixtral 8×7B: total and active parameters?
About 46.7B total and 12.9B active per token: only the feed-forward sublayers are replicated, and each token uses 2 of 8 experts.
Write the Switch load-balancing loss.
, with the share of tokens dispatched to expert and its mean router probability.
What is the difference between and in the balance loss?
is a count of argmax decisions (no gradient); is a mean of softmax probabilities (differentiable). The gradient flows through , weighted by the real loads .
Gradient of the Switch loss with respect to the router logit ?
with .
Formula for the expert capacity?
, with cf the capacity factor.
What happens to a token whose expert is full?
That assignment is dropped: the expert's output for it is 0. If all its assignments are dropped, the residual connection carries it unchanged to the next layer.
What does the router z-loss penalize, and what is its gradient?
, the squared log-sum-exp of the router logits; gradient .
How many all-to-alls does one MoE layer need per training step, and why?
Four: dispatch and combine in the forward pass, and the same two in reverse in the backward pass.
9. Interview angle #
- "Mixtral is 8×7B: how many parameters, how many active?" — About 47B and 13B; only the feed-forward sublayers are replicated.
- "Why does a router collapse, and how do you prevent it?" — Rich-get-richer feedback; the Switch loss, noisy top-, DeepSeek-V3's biases, expert-choice routing.
- "Derive the gradient of the Switch loss." — ; is a constant count.
- "What limits MoE training on many GPUs?" — Four all-to-alls per layer per step, stragglers, bandwidth between nodes.
- "Your bf16 MoE run has loss spikes. What do you check?" — Router logit size (), the z-loss, a float32 router, the initialization scale, per-expert load and drop rate.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution, and two demos:
- Write
top_k_gating(raw and renormalized gates) and check it on the worked example. - Write a sparse MoE forward pass with SwiGLU experts and check it against a dense reference.
- Write the Switch load-balancing loss and check its gradient against the formula of section 3.3.
- Write capacity-limited dispatch with the GShard priority order (top-1 and top-2).
- Write the router z-loss and check its value and gradient.
Demos: a tiny MoE trained with and without the balancing loss (watch one expert die without it), and the parameter counts of Mixtral 8×7B and DeepSeek-V3.
11. Watch and read #
- Fedus, Zoph and Shazeer, Switch Transformers (2021): top-1 routing, capacity, the load-balancing loss, selective precision and expert parallelism.
- Hugging Face, Mixture of Experts Explained: a readable overview of routing, load balancing, the z-loss and when to use MoE.
- Zoph et al., ST-MoE: Designing Stable and Transferable Sparse Expert Models (2022): the router z-loss and the effect of rounding in the router.
- Jiang et al., Mixtral of Experts (2024): the top-2 router and the results against dense models.
- DeepSeek-AI, DeepSeek-V3 Technical Report (2024): auxiliary-loss-free balancing, shared and fine-grained experts, node-limited routing.
- Shazeer et al., Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer (2017): noisy top- gating and the first observation of collapse.
- Dai et al., DeepSeekMoE (2024): fine-grained and shared experts; Gale et al., MegaBlocks (2022): dropless MoE; Zhou et al., Mixture-of-Experts with Expert Choice Routing (2022).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.