Simple Algorithm
Deep Learning · Emergence · 28 min

Mixture of Experts

Sparse routing, load balancing and conditional computation at scale.

A dense transformer uses every weight on every token. A mixture of experts replaces a feed-forward layer by many of them and a router that sends each token to one or two, so the parameter count can grow by an order of magnitude while the computation per token barely moves. The difficulty is the router: left alone, it sends nearly everything to a few favorites. This lesson covers the routing rules, the losses and tricks that keep the load even, and what sparse models cost to train and serve.

What you’ll learn

  • Define a sparse mixture-of-experts layer with top-kk gating, and separate total from active parameters.
  • Explain why routers collapse, and prove that the Switch auxiliary loss αE∑ifiPi\alpha E\sum_if_iP_i is minimized by uniform routing.
  • Compute expert capacity, and compare token-choice, expert-choice, dropless and auxiliary-loss-free routing.
  • Account for the memory and communication costs of sparse models, verify the published parameter counts of Mixtral 8×7B, and summarize what experts specialize in.

Conditional computation

The idea predates transformers. In the adaptive mixtures of local experts of Jacobs, Jordan, Nowlan and Hinton (1991), a gating network assigns each input softly to several expert networks, trained together so that each expert specializes on part of the input space; Jordan and Jacobs (1994) stacked gates into a hierarchy trained with EM. Every expert still ran on every input. Conditional computation keeps only a few: Shazeer et al. (2017) placed a mixture-of-experts layer with thousands of experts between LSTM layers, routed each position of each sequence to a handful of them, and reported more than 1000-fold increases in model capacity, up to 137 billion parameters, with only minor losses in computational efficiency.

In a transformer the experts are feed-forward networks. A router with weights Wr∈RE×dW_r\in\R^{E\times d} scores the EE experts for each token, keeps the kk best and mixes their outputs:

y=∑i∈Tk(x)gi(x) FFN⁡i(x),p(x)=softmax⁡(Wrx),Tk(x)=indices of the k largest pi(x)\mathbf y=\sum_{i\in\mathcal T_k(\mathbf x)}g_i(\mathbf x)\,\operatorname{FFN}_i(\mathbf x),\qquad\mathbf p(\mathbf x)=\softmax(W_r\mathbf x),\qquad\mathcal T_k(\mathbf x)=\text{indices of the }k\text{ largest }p_i(\mathbf x)
The gate values gig_i are the selected probabilities, used as they are (Switch, with k=1k=1) or renormalized over the kk chosen experts. Shazeer et al. (2017) added tunable Gaussian noise to the router logits before the top-kk selection, H(x)i=(Wgx)i+εiSoftplus⁡((Wnoisex)i)H(\mathbf x)_i=(W_g\mathbf x)_i+\varepsilon_i\operatorname{Softplus}\big((W_{\text{noise}}\mathbf x)_i\big), to spread the load.

With EE experts, each the size of a dense FFN, and top-kk routing, the FFN's total parameters grow by a factor EE while its active parameters and FLOPs per token grow only by kk, plus a router of EdEd weights. Attention, embeddings and normalizations are shared by all tokens and count fully in both. Sparse models therefore decouple two quantities that dense models tie together: how much the network can store, and how much it computes per token.

Why routers collapse, and how to balance them

Routing has a rich-get-richer dynamic. An expert that receives more tokens receives more gradient, improves faster, and earns higher router scores, which bring it more tokens. Left alone, a router can end up sending most tokens to a few experts: the others are wasted parameters, and with a fixed capacity per expert (next step) the favorites overflow. Every practical MoE therefore adds a load-balancing pressure. Shazeer et al. (2017) penalized the squared coefficient of variation of each expert's total gate value over a batch; the Switch Transformer (Fedus, Zoph & Shazeer, 2022) simplified it:

