494. Compute the Switch Transformer load-balancing loss
A mixture-of-experts router can collapse and send every token to the same expert. Switch Transformer adds an auxiliary loss that is smallest when tokens spread evenly.
For router logits of shape (tokens, E):
- probs = softmax over experts
- f_i = fraction of tokens whose top-1 expert (argmax, ties to lower index) is i
- P_i = mean router probability for expert i across tokens
- loss = E * sum_i f_i * P_i
Write load_balance_loss(logits). Return a float. Perfectly balanced routing gives about 1.0.
def load_balance_loss(logits)Example 1
Input: logits = np.tile([10.0, 0.0, 0.0, 0.0], (8, 1))
Output: 3.999455
Constraints
logitshas shape(tokens, E)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
The loss multiplies how often each expert is picked by its average router probability, so it grows when both pile up on the same experts.
Hint 2
Take a stable softmax over each row, count top-1 choices per expert to get f, average the probabilities over tokens to get P, then return E times the sum of f * P.
Hint 3
Use np.bincount(np.argmax(z, axis=1), minlength=E) / T so experts that are never picked still get a 0 entry, and subtract the row max before np.exp.
Common mistakes
- The buggy version drops it.
Understand the idea
A mixture-of-experts router can collapse and send almost every token to one expert, which then becomes a bottleneck. The load-balancing loss multiplies two things for each expert: f_i, the fraction of tokens whose top choice is that expert, and P_i, the average router probability for it. The sum is smallest when both are spread evenly. Multiplying by E makes perfect balance score about 1, whatever the expert count. Worked example, 2 experts, 2 tokens. Collapsed: logits [[2, 0], [2, 0]], probs [0.881, 0.119] for both, f = [1, 0], P = [0.881, 0.119], loss = 2 x (1 x 0.881 + 0) = 1.762. Balanced: logits [[1, 0], [0, 1]], f = [0.5, 0.5], P = [0.5, 0.5], loss = 2 x (0.25 + 0.25) = 1.0.
probs = softmax per token; f_i from argmax (ties to lower index); P_i = mean prob; loss = E x sum(f_i P_i)
Only P carries gradient. Switch Transformer and later MoE LLMs add this auxiliary loss.