Mixture of experts¶
A mixture-of-experts layer replaces one big feed-forward network with many smaller ones and a router that sends each token to only a few of them. Parameters, which store knowledge, stop costing compute per token; the bill moves to memory, communication and the hard problem of keeping every expert busy.
10,000 ft
A dense transformer spends the same arithmetic on every token: every parameter multiplies every token. Conditional computation breaks that link. In a mixture of experts (MoE), the feed-forward half of each block is split into many experts and a learned router activates a handful per token, so a model can hold hundreds of billions or a trillion parameters while each token costs what a model ten to thirty times smaller would. That shifts the scaling-law trade-off: for a fixed training compute budget, an MoE reaches lower loss than a dense model. By 2025 most open frontier models were MoEs — Mixtral, DeepSeek-V3, Qwen3's largest models, Llama 4, gpt-oss and Kimi K2 — and the design shapes everything downstream: distributed training (experts spread across GPUs), serving (all weights resident, few active) and quantisation. MoE cuts FLOPs per token in the way that MLA and GQA cut cache bytes per token; DeepSeek's architecture uses both.
2,000 ft
- Split the FFN. Each MoE layer holds \(E\) expert MLPs (and sometimes one or two shared experts every token uses).
- Score. A router — one small linear map — gives each token a score per expert.
- Select. Keep the top \(k\) scores (\(k\) = 1 to 8 in practice); every other expert is skipped for that token.
- Mix. The layer output is the gate-weighted sum of the chosen experts' outputs. The gates are differentiable, so the router learns which experts help which tokens.
- Balance. Left alone, the router collapses onto a few favourite experts. An auxiliary loss or an adaptive per-expert bias spreads the load; a capacity limit caps how many tokens one expert may take.
- Distribute. Experts live on different GPUs; tokens travel to their experts and back in two all-to-all exchanges per layer.
Ground level¶
Why the feed-forward layer is the one to split¶
In a standard block, attention mixes information between positions and the feed-forward network (FFN) transforms each position on its own. The FFN holds most of a dense model's non-embedding parameters — in Llama 3 8B, a SwiGLU FFN of width \(3.5d\) has \(3 \cdot 3.5d^2 = 10.5d^2\) parameters per layer against \(2.5d^2\) for its grouped-query attention, about 80% — and it behaves like a large key–value memory: the first matrix's rows act as patterns matched against the input, the second's as the values written back when a pattern fires (Geva et al., 2020). Most of a model's factual knowledge seems to sit there.
A memory does not need to be read in full for every query. When a token is def, the parameters that store facts about 18th-century opera are irrelevant. An MoE turns that observation into architecture: cut the FFN into experts, and let each token read only the slices it needs. Because the FFN is per-position, this is easy — each token can be sent to a different expert with no change to how positions interact. Attention, which must see all positions together, stays dense.
The router, with real numbers¶
The router is a matrix \(W_g \in \mathbb{R}^{d \times E}\) (equivalently one learned vector \(\mathbf{e}_i\) per expert). For a token state \(\mathbf{u}\) it produces logits \(\mathbf{u}^\top W_g\), one per expert. Take \(E = 4\) and logits \((2.1,\ 0.3,\ 1.6,\ -0.5)\):
| expert | logit | softmax over all four | chosen (top-2)? | gate |
|---|---|---|---|---|
| 0 | 2.1 | 0.542 | yes | 0.622 |
| 1 | 0.3 | 0.090 | no | 0 |
| 2 | 1.6 | 0.329 | yes | 0.378 |
| 3 | −0.5 | 0.040 | no | 0 |
Mixtral's rule is \(G(\mathbf{u}) = \operatorname{softmax}(\operatorname{TopK}(\mathbf{u}^\top W_g))\): keep the two largest logits, set the rest to \(-\infty\), softmax. That gives gates \(e^{2.1}/(e^{2.1} + e^{1.6}) = 0.622\) and \(0.378\) — exactly the full softmax probabilities of the chosen experts, renormalised to sum to one. The layer output is \(0.622\,\text{FFN}_0(\mathbf{u}) + 0.378\,\text{FFN}_2(\mathbf{u})\); experts 1 and 3 do no work at all for this token.
Variants differ only in the scoring function. Switch Transformer used \(k = 1\) and the full softmax probability as the gate. DeepSeek-V3 scores each expert with an independent sigmoid, \(s_i = \sigma(\mathbf{u}^\top\mathbf{e}_i)\), picks the top 8, and normalises the 8 chosen scores to sum to one (arXiv:2412.19437, §2.1.2). gpt-oss applies a softmax over only the selected experts' scores, as Mixtral does (gpt-oss model card).
Total parameters versus active parameters¶
An MoE has two sizes. Total parameters decide memory: every expert must be loaded somewhere. Active parameters — those used for one token — decide FLOPs per token, and hence training and decoding compute.
Worked example: why "8×7B" is not 56B. Mixtral 8x7B has Mistral 7B's shape — width \(d = 4096\), SwiGLU FFN width 14,336, 32 layers, 32 query heads and 8 KV heads of width 128, a 32,000-token vocabulary — with every FFN replaced by 8 experts and top-2 routing (arXiv:2401.04088).
| component | parameters | count |
|---|---|---|
| one expert (\(3 \times 4096 \times 14336\)) | 176.2M | |
| all experts (\(\times 8 \times 32\) layers) | 45.10B | total only |
| two experts per layer (\(\times 2 \times 32\)) | 11.27B | active |
| attention (\(2 \cdot 4096^2 + 2 \cdot 4096 \cdot 1024\) per layer \(\times 32\)) | 1.34B | both |
| embeddings and output head (\(2 \times 32000 \times 4096\)) | 0.26B | both |
| total | 46.7B | the paper's "47B" |
| active | 12.9B | the paper's "13B" |
Attention and embeddings are not duplicated, so "8×7B" undercounts nothing and overcounts the shared parts: 46.7B, not 56B. Each token costs roughly what a 13B dense model costs, yet the model reads from 47B parameters of memory. Mixtral matched or beat Llama 2 70B across the paper's benchmarks with about a fifth of its active parameters.
The table below shows how far the ratio has moved since. Each row is from the model's own report; the percentage is active ÷ total.
| model (release) | total | active | experts per MoE layer | routed per token | shared |
|---|---|---|---|---|---|
| Mixtral 8x7B (Dec 2023) | 46.7B | 12.9B | 8 | 2 | 0 |
| DeepSeek-V3 (Dec 2024) | 671B | 37B | 256 | 8 | 1 |
| Llama 4 Maverick (Apr 2025) | 400B | 17B | 128 | 1 | 1 |
| Qwen3-235B-A22B (May 2025) | 235B | 22B | 128 | 8 | 0 |
| Kimi K2 (Jul 2025) | 1.04T | 32.6B | 384 | 8 | 1 |
| gpt-oss-120b (Aug 2025) | 116.8B | 5.1B | 128 | 4 | 0 |
Sources: Mixtral, DeepSeek-V3, Llama 4 ("each token is sent to the shared expert and also to one of the 128 routed experts"; dense and MoE layers alternate), Qwen3, Kimi K2, gpt-oss.
Routing collapse and load balancing¶
Training a router has a built-in positive feedback loop. Early on, a few experts happen to score slightly higher for many tokens. They receive those tokens, get gradient, improve, and therefore score higher still. Other experts receive almost nothing and never improve. Shazeer et al. observed exactly this: the gating network "tends to converge to a state where it always produces large weights for the same few experts" (arXiv:1701.06538). A collapsed MoE wastes its parameters, and on a cluster where each expert has its own GPU it wastes hardware too: the busiest GPU sets the pace for every layer.
Four tools keep the load even.
1. An auxiliary balancing loss. Switch Transformer's version is now standard (arXiv:2101.03961, §2.2). Over a batch of \(T\) tokens, let \(f_i\) be the fraction of tokens dispatched to expert \(i\) and \(P_i\) the mean router probability for expert \(i\):
\(f_i\) is a count, so it has no gradient; \(P_i\) is a mean of softmax outputs, so it does. The gradient therefore pushes probability down on experts in proportion to how many tokens they already receive. Under perfect balance \(f_i = P_i = 1/E\) and the sum is \(E \cdot E \cdot (1/E^2) = 1\). With \(E = 4\), \(f = (0.50, 0.25, 0.15, 0.10)\) and \(P = (0.45, 0.25, 0.18, 0.12)\), it is \(4 \times 0.3265 = 1.306\). Switch used \(\alpha = 10^{-2}\), chosen by sweeping \(10^{-1}\) to \(10^{-5}\).
2. A capacity limit. For fixed-shape tensors (which TPUs and early GPU kernels needed), each expert gets a buffer of
Tokens beyond the buffer are dropped: they skip the layer and pass through on the residual connection. Switch found capacity factors of 1.0–1.25 worked best. Our NumPy MoE below, with a random router and 8 experts, drops 61 of 1,024 assignments at factor 1.0 and none at 1.25. Modern GPU kernels such as MegaBlocks' block-sparse formulation avoid the fixed buffer entirely, so no tokens need be dropped (arXiv:2211.15841); DeepSeek-V3 reports dropping no tokens in training or inference.
3. A bias instead of a loss. The auxiliary loss works by distorting the training gradient, and a strong one costs quality. DeepSeek's auxiliary-loss-free balancing adds a per-expert bias \(b_i\) to the scores only when choosing the top \(k\), then sets the gate from the unbiased score (Wang et al., 2024). After each step, \(b_i\) falls by \(\gamma\) if expert \(i\) was overloaded and rises by \(\gamma\) if it was underloaded. No gradient flows through \(b_i\); it is a controller, like a thermostat. DeepSeek-V3 used \(\gamma = 0.001\) for the first 14.3T tokens and kept only a tiny sequence-level auxiliary loss (\(\alpha = 0.0001\)) as a safety net.
4. A router z-loss for numerical stability, from ST-MoE (arXiv:2202.08906):
which penalises large router logits. Large logits make the exponentials in the softmax sensitive to rounding — and bfloat16 has, as the ST-MoE authors put it, up to 65,536× worse round-off than float32. For our example logits the log-sum-exp is 2.71; multiply the logits by ten and it becomes 21.0, so the penalty grows from 7.4 to 441. ST-MoE weights it by \(c_z = 0.001\). Switch Transformer attacked the same instability by computing the router in float32 while keeping everything else in bfloat16, and by shrinking the initialisation scale tenfold.
Fine-grained and shared experts¶
Early MoEs copied the dense FFN: each expert as wide as the FFN it replaced, 8 to 64 of them, top-1 or top-2. DeepSeekMoE argued for two changes (arXiv:2401.06066).
Fine-grained experts. Split each expert into \(m\) narrower ones and route to \(m\) times as many, keeping FLOPs fixed. The number of possible expert combinations a token can use explodes. With 16 experts and top-2 there are \(\binom{16}{2} = 120\) combinations; split each into 4 (64 experts, top-8) and there are \(\binom{64}{8} = 4{,}426{,}165{,}368\). More combinations let the model compose knowledge more precisely. Krajewski et al. formalised this as a granularity hyperparameter and found that the habit of making experts as large as the dense FFN "is not optimal at almost any computational budget" (arXiv:2402.07871).
Shared experts. Some knowledge — syntax, frequent words — every token needs. If every routed expert must relearn it, capacity is wasted on copies. A shared expert that processes every token holds that common core, leaving routed experts free to specialise. DeepSeek-V3 has 1 shared and 256 routed experts, each of width 2,048 against a model width of 7,168; Kimi K2 kept the design and raised the routed count to 384. Not everyone agrees: Qwen3's MoE models dropped the shared experts that Qwen2.5-MoE had (arXiv:2505.09388).
How sparse should you go? Kimi K2's authors define sparsity as total experts ÷ active experts and report that, at fixed active parameters, raising it keeps lowering loss: to reach the same validation loss, sparsity 48 needed 1.69×, 1.39× and 1.15× fewer FLOPs than sparsity 8, 16 and 32. They stopped at 48 (8 of 384) to keep infrastructure cost in check (arXiv:2507.20534).
Other ways to route¶
Token-choice top-\(k\) (each token picks experts) dominates, but the alternatives teach what the design space is.
- Expert choice. Flip the selection: each expert picks its top-\(c\) tokens from the batch. Load is perfectly balanced by construction and important tokens can get more experts. The cost is causality: in a decoder, whether a token is chosen depends on other tokens in the batch, including later ones (arXiv:2202.09368).
- Hash routing. Assign tokens to experts by a fixed hash of the token id. No learned router, no balancing problem, and it works surprisingly well (arXiv:2106.04426) — a useful baseline that shows how much of routing's benefit is just "more parameters".
- BASE layers. Solve routing as a linear assignment problem so each expert gets exactly equal load (arXiv:2103.16716).
- Soft MoE. Each expert processes a weighted average of all tokens rather than a subset: fully differentiable, no dropping, but again not causal, so it has been used in vision rather than in language decoders (arXiv:2308.00951).
What experts actually learn¶
The name suggests a biology expert and a law expert. That is not what happens. Mixtral's routing analysis found expert assignment very similar for ArXiv papers, PubMed abstracts and PhilPapers documents — no obvious topic specialisation; the router follows syntax and surface form — indentation tokens in Python always go to the same experts, and consecutive tokens often share experts (arXiv:2401.04088, §5). At layer 15, a token's first-choice expert matched the previous token's 23.6–28.4% of the time, against 12.5% by chance. OLMoE, with 64 small experts, reports clearer domain and vocabulary specialisation (arXiv:2409.02060), consistent with the fine-grained argument: small experts can afford to be narrow.
MoE on real hardware¶
Expert parallelism. A model like DeepSeek-V3 cannot hold all experts on one GPU, so experts are spread across devices. Each MoE layer then runs two all-to-all exchanges: dispatch (every GPU sends each of its tokens to the GPUs holding that token's experts) and combine (results come back). This is communication that dense models do not have, and it scales with \(k\) and with the number of devices a token touches. DeepSeek-V3 limits each token to experts on at most 4 nodes so that slow inter-node links carry less traffic, and overlaps communication with computation (arXiv:2412.19437, §3.2).
Serving: cheap in FLOPs, expensive in memory. Every expert must be resident, so a 671B MoE needs the memory of a 671B model even though each token computes like a 37B one. By our count, about 656B of DeepSeek-V3's 671B parameters sit in its MoE layers (58 layers × 257 experts × \(3 \times 7168 \times 2048\)). This is why MoE weights are the first thing quantised: gpt-oss ships its MoE weights in MXFP4 at about 4.25 bits per parameter, so the 117B model fits on one 80 GB GPU.
Decode bandwidth depends on the batch. Decoding is memory-bound: a step's time is set by bytes read. With one sequence, a step reads only the experts that token chose — the MoE advantage in full. But a batch of \(B\) tokens touches the union of their choices. If routing were uniform and independent, the expected number of distinct experts touched per layer is
For \(E = 256\), \(k = 8\): 8 experts at \(B = 1\), 102 at \(B = 16\), 163 at \(B = 32\), 222 at \(B = 64\). By batch 32 a step reads almost two-thirds of all expert weights. Large-batch MoE serving therefore spreads experts across many GPUs so each holds few, which is what DeepSeek's inference deployment does.
History¶
Thirty years from a gating network to the default architecture
1991 — Jacobs, Jordan, Nowlan and Hinton's Adaptive Mixtures of Local Experts trains several networks plus a gating network that softly assigns each training case to one expert, and shows the experts divide a vowel-recognition task between them (paper page). 1994 — Jordan and Jacobs make the mixture hierarchical and train it with EM, linking it to mixture models. 2017 — Shazeer et al. make it sparse: noisy top-\(k\) gating, thousands of experts, a 137B-parameter LSTM model, and the first balancing losses. 2020 — GShard scales a top-2 MoE translation model past 600B parameters on 2,048 TPU v3 chips with automatic sharding (arXiv:2006.16668). 2021 — Switch Transformer shows top-1 suffices, trains in bfloat16, reports up to 7× pre-training speedups over T5 and a 1.6T-parameter, 2,048-expert model; GLaM (1.2T) beats GPT-3's zero- and one-shot scores for a third of its training energy (arXiv:2112.06905). 2022 — ST-MoE fixes stability (router z-loss) and fine-tuning; expert choice routing; MegaBlocks makes dropless GPU MoE practical; sparse upcycling turns dense checkpoints into MoEs (arXiv:2212.05055). Dec 2023 — Mixtral 8x7B, the first open MoE that most practitioners ran. 2024 — DeepSeekMoE (fine-grained + shared experts), DeepSeek-V2 and V3 (auxiliary-loss-free balancing, 671B/37B), OLMoE (fully open, 7B/1B). 2025 — the open frontier goes sparse: Llama 4, Qwen3, Kimi K2 (1T), gpt-oss.
First principles¶
Why sparsity buys loss per FLOP. Scaling laws say loss falls with parameters \(N\) and data \(D\), and dense training compute is \(C \approx 6ND\). That formula hides an assumption: every parameter touches every token. Parameters do two different jobs — they store (knowledge, associations) and they compute (transform the current token). A token about chemistry needs to compute with the chemistry slice of the store, not all of it. MoE separates the two: total parameters set storage, active parameters set compute, and \(C \approx 6N_\text{active}D\). Clark et al. fitted scaling laws in which parameter count and compute are "two independent axes along which an increase leads to better performance" (arXiv:2202.01169), but with a fixed training length their fits predicted dense models overtaking MoE beyond about 1T parameters. Krajewski et al. let the number of tokens and the expert size vary too, and found the opposite: a compute-optimal MoE at \(10^{20}\) FLOPs matched a dense model trained with 20× the compute, and the saving rose past 40× beyond \(10^{25}\) FLOPs (arXiv:2402.07871). The point is not that MoE is free: it buys lower loss per FLOP with memory and communication.
Why the selection is hard but still trainable. Top-\(k\) is a discrete choice with zero gradient almost everywhere. MoE gets around it without any estimator trick: the gate values multiply the expert outputs, and gates are smooth functions of the router logits. If increasing the gate on expert 2 would have lowered the loss, the gradient raises expert 2's logit for tokens like this one, and next time it may cross into the top \(k\). Only the chosen experts provide this signal. Shazeer et al. conjectured that routing to \(k > 1\) experts was needed for non-trivial router gradients — with two choices the router can compare them. Switch Transformer showed that \(k = 1\) trains fine provided the gate is the chosen expert's full softmax probability (derived below).
Why the system collapses without help, and why \(f \cdot P\) fixes it. Collapse is a rich-get-richer dynamic: load brings gradient, gradient brings improvement, improvement brings load. Any fix must push against the current load. The product \(f_i P_i\) does exactly that: its gradient with respect to \(P_i\) is \(f_i\), so experts that already have many tokens are pushed down hardest. Using only \(P_i\) would push on probabilities without knowing about actual dispatches; using only \(f_i\) would have no gradient. The aux-loss-free bias uses the same signal — the observed load — as a control input outside backpropagation.
What breaks if you change the parts.
- Route attention instead of the FFN. Attention's job is to see all positions; per-token sparsity there removes exactly that. (Attention-head mixtures exist but have not displaced dense attention.)
- Use huge \(k\). You approach a dense model with extra router overhead: compute returns, sparsity's advantage goes.
- Make experts tiny and numerous without care. Per-expert matrix multiplications become too small to run efficiently on GPUs, and the all-to-all traffic grows with the number of destinations. DeepSeek-V3's node limit and Kimi K2's stopping point at sparsity 48 are both responses to this.
- Drop balancing. Collapse; in expert parallelism, one overloaded GPU stalls all others.
The maths¶
The layer. For a token state \(\mathbf{u}_t \in \mathbb{R}^d\), \(N_s\) shared experts and \(N_r\) routed experts, each an MLP \(\text{FFN}_i: \mathbb{R}^d \to \mathbb{R}^d\):
This is DeepSeek-V3's form (its equations 12–16). Set \(N_s = 0\), \(b_i = 0\) and replace the sigmoid by a softmax, and you have Mixtral's \(\operatorname{softmax}(\operatorname{TopK}(\cdot))\) (softmax over the selected logits equals the renormalised full softmax restricted to them).
Shapes. Batch of \(T\) tokens: \(U \in \mathbb{R}^{T \times d}\); router logits \(UW_g \in \mathbb{R}^{T \times E}\); top-\(k\) indices \(\in \{1..E\}^{T \times k}\); gates \(\in \mathbb{R}^{T \times k}\). Each expert \(i\) receives the \(T_i\) rows routed to it, a matrix \(\mathbb{R}^{T_i \times d}\), with \(\sum_i T_i = Tk\) (minus any dropped).
FLOPs and parameters. For a SwiGLU expert of width \(d_e\): \(3dd_e\) parameters and \(6dd_e\) FLOPs per token (forward). Per MoE layer: total parameters \((N_s + N_r)\,3dd_e + dN_r\); active \((N_s + K_r)\,3dd_e + dN_r\). Router FLOPs \(2dN_r\) are negligible (\(2 \cdot 7168 \cdot 256 \approx 3.7\)M against \(9 \cdot 6 \cdot 7168 \cdot 2048 \approx 793\)M for DeepSeek-V3's active experts).
Derivation: the router's gradient flows only through the chosen gates
Let \(\mathcal{S}_t\) be the chosen set for token \(t\) and \(\mathbf{y}_i = \text{FFN}_i(\mathbf{u}_t)\). With softmax-over-selected gates \(g_i = e^{x_i}/\sum_{j \in \mathcal{S}_t} e^{x_j}\) for \(i \in \mathcal{S}_t\) and output \(\mathbf{o} = \sum_{i \in \mathcal{S}_t} g_i\mathbf{y}_i\), the upstream gradient \(\boldsymbol{\delta} = \partial\mathcal{L}/\partial\mathbf{o}\) gives
using the softmax Jacobian \(\partial g_j/\partial x_i = g_j(\mathbf{1}[i=j] - g_i)\). For \(i \notin \mathcal{S}_t\) the derivative is zero (top-\(k\) is locally constant). Read it as: raise the logit of a chosen expert whose output is better aligned with the descent direction than the gate-weighted average. With \(k = 1\) and softmax-over-selected, \(g = 1\) always and this gradient vanishes — which is why Switch uses the full softmax probability \(p_i\) as the gate: then \(\partial \mathcal{L}/\partial x_j = p_i\,\boldsymbol{\delta}^\top\mathbf{y}_i(\mathbf{1}[i=j] - p_j)\) is non-zero for every expert, including unchosen ones, which get pushed down when the chosen one helps.
Derivation: the balancing loss is minimised by uniform routing
Write \(\mathcal{L}_\text{aux}/\alpha = E\sum_i f_iP_i\) with \(\sum_i f_i = \sum_i P_i = 1\). If the router's dispatches follow its probabilities on average, \(f_i \approx P_i\), and
by Cauchy–Schwarz, with equality iff every \(P_i = 1/E\). So the loss is 1 at perfect balance and grows with the spread: in fact \(E\sum_i P_i^2 = 1 + E^2\operatorname{Var}(P)\), where \(\operatorname{Var}\) is the variance over experts. The gradient used in training treats \(f\) as a constant: \(\partial(\mathcal{L}_\text{aux}/\alpha)/\partial P_i = E f_i\), the observed overload. (DeepSeek-V3's version multiplies \(f_i\) by \(N_r/K_r\) so that perfect balance gives \(f_i = 1\); the logic is identical.)
Derivation: expected number of experts a batch touches
Suppose each of \(B\) tokens picks a set of \(k\) distinct experts uniformly at random, independently. A given expert is missed by one token with probability \(\binom{E-1}{k}/\binom{E}{k} = 1 - k/E\), and by all \(B\) tokens with probability \((1 - k/E)^B\). By linearity of expectation over the \(E\) experts,
The bytes a decode step must read from expert weights scale with this number, so the "active parameter" saving in bandwidth holds only while \(Bk \ll E\). Real routing is not uniform (locality makes it somewhat better, hot experts make the busiest device worse), but the shape is right.
Aux-loss-free bias update. With \(\bar{c} = Tk/E\) the mean load and \(c_i\) the observed load of expert \(i\) over the last step:
The bias moves only the selection threshold; gates still use \(s_{i,t}\), so the function the expert outputs are combined with is untouched.
Build it¶
Two NumPy programs (NumPy 2, CPU): a complete top-\(k\) MoE layer with the balancing loss, z-loss and capacity, then DeepSeek-style bias balancing rescuing a skewed router.
1. A top-k MoE layer.
import numpy as np
rng = np.random.default_rng(0)
T, d, d_ff, E, k = 512, 64, 128, 8, 2 # tokens, width, expert width, experts, top-k
def init(*shape, scale=1.0):
return rng.normal(0, scale / np.sqrt(shape[-2]), shape)
W_g = init(d, E) # router
W1, W2 = init(E, d, d_ff), init(E, d_ff, d) # E independent 2-layer MLP experts
X = rng.normal(size=(T, d))
def moe(X, capacity_factor=None):
logits = X @ W_g # (T, E)
top = np.argsort(-logits, axis=1)[:, :k] # (T, k) chosen experts
sel = np.take_along_axis(logits, top, 1)
gates = np.exp(sel - sel.max(1, keepdims=True))
gates /= gates.sum(1, keepdims=True) # softmax over the k chosen
cap = None if capacity_factor is None else int(capacity_factor * T * k / E)
Y, load, dropped = np.zeros_like(X), np.zeros(E, int), 0
for e in range(E):
tok, slot = np.nonzero(top == e) # tokens that picked expert e
if cap is not None and len(tok) > cap:
dropped += len(tok) - cap; tok, slot = tok[:cap], slot[:cap]
load[e] = len(tok)
h = np.maximum(X[tok] @ W1[e], 0) # expert e runs only on its tokens
Y[tok] += gates[tok, slot, None] * (h @ W2[e])
# Switch-style auxiliary loss: E * sum_i f_i * P_i (1.0 when perfectly balanced)
P = np.exp(logits - logits.max(1, keepdims=True)); P /= P.sum(1, keepdims=True)
f = np.bincount(top.ravel(), minlength=E) / (T * k)
aux = E * np.sum(f * P.mean(0))
z = np.mean(np.log(np.exp(logits).sum(1)) ** 2) # router z-loss
return Y, load, dropped, aux, z
Y, load, dropped, aux, z = moe(X)
print("tokens per expert:", load, " (ideal", T * k // E, ")")
print(f"aux loss {aux:.3f} z-loss {z:.3f}")
for cf in (1.0, 1.25, 2.0):
_, _, dropped, _, _ = moe(X, cf)
print(f"capacity factor {cf}: {dropped} of {T*k} assignments dropped")
dense_flops = 2 * T * (2 * d * d_ff) * E # every expert on every token
moe_flops = 2 * T * (2 * d * d_ff) * k + 2 * T * d * E # k experts + router
print(f"FLOPs: all {E} experts {dense_flops/1e6:.1f}M vs top-{k} {moe_flops/1e6:.1f}M")
tokens per expert: [116 136 105 159 135 125 143 105] (ideal 128 )
aux loss 1.011 z-loss 6.358
capacity factor 1.0: 61 of 1024 assignments dropped
capacity factor 1.25: 0 of 1024 assignments dropped
capacity factor 2.0: 0 of 1024 assignments dropped
FLOPs: all 8 experts 134.2M vs top-2 34.1M
Even an untrained random router is uneven (105 to 159 tokens per expert), and the auxiliary loss is just above its floor of 1. Dropped tokens are not lost: in a real model their residual stream skips the layer.
2. Loss-free balancing rescues a skewed router.
import numpy as np
rng = np.random.default_rng(1)
d, E, k, T, gamma = 64, 16, 2, 1024, 0.01
W_g = rng.normal(0, 1 / np.sqrt(d), (d, E))
skew = np.linspace(-1.0, 1.0, E) # a router that already prefers some experts
b = np.zeros(E) # DeepSeek-V3 style balancing bias
def route(X, b):
s = 1 / (1 + np.exp(-(X @ W_g + skew))) # sigmoid affinities (T, E)
top = np.argsort(-(s + b), axis=1)[:, :k] # bias only changes WHICH experts...
g = np.take_along_axis(s, top, 1)
return top, g / g.sum(1, keepdims=True) # ...gates still come from s
def max_over_mean(top):
load = np.bincount(top.ravel(), minlength=E)
return load, load.max() / load.mean()
for step in range(301):
X = rng.normal(size=(T, d))
top, gates = route(X, b)
load, mvm = max_over_mean(top)
b += gamma * np.sign(load.mean() - load) # under-loaded up, over-loaded down
if step in (0, 10, 50, 300):
print(f"step {step:3d} max/mean load {mvm:4.2f} "
f"busiest {load.max():4d} idle-ish {load.min():4d}")
print("final bias (first 4, last 4):", np.round(b[:4], 2), np.round(b[-4:], 2))
step 0 max/mean load 2.92 busiest 374 idle-ish 2
step 10 max/mean load 1.53 busiest 196 idle-ish 19
step 50 max/mean load 1.30 busiest 166 idle-ish 88
step 300 max/mean load 1.32 busiest 169 idle-ish 104
final bias (first 4, last 4): [0.26 0.16 0.17 0.12] [-0.1 -0.11 -0.13 -0.13]
The busiest expert starts with 2.9× the average load and one expert gets 2 tokens out of 2,048 assignments. Within 50 steps the bias brings it to about 1.3× — close to the 1.15× that perfectly uniform random routing would show on batches this size, which is pure sampling noise. The learned bias mirrors the skew: positive for neglected experts, negative for popular ones.
Things to try
- In program 1, train the router: add a toy regression target, backpropagate through the gates only (the derivation above), and watch load drift without the aux loss.
- In program 2, set
gamma = 0.1and0.001. Too large oscillates; too small is slow. DeepSeek-V3 used 0.001 over trillions of tokens. - Replace top-\(k\) with expert choice (each expert takes its top \(Tk/E\) tokens by score) and count how many tokens get zero experts.
- Compute total and active parameters for Qwen3-235B-A22B from its config on Hugging Face and check the "A22B".
In practice¶
- Defaults as of 2026. Fine-grained routed experts (64–384 per layer), top-4 to top-8, often one shared expert; the first one to three layers kept dense (DeepSeek-V3: 3, Kimi K2: 1); sigmoid or softmax scoring with renormalised gates; aux-loss-free or global-batch balancing with a small auxiliary term; router computed in float32.
- Budget memory by total parameters, compute by active. A "30B-A3B" model decodes about as fast as a 3B dense model at batch 1 but needs 30B parameters of memory. On a single GPU or a laptop that trade can go either way; on Apple Silicon's large unified memory it is often a win (see on-device AI).
- Quantise the experts first. They are >90% of the weights and each sees only a fraction of tokens, so per-expert error matters less than in dense layers.
- Fine-tuning is touchier than dense. ST-MoE found sparse models overfit small fine-tuning sets more readily, preferred smaller batches and higher learning rates than dense models, and fine-tuned about as well when only the non-MoE parameters were updated — while updating only the experts hurt badly (§4.1–4.3). Keep balancing on during fine-tuning. LoRA on attention and shared experts is a common cheap start.
- Upcycling. Initialise every expert as a copy of a trained dense FFN and continue training; it reaches a good MoE cheaper than training from scratch (Komatsuzaki et al.).
- Watch per-expert load in training dashboards, not just total loss. A drifting max/mean ratio is the early warning of collapse or of a token distribution shift.
Common misconceptions¶
- "Mixtral 8x7B is a 56B model." It has 46.7B parameters; attention and embeddings are shared.
- "Each expert is a domain specialist." Routing follows syntax and token identity far more than topic, at least for coarse experts.
- "MoE is cheaper to serve." It is cheaper in FLOPs per token, not in memory, and at large batch it reads most expert weights per step anyway.
- "The top-k choice is learned by gradient." The scores are; the discrete choice follows them. Balancing biases are not learned by gradient at all.
- "Dropped tokens are deleted." They skip one MoE layer through the residual connection.
Check yourself¶
A layer has 64 routed experts (top-6) and 2 shared experts, each a SwiGLU of width 1,408, in a model of width 2,048. How many expert parameters per layer are total, and how many active?
One expert: \(3 \times 2048 \times 1408 = 8{,}650{,}752 \approx 8.65\)M. Total: \(66 \times 8.65 \approx 571\)M. Active: \((2 + 6) \times 8.65 \approx 69\)M, about 12% of the layer's expert parameters. (Plus a \(2048 \times 64\) router.)
Why does the Switch balancing loss use f_i · P_i rather than just f_i or just P_i?
\(f_i\) (fraction of tokens dispatched) reflects the real load but is a count with no gradient. \(P_i\) (mean router probability) has a gradient but on its own does not know which experts are actually overloaded. In the product, \(f_i\) acts as a per-expert weight on the gradient of \(P_i\), pushing probability down hardest where load is highest. Under \(f \approx P\) it equals \(E\sum P_i^2 \ge 1\), minimised at uniform routing.
How does DeepSeek-V3 balance load without letting the balancing objective distort the language-modelling gradient?
It adds a per-expert bias to the routing scores only for the top-\(k\) selection; the gate weights use the unbiased scores. After each step the bias of each overloaded expert drops by \(\gamma\) and of each underloaded expert rises by \(\gamma\). No gradient flows through the bias, so the LM loss is untouched; only a very small sequence-wise auxiliary loss remains.
With 16 experts and top-2, there are 120 possible expert combinations per token. How many if each expert is split into 4 and you route top-8? Why might that help?
\(\binom{64}{8} = 4{,}426{,}165{,}368\). Same FLOPs, vastly more ways to combine knowledge, so each token can assemble a more precise mixture and each small expert can specialise more narrowly. The cost is more, smaller matrix multiplications and more communication destinations.
A model has E = 128 experts and k = 4. At batch size 1 a decode step reads 4 experts per layer. Roughly how many at batch 32, assuming uniform independent routing?
\(128(1 - (1 - 4/128)^{32}) = 128(1 - 0.9688^{32}) \approx 128(1 - 0.362) \approx 82\). Almost two-thirds of the experts, so the bandwidth advantage of sparsity has largely gone at that batch size.
Hard: why can't a decoder-only language model use expert-choice routing directly at inference?
In expert choice each expert picks its top-\(c\) tokens from the whole batch, so whether token \(t\) is processed depends on the scores of other tokens — including tokens later in the same sequence that do not exist yet during generation. That breaks the causal, token-by-token computation; the training-time behaviour cannot be reproduced at decode without approximations.
Hard: with k = 1 and gates computed as a softmax over only the selected expert, what goes wrong, and how does Switch avoid it?
The gate is always exactly 1, independent of the logits, so the router receives no gradient at all and never learns. Switch uses the full-softmax probability \(p_i\) of the chosen expert as its gate. Then \(\partial\mathcal{L}/\partial x_j = p_i\,\boldsymbol{\delta}^\top\mathbf{y}_i(\mathbf{1}[i=j] - p_j)\), which is non-zero for every expert.
Hard: give two reasons a dense 70B model might be preferable to a 400B-total, 17B-active MoE for a given product.
Memory: the MoE needs roughly 400B parameters resident, many more GPUs or far heavier quantisation than 70B. Batch economics: at high concurrency the MoE touches most experts per step anyway and pays all-to-all communication, eroding its per-token speed advantage. Others: dense models are simpler to fine-tune and to run on a single node, and per-token quality depends on more than active parameters.
Go deeper¶
Papers
- Adaptive Mixtures of Local Experts — Jacobs, Jordan, Nowlan, Hinton, 1991. Where the idea starts: a gating network allocating training cases to competing experts.
- Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer — Shazeer et al., 2017. Noisy top-k gating and the first balancing losses; §2–4.
- GShard — Lepikhin et al., 2020. Top-2 routing, expert capacity and how to shard it across 2,048 TPUs.
- Switch Transformers — Fedus, Zoph, Shazeer, 2021. Top-1 routing, the f·P balancing loss, capacity factor, selective precision. The most readable MoE paper.
- ST-MoE — Zoph et al., 2022. A design guide: stability (router z-loss), fine-tuning and what experts learn.
- Mixtral of Experts — Jiang et al., 2024. Short; §5's routing analysis is the best antidote to the "domain expert" myth.
- DeepSeekMoE — Dai et al., 2024. Fine-grained and shared experts, argued from combinatorics.
- Auxiliary-Loss-Free Load Balancing — Wang et al., 2024. The bias controller, with ablations against aux-loss strength.
- DeepSeek-V3 Technical Report — DeepSeek-AI, 2024. §2.1.2 (the MoE), §3.2 (expert-parallel training and all-to-all overlap).
- Scaling Laws for Fine-Grained Mixture of Experts — Krajewski et al., 2024. Granularity as a scaling variable.
- MegaBlocks — Gale et al., 2022. Dropless MoE via block-sparse kernels.
- OLMoE — Muennighoff et al., 2024. Fully open MoE with data, logs and many training ablations.
- A Review of Sparse Expert Models in Deep Learning — Fedus, Dean, Zoph, 2022. A survey by the Switch authors.
Videos and lectures
- Stanford CS25 V4: Demystifying Mixtral of Experts — Albert Jiang (Mistral AI), 2024. The Mixtral team on design and routing analysis.
- CMU Advanced NLP 2024 (14): Ensembling and Mixture of Experts — Graham Neubig. Places MoE among ensembling and merging methods.
Articles and blog posts
- Mixture of Experts Explained — Sanseviero et al., Hugging Face, 2023. Thorough overview with history, training and serving tips.
- A Visual Guide to Mixture of Experts — Maarten Grootendorst, 2024. Dozens of diagrams; good for the 2,000-ft picture.
Courses and books
- Stanford CS336: Language Modeling from Scratch — Its current schedule has a lecture on "Attention alternatives and mixture of experts", plus inference and systems lectures.
Code
- databricks/megablocks — Dropless MoE training kernels.
- deepseek-ai/DeepEP — DeepSeek's expert-parallel all-to-all communication library.
- allenai/OLMoE — Training code and configs for a fully open MoE.
Where this leads¶
- Beyond transformers — the other big architectural bet: replace attention's growing cache with a fixed-size state.
- Distributed training — expert parallelism alongside data, tensor and pipeline parallelism.
- Serving LLMs — how engines batch, place experts and overlap communication.
- Quantisation — the usual way to fit all those experts in memory.
- Reasoning models — many of today's reasoning models are MoEs, because cheap tokens matter when a model thinks for thousands of them.