Laux=α E∑i=1Efi Pi,fi=1T∑x∈B1[arg⁡max⁡jpj(x)=i],Pi=1T∑x∈Bpi(x)\mathcal L_{\text{aux}}=\alpha\,E\sum_{i=1}^{E}f_i\,P_i,\qquad f_i=\frac1T\sum_{\mathbf x\in\mathcal B}\mathbb 1\big[\arg\max_jp_j(\mathbf x)=i\big],\qquad P_i=\frac1T\sum_{\mathbf x\in\mathcal B}p_i(\mathbf x)
fif_i is the fraction of the batch's TT tokens dispatched to expert ii and PiP_i the average router probability it receives; Switch used α=10−2\alpha=10^{-2}. The factor EE makes the loss equal to α\alpha under uniform routing whatever the number of experts.
DerivationProof of (b)
  1. Laux=αE∑iPi2,∑iPi=1\mathcal L_{\text{aux}}=\alpha E\sum_iP_i^2,\qquad\sum_iP_i=1

    With f=Pf=P the loss is a scaled sum of squares of a probability vector:

  2. E∑iPi2 ≥ 1⟹Laux≥α,equality iff Pi=1EE\sum_iP_i^2\ \ge\ 1\quad\Longrightarrow\quad\mathcal L_{\text{aux}}\ge\alpha,\quad\text{equality iff }P_i=\tfrac1E

    By the Cauchy–Schwarz inequality, 1=(∑iPi⋅1)2≤E∑iPi21=\big(\sum_iP_i\cdot1\big)^2\le E\sum_iP_i^2, with equality iff all PiP_i are equal:

  3. 8(0.52+7⋅(0.57)2)=8(0.25+0.257)≈2.298\Big(0.5^2+7\cdot\big(\tfrac{0.5}{7}\big)^2\Big)=8\Big(0.25+\tfrac{0.25}{7}\Big)\approx2.29

    Any imbalance raises the loss. For example, with E=8E=8 and one expert holding half the probability, the rest split evenly, the loss is about 2.29 α2.29\,\alpha:

Stability. Router logits can also grow during training, and exponentials of large logits are where low-precision arithmetic fails. Switch computed the router in float32 even when the rest of the model used bfloat16. ST-MoE (Zoph et al., 2022) added a router z-loss that penalizes large log-partition values,

Lz=1B∑x∈B(log⁡∑j=1Ee(Wrx)j)2,\mathcal L_z=\frac1B\sum_{\mathbf x\in\mathcal B}\Big(\log\sum_{j=1}^{E}e^{(W_r\mathbf x)_j}\Big)^2,

with a weight of 10−310^{-3}, which improved training stability without hurting quality; they used it to train a 269-billion-parameter sparse model.

Capacity and routing rules

Accelerators want static shapes, so token-choice MoEs give each expert a fixed buffer. With TT tokens in a batch routed to kk experts each, the expert capacity is

C=⌈kTE×capacity factor⌉.C=\Big\lceil\frac{kT}{E}\times\text{capacity factor}\Big\rceil.

Tokens beyond an expert's capacity are dropped: they skip the layer and continue through the residual connection unchanged. A capacity factor above 11 leaves slack for imbalance at the price of padding and wasted computation.

Predict before you look

A batch of T=4096T=4096 tokens is routed top-2 across E=64E=64 experts with capacity factor 1.251.25. How many token slots does each expert get?

Show the answer

160 tokens

kT/E=2×4096/64=128kT/E=2\times4096/64=128 assignments per expert on average, times 1.251.25 gives 160160 slots. An expert chosen by more than 160 tokens drops the excess; total buffer space is 64×160=10,24064\times160=10{,}240 slots for 8,1928{,}192 assignments.

RuleHow tokens and experts are matchedTrade-offs
Token choice, top-2 (GShard; Lepikhin et al., 2021)each token picks its two best experts; capacity limits; the second expert is used with probability proportional to its gate weightscaled to 600 billion parameters for translation from 100 languages; drops tokens under imbalance
Token choice, top-1 (Switch)each token picks one expertsimplest and cheapest routing; up to 7× faster pretraining than a dense T5 with the same compute per token
Expert choice (Zhou et al., 2022)each expert picks its top tokens from the batchperfect balance by construction and a variable number of experts per token; the choice depends on other tokens in the batch, including later positions, which does not fit causal decoding directly
Dropless (MegaBlocks; Gale et al., 2023)block-sparse matrix products accept any number of tokens per expertno dropping and no padding; needs specialized kernels
Fine-grained and shared experts (DeepSeekMoE; Dai et al., 2024)split experts into smaller ones and route to more of them; a few shared experts process every tokenmany more expert combinations; shared experts hold common knowledge
Auxiliary-loss-free balancing (Wang et al., 2024)add a per-expert bias to the routing scores before the top-kk selection, and adjust it after each step according to the expert's recent loadbalances without an auxiliary gradient that competes with the language-modeling loss; used in DeepSeek-V3
DeepSeek-V3 (DeepSeek-AI, 2024) combines several of these: 256 routed experts and one shared expert in every MoE layer (all layers but the first three), 8 routed experts per token, bias-based balancing with a small sequence-level balance loss, for 671 billion total and 37 billion active parameters.

