Search

Search papers and lessons

Mixture of Experts

Level 4 · 10 min read

A mixture of experts layer holds many sub-networks and a router that sends each input to only a few of them, so the model can grow its parameter count without growing the compute per input.

On this page

  • Colour = topic mix
  • Linear algebra
  • Neural network basics
  • Discrete math
  • Architectures
  • Efficiency
  • Probability
  • Sign in to see your progress

TL;DR

A mixture of experts (MoE) layer replaces one big network with many smaller ones, called experts, and a small router network. For each input the router produces a score for every expert, and only the top few experts run. Their outputs are combined using the router's weights. The model can hold many times more parameters than a dense model, but each input pays for only the few experts it uses. The cost is that the router must be trained to spread the work evenly, or some experts go unused.

Where you'll see it: inside the feedforward blocks of large language models such as Mixtral and Switch Transformer, and in the scaling recipes that let labs grow model capacity faster than their compute budget.

Intuition

A clinic with specialists

Picture a hospital with a front desk and twenty specialists. The desk does not send every patient to every doctor. It looks at the patient's symptoms and sends them to the two specialists most likely to help, and it combines their advice. The hospital has the knowledge of twenty doctors, but each patient only occupies the time of two.

A dense network works the other way. Every input passes through every weight, so doubling the number of parameters roughly doubles the work per input. A mixture of experts breaks that link. Parameters can keep growing, because each new expert only costs time on the inputs routed to it.

flowchart LR
  X[Input token] --> R[Router scores each expert]
  R -->|top 2 of 8| E2[Expert 2]
  R -->|top 2 of 8| E5[Expert 5]
  R -.->|not selected| E1[Experts 1, 3, 4, 6, 7, 8 idle]
  E2 --> S[Weighted sum]
  E5 --> S
  S --> Y[Output]

Why the router should be soft

The router does not make a hard choice that cannot be trained. It produces a set of weights that sum to one, so the output is a smooth blend of the chosen experts. Gradients can then flow back into the router, and the router learns which expert suits which kind of input. The plot below shows how the weight on one expert rises as its score grows, when two other experts have scores of zero.

−2−10123400.20.40.60.81router score for expert 1gate weight
  • weight on expert 1
With the other two experts scored 0, a higher score gives expert 1 a larger share of the output. Near 0 the router is undecided; far above 0 it is close to a hard choice.

The math

The dense mixture

Let there be EE experts, each a function fi(x)f_i(\mathbf{x}) mapping an input x\mathbf{x} to an output vector. The router computes a score for each expert, z(x)=Wgx\mathbf{z}(\mathbf{x}) = W_g \mathbf{x}, where WgW_g is a learned matrix with one row per expert. The gate is the Softmax of those scores:

gi(x)=exp⁡(zi(x))∑j=1Eexp⁡(zj(x)).g_i(\mathbf{x}) = \frac{\exp\big(z_i(\mathbf{x})\big)}{\sum_{j=1}^{E} \exp\big(z_j(\mathbf{x})\big)}.

The layer output is the weighted sum

y(x)=∑i=1Egi(x) fi(x).y(\mathbf{x}) = \sum_{i=1}^{E} g_i(\mathbf{x})\, f_i(\mathbf{x}).

Here x\mathbf{x} is the input vector, fif_i is expert ii, and gi(x)g_i(\mathbf{x}) is its share of the output. The gates are positive and sum to one, so yy is a convex combination of the expert outputs. This is fully differentiable, but it runs every expert on every input, so it saves no compute. It is only useful as a baseline.

Sparse top-k gating

The sparse version keeps only the kk largest scores and sets the rest to minus infinity before the softmax, so their gates become exactly zero:

G(x)=softmax(TopK(Wgx,k)),y(x)=∑i∈TopKGi(x) fi(x).G(\mathbf{x}) = \mathrm{softmax}\big(\mathrm{TopK}(W_g \mathbf{x}, k)\big), \qquad y(\mathbf{x}) = \sum_{i \in \mathrm{TopK}} G_i(\mathbf{x})\, f_i(\mathbf{x}).

Only kk experts run, so the compute per input is roughly kk expert evaluations, whatever EE is. Shazeer and colleagues in 2017 also added tunable noise to the scores during training, so that the router explores different experts, and they added an importance loss to balance the load. Most later systems use plain top-kk with an auxiliary loss, which is the version described here.

