Level 3 In-Depth AI · Transformers and Language Models
Mixture of Experts
Instead of one big feed-forward block that every token passes through, keep many smaller "experts" and let a router send each token to just a few. The model gets the knowledge capacity of a huge network at the compute cost of a small one.
- Level
- ●●●●● Advanced
- Reading
- 11 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 28 concepts →
- Quiz
- 5 questions ↓
Read first
The TransformerThis leads to
—The full path from zero — 28 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- Mixture of Experts
Read them roughly in this order. See it on the concept map →
Why it matters
In a standard ("dense") The Transformer, every token passes through every weight. Make the model twice as big and every token costs twice as much to process, in training and at inference. Scaling laws say bigger models are better, so this link between size and cost is painful.
A mixture of experts (MoE) breaks that link. Each Transformer block's feed-forward network (the MLP) is replaced by many parallel copies, the experts, plus a small router that picks a few experts for each token. All the experts together hold a lot of parameters and therefore a lot of knowledge, but any single token only runs through, say, 2 of 8, or 8 of 256. Such a network is called a sparse model: most of it sits idle for any given token.
The numbers are striking. Mistral AI's Mixtral 8x7B (December 2023) has about 47 billion parameters in total but uses about 13 billion for each token, and matched or beat the dense Llama 2 70B on most of the benchmarks in its paper. DeepSeek-V3 (December 2024) has 671 billion parameters but activates only 37 billion per token. Many of the strongest open models of 2024–2025 (DeepSeek-V3 and R1, Qwen3's largest models, Llama 4) are MoEs, and several frontier closed models are widely believed to be too, although their makers have not published details.
The intuition
Think of a large hospital. There is no single doctor who knows everything; there are dozens of specialists. A triage nurse at the door looks at each patient and sends them to the two most relevant specialists. The hospital as a whole has enormous expertise, but each patient only takes up the time of two doctors.
In an MoE layer:
- The experts are the specialists: ordinary feed-forward networks, each with its own weights.
- The router (also called the gate or gating network) is the triage nurse: a tiny linear layer that scores every expert for the current token.
- Top-k routing sends the token to the highest-scoring experts and mixes their outputs, weighted by the router's scores.
The specialists are not assigned by humans. Nobody tells expert 3 to handle chemistry. The router and the experts are trained together, by ordinary Backpropagation, and the division of labour emerges. In practice it is often less tidy than the hospital picture: studies of Mixtral found experts specialising more by token type and syntax (punctuation, code indentation, certain word pieces) than by topic.
Key idea An MoE layer replaces one feed-forward block with many experts and a router that picks the top for each token. Total parameters (memory, knowledge capacity) and active parameters (compute per token) become two different numbers.
How it works
The router
For a token whose hidden vector is (length ), the router is a single weight matrix of size for experts. It produces one score, a logit, per expert, turned into probabilities by a softmax:
Keep the largest, renormalise them to sum to 1, and combine the chosen experts' outputs:
Here is expert 's output (a normal two-layer MLP) and is its gate weight. The unchosen experts are never run. (Some models, such as Switch Transformer, skip the renormalisation; details vary.)
Worked example. Four experts, top-2. The router gives one token the logits . Exponentiating: , , , , total . Probabilities: . The top two are experts 1 and 2. Renormalised: and . So
and experts 3 and 4 do no work for this token. Because the output depends on and , gradients flow into the router and teach it which experts help.
Total versus active parameters
For Mixtral 8x7B: each layer has 8 experts and uses 2. Attention layers, embeddings and the router are shared by all tokens. Total parameters are about 46.7 billion, but the parameters each token actually uses, its active parameters, are about 12.9 billion. (The name "8x7B" is a little misleading: it is not 8 separate 7B models, because only the MLPs are duplicated, so the total is less than 56B.)
This creates a trade-off:
- Compute per token (and so training cost and generation speed) follows the active count, so Mixtral computes like a 13B model.
- Memory follows the total count: all 47B parameters must be loaded, because any token might need any expert. Mixtral needs roughly the memory of a 47B dense model.
MoEs therefore shine when memory is plentiful relative to compute: in data centres serving many users at once, where batches are big enough to keep every expert busy. On a single consumer GPU with little memory, a dense model of the same total size is often impossible and a smaller dense model may be a better fit.
Load balancing
Left alone, routing collapses. Early in training a few experts happen to be slightly better, so the router sends them more tokens, so they train faster and get better, so they get even more tokens. The other experts starve, and the model degenerates into a small dense one. Hardware suffers too: if one expert receives half the tokens, its GPU becomes the bottleneck while the others idle.
The classic fix is an auxiliary load-balancing loss added to the training loss. In the Switch Transformer form, with experts, let be the fraction of tokens in the batch routed to expert , and the average router probability given to expert . Then
with a small coefficient (0.01 in the Switch paper). It is smallest when both are spread evenly (, giving before multiplying by ) and grows when tokens pile onto experts that also get high probability. The term itself has no gradient (counting is not differentiable), but does, so the router learns to spread probability out.
Related mechanisms:
- Expert capacity: each expert accepts at most a fixed number of tokens per batch (the capacity factor times its fair share, for example 1.25 ×). Overflow tokens are dropped from that layer and pass through only the residual connection.
- Noisy routing: adding noise to router logits during training, as in the 2017 paper, encourages exploration.
- Auxiliary-loss-free balancing: DeepSeek-V3 adds a per-expert bias to the routing scores (used only for choosing experts, not for weighting them) and nudges it up for under-used experts and down for over-used ones after each step, avoiding the quality cost of a strong auxiliary loss.
Fine-grained and shared experts
The DeepSeekMoE design, used in DeepSeek-V2 and V3, makes experts smaller and more numerous (V3 has 256 routed experts per layer, of which 8 are chosen per token) and adds shared experts that every token always uses. The shared experts capture common knowledge, so the routed ones can specialise. Many 2025 MoEs follow this pattern of many small experts with top-8 or so.
Training and serving at scale
With hundreds of experts the model doesn't fit on one GPU. Expert parallelism places different experts on different GPUs and sends each token to wherever its experts live, then sends the results back. This "all-to-all" communication is a major engineering cost of MoE, and much of DeepSeek-V3's report is about hiding it behind computation. MoEs were historically known for unstable training (sudden loss spikes), addressed with tricks such as computing the router in 32-bit precision and the "router z-loss" from Google's ST-MoE work.
In code
A complete top-k MoE layer in PyTorch, with the Switch-style load-balancing loss.
import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)
class MoE(nn.Module):
def __init__(self, d=64, d_ff=256, n_experts=8, k=2):
super().__init__()
self.k, self.n = k, n_experts
self.router = nn.Linear(d, n_experts, bias=False) # one score per expert
self.experts = nn.ModuleList(
nn.Sequential(nn.Linear(d, d_ff), nn.GELU(), nn.Linear(d_ff, d))
for _ in range(n_experts))
def forward(self, x): # x: (tokens, d)
probs = F.softmax(self.router(x), dim=-1) # (tokens, n_experts)
top_p, top_i = probs.topk(self.k, dim=-1) # best k experts per token
top_p = top_p / top_p.sum(-1, keepdim=True) # renormalise their weights
out = torch.zeros_like(x)
for e in range(self.n): # each expert sees only its tokens
tok, slot = (top_i == e).nonzero(as_tuple=True)
if len(tok):
out[tok] += top_p[tok, slot, None] * self.experts[e](x[tok])
# Switch-style load-balancing loss: n * sum_e (fraction routed to e) * (mean prob of e)
frac = F.one_hot(top_i[:, 0], self.n).float().mean(0)
aux = self.n * (frac * probs.mean(0)).sum()
return out, top_i, aux
moe = MoE()
x = torch.randn(1000, 64)
y, top_i, aux = moe(x)
print("output shape:", tuple(y.shape))
print("tokens per expert:", torch.bincount(top_i.flatten(), minlength=8).tolist())
print(f"load-balancing loss: {aux.item():.3f} (1.0 = perfectly balanced)")
total = sum(p.numel() for p in moe.parameters())
active = sum(p.numel() for p in moe.experts[0].parameters()) * moe.k + moe.router.weight.numel()
print(f"parameters: {total:,} total, {active:,} used per token")
# output shape: (1000, 64)
# tokens per expert: [248, 251, 240, 235, 228, 281, 252, 265]
# load-balancing loss: 1.003 (1.0 = perfectly balanced)
# parameters: 265,216 total, 66,688 used per token
At random initialisation the routing is nearly balanced. During training you add alpha * aux (for example 0.01 * aux) to the language-model loss to keep it that way. The loop over experts is the clearest way to write it; real implementations sort tokens by expert and use batched or grouped matrix multiplications, and spread experts across GPUs.
Common pitfalls
- Comparing MoE and dense models by total parameters. Compare by active parameters for compute and speed, by total parameters for memory. "A 47B model as fast as a 13B one" and "a 13B-compute model that needs 47B of memory" are both true.
- Routing collapse. If a few experts receive almost all tokens, check that the auxiliary loss is applied and not too small.
- Fine-tuning instability. MoEs have been reported to overfit more easily than dense models during fine-tuning. Freezing the router, or using a higher dropout, can help.
- Small-batch inference. With one user, each token needs different experts, so you load many experts' weights for little work. MoEs are most efficient at high batch sizes.
- Token dropping at evaluation time. Capacity limits tuned for training can silently drop tokens at inference. Use a higher capacity factor, or none, at inference.
Watch out "Experts" are not topic specialists you can inspect or swap out. The division of labour is learned and often unintuitive. Don't build product logic on the assumption that expert 5 "is the coding expert".
Variations
- Top-1 routing (Switch Transformer): cheapest, one expert per token.
- Expert choice routing: experts pick their top tokens instead of tokens picking experts, guaranteeing perfect balance.
- Shared plus routed experts (DeepSeekMoE): a few always-on experts plus many small routed ones.
- MoE in attention and mixture-of-depths (letting some tokens skip whole layers) apply the same "conditional computation" idea elsewhere.
- Upcycling: start an MoE by copying a trained dense model's MLP into every expert, then continue training.
- MoE pairs naturally with the inference tricks in The KV Cache and Fast Inference, Quantization and Distributed Training.
A bit of history
The idea is old. Robert Jacobs, Michael Jordan, Steven Nowlan and Geoffrey Hinton introduced "adaptive mixtures of local experts" in 1991, with a gating network choosing among small expert networks. The modern form arrived in 2017 with Noam Shazeer and colleagues at Google ("Outrageously Large Neural Networks"), who put a sparsely gated layer with up to thousands of experts between LSTM layers, used noisy top-k routing and a balancing loss, and trained models with up to 137 billion parameters.
Google pushed MoE into Transformers with GShard (2020, 600 billion parameters for translation) and the Switch Transformer (2021, top-1 routing, up to 1.6 trillion parameters, with up to 7× faster pretraining than a dense T5 baseline at the same compute). Open MoE language models became mainstream with Mistral AI's Mixtral 8x7B in December 2023, and DeepSeek-V2 and V3 (2024) showed MoE at frontier scale with fine-grained experts and much lower training cost than comparable dense models. By 2025 MoE had become a default architecture for very large open models.
Try it
- Change
kto 1 and then 4. How do "used per token" parameters change? What stays the same?- Make routing unbalanced: replace the input with
x = torch.randn(1000, 64) + 0.5and addmoe.router.weight.data[0] += 0.05before the forward pass. Print tokens per expert and the auxiliary loss. How far above 1 does the loss rise, and which expert is overloaded?- By hand: with router logits and top-2, which experts are chosen and what are their gate weights after renormalisation?
Hint for 3: the two experts with logit 1.0 tie for second place;
topkpicks one of them.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Mixture of Experts Explained
A thorough illustrated tour of MoE: routing, load balancing, capacity, training and serving, and the history from 1991 to Mixtral.
Mixtral of Experts
An open sparse mixture-of-experts LLM.
Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity
Routes each token to a single expert (top-1), with a simple auxiliary load-balancing loss and expert capacity.
Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer
The paper that brought mixture of experts to deep learning: a trainable gate picks a few of thousands of experts per token, with a load-balancing loss.
DeepSeek-V3 Technical Report
A 671B-parameter MoE with 37B active per token, fine-grained and shared experts, and auxiliary-loss-free load balancing. The base model of DeepSeek-R1.
Stanford CS336: Language Modeling from Scratch
Build every part of an LLM yourself, from tokenizer to training, scaling and alignment.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/mixture-of-experts.md