Fine-grained routing pays off combinatorially. Choosing 2 of 16 experts allows (162)=120\binom{16}{2}=120 combinations; splitting each expert into four and choosing 8 of 64 allows (648)≈4.4×109\binom{64}{8}\approx4.4\times10^9, at the same parameter count and nearly the same computation. In the bias-based scheme the bias only decides which experts are selected; the gate weights that mix their outputs still come from the unbiased scores, so balancing does not distort what each expert contributes.

What sparsity costs, and what experts learn

DerivationMixtral 8×7B by the numbers
  1. 3⋅4096⋅14,336≈176.2M,2⋅40962⏟WQ,WO+2⋅4096⋅1024⏟WK,WV≈41.9M3\cdot4096\cdot14{,}336\approx176.2\text{M},\qquad\underbrace{2\cdot4096^2}_{W_Q,W_O}+\underbrace{2\cdot4096\cdot1024}_{W_K,W_V}\approx41.9\text{M}

    Mixtral (Jiang et al., 2024) has L=32L=32 layers of width d=4096d=4096, attention with 32 query heads and 8 key–value heads of size 128, a vocabulary of 32,000, and in every layer 8 SwiGLU experts of hidden width 14,336, of which each token uses 2. One expert and one attention sublayer hold

  2. Ntotal≈32 (8×176.2+41.9)M+262M≈46.7BN_{\text{total}}\approx32\,(8\times176.2+41.9)\text{M}+262\text{M}\approx46.7\text{B}

    Add 32 layers of 8 experts, attention, input and output embeddings (2×32,000×4096≈2622\times32{,}000\times4096\approx262M), routers and norms:

  3. Nactive≈32 (2×176.2+41.9)M+262M≈12.9BN_{\text{active}}\approx32\,(2\times176.2+41.9)\text{M}+262\text{M}\approx12.9\text{B}

    Each token runs through 2 experts per layer, so the parameters it actually uses are

  4. 46.7B<8×7B46.7\text{B}<8\times7\text{B}

    These match the published figures: each token has access to 47 billion parameters but uses 13 billion. The name suggests 8×7=568\times7=56 billion, but only the FFNs are replicated; attention and embeddings are shared.

Memory and communication. Active parameters set the FLOPs; total parameters set the memory. Every expert must be stored, and in decoding the tokens of even a moderate batch together touch most experts in every layer, so nearly all expert weights are read from memory at each step although each serves only a few tokens. In training, experts are spread over devices (expert parallelism), and each MoE layer needs two all-to-all exchanges: one to send every token to its experts' devices, one to bring the results back. GShard and Switch were built around this communication pattern; for parallelism in general see Data, Tensor & Pipeline Parallelism.

Scaling. Clark et al. (2022) fitted scaling laws to routed language models across five orders of magnitude, with hundreds of experts and hundreds of billions of parameters. Parameter count and computation acted as two independent axes of improvement, and an effective parameter count put all their models on one scaling curve. Sparse upcycling (Komatsuzaki et al., 2023) starts an MoE from a trained dense checkpoint by copying its FFN into every expert.

