Mixture-of-Experts

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.

Grow the layer, not the cost

65,536

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

The Capacity Wall

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.

Split one layer into experts

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.

256
4

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.

ObstacleWhy it bitesFix, and where
BranchingGPUs are fast at dense matrix math and slow at turning parts on and offmask to exact zeros inside the softmax (Ch 1 and 2)
Shrinking batcheach expert sees only a slice of the batchpool batches across devices and time steps (Ch 4)
Bandwidthdevices compute far faster than they ship datawide hidden layers in each expert (Ch 4)
Balancethe gate favours a few expertstwo extra losses (Ch 5 and 6)
Small dataearlier tests used a few hundred thousand images1 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.

  1. The sparsely-gated layer: a weighted sum where most weights are exactly zero.
  2. Noisy top-k gating: how the gate makes those zeros.
  3. Training the gate: why k must be at least 2.
  4. Batches and bandwidth: keep each expert busy.
  5. Load balancing: the importance and load losses.
  6. Watch a router collapse: the losses at work.
  7. 137 billion parameters: the results, the hero's numbers.
  8. The router as an embedding: MoEE, seven years later.
  9. Two signals, one score: combine router weights and hidden states.
  10. Field guide: numbers, code, links and the credit.
What stopped conditional computation from working at scale before 2017?

Chapter 1

The Sparsely-Gated Layer

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.

Say it aloud

y equals the sum over i from one to n of G of x, sub i, times E-i of x.

y
y the layer's output for this token: a vector of 512 numbers in the paper's language models.
Σi=1..n
the sum over i from one to n add one term per expert.
G(x)i
G of x, sub i the gate's weight for expert i. All but k of the n weights are exactly 0.
Ei(x)
E-i of x what expert i outputs for the token.
In plain words

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 numbers

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.

Route one token

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.

The layer is y = Σ G(x)i Ei(x). Where does the saving in compute come from?

Chapter 2

Noisy Top-K Gating

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.

Say it aloud

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.

H(x)i
H of x, sub i expert i's noisy score for this token.
(x · Wg)i
x times W-g, sub i the clean logit: how well the gate thinks expert i fits x.
StandardNormal()
a standard normal sample a fresh random number, mean 0 and spread 1, drawn per expert per pass.
Softplus(·)
softplus of x times W-noise, sub i the noise size, learned. Softplus(z) = ln(1 + ez) is always above 0.
In plain words

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 numbers

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.

Say it aloud

G of x equals softmax of keep-top-k of H of x and k.

G(x)
G of x the gate's n weights. k are positive and sum to 1; the rest are 0.
Softmax
softmax raise e to each score and divide by the total, so the weights sum to 1.
KeepTopK
keep-top-k keep the k largest scores; replace the rest with minus infinity.
H(x)
H of x the n noisy scores from the line above.
k
k how many experts run per token: 4 in the paper's language models.
In plain words

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 numbers

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.

Draw the noise, keep the top k

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.

4
2
1.0

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.

What happens to an expert that is not in the top k after the noise is added?

Chapter 3

Training the Gate

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.

QuestionKindGradient
Which k experts survive?a hard cut (KeepTopK)none
How do the survivors share the weight?a softmax over real numberssmooth, 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).

Say it aloud

The partial of G-one with respect to h-one equals G-one times one minus G-one.

∂G1 / ∂h1
the partial of G-one with respect to h-one how fast expert 1's weight moves when its score moves a little, with h2 held still.
G1
G-one expert 1's weight among the two survivors, between 0 and 1.
(1 − G1)
one minus G-one the weight left for expert 2, which is G2.
In plain words

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.

With numbers

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.

Find the slope the gate learns from

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.

1.5

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.

With this gate, why must k be greater than 1?

Chapter 4

Batches and Bandwidth

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.

Say it aloud

The batch per expert is about k times b times d, over n.

batch per expert
batch per expert how many tokens one expert processes per step, on average.
k
k experts per token, 4 here.
b
b tokens in one device's batch.
d
d devices that pool their batches before routing. With no pooling, d = 1.
n
n experts that share the calls.
In plain words

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 numbers

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.

Feed every expert

The bars use a log scale. Add experts and watch the expert batch shrink. Add devices and watch pooling win it back.

512
16

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:

  1. Mix data and model parallelism. Each device holds a copy of the normal layers and the gate, but each expert lives once, on one device. Devices run in step, so their tokens pool.
  2. Batch over time steps. The same MoE runs at every position, so the code waits for the whole sequence and calls the MoE once.
  3. Widen each expert. An expert computes about s × h per token but ships only its input and output, about s numbers. Their ratio is h, the hidden width.
  4. Save memory. Recompute expert activations in the backward pass. Drop Adam's first moment and store the second moment as a row average and a column average.
compute / data shipped ≈ (s · h) / s = h. For s = 512, h = 1,024: (2 × 512 × 1,024) / (2 × 512) = 1,024.

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.

One device routes b = 2,048 tokens to k = 4 of n = 512 experts, with no pooling. About how many tokens does each expert get?

Chapter 5

Load Balancing

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.

Say it aloud

L-importance of X equals w-importance times C-V of the sum over x in X of G of x, squared.

