Top-k gating lets each example pick its experts, so some experts end up with more examples than others. For some of its experiments the Sparsely-Gated MoE paper flips the choice around: each expert picks its top examples from the batch, so every expert processes exactly . At inference there is no batch to compare against, so the paper learns a threshold per expert to imitate the batchwise choice. Implement both masks, the gating that uses them and the loss that trains the thresholds.
Let G be the softmax gate values, shape (batch, n) (each row sums to 1).
batchwise_mask(G, k)
int array of shape (batch, n).masked_gates(G, M)
M is 1 and renormalize each row to sum to 1. A row whose mask is all zeros stays all zeros (no NaN).threshold_mask(G, T)
T has one threshold per expert. Return an int array: 1 where G[r, i] > T[i], else 0.batchwise_loss(G, T, M)
float,