Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Mixture of Experts,
explained.
A hospital doesn't send every patient to every doctor — a receptionist points each one to the right specialist. This idea, applied to neural networks, is why a model can carry hundreds of billions of parameters yet stay cheap to run: for any given token, almost all of it stays asleep.
What changes here: size stops implying cost
Rung 1, so the comparison is against the dense network every other ladder assumes. In a dense model, every parameter participates in every token's computation. That means the two things you most want to separate are welded together: to give the model more capacity you must also make every forward pass more expensive, for training and for every request you ever serve.
The change is conditional computation. Replace one large feed-forward layer with many expert sub-networks plus a small gating network that reads each token and selects a few experts to handle it. Only the selected experts run. Total parameter count can then grow by a large factor while the arithmetic per token stays roughly flat — the model is enormous in storage and ordinary in cost, and capacity and compute are decoupled.
Two failure modes are inherent to that design and both are addressed here, because neither is optional. The first is collapse: the gate has every incentive to converge on a few experts, since the experts it picks get trained and improve, so the rest stay bad and are never picked. The fix is an auxiliary loss that penalises unbalanced routing, plus noise in the gate so alternatives get sampled. The second is the shrinking batch: if a batch of tokens is split across many experts, each expert sees only a sliver, and the matrix multiplications that hardware is fast at become small and inefficient. Both are consequences of sparsity rather than bugs in this implementation, and both reappear in every rung above.
The dense-model tax
In a normal dense network, every parameter is used for every input. That's a hard tax: to make the model twice as capable you double the parameters, and now every single token costs twice as much compute. Capacity and cost are chained together, so scaling up gets expensive fast.
But intuitively, that's wasteful. A token about French poetry and a token about Python syntax probably don't need the same billions of parameters. What if different parts of the model handled different kinds of input?
The idea: many specialists, one receptionist
A Mixture of Experts replaces one big dense layer with many smaller sub-networks — the experts — plus a small gating network that acts as a receptionist. For each token, the gate picks just the top one or two experts to handle it. The rest sit idle for that token.
So the model can have dozens or hundreds of experts — an enormous total parameter count — while any single token only ever touches a couple of them. This is sparse activation: lots of capacity, little compute per token.
The gating network
The gate is itself learned. For each token it scores every expert, keeps the highest few (top-k routing, often k=1 or 2), and sends the token only to those. Their outputs are blended, weighted by the gate's scores. Over training, the gate discovers which experts are good at what and routes accordingly.
Only the two lit experts run. The other N−2 — the bulk of the model's parameters — cost nothing for this token.
The catch: load balancing
Left to its own devices, the gate cheats. It finds a few experts that work well early on and keeps sending everything to them, while most experts starve — never getting enough tokens to learn anything. A model with 128 experts that only ever uses 4 is mostly dead weight.
The fix is an auxiliary load-balancing loss that penalizes lopsided routing and nudges the gate to spread tokens across all experts. Getting this balance right is one of the central engineering challenges of training MoE models.
Why it still matters
Mixture of Experts is one of the main levers behind the frontier. Open models like Mixtral and DeepSeek are MoE, and several leading proprietary models are widely believed to be as well. When you hear a model has "hundreds of billions of parameters" but runs surprisingly cheaply, MoE is usually why — only a slice of it wakes up for each token.
The deeper idea — conditional computation, spending compute only where it's needed — is one of the most powerful tools we have for scaling models without scaling their bills. This paper is where it went from theory to practice.
How the sparsely-gated MoE layer runs, step by step
The 2017 paper by Shazeer and colleagues puts its mixture-of-experts layer inside recurrent models, not Transformers: in its language models the layer sits between two stacked LSTM layers, and in its translation models inside the encoder and decoder. One pass through the layer goes like this.
- Batch every time step together. The LSTM below is unrolled first, and its outputs at all time steps of all sequences reach the MoE layer at once, as one large batch. Applying the layer convolutionally across time multiplies the number of examples each expert can see by the sequence length.
- Score every expert. The gate computes one clean score per expert, x·Wg, and a second projection, x·Wnoise, that sets how much Gaussian noise to add to each expert's score during training. A softplus keeps the noise scale positive.
- Keep the top k. All but the k largest noisy scores are set to −∞, and a softmax over the survivors gives weights that sum to 1. Every other expert gets exactly zero weight and is never computed. The paper uses small values of k.
- Dispatch across devices. The LSTM layers and the gate are replicated with data parallelism, each of d devices processing its own batch of b examples. The experts are not replicated: each lives on one device, and every device sends each example to the devices holding its chosen experts. An expert therefore receives about k·b·d/n examples from all devices combined, rather than the k·b/n it would get from one device's batch. This is the paper's answer to what it calls the shrinking batch problem.
- Compute and combine. Each expert is a small feed-forward network with one ReLU hidden layer. The outputs are sent back, multiplied by their gate weights and summed: y = Σ G(x)i·Ei(x).
- Add two balancing losses. Over each batch, an expert's importance is the sum of its gate weights, and the importance loss is a weight times the squared coefficient of variation of those sums. Equal importance can still hide unequal example counts, so a second load loss uses the noise to compute a smooth probability that each example selects each expert, and penalizes the squared coefficient of variation of the summed probabilities.
- Backpropagate through the gate. Gradients reach Wg and Wnoise through the gate weights of the selected experts and through the balancing losses. Experts that an example did not select get no gradient from it.
- Go hierarchical for thousands of experts. For the largest layers, a primary gate picks a few groups of experts and a secondary gate inside each group picks experts, so no single softmax has to span tens of thousands of options.
Making it efficient on 2017 hardware
The binding constraint was arithmetic per byte moved: an expert does little computation for each input and output it exchanges over the network, so the paper makes the experts' hidden layers large relative to their inputs and outputs, and batches examples across time steps and devices. The largest model, with 131,072 experts and about 137B parameters, trained on a corpus of about 100 billion words of Google News.
Noisy top-k gating and the importance loss
Ei— expert i, one of n;G(x)i— its gate weight, zero for all but k experts, so the sum runs over only k terms in practice.KeepTopK— leaves the k largest scores and sets the rest to −∞, so the softmax gives them exactly 0.Softplus((x·Wnoise)i)— a positive noise scale learned per expert from the input. Noise lets close runners-up sometimes win, and it is what makes the load loss differentiable.CV— the coefficient of variation, standard deviation over mean, across experts for a batch X;wimportance— a hand-set weight.
At the extremes: k = n turns the layer back into a dense mixture with every expert computed. With the noise scale at zero the gate is deterministic and the smooth load estimate disappears. CV = 0 means every expert collected the same total gate weight, and one expert taking everything maximizes it. The load loss swaps G for P(x, i) = Φ(((x·Wg)i − kth_excluding(H(x), k, i)) / Softplus((x·Wnoise)i)): the probability that expert i stays in the top k when only its own noise is redrawn.
What the 2017 MoE models achieved
The comparisons hold computation per time step roughly fixed and grow only the expert count, so any gain is bought with parameters, not compute.
| Task | MoE result | Comparison |
|---|---|---|
| 1 Billion Word benchmark, test perplexity | 28.0 after 10 epochs, with about 4.4B parameters | Best published LSTM: 30.6 after 100 epochs, at similar computation per step |
| 100-billion-word Google News corpus | 65,536 experts, about 68B parameters: 39% lower perplexity | Dense model with matched computation |
| Same corpus, 131,072 experts, about 137B parameters | Slightly worse than 65,536 experts | The authors suggest too much sparsity |
| WMT'14 English to French and to German | Better BLEU than GNMT on both | GNMT, the strong recurrent baseline, at higher computation per token |
The layers held up to 131,072 experts and up to 137B parameters while beating strong dense baselines at a fraction of the compute. Inspecting the gate showed experts specializing by syntax and meaning, with individual experts drawing tokens from a coherent topic. The same capacity-for-compute trade reads clearly in later terms: a Mixtral-8×7B-shaped model stores about 47B parameters but runs about 13B per token, and giving it 64 experts would raise storage to about 363B with the same compute per token. The Switch Transformer later simplified routing to one expert per token and passed a trillion parameters.
The balancing ablation
The paper trained the same model with each balancing loss switched on and off. With neither loss, test perplexity was markedly worse, about 39.8 against about 35.6 with them, and the busiest expert received roughly 17.8 times the average load. Either loss alone recovered most of the gap, and using both gave the evenest load. The negative result at 131,072 experts is the other limit: past some point, extra sparsity stopped buying quality.
What the authors admit, and what happened next
The paper is direct about the costs sparsity introduces: routing tokens to experts that live on different devices is a communication problem, so the gains are contingent on the interconnect, and the auxiliary balancing loss is a term that is explicitly fighting the objective you actually care about — it exists to keep the mechanism healthy, not to make the model better at language.
One belief it establishes was later overturned. Routing to at least two experts was argued to be necessary for the gate to receive a useful learning signal, on the reasoning that you need to compare alternatives to know a choice was good. Rung 2 shows a single expert per token works, which removes roughly half the cost and most of the complexity.
How it held up: it is the architectural basis of the current frontier. The models at the top of this ladder and several on the open-weights ladder are mixtures of experts, and the reason is exactly the decoupling above — it is the only known way to buy capacity without buying proportional serving cost. What has been revised is every mechanism: top-1 replaced top-k, and rung 3 removes the auxiliary loss itself in favour of something that does not compete with the language objective.
Count the parameters that actually fire
"Hundreds of billions of parameters but runs cheap" is a claim you can verify with multiplication. This computes a Mixtral-8×7B-shaped model's total parameters (capacity) and active parameters per token (compute) from first principles — and lands on the real ~47B / ~13B. Then crank the expert count to 64 and watch total explode past 360B while active never budges off 13B. That flat column is conditional computation; capacity and cost, finally unchained. Change E, k, or the dimensions.
Write the body of active_params. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 5 assertions below — they start red.
- Storing more experts raises total capacity
- Active params depend on top-k, not the expert count
- Only a fraction of the model fires per token
- Adding experts raises capacity but not per-token compute
- A Mixtral-shaped config lands near 47B total / 13B active
Questions people ask about Mixture of Experts
How does noisy top-k gating work?
For each input, the gate computes one score per expert as a linear function of the input, then adds Gaussian noise whose scale is itself a learned function of the input, passed through a softplus so it stays positive. It keeps the k highest noisy scores, sets the rest to minus infinity, and applies a softmax, so exactly k experts get nonzero weights that sum to one. Only those k experts are computed, and their outputs are added together, weighted by the gate. The noise matters in two ways: it lets near-ties between experts go either way during training, which spreads traffic, and it makes the load-balancing loss smooth enough to differentiate.
What is the load-balancing loss in the original mixture-of-experts paper?
There are two. The importance loss sums each expert's gate weights over a batch and penalizes the squared coefficient of variation of those sums, scaled by a hand-set weight, so no expert collects much more total weight than the others. But equal total weight can hide unequal traffic, for example one expert receiving a few examples with large weights and another receiving many with small weights, so a second load loss balances the number of examples. Counting examples is not differentiable, so the paper replaces the count with a probability: given the noise, the chance that each expert stays in the top k for each example, computed with the normal CDF.
What is the shrinking batch problem in mixture of experts?
If a batch of b examples is split among n experts and each example uses k of them, each expert sees only about k times b divided by n examples. With thousands of experts that is a handful per expert, and small matrix multiplications waste the hardware. The 2017 paper fixed this two ways. It mixed data and model parallelism: the ordinary layers and the gate are copied across d devices, each with its own batch, but each expert exists only once, so it receives examples from all devices, about k·b·d/n in total. And it applied the MoE layer to all time steps of the LSTM at once, multiplying the batch by the sequence length.
How large were the mixture-of-experts models in the 2017 paper?
The largest had 131,072 experts and about 137 billion parameters, trained on a corpus of roughly 100 billion words from Google News. To route among that many experts it used a hierarchical gate: a primary gate chooses among groups, and a secondary gate chooses experts within each group. Quality kept improving with expert count up to 65,536 experts, about 68 billion parameters, where perplexity was 39% below a dense model of matched computation, and then got slightly worse at 131,072, which the authors suggest may reflect too much sparsity. On the standard 1-billion-word benchmark, models of about 4 billion parameters beat the best published LSTM results at similar computation.
Why did the 2017 paper route each token to more than one expert?
The paper used small values of k greater than one, and the later Switch Transformer paper summarized its reasoning as a conjecture that a router needs to compare at least two experts to receive a useful gradient: with a single choice, the gate weight is the only signal about whether that choice was good. Switch showed in 2021 that top-1 routing trains well. But top-1 did not become the norm. Mixtral routes each token to 2 of 8 experts, and DeepSeek-V3 to 8 of 256 routed experts plus one shared expert. Routing to more than one expert turned out to be a quality and cost trade-off, not a training necessity.
4 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
Sixteen devices each hold a batch of 1,024 examples; there are 256 experts and k = 4. How many examples does each expert see with and without the paper's mixed parallel scheme?
Show answer
Without it, from one device's batch: k·b/n = 4 × 1,024 / 256 = 16. With experts shared across devices: k·b·d/n = 4 × 1,024 × 16 / 256 = 256, sixteen times more, enough to keep each expert's matrix multiplies efficient.
Over a batch, four experts collect total gate weights of 6, 1, 1 and 0. What is the squared coefficient of variation, and what is it for an even split?
Show answer
Mean 2; deviations 4, −1, −1, −2, so the variance is (16 + 1 + 1 + 4)/4 = 5.5 and the standard deviation ≈ 2.35. CV ≈ 1.17 and CV^2 ≈ 1.38. An even 2, 2, 2, 2 gives 0, the minimum of the importance loss.
Noisy scores for four experts are 1.2, 3.0, 2.9 and −0.5, with k = 2. What are the gate weights, and how does an unpicked expert ever get trained?
Show answer
Keep 3.0 and 2.9; the softmax over them gives e^0.1/(1 + e^0.1) ≈ 0.525 and 0.475, and the others exactly 0. Noise is redrawn every step, so a close runner-up is sometimes pushed into the top k, and that is when it receives gradient.
Why can the load loss not simply count how many examples chose each expert?
Show answer
A count is a step function of the parameters: small changes to Wg do not change it until some example flips, so its gradient is zero almost everywhere. With Gaussian noise, the probability that an expert stays in the top k is the normal CDF Φ of a smooth expression, which does have a useful gradient.
One model, many experts
Sparsity: route each token to a few experts and buy parameter count without paying for it at inference. 2017 idea, 2026 frontier default.
- 1Mixture of Experts2017
- 2Switch Transformer2022
- 3DeepSeek-V32024
- 4DeepSeek-V42026
- 5Qwen4-Coder2026
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- BERTThe paper that made "pre-train once, fine-tune anywhere" the default for NLP. Bidirectional context, masked language modeling, next-sentence prediction, the [CLS]/[SEP] tokens, and the GLUE sweep — explained with analogies, not just equations.Read →
- Chain-of-Thought PromptingShow a model a few worked examples with their reasoning and it starts solving problems it used to fail. Why reasoning emerges only at scale, the GSM8K jump, zero-shot "Let's think step by step", and how CoT seeded modern reasoning models.Read →
- LoRAThe paper that made fine-tuning affordable. Freeze the giant pretrained model and train two tiny low-rank matrices instead — up to 10,000x fewer trainable parameters, no extra inference latency, and swappable per-task adapters. The road to QLoRA and PEFT.Read →
- Direct Preference OptimizationRLHF without the RL. Align a model to human preference pairs with one simple classification-style loss — no separate reward model, no unstable reinforcement learning. Why "your LM is secretly a reward model", and how DPO became the default alignment method.Read →
- ChinchillaThe compute-optimal scaling law that said models were too big. Parameters and training tokens should scale together — ~20 tokens per parameter — so a 70B model trained on 1.4T tokens beat the 280B giants. Why every model since trains on trillions of tokens.Read →