Gradients still flow through the surviving gate values, so the router learns, even though the choice of which experts run is discrete. With k=1k = 1 this formula would give a gate of exactly 1 and no gradient to the router, so top-1 systems such as Switch Transformer instead take the softmax over all EE scores and multiply the chosen expert's output by its (unrenormalised) probability.

The load-balancing loss

Without any intervention, the router tends to send most inputs to a few favourite experts. Those experts get trained more, become better, and attract even more inputs. The rest starve. To prevent this, Fedus and colleagues added an auxiliary loss. Let ϕi\phi_i be the fraction of tokens in a batch whose top choice is expert ii, and let PiP_i be the average gate probability that the router gives expert ii over the batch. With EE experts and a small coefficient α\alpha, the loss is

Laux=α E∑i=1Eϕi Pi.\mathcal{L}_{\text{aux}} = \alpha\, E \sum_{i=1}^{E} \phi_i\, P_i.

The loss is built so that perfectly uniform routing, ϕi=Pi=1/E\phi_i = P_i = 1/E, is the balanced target: there the sum equals 1/E1/E and the loss equals its baseline value α\alpha. Skewed routing, where the same experts get both a large share of tokens and a large gate probability, pushes the sum above that baseline. This is a heuristic that encourages balance, not a strict minimum over arbitrary distributions. The loss is added to the main training loss, and its gradient pushes the router toward spreading tokens evenly. The Switch Transformer paper uses α=0.01\alpha = 0.01.

Worked examples

Example 1: one token through a top-2 layer

A layer has three experts and k=2k = 2. For one input x\mathbf{x}, the router produces scores z=(2.0, 0.5, 1.0)\mathbf{z} = (2.0,\ 0.5,\ 1.0). The three expert outputs at this input are f1=3f_1 = 3, f2=−5f_2 = -5 and f3=1f_3 = 1.

Example
Routing one token
  1. Full softmax of the scores. The exponentials are e2.0≈7.389e^{2.0} \approx 7.389, e0.5≈1.649e^{0.5} \approx 1.649 and e1.0≈2.718e^{1.0} \approx 2.718. Their sum is 11.75611.756. So the gates are g=(0.6285, 0.1402, 0.2312)g = (0.6285,\ 0.1402,\ 0.2312).
  2. Top-2 selection. The two largest scores are for experts 1 and 3. Expert 2 is dropped, so it is not evaluated at all.
  3. Renormalise the two kept gates. Their sum is 0.6285+0.2312=0.85970.6285 + 0.2312 = 0.8597. The weights become 0.6285/0.8597≈0.73110.6285 / 0.8597 \approx 0.7311 for expert 1 and 0.2312/0.8597≈0.26890.2312 / 0.8597 \approx 0.2689 for expert 3.
  4. Combine the expert outputs: y=0.7311×3+0.2689×1=2.193+0.269=2.462y = 0.7311 \times 3 + 0.2689 \times 1 = 2.193 + 0.269 = 2.462.

Interpretation: the output is about 2.46. It is close to expert 1's answer, because the router favours it, but expert 3 still contributes. Expert 2 gave the most extreme output, −5-5, and it had no effect at all, because the router did not select it. The compute spent was two expert calls out of three.

Example 2: parameters versus compute

Take a Transformer layer with model width d=1024d = 1024 and a feedforward hidden size of 40964096. A dense feedforward block has two weight matrices, one of size 1024×40961024 \times 4096 and one of size 4096×10244096 \times 1024, so about 2×1024×4096=8,388,6082 \times 1024 \times 4096 = 8{,}388{,}608 parameters (ignoring biases). Every token uses all of them.

Example
Replacing the block with 64 experts
  1. Make each expert an identical feedforward block, so each has 8,388,6088{,}388{,}608 parameters.
  2. Use 64 experts with top-1 routing. The total is 64×8,388,608=536,870,91264 \times 8{,}388{,}608 = 536{,}870{,}912, about 537 million parameters in the layer.
  3. The router adds 1024×64=65,5361024 \times 64 = 65{,}536 parameters, a small change.
  4. Each token runs one expert, so its feedforward compute is about 8.48.4 million parameters' worth, the same as the dense block.

