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.

Signaturedef load_balance_loss(logits)

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. Rule: 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: random routerload_balance_loss(_z)
  • Sample 2: collapsed routerload_balance_loss(np.tile([10.0, 0.0, 0.0, 0.0], (8, 1)))