The Switch-style auxiliary loss rewards an even load, but "even" depends on which tokens you count over: one sequence, one micro-batch, or the whole global batch. Implement the loss at all three scopes, the device-level form that balances GPUs instead of experts, and the gradient that the micro-batch loss sends into the router logits.
For a set of tokens with full router probabilities (rows sum to 1) and top- choices, let be the number of times expert was chosen (each token's choices count once), and
aux_loss(probs, idx, alpha, scope)
probs: (M, B, L, N), idx: (M, B, L, k): micro-batches of sequences of tokens.scope="sequence": compute for every sequence separately () and return the mean over all sequences.scope="micro_batch": compute for every micro-batch () and return the mean over the micro-batches.scope="global": compute once over all tokens.device_loss(probs, idx, alpha, num_devices)
aux_loss_grad(logits, idx, alpha)
logits (T, N) with , idx (T, k). The counts are not differentiable, so is a constant. Return as a (T, N) array.