Specialization. Experts specialize less by topic than the name suggests. ST-MoE found encoder experts specializing in kinds of tokens, such as punctuation, proper nouns or numbers, and decoder experts showing little specialization. In Mixtral, routing showed no obvious pattern by topic or domain; it followed syntax instead (for example, Python's self or indentation), and consecutive tokens were often sent to the same experts.

Key takeaways

  • An MoE layer routes each token to the top kk of EE expert FFNs, so FFN parameters grow by EE while FLOPs grow by kk; attention and embeddings remain shared.
  • Routers collapse through a rich-get-richer dynamic; the Switch loss αE∑ifiPi\alpha E\sum_if_iP_i is at least α\alpha, with equality for uniform routing when f=Pf=P, and a router z-loss keeps logits small for stable low-precision training.
  • Expert capacity is ⌈kT/E×capacity factor⌉\lceil kT/E\times\text{capacity factor}\rceil; alternatives to token-choice routing with dropping include expert choice, dropless block-sparse kernels, fine-grained and shared experts, and bias-based balancing without an auxiliary loss.
  • Sparse models trade compute for memory and communication: Mixtral 8×7B stores 46.7 billion parameters and uses 12.9 billion per token, and expert parallelism needs two all-to-all exchanges per layer.
  • Experts specialize more in token types and syntax than in topics, and parameter count and computation act as separate axes of scaling.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A Switch layer (top-1) routes a batch of 20482048 tokens across 3232 experts with capacity factor 1.51.5. What is each expert's capacity?

  1. 6464 tokens
  2. 9696 tokens
  3. 192192 tokens
  4. 30723072 tokens
Show the answer

B. 9696 tokens

C=⌈kT/E×1.5⌉=⌈2048/32×1.5⌉=96C=\lceil kT/E\times1.5\rceil=\lceil2048/32\times1.5\rceil=96. An expert receiving more than 96 tokens drops the rest.

Question 2

When is the Switch auxiliary loss αE∑ifiPi\alpha E\sum_if_iP_i smallest, assuming the router's dispatch fractions match its average probabilities?

  1. When every expert receives the same share, Pi=1/EP_i=1/E
  2. When one expert receives every token
  3. When the router probabilities are all close to zero
  4. It is constant, since the PiP_i sum to one
Show the answer

A. When every expert receives the same share, Pi=1/EP_i=1/E

With f=Pf=P the loss is αE∑iPi2\alpha E\sum_iP_i^2, and by Cauchy–Schwarz E∑iPi2≥(∑iPi)2=1E\sum_iP_i^2\ge(\sum_iP_i)^2=1, with equality only for uniform routing.

Question 3

Mixtral 8×7B has 8 experts per layer and routes each token to 2. Why does it have about 47 billion parameters rather than 56 billion, and use about 13 billion per token?

  1. Its experts are smaller than a 7B model's whole FFN
  2. Only the feed-forward layers are replicated eight times; attention and embeddings are shared, and each token uses two experts
  3. Half of the experts are pruned after training
  4. The router's parameters replace the attention layers
Show the answer

B. Only the feed-forward layers are replicated eight times; attention and embeddings are shared, and each token uses two experts

Each expert is a full SwiGLU FFN of about 176 million parameters per layer. Eight of them in 32 layers give 45.1 billion; shared attention (1.3 billion) and embeddings (0.26 billion) bring the total to 46.7 billion, and two experts per token give 12.9 billion active.

Question 4

In auxiliary-loss-free balancing, a per-expert bias is added to the routing scores. What does the bias affect?

  1. Both which experts are selected and how their outputs are weighted
  2. Only the language-modeling loss, through an extra gradient
  3. Which experts are selected; the gate weights still come from the unbiased scores
  4. The capacity factor of each expert
Show the answer

C. Which experts are selected; the gate weights still come from the unbiased scores

The bias is raised for underloaded experts and lowered for overloaded ones after each step, steering the top-kk choice without a gradient that competes with the main loss, and without changing how much each chosen expert contributes.

Further reading

  • R. A. Jacobs, M. I. Jordan, S. J. Nowlan & G. E. Hinton, "Adaptive mixtures of local experts," Neural Computation 3 (1991).
  • N. Shazeer, A. Mirhoseini, K. Maziarz, A. Davis, Q. Le, G. Hinton & J. Dean, "Outrageously large neural networks: The sparsely-gated mixture-of-experts layer," ICLR (2017).
  • W. Fedus, B. Zoph & N. Shazeer, "Switch Transformers: Scaling to trillion parameter models with simple and efficient sparsity," JMLR 23 (2022).
  • B. Zoph et al., "ST-MoE: Designing stable and transferable sparse expert models," arXiv:2202.08906 (2022).
  • A. Q. Jiang et al., "Mixtral of experts," arXiv:2401.04088 (2024).
  • D. Dai et al., "DeepSeekMoE: Towards ultimate expert specialization in mixture-of-experts language models," ACL (2024).