All courses

Mixture-of-experts layers

Replace the FFN with E expert FFNs and a small learned router that sends each token to the top-k of them. Distinguish total parameters (memory) from active parameters (FLOPs per token). Explain the extra load-balancing loss added during training to keep experts evenly used.

Builds on: FLOPs per token: 2N forward, 6N training, The LLM training loop

▶ Watch this lesson Start the whole course

What the animation says

Every token pays for every weight

In a dense transformer, every token passes through every weight. Each weight costs a multiply and an add, so a forward pass is about two FLOPs per parameter, per token. More parameters means proportionally more compute. And most parameters live in the feed-forward layers: about two-thirds of each block. So could a model hold far more feed-forward weights, while each token pays for only a few?

Experts and a router

A mixture-of-experts layer replaces the one feed-forward network with several, called experts. Here, four. A router, one tiny linear layer, scores the token against each expert. A softmax turns the scores into gates. The token goes only to its top two experts. Their outputs are mixed using those gates, rescaled to add up to one. Here are this token's gates. Tap the two experts it is sent to.

Stored versus active

All four experts must be stored. But this token computes through, and sends gradient through, only two. Now scale up: thirty-two blocks, width four thousand ninety-six, eight experts, top two. Each block holds attention, about sixty-seven million, plus eight experts of about a hundred thirty-four million each. Stored in total: about thirty-six and a half billion. Used by one token: attention plus two experts, about ten point seven billion. So roughly how much forward compute does one token cost?

Memory follows total, compute follows active

About twenty-one gigaflops: two FLOPs for each active parameter, not for every stored one. Memory is different. All thirty-six and a half billion must be stored: at two bytes each, about seventy-three gigabytes. The dense model, with one feed-forward network per block, has about six point four billion parameters. So this MoE stores almost six times as much, yet each token costs well under twice the compute. The rule: storage counts every expert. Compute counts attention plus the chosen experts, times two.

Collapse and the balance loss

Left alone, the router collapses: experts favoured early get more tokens, train faster, and get picked even more. The fix is a balance loss. Over a batch, f is each expert's share of assignments, and P is its average gate. Multiply f by P for each expert, sum, and times the number of experts. With even usage, it hits its minimum: one. It's added to the training loss with a small weight, about one percent. Here's a collapsed batch. Tap the experts whose gates this loss pushes down.

More parameters without more compute?

In a dense transformer every token passes through every weight, so a forward pass costs about $2N$ FLOPs per token. More capacity means proportionally more cost. With $d_{ff}=4d$, the FFN sublayers hold about two-thirds of $N$: $8d^2$ of each block's $12d^2$. Can we give the model many more FFN parameters while each token pays for only a few? A **mixture-of-experts (MoE)** layer does exactly this.

Many FFNs, a router picks a few

Replace each block's single FFN with $E$ separate FFNs, called **experts**. Add a **router**: one tiny linear layer that scores the token's running vector against each expert. Each token goes only to its top-$k$ experts (e.g. 2 of 8), and their outputs are mixed using the router's weights. Every expert must be stored, but a token computes through, and sends gradient through, only $k$ of them.

Routing rule and the balance loss

Router $W_r\in\mathbb R^{d\times E}$. For a token's running vector, a row $u\in\mathbb R^{1\times d}$: $g=\text{softmax}(uW_r)$, and $S$ is the set of indices of the $k$ largest $g_i$. $$y=\sum_{i\in S}\frac{g_i}{\sum_{j\in S}g_j}\,\text{FFN}_i(u)$$ Left alone, the router **collapses**: experts favoured early get more tokens, train faster, and get picked even more. To prevent this, take a batch of $T$ tokens, which makes $T\cdot k$ token-to-expert assignments. Let $f_i$ be the fraction of those assignments that go to expert $i$, and $P_i$ the mean of $g_i$ over the batch. Then $$\mathcal L_{\text{bal}}=E\sum_i f_iP_i$$ Train on $\mathcal L+\alpha\mathcal L_{\text{bal}}$ with $\alpha\approx0.01$. $\mathcal L_{\text{bal}}$ reaches its minimum of 1 when usage is uniform. Its gradient flows through $P_i$.

Total vs active parameters, in numbers

Take $d=4096$, $L=32$, and a GELU FFN with $d_{ff}=4d$, ignoring embeddings. Per block: attention is $4d^2\approx67$M and one FFN is $8d^2\approx134$M. The dense model has $32\times201$M ≈ **6.4B** parameters. MoE with $E=8$, $k=2$ (the router's $dE\approx33$K is negligible): - **Total:** $32\times(67+8\cdot134)$M ≈ **36.5B**, about 73 GB at 2 bytes each. - **Active:** $32\times(67+2\cdot134)$M ≈ **10.7B**, so about 21 GFLOP per token forward.

An MoE layer and its balance loss

This runs on $T$ tokens with $E=4$ experts and top-2 routing. Each token touches only 2 of the expert weight sets. The last line computes $E\sum_i f_iP_i$ for this batch.
import numpy as np
T, d, E, k, dff = 6, 8, 4, 2, 32; rng = np.random.default_rng(0)
X = rng.normal(size=(T, d)); Wr = rng.normal(size=(d, E))
W1 = rng.normal(size=(E, d, dff)) / d**.5; W2 = rng.normal(size=(E, dff, d)) / dff**.5
g = np.exp(X @ Wr); g /= g.sum(1, keepdims=True)   # router probs [T, E]
top = np.argsort(-g, 1)[:, :k]                      # chosen experts [T, k]
Y = np.zeros_like(X)
for t in range(T):
    w = g[t, top[t]] / g[t, top[t]].sum()            # renormalised gates
    for i, wi in zip(top[t], w): Y[t] += wi * np.maximum(X[t] @ W1[i], 0) @ W2[i]
f = np.bincount(top.ravel(), minlength=E) / (T * k); P = g.mean(0)
print("balance loss:", E * (f * P).sum())          # 1.0 if perfectly even

Remember

An MoE layer is $E$ expert FFNs plus a router that sends each token to its top-$k$. Memory scales with **total** parameters; FLOPs per token (≈ $2N_{\text{active}}$ forward) scale with **active** ones. A small balance loss $E\sum_i f_iP_i$ stops the router from piling tokens onto a few experts.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.