Mathematical Prerequisites for Mixture of Experts — Part 2
Building the math foundations you need for sparse MoEs and the Switch Transformer — softplus, top-k masking, mean and variance, coefficient of variation, indicator functions, argmax, differentiability, and the dot-product loss — all derived step by step with one consistent example.
In Part 2 of the Mixture of Experts series, we scale MoEs from 4 experts to thousands, introduce sparse gating, and derive the Switch Transformer. The mathematics is different from Part 1 — instead of Gaussian likelihoods and the EM algorithm, we need tools for sparsity, load balancing, and differentiability. By the end of this post, you will have every mathematical tool required to follow Part 2 from the first equation to the last.
We assume you have read the prerequisites for Part 1, where we built softmax, Gaussian densities, Bayes’ theorem, and the mixture log-likelihood. We will not re-derive those here. Instead, we build six new tools — each one earning its place by being directly used in Part 2.
The Running Example
We have 4 experts and a batch of 8 tokens. Each token is routed to some subset of the experts. This is the same setup used throughout Part 2.
For concreteness, suppose the gating network produces the following raw scores (logits) for one specific token:
These are the scores for experts 1, 2, 3, and 4 respectively. Expert 3 has the highest score (3.4), expert 1 has the second highest (2.1). We will use these four numbers for every concept in this post.
For batch-level concepts, we will use 8 tokens routed across the 4 experts as follows:
| Token | Routed to expert |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| 4 | 3 |
| 5 | 1 |
| 6 | 3 |
| 7 | 2 |
| 8 | 4 |
Expert 1 receives 3 tokens, experts 2 and 3 receive 2 each, and expert 4 receives 1. We will use these counts for every batch-level computation.
1. The Softplus Function
In Part 2, Shazeer et al. add tunable noise to the gating logits. The noise magnitude must be positive — you cannot have a negative standard deviation. The softplus function guarantees positivity:
Let us verify that this is always positive. Since for all , we have , so . The output is strictly positive for every input — exactly what we need for a noise scale.
Why not just use ? The exponential is also always positive, but it grows explosively: . The softplus grows much more gently. For large positive :
because dominates the 1. For large negative :
because . So softplus behaves like when is large and positive, and like when is large and negative. It is a smooth, always-positive version of — the ReLU function. This is why the softplus is sometimes called a “smooth ReLU.”
Numerical check
Let us compute Softplus for several values:
All outputs are positive. At , the output () is nearly equal to () — confirming the large- approximation . At , the output () is close to zero — confirming the negative- approximation .
In Part 2, the noise term in Shazeer et al.’s gating is . The Softplus ensures the noise scale is always positive regardless of what the learned weights produce.
2. Top-K Selection and the Masking Trick
Standard softmax (from the Part 1 prerequisites) converts all scores into nonzero probabilities. In Part 2, we want sparse gating: only experts should receive nonzero probability, and the rest should be exactly zero. The top-k masking trick achieves this in two steps.
Step 1: Identify the top scores. Given a vector of scores , find the largest values.
Step 2: Mask the rest with . Define a new vector:
Then apply softmax to the result.
Why works. Recall that softmax computes . When :
So the numerator for the masked entries is exactly zero, making . The denominator only accumulates contributions from the non-masked entries. The result is a probability vector with exactly nonzero entries that sum to 1.
This is different from simply setting after softmax. If we applied softmax first and then zeroed out entries, the remaining entries would no longer sum to 1. By masking before softmax, we ensure the nonzero entries sum to 1 automatically — softmax handles the normalisation.
Numerical check
Using our running example with :
The top-2 scores are and . After masking:
Applying softmax to the masked vector:
Check: . Exactly 2 nonzero entries, summing to 1.
Compare this to full softmax (no masking): , , sum . Then , , , . All four entries are nonzero — we would have to compute all four expert outputs. With top-2 masking, we only compute 2 expert outputs. With experts and , we would compute 2 instead of 4096 — the entire point of sparse gating.
3. Mean, Variance, and Standard Deviation
Part 2 uses the coefficient of variation to measure how unbalanced the experts are. This requires three building blocks: mean, variance, and standard deviation. We derive all three using the expert importance values from our running example.
3.1 Mean
The mean (or average) of values is their sum divided by :
The mean answers: if we spread the total evenly across all entries, how much would each get?
Numerical check
From our routing table, the number of tokens each expert receives is . In Part 2, this is called the importance vector. Its mean:
Each expert would receive 2 tokens on average. Expert 1 receives more than average (3), expert 4 receives less (1).
3.2 Variance
The variance measures how spread out the values are from their mean. It is the average squared deviation:
Each term measures how far value is from the mean, squared. Squaring ensures deviations above and below the mean both contribute positively — the same reasoning as squared error from the Part 1 prerequisites.
Numerical check
With and :
The variance is 0.5. If all experts received exactly 2 tokens, every deviation would be zero and the variance would be 0. The farther the values are from the mean, the larger the variance.
3.3 Standard deviation
The standard deviation is the square root of the variance:
Why take the square root? Variance is measured in squared units — if the values are token counts, the variance has units of “tokens squared.” The standard deviation brings us back to the original units (tokens), making it directly comparable to the mean.
Numerical check
The standard deviation is 0.707 tokens. Roughly speaking, expert loads deviate from the mean by about 0.7 tokens on average.
4. Coefficient of Variation
Part 2 uses the coefficient of variation (CV) as a load balancing penalty. The CV is the standard deviation divided by the mean:
Why divide by the mean? Because the standard deviation alone does not tell us whether the spread is “large” or “small” relative to the values themselves. A standard deviation of 10 is large when the mean is 20 (values are all over the place), but small when the mean is 10{,}000 (values are tightly clustered relative to their size). The CV normalises the spread by the scale of the data.
The key property. The CV equals zero if and only if all values are equal. When all values are equal, the standard deviation is zero (no spread), so . Any departure from uniformity makes the CV positive. This is exactly what we want for a load balancing penalty — it should be zero when experts are perfectly balanced and positive when they are not.
Shazeer et al. use (the square of the coefficient of variation) as the importance loss:
Squaring the CV serves two purposes. First, it keeps the loss non-negative (though CV is already non-negative, the square emphasises large imbalances). Second, the squared CV is smoother — its derivative at is zero, so it does not create a gradient discontinuity when experts are perfectly balanced.
Numerical check
Using our values , , :
Now suppose all experts received equal load: . Then , , , and . The loss vanishes — no penalty for perfect balance.
For a more extreme imbalance, : , , , , . The penalty grew from 0.125 to 0.750 — a 6x increase, reflecting the much worse imbalance.
5. The Indicator Function and Argmax
Part 2 uses two closely related tools to describe hard routing decisions: the indicator function and the argmax.
5.1 Argmax
The argmax of a vector returns the index of the largest element, not the element itself:
The distinction between max and argmax is important. The max answers “what is the largest value?” The argmax answers “which entry has the largest value?”
Numerical check
For :
In Part 2, the Switch Transformer routes each token to the single expert with the highest gate logit: . This says: compute the router scores for all experts, then pick the expert whose score is largest. The argmax gives us the expert number, not the score.
5.2 The indicator function
The indicator function equals 1 when the condition is true and 0 when it is false:
That is the entire definition — nothing more.
Numerical check
Suppose token 1 is routed to expert . Then:
5.3 Counting with indicators
The indicator function lets us express counts as sums. The number of tokens routed to expert in a batch of tokens is:
Each term is either 0 or 1, and summing them counts how many tokens were assigned to expert .
Numerical check
From our routing table (tokens assigned to experts ), the count for expert 1 is:
The fraction of tokens dispatched to expert 1 is:
This is exactly the quantity from Fedus et al.’s load balancing loss in Part 2.
6. Differentiable vs. Non-Differentiable Functions
The load balancing loss in Part 2 rests on a subtle but critical distinction: some functions have gradients and some do not. Understanding this distinction is essential for seeing why the loss is designed the way it is.
6.1 What differentiable means
A function is differentiable at a point if it has a well-defined slope (derivative) at that point. Visually, this means the function has no jumps, corners, or discontinuities at — you could draw a single, unique tangent line to the curve.
The derivative measures how much changes when we nudge by a tiny amount. If is differentiable, this change is smooth and predictable.
The softmax function is differentiable everywhere. If we nudge the router weights by a tiny amount, the softmax probabilities change smoothly and predictably. Gradients flow through softmax without any issues.
6.2 What non-differentiable means
A function is non-differentiable at a point where it has a jump or a corner — the slope is not well-defined because the function changes abruptly.
The argmax function is non-differentiable. Consider a simple case with two scores: . The argmax is:
As increases from below to above , the argmax jumps from 2 to 1 — an instantaneous switch with no gradual transition. There is no meaningful “slope” at the switching point .
The indicator function inherits this problem. It is either 0 or 1 with no values in between, and jumps discontinuously. No gradient can flow through it.
6.3 Why this matters for load balancing
In Part 2, Fedus et al. define two quantities:
The first quantity counts hard routing decisions — it uses the indicator function and argmax, both of which are non-differentiable. We cannot compute because the indicator has no meaningful derivative.
The second quantity averages soft router probabilities — it uses the softmax output , which is differentiable. We can compute and use it to update the router weights via gradient descent.
The load balancing loss multiplies these two quantities together. When we differentiate this product with respect to , by the product rule of calculus:
The second term vanishes because does not exist (or is zero almost everywhere). The gradient flows entirely through the differentiable term :
This is the entire design insight: acts as a fixed coefficient that scales the gradient of . When expert receives too many tokens (high ), the gradient of is amplified, pushing the router to reduce the probability assigned to expert . The non-differentiable counting function provides the signal about what is wrong, while the differentiable probability provides the pathway for fixing it.
Numerical check
Using our routing () and suppose :
The gradient contribution from expert 1: .
The gradient contribution from expert 4: .
Expert 1’s gradient is scaled by 0.375 while expert 4’s is scaled by 0.125 — a 3x ratio. The router receives a stronger push to reduce probability for expert 1 (the overloaded one) than for expert 4 (the underloaded one). This is how the loss encourages balance.
7. The Dot Product as a Balancing Loss
The load balancing loss from Fedus et al. is built on the dot product (also called inner product or scalar product) of two vectors. The dot product multiplies corresponding entries and sums:
The dot product takes two vectors of the same length and produces a single number.
7.1 What the dot product measures
The dot product is large when both vectors have large values in the same positions. If is large whenever is large, the products are all large and their sum is large. If the large values of and occur in different positions, the products are smaller.
This makes the dot product a measure of alignment between two vectors. In the context of load balancing, (fraction of tokens per expert) and (fraction of probability per expert). The dot product is large when experts that receive many tokens also receive high probability — exactly the imbalance we want to penalise.
7.2 The dot product under uniform distribution
Under perfect balance, every expert receives the same fraction of tokens and the same fraction of probability. With experts:
The dot product becomes:
This is the minimum possible value of the dot product, given the constraints and . This is a consequence of the Cauchy-Schwarz inequality: for non-negative vectors with fixed sums, the dot product is minimised when both vectors are uniform.
Any deviation from uniformity increases the dot product. This is why Fedus et al. use as the loss — the factor of normalises so that the uniform-case loss is , independent of the number of experts.
Numerical check
With and :
The loss (with and ):
Under perfect uniformity ():
The actual loss () exceeds the uniform-case loss (), penalising the imbalance. The difference () creates a gradient that pushes the router toward more uniform probability allocation.
8. Expert Capacity and Integer Arithmetic
Part 2 introduces a fixed buffer size for each expert called the expert capacity. The formula involves integer arithmetic that is worth making precise.
where is the number of tokens, is the number of experts, and is the capacity factor — a hyperparameter that controls how much buffer space each expert gets. The notation means the floor function: round down to the nearest integer, since we cannot process a fractional token.
The ratio is the number of tokens each expert would receive under perfect balance. The capacity factor scales this up to provide buffer room for imbalanced routing.
Why this matters
If the router sends more tokens to an expert than its capacity allows, the excess tokens are dropped — they skip the expert entirely and pass through the residual connection unchanged. Setting the capacity too low means many tokens are dropped and never processed by any expert. Setting it too high wastes memory on empty buffer slots that are never filled.
Numerical check
With tokens and experts:
Capacity factor :
Each expert can process at most 2 tokens. In our routing, expert 1 receives 3 tokens but can only process 2 — one token is dropped. Total buffer across experts: slots for 8 tokens. No wasted space, but risk of dropping.
Capacity factor :
Each expert can now handle up to 3 tokens. Expert 1 receives 3 tokens and processes all of them — no dropping. Total buffer: slots for 8 tokens. Four slots are wasted (padding).
Capacity factor :
Each expert processes at most 1 token. Expert 1 drops 2 of its 3 tokens, experts 2 and 3 each drop 1 of their 2 tokens. Total dropped: 4 out of 8 tokens — half the batch is unprocessed. This is far too aggressive.
The tension is clear: larger reduces dropping but wastes memory. Fedus et al. found that to works best — the load balancing loss keeps the routing balanced enough that very little capacity buffer is needed.
Summary
We have built six tools for Part 2. The softplus function guarantees positive noise scales by smoothly approximating . Top-k masking with forces softmax to produce exactly nonzero probabilities, enabling sparse gating where only out of experts are computed. Mean, variance, standard deviation, and the coefficient of variation measure how unbalanced expert loads are — the CV equals zero at perfect balance and increases with any deviation, making its square a natural load balancing penalty. The indicator function and argmax describe hard routing decisions: the argmax picks the best expert, the indicator counts how many tokens go where. The distinction between differentiable functions (softmax probabilities) and non-differentiable functions (argmax, indicators) explains why the load balancing loss multiplies by — gradients flow through the differentiable while the non-differentiable acts as a fixed scaling factor. The dot product measures alignment between routing counts and routing probabilities, reaching its minimum at uniform balance. And expert capacity arithmetic sets the buffer size per expert, trading dropped tokens against wasted memory.
With these tools in hand, we are ready for Part 2, where we derive sparse gating, the Switch Transformer, and load balancing losses from scratch.
Previous: Mixture of Experts from Scratch — Part 1
Next: Mixture of Experts from Scratch — Part 2
Enjoyed this post?
Subscribe to get notified when I publish new posts. No spam, unsubscribe anytime.