Interpretation: the layer holds 64 times the parameters of the dense block at about the same cost per token. The price is memory, because all 537 million parameters must be stored, and communication, because in a large cluster the tokens must be sent to the devices that host their experts.

Tradeoffs and failure modes

Mixture of experts buys capacity at a price, and most of the difficulty is in the routing.

SituationWhat goes wrongBetter choice
Router favours a few expertsThose experts overfit and others starve, so capacity is wastedAuxiliary load-balancing loss, plus capacity limits per expert
Experts spread across many devicesEvery layer needs an all-to-all exchange of tokens, which can dominate run timePlace experts to minimise traffic, or use fewer, larger experts
Small batches or fine-tuning on little dataEach expert sees very few examples, and the router is noisyFewer experts, or a dense model at this scale
Serving on limited memoryAll experts must be resident even though few run per tokenQuantisation, or offloading to a dense model if memory is the constraint
Training instabilityLarge router logits can make the softmax saturate and gradients erraticRouter z-loss, or a lower learning rate for the router

A common confusion is between total and active parameters. A model described as having 47 billion parameters with 13 billion active per token is a sparse model, and its per-token cost matches a 13-billion-parameter dense model, not a 47-billion one. The memory footprint, however, matches the full count.

Routing also introduces dropped tokens. Systems that cap how many tokens each expert accepts per batch will drop the overflow, which changes the output. Designs differ in how they handle this, and it is worth checking before comparing results.

History

Jacobs, Jordan, Nowlan and Hinton proposed adaptive mixtures of local experts in 1991, with a gating network that learned to divide the input space among networks. Jordan and Jacobs extended it to hierarchies in 1994. For many years it stayed a niche method, because training everything at once was hard and the compute saving of sparsity was not yet needed.

Shazeer and colleagues brought it back in 2017 with a sparsely gated layer inside a recurrent language model. They showed that a model with far more parameters could be trained at a similar compute cost, and that the load-balancing problem had to be solved directly. Later work at Google, including GShard in 2020 and Switch Transformer in 2021, scaled top-1 and top-2 routing to very large transformers. Open models such as Mixtral 8x7B in 2023 applied top-2 routing among eight experts per layer and showed that the idea worked in widely used models.

Check yourself

QuestionWhy does the top-k router make the compute per token roughly independent of the number of experts?Show answer

Only kk experts are evaluated for each token, and the others are skipped entirely. Adding more experts adds parameters that a given token does not use, so the cost per token depends on kk and the size of each expert, not on the total count. The router itself does grow with the number of experts, but only by a small matrix.

QuestionA router gives logits (1,0,2,−1)(1, 0, 2, -1) over four experts. What is the gate weight for expert 3 under a full softmax, and what is it under top-1 routing?Show answer

The exponentials are e1≈2.718e^1 \approx 2.718, e0=1e^0 = 1, e2≈7.389e^2 \approx 7.389 and e−1≈0.368e^{-1} \approx 0.368. Their sum is 11.47511.475. The full softmax gives expert 3 a weight of 7.389/11.475≈0.6447.389 / 11.475 \approx 0.644. Under top-1 routing expert 3 is the only one that runs. If the gate is renormalised over the kept experts its weight is exactly 1; Switch-style routing instead keeps the full-softmax value 0.644 as the scale on its output.

QuestionWhy does the load-balancing loss use the product of fif_i and PiP_i, rather than just penalising ϕi\phi_i?Show answer

The dispatch fraction ϕi\phi_i is computed from a hard choice, so it is not differentiable. The gate probability PiP_i is differentiable, so the product lets the gradient reach the router through PiP_i, while ϕi\phi_i tells the loss which experts are actually loaded. Minimising the sum encourages both toward uniform, so the router learns to route more evenly.

QuestionA team has 8 experts of size 2 billion parameters each in a layer, routes top-2, and trains with a 0.01 load-balancing coefficient. Roughly how many parameters does the layer hold, and how many run per token?Show answer

The layer holds 8×2=168 \times 2 = 16 billion parameters, and each token runs 2×2=42 \times 2 = 4 billion of them, plus a small router. The layer is eight times the size of a single expert in capacity but costs about twice a single expert per token. The team must still store all 16 billion parameters, which is the main memory cost.

Sources