Mixture of Experts: Bigger Models at the Same Compute
How sparse Mixture-of-Experts layers route each token to a few expert networks, why that decouples parameter count from compute, and the practical issues: load balancing, capacity, memory and communication.
Scaling laws say bigger models are better — but in a normal (dense) Transformer every Parameter is used for every token, so doubling parameters doubles the compute per token. A Mixture of Experts (MoE) breaks that link: it holds many parameters but activates only a few for each token. Mixtral 8×7B has ~47B parameters yet uses ~13B per token; DeepSeek-V3 has 671B total with 37B active. Many frontier LLMs are believed to use MoE for exactly this reason: more knowledge capacity at roughly the inference cost of a much smaller model.
How an MoE layer works
In a Transformer block, the feed-forward network (FFN) holds about two-thirds of the parameters. An MoE layer replaces that single FFN with N parallel FFNs — the experts — plus a small linear router (gating network). Attention layers stay shared.
- The router computes a score for every expert from the token's hidden vector x: logits = W_r · x.
- Keep only the top-k experts (e.g. k = 2 of 8) and turn their scores into weights with a Softmax.
- Send the token to those k experts only; the other experts do no work for this token.
- Combine the expert outputs as a weighted sum. Different tokens in the same sentence can use different experts, in every layer.
- y
- output vector of the MoE layer for one token
- Σ_{i ∈ TopK(x)}
- sum over only the k experts selected for token x
- gᵢ(x)
- gate weight of expert i for this token (the chosen weights sum to 1)
- Eᵢ(x)
- output of expert i, an ordinary FFN applied to x
- softmaxᵢ
- softmax over the kept scores, taking entry i
- TopK
- keep the k largest scores, drop (mask out) the rest
- W_r
- router weight matrix: d_model → N experts
- x
- the token's hidden vector
▸Worked example
A short history
- 1991 — Adaptive mixtures of local experts (Jacobs, Jordan, Nowlan & Hinton): a gating network softly combines several small networks.
- 2017 — Sparsely-gated MoE (Shazeer et al.)[1]: noisy top-k gating between LSTM layers with thousands of experts and up to 137B parameters, showing sparse conditional computation works at scale.
- 2020 — GShard[2]: MoE Transformers for translation sharded across 2,048 TPU cores, introducing expert capacity and automatic sharding.
- 2021 — Switch Transformer (Fedus et al.)[3]: simplified routing to top-1, a simple load-balancing loss, bf16 training stability tricks; up to 7× faster pretraining than a dense T5 baseline at equal compute, and trillion-parameter models.
- 2024 — Mixtral 8×7B (Jiang et al.)[4]: open-weights decoder LLM with 8 experts and top-2 routing in every layer; matched or beat Llama 2 70B on most benchmarks while using ~13B active parameters.
Load balancing and capacity
Left alone, routers collapse: a few experts get slightly better early, receive more tokens, get even better, and the rest starve. Training adds an auxiliary load-balancing loss that is minimised when tokens are spread evenly. For efficient batched hardware execution, each expert also gets a fixed capacity — the maximum number of tokens it accepts per batch. Tokens routed to a full expert overflow and are dropped (they skip the layer through the residual connection), so capacity is a trade-off between wasted compute and dropped tokens.
- L_aux
- auxiliary load-balancing loss, added to the main language-model loss
- α
- alpha, small weight of the auxiliary loss (e.g. 0.01)
- N
- number of experts
- Σᵢ
- sum over all experts i = 1 … N
- fᵢ
- fraction of the batch's tokens actually dispatched to expert i
- Pᵢ
- average router probability given to expert i over the batch
- capacity_factor
- slack above a perfectly even split (e.g. 1.0–1.25)
- tokens_per_batch
- tokens processed in the batch
- k
- experts per token (top-k)
▸Worked example
The trade-off: compute vs memory
| Metric | Dense ~13B | Mixtral 8×7B (MoE) | Dense ~47B |
|---|---|---|---|
| Total parameters | 13B | ~47B | 47B |
| Active per token | 13B | ~13B | 47B |
| FLOPs per token | 1× | ≈ 1× | ≈ 3.6× |
| Memory for weights (FP16) | 26 GB | ~94 GB | 94 GB |
| Quality | Baseline | Close to much larger dense models | High |
At scale, experts are spread across GPUs (expert parallelism, a form of Model parallelism), and every MoE layer needs two all-to-all communications — send tokens to their experts' GPUs and bring results back. Fast interconnects are therefore essential. And despite the name, experts rarely become human-readable “topic specialists”: the Mixtral authors found little routing specialisation by domain (math vs biology vs philosophy) and more by syntax and token type, such as Python indentation or common words.
The knobs
- What it is
- How many expert FFNs each MoE layer contains.
- ↑ If you increase it
- More total parameters and capacity at the same per-token compute; quality improves with diminishing returns, but memory, communication and load-balancing difficulty grow.
- ↓ If you decrease it
- Simpler, smaller, easier to serve; approaches a dense model as N → 1.
- Typical values
- 8–64 per layer; some recent models use 100+ small “fine-grained” experts plus shared experts.
- What it is
- How many experts process each token.
- ↑ If you increase it
- Smoother, often better quality and more stable training; compute per token grows linearly with k.
- ↓ If you decrease it
- k = 1 (Switch) is cheapest and simplest, but each token relies on a single expert and routing is noisier.
- Typical values
- 1 (Switch), 2 (GShard, Mixtral), up to ~8 among many fine-grained experts.
- What it is
- Slack on each expert's token buffer relative to a perfectly even split.
- ↑ If you increase it
- Fewer dropped tokens, but more padding, wasted compute and memory.
- ↓ If you decrease it
- Efficient, but more tokens overflow and skip the expert computation, hurting quality.
- Typical values
- 1.0–1.25 in training, higher (≥ 2) or dropless implementations at inference.
- What it is
- Weight of the load-balancing loss relative to the language-modelling loss.
- ↑ If you increase it
- More uniform expert usage, but routing is forced toward uniformity even when some experts would genuinely be better — main loss suffers.
- ↓ If you decrease it
- Router freedom, but risk of collapse onto a few experts.
- Typical values
- ≈ 0.01 (Switch Transformer).
In code: a minimal top-k MoE layer
import torch, torch.nn as nn, torch.nn.functional as F
class MoE(nn.Module):
def __init__(self, d_model=512, d_ff=2048, n_experts=8, top_k=2):
super().__init__()
self.top_k = top_k
self.router = nn.Linear(d_model, n_experts, bias=False)
self.experts = nn.ModuleList(
nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model))
for _ in range(n_experts))
def forward(self, x): # x: (tokens, d_model)
logits = self.router(x) # (tokens, n_experts)
top_w, top_i = logits.topk(self.top_k, dim=-1)
top_w = F.softmax(top_w, dim=-1) # renormalise over chosen experts
out = torch.zeros_like(x)
for e, expert in enumerate(self.experts):
tok, slot = (top_i == e).nonzero(as_tuple=True)
if tok.numel():
out[tok] += top_w[tok, slot, None] * expert(x[tok])
# Switch-style load-balancing loss (using each token's top-1 choice)
probs = F.softmax(logits, dim=-1)
frac = F.one_hot(top_i[:, 0], probs.size(-1)).float().mean(0)
aux = probs.size(-1) * (frac * probs.mean(0)).sum()
return out, aux # add 0.01 * aux to the main loss▸Go deeper: why sparsity is a good bet
Compute-optimal scaling says loss falls with both parameters and training tokens. MoE lets you increase the parameter count — and therefore the model's capacity to store facts and patterns — without increasing the FLOPs spent on each token, so for a fixed training budget an MoE usually reaches a lower loss than a dense model. Variants keep evolving: fine-grained experts (many small experts, higher top-k), shared experts that every token uses for common knowledge, auxiliary-loss-free balancing with per-expert bias terms, and expert-choice routing, where experts pick their tokens instead of tokens picking experts[5].
Quiz
References
- [1]Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts LayerPaperShazeer et al.2017arxiv.org
- [2]GShard: Scaling Giant Models with Conditional Computation and Automatic ShardingPaperLepikhin et al.2020arxiv.org
- [3]Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient SparsityPaperFedus et al.2021arxiv.org
- [4]Mixtral of ExpertsPaperJiang et al.2024arxiv.org
- [5]Mixture of Experts ExplainedArticleHugging Face (Sanseviero et al.)2023huggingface.co