Route tokens with expert capacity and drop the overflow
Why it matters Switch Transformer and GShard-style training drop tokens with exactly this rule.
Training-time MoE gives each expert a fixed capacity. Tokens beyond it are dropped and pass through the residual.
Write capacity_route(expert_ids, n_experts, capacity_factor). expert_ids is the top-1 expert per token, in token order. Capacity C = ceil(capacity_factor * n_tokens / n_experts). Tokens are accepted in order until their expert has C tokens. Return (slots, dropped) where slots[i] is the position of token i inside its expert's buffer, or -1 if dropped, and dropped is the number of dropped tokens.
def capacity_route(expert_ids, n_experts, capacity_factor)Example
capacity_route([0, 0, 0, 1], 2, 1.0) has C 2, slots [0, 1, -1, 0], dropped 1.
Understand the idea
During MoE training every expert gets a fixed-size buffer so the batch has static shapes. The capacity is the average number of tokens per expert, times a capacity factor for slack. Tokens arrive in order; once an expert's buffer is full, extra tokens sent to it are dropped and simply pass through the residual connection. Worked example: expert_ids [1, 1, 0, 1, 1, 2], 3 experts, factor 1.0. C = ceil(1.0 * 6 / 3) = 2. Token 0 takes slot 0 of expert 1, token 1 takes slot 1, token 2 takes slot 0 of expert 0. Tokens 3 and 4 also want expert 1, which is full, so they get -1. Token 5 takes slot 0 of expert 2. slots [0, 1, 0, -1, -1, 0], dropped 2. Rule: C = ceil(capacity_factor * n_tokens / n_experts); keep a counter per expert; for each token in order, if its expert's count is below C, its slot is the count and the count goes up, else the slot is -1. Use a ceiling, not a floor. Used in: Switch Transformer style MoE training.