Balance the Gate Before It Collapses
A mixture-of-experts layer sends each example to a few experts chosen by a gating network. Left alone, the gate tends to settle on the same few experts: they get trained more, so they get chosen more. The Sparsely-Gated MoE paper counters this with a soft penalty on how unevenly the gate spreads its weight over a batch. Implement it.
importance(gates)
gates is a 2-D array of shape (batch, n_experts): row x holds the gate values G(x) for one example (non-negative, mostly zeros, each row summing to 1).
- Return a 1-D float array with each expert's importance, the sum of its gate values over the batch:
Importance(X)i=x∈X∑G(x)i
cv_squared(values, eps=1e-10)
- The squared coefficient of variation of a 1-D array: the population variance (divide by the count, not count − 1) over the squared mean,
CV2=vˉ2+ϵVar(v)
- Return
0.0 when the array has fewer than 2 entries. Return a Python float.
importance_loss(gates, w_importance)
- Return wimportance⋅CV2(Importance(X)) as a Python
float.
Hints
- One reduction over the batch axis gives the importance vector.
- A perfectly even importance vector has variance 0, so its loss is 0 however large the batch.