← All notes
Course chapters
On this page

Lesson 27 · Large language models

Mixture of experts

Route token representations to selected feed-forward experts. Calculate top-k gates, compare total and active parameter counts, and examine load balancing, capacity and communication trade-offs.

1. More capacity, without running every branch

Increasing a model's parameter capacity can improve its performance when paired with suitable data and training. But storing and evaluating a larger model also introduces costs. More parameters do not automatically mean better answers, and latency does not follow parameter count by a universal fixed ratio.

A dense Transformer normally applies the same attention and feed-forward sublayers at each position. Can we provide several alternative feed-forward networks while executing only a few for each token?

That is the central idea of a sparsely activated mixture of experts, or MoE. The model stores multiple expert networks and routes each token representation to a selected subset.

Pause and think

If only two out of eight experts process one token, can the other six experts still be useful?

I've thought about it — show the answerHide answer

Yes. Other token representations can select them, so the model can use different parts of its parameter capacity for different inputs.

The inactive experts still require storage, and routing does not guarantee that every expert is useful or well trained. Utilisation and training quality matter.

2. Why replace the feed-forward network?

For a conventional block with model width dd, full-width query, key, value and output projections contain approximately 4d24d^2 attention parameters, ignoring biases.

A non-gated FFN with width d→4d→dd\rightarrow4d\rightarrow d contains approximately:

d(4d)+(4d)d=8d2.d(4d)+(4d)d=8d^2.

Within that simplified block, the FFN accounts for:

8d24d2+8d2=23\frac{8d^2}{4d^2+8d^2}=\frac23

of the attention-plus-FFN weights. This is a useful example, not a universal ratio. Gated FFNs, different hidden widths, shared key/value heads and other architecture choices change the counts.

A typical sparse MoE replaces an FFN with multiple expert FFNs plus a router. Attention and other parts of the block remain shared. Some architectures use MoE only in selected layers, or combine routed and shared experts.

FFNs contribute to learned associations, but describing them as the model's only “knowledge warehouse” is too literal. Information and computation are distributed across embeddings, attention, experts and the rest of the network.

3. Route each token to selected experts

For a contextual representation xx, a simple router calculates logits zz and probabilities pp:

z=xWr+br,p=softmax⁡(z).z=xW_r+b_r,\qquad p=\operatorname{softmax}(z).

Select a set S(x)S(x) containing the top kk experts. In the convention used in our example, renormalise the selected probabilities:

gi(x)={pi∑j∈S(x)pj,i∈S(x),0,i∉S(x).g_i(x)=\begin{cases} \dfrac{p_i}{\sum_{j\in S(x)}p_j},&i\in S(x),\\ 0,&i\notin S(x). \end{cases}

The expert outputs are combined as:

y=∑i∈S(x)gi(x)Ei(x).y=\sum_{i\in S(x)}g_i(x)E_i(x).

Contextual token representation x → router scores → select experts

Expert 1

selected

Expert 2

not selected

Expert 3

selected

Expert 4

not selected

y=g1(x)E1(x)+g3(x)E3(x)y=g_1(x)E_1(x)+g_3(x)E_3(x)

Combine selected outputs → residual stream

Figure 27-1. A four-expert, top-two example. Two experts run for this token in this layer; another token or layer may select a different pair.

For logits [3.1,0.5,2.4,−1.0][3.1,0.5,2.4,-1.0], top-two routing selects experts 1 and 3. Their renormalised weights are approximately 0.66820.6682 and 0.33180.3318.

The full four-way Softmax probabilities are different from those two selected weights. Selecting and then normalising must not be confused with simply reporting the original probabilities.

Expert 1 · selected

Logit 3.10 · full Softmax 62.99% · selected weight 0.6682

Fixed output: [1, 0]

Expert 2 · inactive for this input

Logit 0.50 · full Softmax 4.68% · selected weight 0.0000

Fixed output: [0, 1]

Expert 3 · selected

Logit 2.40 · full Softmax 31.28% · selected weight 0.3318

Fixed output: [2, 1]

Expert 4 · inactive for this input

Logit -1.00 · full Softmax 1.04% · selected weight 0.0000

Fixed output: [-1, 2]

Combined output: [1.3318, 0.3318]

Hand-picked logits and expert outputs, not a trained model. We renormalise selected probabilities; ties favour the lower expert index. Choosing all four experts removes sparse expert selection in this example.

Experiment 27-A. Calculate full router probabilities, select top-k experts and combine fixed example outputs.

The expert output vectors in this experiment are fixed by hand. Changing the preset changes the example logits, not the behaviour of a trained FFN. The experiment is designed to make selection and weighted addition inspectable.

Routing conventions vary. Some designs use top-one routing, retain different gate normalisations or use other assignment rules. Top-k membership is discrete, so training a router is not simply taking an ordinary derivative through the index-selection operation. Gate values, auxiliary objectives and architecture-specific training methods provide learning signals.

Routing is usually computed per token representation and per MoE layer, rather than choosing one expert pair for an entire conversation. Different layers can route the same token differently.

The analogy with multi-head attention has limits: standard attention heads normally all run, while sparse MoE deliberately skips unselected expert computation.

4. Count total parameters and active work separately

Let PsP_s denote shared weights, PeP_e the weights in one expert and PrP_r the router weights. With NN stored experts and kk selected experts per token:

Ptotal=Ps+NPe+Pr,P_{\mathrm{total}}=P_s+NP_e+P_r, Pactive≈Ps+kPe+Pr.P_{\mathrm{active}}\approx P_s+kP_e+P_r.

The active count includes the router because it still scores all experts in this example. Other designs may organise routing differently.

Shared attention weights: 1,048,576

Weights per expert: 2,097,152

Router weights: 4,096

Total block weights: 17,829,888

Active block weights per token: 5,246,976

Dense baseline block: 3,145,728

Total / dense baseline: 5.668× · active / dense baseline: 1.668×

Model width 512; each expert uses a non-gated 512 → 2048 → 512 FFN. Counts include a 512 × N router and standard full-width attention projections, but omit biases, normalisation, embeddings and other layers. Active weight count is not measured FLOPs, memory traffic or latency.

Figure 27-2 / Experiment 27-B. Count total and active weights for a specified single block, including its shared attention and router.

Adding experts while holding kk fixed increases stored capacity much more than selected expert work. But selecting two experts of the same size also performs approximately twice the expert FFN work of selecting one. It is not automatically the same compute as the original single-FFN block.

Mixtral 8×7B is a published example with eight experts per layer and two selected for each token. Its paper reports approximately 47 billion total parameters and 13 billion active parameters per token. The name does not mean eight independent seven-billion-parameter models: shared attention and other shared components are counted once.

These counts illustrate sparse activation; they are not interchangeable with measured FLOPs, GPU memory traffic, latency or quality. Actual speed depends on batching, hardware, expert placement and implementation.

A model with more experts can gain capacity, but the amount of usable knowledge and performance cannot be read directly from its total parameter count. Training data, expert utilisation and optimisation remain important.

5. Load balance, capacity and communication

Experts do not come with assigned professions

An expert is a learned neural subnetwork, not a separately prompted person or agent. Labels such as “law expert”, “coding expert” and “poetry expert” can be misleading if presented as facts about its learned role.

Routing can correlate with token forms, syntax, language or other features. Useful specialisation can emerge, but it need not match a neat human-readable topic label, and it should be investigated rather than assumed.

Uneven routing wastes capacity

If most tokens are sent to one expert, that expert becomes a bottleneck while others receive less work. Training often includes load-balancing mechanisms, but the exact method varies; an auxiliary loss is not the only possible approach.

Even top-one assignment

Expert 1: 3 assignments

Expert 2: 3 assignments

Expert 3: 3 assignments

Expert 4: 3 assignments

Skewed top-one assignment

Expert 1: 9 assignments

Expert 2: 1 assignments

Expert 3: 1 assignments

Expert 4: 1 assignments

Figure 27-3. Two illustrative distributions of 12 top-one assignments. With a capacity of three assignments per expert, the skewed case has six overflow assignments; how they are handled depends on the routing implementation.

Some implementations impose a per-expert capacity on token assignments. Overflow assignments may be dropped, rerouted or handled using a different policy. In a dropped-branch scheme, a residual path can carry the representation onwards; it does not mean the token is deleted from the sequence. Dropless implementations make different memory and execution trade-offs.

A schematic training objective can include an auxiliary term:

L=Ltask+λLbalance.\mathcal L=\mathcal L_{\mathrm{task}}+\lambda\mathcal L_{\mathrm{balance}}.

Its detailed definition depends on the model. Balancing utilisation is an engineering and optimisation goal, not a guarantee that all experts will learn distinct useful functions.

Sparse execution still needs stored weights

An expert that is inactive for the current token does not disappear from the model. Serving systems must make the full set of required weights available, often sharded across accelerators. Offloading or fetching weights on demand can reduce resident accelerator memory at a transfer and latency cost; it is too strong to say every expert must always reside on one GPU.

When experts are distributed, dispatching token representations and returning expert outputs requires communication. This can offset arithmetic savings, particularly with small batches or uneven loads. Packing work efficiently and balancing compute with network traffic are part of making sparse activation useful in practice.

Pause and think

Can a model with fewer active parameters still use more memory or respond more slowly than a smaller dense model?

I've thought about it — show the answerHide answer

Yes. It can store many inactive experts and spend time dispatching work, transferring data or waiting for overloaded devices.

Active parameter count is one accounting measure. End-to-end resource use needs measurement on the actual system and workload.

6. What you have discovered

  • Sparse MoE commonly replaces an FFN with several expert networks and a learned router.
  • The router selects experts for each contextual token representation; selected outputs are combined using architecture-specific gate weights.
  • Total stored capacity and per-token active work are different quantities.
  • More experts at fixed selection count do not promise fixed latency, automatic quality gains or lower memory requirements.
  • Load balance, assignment capacity and distributed communication are central practical constraints.

Next, we will study model distillation: how a student can learn from a teacher's outputs or distributions, and what can be retained or lost when reducing the deployed model.

Check your understanding

1. How can a sparse MoE have many total parameters without evaluating every expert for each token?
2. What does a token router do in the illustrated top-k MoE?