Limportance(X)
L-importance of X the extra loss for this batch.
wimportance
w-importance a hand-set scale: 0.1 in the paper's language models.
CV
C-V the coefficient of variation: standard deviation over mean, across the n experts. 0 when all are equal.
Σx∈X G(x)
the sum over x in X of G of x the importance vector: each expert's total gate weight over the batch.
2
squared grows fast as the spread grows.
In plain words

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 numbers

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).

Say it aloud

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.

P(x, i)
P of x and i the chance that expert i is in the top k after a fresh draw of its own noise.
Φ
Phi the standard normal CDF: the chance a normal sample falls below a value. It is smooth.
(x · Wg)i
x times W-g, sub i expert i's clean logit.
kth_excluding
k-th-excluding of H of x, k and i the bar to beat: the k-th largest noisy score among the other experts.
Softplus(·)
softplus of x times W-noise, sub i expert i's noise size.
In plain words

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.

With numbers

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.

Turn a count into a chance

The bell shows where the noisy score can land. The teal area past the pink bar is P. Drag the clean logit.

0.5

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.

Why does the load loss use P(x, i) instead of counting the tokens each expert gets?

Chapter 6

Watch a Router Collapse

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.

Collapse it, then hold it

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, wloadTest perplexityCV(Importance)CV(Load)max / mean load
0.0, 0.039.83.043.0117.80
0.2, 0.035.60.060.171.47
0.0, 0.235.70.220.041.15
0.1, 0.135.60.060.051.14
0.01, 0.0135.70.480.111.37
1.0, 1.035.70.030.021.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.

In Table 6, what happens when both balancing losses are off?

Chapter 7

137 Billion Parameters

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.

Hold compute, add experts

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.

parameters: 4,303 / 151 = 28.5 times more. compute: 8.9 / 151 = 0.059, about 6%.

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'14MoE BLEUGNMT BLEUOps per token
English to French40.5639.2285M against 214M
English to German26.0324.9185M 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.

The 4,096-expert model beats the best dense model (34.1 against 34.7) at about 6% of its compute. What does this show?

Chapter 8

The Router as a Free Embedding

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.

Say it aloud

e-R-W equals g-one of H-one, then each layer in turn, through g-L of H-L, stacked end to end.

eRW
e-R-W the routing-weight embedding: one vector per sentence, of length N(1) + … + N(L).
g(1)(H(1))
g-one of H-one layer 1's softmax over its experts, for the last token. It sums to 1.
; … ;
then each layer in turn the semicolons mean "place end to end", in layer order.
g(L)(H(L))
g-L of H-L the last layer's softmax over its experts.
In plain words

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.

With numbers

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.

Compare two sentences by their routes

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.

Why can routing weights serve as an embedding with no extra training?

Chapter 9

Two Signals, One Score

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)ScoreWhat it says
Mutual information (AMI, NMI)0.29 of 1.00the clusterings share a little structure
Jaccard similarity0.06 of 1.00they rarely group the same sentences
Rank correlation, RW with HS0.51the lowest pair in the study
Across 9 prompts, RW with RW0.63RW 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 α.

Say it aloud

sim-final equals sim-H-S plus alpha times sim-R-W.

simfinal
sim-final the score MoEE gives a sentence pair. Higher means more alike.
simHS
sim-H-S the cosine similarity of the two last-token hidden states.
α
alpha a hand-set weight for the routing signal.
simRW
sim-R-W the cosine similarity of the two routing-weight vectors.
In plain words

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 numbers

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.

Read the main table

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 α.

Why does the weighted sum of similarities beat concatenating the two vectors?

Chapter 10

Field Guide

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.

TermMeaningNumber to remember
Expertone small feed-forward network512 → 1,024 → 512: 1,048,576 weights
Noisy top-k gatenoise, keep k, mask the rest to −∞, softmaxH = 2.3, 0.8, 0.6, −2.0 gives 0.818, 0.182, 0, 0
Gate slopeG1(1 − G1) for k = 20.149; 0 when k = 1
Batch per expertk · b · d / n16 alone, 256 pooled over 16 devices (toy)
Importance, loadsummed weight; summed P(x, i)w = 0.1 each; no loss: max/mean 17.80
Sparsityshare of the layer idle per token99.994% at 65,536 experts
Capacity vs computeMoE-4096-h against the best dense model28.5× the parameters, 6% of the compute
Largest layer131,072 experts137 billion parameters, 0.30 TFLOPS/GPU
eRWfull router softmax per layer, stackedOLMoE 16 × 64 = 1,024 numbers
MoEE (sum)simHS + α · simRWDeepSeekMoE 35.36 to 43.30 (+22.45%)

Checklist

  1. Mask to −∞ before the softmax. Check that cut experts get exactly 0.
  2. Keep k at 2 or more with this gate.
  3. Log the batch per expert. Grow the pooled batch when you grow n.
  4. Turn on both CV losses, and start Wg and Wnoise at zero.
  5. Log max / mean load every step.
  6. For an MoEE embedding, take the last token's full softmax at every layer, and add similarities; do not stack vectors.
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)

What the authors leave open

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.

Keep going

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.

The takeaway. A gate that picks k of n experts separates what a layer stores from what each token pays. Train it so it stays balanced, and its choices also describe the input.

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.

CS 8803 LLM Seminar, Session 04: Mixture-of-Experts
Sparsely-gated MoE paper · MoEE paper · Back to Gleams