A small gate sends each token to 4 of up to 131,072 expert networks. One layer grew to 137 billion parameters, and each token still cost under 10 million operations.
Drag the number of experts. Watch the parameter bar climb while the compute bar stays put. Then switch to the dense model. Then we build, piece by piece, the gate, the balancing losses and the systems tricks. Last comes the 2024 finding: the gate's choices make a free embedding.
You need a little Python, what a matrix multiply is and what softmax does. We build the rest from zero.
Session 4 of Georgia Tech CS 8803, LLM seminar. It rests on two papers: Shazeer, Mirhoseini, Maziarz, Davis, Le, Hinton and Dean, Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer (ICLR 2017), and Li and Zhou, Your Mixture-of-Experts LLM Is Secretly an Embedding Model For Free (2024). Every idea is re-taught here in our own words and devices.
Numbers from the paper's Table 8: 100 billion words of news, one epoch, all models near 8 to 10 million operations per token. The dense baseline is 4xLSTM-512. Parameters count the MoE layer only. The moving token is an animation, not data.
Chapter 0
See why a dense layer makes every token pay for every weight
You train a language model on 100 billion words of news. More parameters would let it hold more rare facts. But in a dense layer, every token multiplies through every weight. Double the weights and every token costs twice as much, on every forward pass.
A sentence about protein folding still pays for the weights that learned French verbs. Shazeer and colleagues open their 2017 paper with this limit: "The capacity of a neural network to absorb information is limited by its number of parameters."
The fix is conditional computation: run only the part of the network that this input needs. Split one big feed-forward layer into n small networks called experts. A small gate reads each token and picks k of them. Total parameters grow with n. The work per token grows with k only.
Each cell is one expert of about a million weights. Lit cells run for this token. Raise n, then raise k, and compare the two bars.
Expert size from the paper's language models: 512 inputs, 1,024 hidden units, 512 outputs, 1,048,576 weights. The choice of which cells light up is random here.
With the paper's expert size: each expert holds 512 × 1,024 + 1,024 × 512 = 1,048,576 weights. With n = 256 and k = 4, the layer stores 268 million weights. Each token touches 4.2 million of them, which is 4 / 256 = 1.6%.
The idea is old: Jacobs and colleagues proposed a mixture of experts in 1991. It had not worked at scale. The paper names five obstacles and fixes each one.
| Obstacle | Why it bites | Fix, and where |
|---|---|---|
| Branching | GPUs are fast at dense matrix math and slow at turning parts on and off | mask to exact zeros inside the softmax (Ch 1 and 2) |
| Shrinking batch | each expert sees only a slice of the batch | pool batches across devices and time steps (Ch 4) |
| Bandwidth | devices compute far faster than they ship data | wide hidden layers in each expert (Ch 4) |
| Balance | the gate favours a few experts | two extra losses (Ch 5 and 6) |
| Small data | earlier tests used a few hundred thousand images | 1 and 100 billion words, and translation (Ch 7) |
Failure. You double the hidden width of a dense layer, and the step time doubles. Measure: multiply-adds per token, before and after. Fix: add experts and keep k fixed.
Chapter 1
Write the layer as a weighted sum of experts, and skip every expert whose weight is zero
The layer has two parts. There are n experts, each a small feed-forward network with its own weights. There is one gating network that reads the token and gives each expert a weight.
Call one token's input vector x. Call expert i's output Ei(x) and the gate's weight for that expert G(x)i. The layer's output y mixes the experts by those weights.
y equals the sum over i from one to n of G of x, sub i, times E-i of x.
Ask the gate for a weight G(x)i per expert. For each expert with a nonzero weight, run it on x and scale its output by that weight. Add the scaled outputs. Experts with weight 0 never run.
With made-up numbers: n = 8, and the gate gives expert 3 the weight 0.7 and expert 6 the weight 0.3. Then y = 0.7 × E3(x) + 0.3 × E6(x). Two experts run, at 1,048,576 multiply-adds each. The other six cost nothing.
The sum looks dense. The saving lives in one line of the paper: "Wherever G(x)i = 0, we need not compute Ei(x)." So the gate must make exact zeros, not small numbers. Chapter 2 builds that gate.
Pick a token. The middle bars are the gate's weights. Only the experts with a nonzero weight light up and run.
Toy gate with made-up logits, n = 8 and k = 2. The token words echo experts the paper inspected (Table 9); the routing here is ours.
A real batch holds thousands of tokens, and each token picks its own experts. So the code groups tokens by expert, runs each expert once on its group, and scatters the results back.
pythondef moe_forward(X, gate, experts): # X: (B, 512), B tokens G = gate(X) # (B, n), all but k per row are 0 Y = torch.zeros_like(X) for i, E in enumerate(experts): rows = G[:, i].nonzero().squeeze(1) # tokens that chose expert i if rows.numel() == 0: continue # the skip: no compute at all Y[rows] += G[rows, i, None] * E(X[rows]) # E: 512 -> 1024 -> 512 return Y
Failure. You run all n experts and multiply most outputs by 0. The answer is right, but the step costs as much as a dense layer. Measure: step time as n grows with k fixed. Fix: gather each expert's tokens first.
Chapter 2
Add learned noise to each expert's score, keep the k best, and set the rest to minus infinity
The simplest gate multiplies x by a weight matrix and takes a softmax. Softmax never outputs an exact 0, so every expert would run. The paper adds two things: noise, and a cut that keeps only the top k.
Call the gate's weight matrix Wg: it turns x into one score per expert, the clean logit. A second matrix, Wnoise, sets how much random noise each expert's score gets. Call the noisy score H(x)i.
H of x, sub i, equals x times W-g, sub i, plus a standard normal sample times softplus of x times W-noise, sub i.
Score expert i with Wg. Work out a noise size from Wnoise. Draw one random number, scale it by the noise size, and add it to the clean logit. That sum is H(x)i.
With made-up numbers: clean logit 1.0, noise size 1.0, random draw −0.2. H = 1.0 + (−0.2) × 1.0 = 0.8. The same token on the next pass may draw +0.9 and score 1.9.
Now cut. KeepTopK keeps the k largest scores and sets every other score to −∞. Softmax turns e−∞ into exactly 0, so the cut experts get weight 0 by construction.
G of x equals softmax of keep-top-k of H of x and k.
Sort the scores H(x). Keep the top k, mask the rest to minus infinity, and take the softmax. The k survivors share a weight of 1; every other expert gets exactly 0.
With made-up numbers: clean logits 2.0, 1.0, 0.5, −0.5, noise draws +0.3, −0.2, +0.1, −1.5 at noise size 1, and k = 2. H = 2.3, 0.8, 0.6, −2.0. Keep 2.3 and 0.8: e2.3 = 9.97 and e0.8 = 2.23, so G = 0.818, 0.182, 0, 0.
Faint bars are clean logits; solid bars add the noise. The pink line is the cut. Press Resample and watch a trailing expert jump the cut.
Toy logits. At n = 4 the first draw is the worked example above. The noise size is one shared number here; the paper learns each expert's size from x.
Why softplus and not ReLU? ReLU is 0 for every negative input, so the model could switch an expert's noise off for good. Softplus(−10) is still 0.0000454.
Failure. You take the softmax first and zero the losers after. The kept weights no longer sum to 1. Measure: check that kept weights sum to 1 and the rest are exactly 0. Fix: mask to −∞ before the softmax, as causal attention does.
Chapter 3
Find the part of the gate that has a gradient, and see why one kept expert is not enough
Picking k of n experts is a hard yes-or-no choice, and a yes-or-no choice has no slope. Yet the paper trains the gate with plain back-propagation. Split the gate's output into two questions.
| Question | Kind | Gradient |
|---|---|---|
| Which k experts survive? | a hard cut (KeepTopK) | none |
| How do the survivors share the weight? | a softmax over real numbers | smooth, nonzero |
The paper states the condition: "If we choose k>1, the gate values for the top k experts have nonzero derivatives with respect to the weights of the gating network." Take k = 2. Call the two kept scores h1 and h2, and expert 1's weight G1 = eh1 / (eh1 + eh2).
The partial of G-one with respect to h-one equals G-one times one minus G-one.
Take expert 1's weight G1. Multiply it by the weight left for expert 2. The product is the slope that back-propagation sends to the gate's scores, and from there into Wg.
From the worked example, h1 = 2.3 and h2 = 0.8, so G1 = 0.818. The slope is 0.818 × 0.182 = 0.149. If expert 1 helped the loss, the gate learns to trust it more. With k = 1, G1 = eh1 / eh1 = 1 for every h1, so the slope is 0.
The curve is expert 1's weight against the score gap h1 − h2. The short line is the slope. Switch to k = 1 and watch the slope vanish.
Exact softmax arithmetic. At k = 1 the device draws the curve only where expert 1 is the single survivor.
Gradients also flow through the gate into x, so the layers below learn to make tokens easy to route. The slope is largest, 0.25, when the two survivors tie. It shrinks as the gate grows sure.
Failure. You set k = 1 with this gate, and the gate's weights never change. Measure: the gradient norm of Wg; it stays at 0. Fix: keep k at 2 or more, or change how the gate's weight enters the output.
Chapter 4
Pool tokens from many devices so that each expert gets a batch worth running
A GPU works well only on big batches: loading weights costs the same for 1 token or 1,000. Sparse routing cuts the batch. Each expert sees only the tokens that chose it.
Call the batch on one device b, the number of devices d, the number of experts n and the experts per token k. Each token makes k expert calls, spread over n experts.
The batch per expert is about k times b times d, over n.
Count all the tokens in the pooled batch, b times d. Each makes k calls. Share the calls evenly over n experts. That is the batch each expert gets.
With made-up numbers: b = 2,048, k = 4, n = 512. One device alone: 4 × 2,048 / 512 = 16 tokens per expert. Pool d = 16 devices: 4 × 2,048 × 16 / 512 = 256. Pooling multiplies the expert batch by d.
The bars use a log scale. Add experts and watch the expert batch shrink. Add devices and watch pooling win it back.
Toy: b = 2,048 tokens per device and k = 4. The formula is the paper's (Section 3.1).
The paper's tricks, in one list:
The paper's numbers: the 100-billion-word models use batches of about 2.5 million words. At n = 65,536 and k = 4, each expert gets 4 × 2,500,000 / 65,536 = 153 tokens per step.
Failure. The 131,072-expert model ran at 0.30 TFLOPS per GPU, against 0.72 at 65,536. Measure: tokens per expert, 4 × 2,500,000 / 131,072 = 76. The paper says the likely cause is that it kept the batch fixed while it doubled the GPUs. Fix: grow b × d with n.
Chapter 5
Add two losses: one for the weight each expert gets, one for the number of tokens it gets
Left alone, the gate "tends to converge to a state where it always produces large weights for the same few experts." Favoured experts train faster and get picked more. The paper adds two penalties to the loss.
The first counts weight. An expert's importance is the sum of its gate weights over a batch X. The coefficient of variation, CV, is standard deviation over mean. A hand-set wimportance scales the loss.
L-importance of X equals w-importance times C-V of the sum over x in X of G of x, squared.
Add up each expert's gate weights over the batch. Find the standard deviation of those totals and divide by their mean. Square it and multiply by wimportance.
With made-up importances 25, 10 and 1: mean 12, standard deviation 9.90, so CV = 0.825 and CV2 = 0.681. At wimportance = 0.1 the loss adds 0.068. Importances 10, 10, 10 add 0.
Importance is not enough. One token at weight 0.9 and nine tokens at 0.1 each both give importance 0.9, but the second expert does nine times the work.
So the second loss counts tokens. A count has no gradient, so the paper uses P(x, i). It is the chance that expert i survives the cut when we draw only its noise again. Call the k-th largest score among the others kth_excluding(H(x), k, i).
P of x and i equals Phi of a fraction. On top: x times W-g, sub i, minus k-th-excluding of H of x, k and i. Below: softplus of x times W-noise, sub i.
Subtract the bar from expert i's clean logit. Divide by its noise size. Phi of the result is the chance expert i clears the bar.
From Chapter 2's example, H = 2.3, 0.8, 0.6, −2.0 and k = 2. For expert 3, the others' scores are 2.3, 0.8, −2.0, so the bar is 0.8. Its clean logit is 0.5 and its noise size 1: P = Φ(−0.3) = 0.382.
The bell shows where the noisy score can land. The teal area past the pink bar is P. Drag the clean logit.
Chapter 2's toy example, noise size 1 for every expert. Moving one expert's clean logit leaves the others' bar unchanged.
Summed over the batch, P(x, i) is each expert's load. The load loss is wload times the squared CV of the load. The paper also starts Wg and Wnoise at zero, so every expert starts equal.
Failure. A device runs out of memory early in training. Measure: busiest expert's tokens over the mean. Fix: the load loss and a zero start.
Chapter 6
Run the rich-get-richer loop, then switch on the balancing losses and watch them hold it
Here is the loop from Chapter 5, running live. Each step routes a batch of tokens to 2 of 12 experts. An expert that gets more than its share grows stronger, so the gate picks it more next time. The balancing losses push the other way.
Bars are each expert's share of the last batch; the line below tracks the busiest expert's load over the mean. Press Play with no loss, then reset and try the losses.
A toy dynamics model, not the paper's training run: a favoured expert's logit grows with its excess load, and the losses pull it back. The two marks are the paper's measured max/mean load (Table 6): 17.80 with no loss, 1.14 with both at 0.1.
The paper ran one 256-expert model six times, changing only the two loss weights, for 10 epochs each.
| wimportance, wload | Test perplexity | CV(Importance) | CV(Load) | max / mean load |
|---|---|---|---|---|
| 0.0, 0.0 | 39.8 | 3.04 | 3.01 | 17.80 |
| 0.2, 0.0 | 35.6 | 0.06 | 0.17 | 1.47 |
| 0.0, 0.2 | 35.7 | 0.22 | 0.04 | 1.15 |
| 0.1, 0.1 | 35.6 | 0.06 | 0.05 | 1.14 |
| 0.01, 0.01 | 35.7 | 0.48 | 0.11 | 1.37 |
| 1.0, 1.0 | 35.7 | 0.03 | 0.02 | 1.07 |
Read it in three facts. With no loss, the busiest expert carries 17.8 times the mean, and perplexity is 39.8. Either loss alone brings perplexity to 35.6 or 35.7. A higher wload gives a lower peak load, which matters for memory on each device.
Failure. Training looks fine, but a few devices sit at full memory while the rest idle. Measure: max / mean load per batch. Fix: raise wload; from 0.1 to 1.0, perplexity did not change.
Chapter 7
Check that more experts at the same compute buy a better model, and find where it stops
Every model in the paper's language tests is two LSTM layers with a MoE layer between them. The question is simple: hold the compute per token near 8 million operations, add experts, and see what happens to perplexity. Perplexity is how surprised the model is by the next word; lower is better.
Shorter bars are better. Compare the dense controls with the sparse models, then switch to the 100-billion-word corpus and find the turn.
1B view: Table 7, test perplexity after 10 epochs, all at 8.4 to 8.9 million operations per token. 100B view: Table 8, perplexity after one pass over 100 billion words, with TFLOPS per GPU.
The dense controls answer a fair doubt. MoE-1-Wide (one hidden layer of 4,096) and MoE-1-Deep (four layers of 1,024) spend the same compute in one dense block. They score 46.1 and 45.7. MoE-32 scores 39.7 with the same compute. The gain comes from many experts, not from bigger matrices.
Against the best published dense model, the numbers are stark. That model, 2xLSTM-8192-1024, scores 34.7 at 151 million operations per token. The 4,096-expert model scores 34.1 with 4,303 million parameters and 8.9 million operations.
On 100 billion words, the 65,536-expert model lowers perplexity by 39% against the dense baseline: (47.0 − 28.9) / 47.0 = 0.385. It runs 4 of 65,536 experts per token, so 1 − 4 / 65,536 = 99.994% of the layer sits idle on each token.
| Translation, WMT'14 | MoE BLEU | GNMT BLEU | Ops per token |
|---|---|---|---|
| English to French | 40.56 | 39.22 | 85M against 214M |
| English to German | 26.03 | 24.91 | 85M against 214M |
The experts specialize with no labels. Sorting one translation expert's inputs by gate weight gives plays a core · plays a critical · play a leading · plays a central. Another gives rapidly growing · swiftly · drastically · the fastest.
Failure. At 131,072 experts and 137 billion parameters, perplexity got worse: 29.2 against 28.9. The paper calls it "possibly a result of too much sparsity." Measure: perplexity and tokens per expert as n grows. Fix: stop at the turn, or grow the batch with n.
Chapter 8
Read the gate's softmax at every layer and keep it as a sentence vector
Seven years on, MoE language models are common: DeepSeekMoE, Qwen1.5-MoE, OLMoE. Li and Zhou asked a new question. The router must judge what kind of input it sees to route it well. Is that judgement a usable embedding, a fixed vector that puts similar sentences close together?
The usual free embedding from a decoder-only model is the hidden state (HS) of the last token at the last layer. Its training goal was the next token. The paper's point: inputs with subtly different meanings may need the same next token, so HS can drop the difference.
Each MoE layer l has N(l) experts. Its gate turns the layer's hidden states H(l) into a softmax over all experts, g(l)(H(l)). These are the routing weights (RW), taken before any top-k cut. Stack them for all L layers.
e-R-W equals g-one of H-one, then each layer in turn, through g-L of H-L, stacked end to end.
Run the sentence through the model once. At each layer l, save the gate's full softmax g(l) for the last token. Put the L saved vectors end to end. That is eRW.
OLMoE-1B-7B has L = 16 layers of 64 experts: 16 × 64 = 1,024 numbers. DeepSeekMoE-16B: 28 × 64 = 1,792. Qwen1.5-MoE-A2.7B: 24 × 60 = 1,440. No extra pass and no training.
Each grid is one sentence: rows are layers, columns are experts, brighter means more weight. Pick a pair and compare the two grids and the two scores.
Illustrative: toy routes for 4 layers of 8 experts and toy hidden states, built to match the pattern of the paper's Tables 6 and 7. The sentence pairs are from those tables; per-sentence weights were not published.
Two choices matter. MoEE keeps the full softmax, not the sparse top-k gate: the runners-up carry information too. It also uses the last token, not an average. In the paper's ablation, RW from the last token scores 61.18 on STS12 to STS16; averaged over all tokens it falls to 46.03.
Chapter 5 pays off here. A collapsed router sends every input to the same few experts, so its vector barely changes. A balanced router must respond to its input, and the embedding reads that response.
Failure. Your RW embedding gives nearly the same vector for every sentence. Measure: the spread of cosine similarities over random pairs. Fix: take the last token's weights and the full softmax, not the top-k mask or a mean.
Chapter 9
Show that routing weights and hidden states disagree, then add their similarities
If RW and HS said the same thing, combining them would not help. The paper clusters the same inputs twice, once by each, and compares the two clusterings.
| Check (DeepSeekMoE-16B) | Score | What it says |
|---|---|---|
| Mutual information (AMI, NMI) | 0.29 of 1.00 | the clusterings share a little structure |
| Jaccard similarity | 0.06 of 1.00 | they rarely group the same sentences |
| Rank correlation, RW with HS | 0.51 | the lowest pair in the study |
| Across 9 prompts, RW with RW | 0.63 | RW is steadier than HS (0.52) |
The paper's case tables show the split. HS gets "the vote will take place today at 5.30 p.m" and "the vote will take place at 17h30" right; RW misses. RW gets "then perhaps we could have avoided a catastrophe" and "we might have been able to prevent a disaster" right; HS misses.
How to combine? Stacking the vectors forces two different geometries into one space. MoEE (sum) keeps them apart. Compute the cosine similarity of the two HS vectors, simHS, and of the two RW vectors, simRW. Blend them with a weight α.
sim-final equals sim-H-S plus alpha times sim-R-W.
Score the pair with hidden states: that is simHS. Score it with routing weights: that is simRW. Multiply simRW by α and add the two. Rank pairs by simfinal.
With made-up numbers: simHS = 0.62, simRW = 0.90, α = 0.5. simfinal = 0.62 + 0.5 × 0.90 = 1.07. A pair with 0.80 and 0.40 scores 1.00, so the paraphrase now ranks higher.
Pick a model and a task family. Turn on PromptEOL to wrap each sentence in a one-word summary prompt.
The paper's Table 3 (no prompt) and Table 4 (PromptEOL), MTEB metrics per task family, no fine-tuning. The dashed line is the supervised SimCSE-BERT average, 53.53, from Table 4.
For DeepSeekMoE-16B with no prompt, MoEE (sum) lifts the average from 35.36 to 43.30: (43.30 − 35.36) / 35.36 = 22.45%. With PromptEOL the gain is 25.96%, and OLMoE reaches 55.16, above supervised SimCSE-BERT at 53.53.
Failure. You concatenate HS and RW and the gain is small. Measure: compare concat with sum on a held-out STS set. Fix: add the two similarities instead, and tune α.
Chapter 10
Keep the terms, the numbers, the code and the links in one place
A sparse MoE layer stores many experts and runs k of them per token. Noisy top-k gating makes exact zeros, k of at least 2 keeps the gate trainable, pooling keeps experts fed, and two CV losses stop collapse. The same gate's full softmax, read at every layer, is a free sentence embedding.
| Term | Meaning | Number to remember |
|---|---|---|
| Expert | one small feed-forward network | 512 → 1,024 → 512: 1,048,576 weights |
| Noisy top-k gate | noise, keep k, mask the rest to −∞, softmax | H = 2.3, 0.8, 0.6, −2.0 gives 0.818, 0.182, 0, 0 |
| Gate slope | G1(1 − G1) for k = 2 | 0.149; 0 when k = 1 |
| Batch per expert | k · b · d / n | 16 alone, 256 pooled over 16 devices (toy) |
| Importance, load | summed weight; summed P(x, i) | w = 0.1 each; no loss: max/mean 17.80 |
| Sparsity | share of the layer idle per token | 99.994% at 65,536 experts |
| Capacity vs compute | MoE-4096-h against the best dense model | 28.5× the parameters, 6% of the compute |
| Largest layer | 131,072 experts | 137 billion parameters, 0.30 TFLOPS/GPU |
| eRW | full router softmax per layer, stacked | OLMoE 16 × 64 = 1,024 numbers |
| MoEE (sum) | simHS + α · simRW | DeepSeekMoE 35.36 to 43.30 (+22.45%) |
pythonimport numpy as np from math import erf, sqrt def Phi(z): return 0.5 * (1 + erf(z / sqrt(2))) # standard normal CDF def noisy_top_k(clean, scale, noise, k): # clean = x@Wg, scale = softplus(x@Wnoise), (n,) H = clean + noise * scale # noisy scores keep = np.argsort(H)[-k:] # the k largest G = np.zeros_like(H) e = np.exp(H[keep] - H[keep].max()) G[keep] = e / e.sum() # softmax over survivors, exact 0 elsewhere P = np.array([Phi((clean[i] - np.sort(np.delete(H, i))[-k]) / scale[i]) for i in range(len(H))]) # chance each expert clears the bar return G, P def cv_squared(v): return (v.std() / v.mean()) ** 2 # 0 when all experts are equal # per batch: aux = w_imp * cv_squared(G_batch.sum(0)) + w_load * cv_squared(P_batch.sum(0)) G, P = noisy_top_k(np.array([2., 1, .5, -.5]), np.ones(4), np.array([.3, -.2, .1, -1.5]), 2) print(G.round(3), P.round(4)) # [0.818 0.182 0. 0.] [0.9192 0.6554 0.3821 0.0968] def moee_sum(hs1, hs2, rw1, rw2, alpha): # rw: last token's softmax, all layers, stacked cos = lambda a, b: a @ b / (np.linalg.norm(a) * np.linalg.norm(b)) return cos(hs1, hs2) + alpha * cos(rw1, rw2)
Shazeer and colleagues aimed for a trillion-parameter model on a trillion-word corpus, and suggest MoE inside recurrent layers and in other domains with enough data. Li and Zhou test six task families on three models and leave open why the last token concentrates the signal.
Credit: Session 4 of Georgia Tech CS 8803, LLM seminar. Papers: Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer (Shazeer et al., ICLR 2017, arXiv 1701.06538) and Your Mixture-of-Experts LLM Is Secretly an Embedding Model For Free (Li and Zhou, arXiv 2410.10814). The toy gates, routes and dynamics are ours.
Teach it back: open Present or Teach and explain noisy top-k gating and the load loss to a friend. Then go back to the expert dial and predict where perplexity turns.