Expert routing: a good score does not guarantee a free slot
专家路由与负载均衡
Trace top-1 dispatch, overflow and residual outputs, then verify a load-balancing gradient without mistaking its scalar value for balanced traffic.
expert-routingStart with the problem
A router can select an expert correctly according to its scores and still fail to execute that expert because its buffer is full. Routing therefore includes more than argmax: it needs a capacity policy, a rule for accepting tokens and a way to handle overflow.
Switch Transformers sends a token to one selected expert, weights that expert’s output by its gate probability, and uses residual connections when expert computation is skipped. GShard studies top-2 group routing with capacity and a different auxiliary-loss convention. Our program implements a small explicit top-1 policy so these choices can be inspected individually.
Definitions and derivation
There are T tokens and E experts. Softmax produces a probability row for each token. We choose its largest entry, breaking ties by the lowest expert index. Each expert accepts tokens in input order up to integer capacity C:
The ceiling is our discrete buffer convention. The retained gate probability comes from the full softmax and is not renormalized to one. Overflow sets the expert contribution to zero; the token’s residual value remains. Unused capacity in another expert is not automatically reassigned, since that would change the routing policy.
The Switch-style balancing statistic uses assignment fractions f and average probability fractions P. We count assignments before capacity rejection and omit the paper’s multiplicative auxiliary coefficient when reporting the value:
If both vectors are uniform, this value is one. But a value of one does not certify uniform assignments. When every probability row is uniform and ties always choose expert zero, f=(1,0,0) while P=(1/3,1/3,1/3); the value is still one. Actual counts, unused slots and overflow must be inspected alongside the scalar objective.
Holding the nondifferentiable assignment fractions fixed, the softmax derivative gives:
The derivative is through P, not through argmax. At the tied-uniform counterexample, this gradient is nonzero even though the loss value equals the balanced reference. Thus identical auxiliary values can correspond to different training signals. A finite-difference check should keep f fixed or use a neighborhood where hard assignments do not change.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program uses six tokens, three experts and capacity factor one. Expert e returns (e+1)x. These simple functions make skipped and weighted contributions visible; no distributed training occurs.
import numpy as np
def route(logits, capacity_factor=1.0):
logits = np.asarray(logits,dtype=float)
if logits.ndim != 2 or not 1 <= logits.shape[0] <= 32 or not 2 <= logits.shape[1] <= 8 or not np.isfinite(logits).all():
raise ValueError('Use a finite token-by-expert logit matrix.')
if not np.isfinite(capacity_factor) or not 0 < capacity_factor <= 4:
raise ValueError('Capacity factor must be in (0,4].')
shifted = logits-logits.max(axis=1,keepdims=True); probabilities = np.exp(shifted); probabilities /= probabilities.sum(axis=1,keepdims=True)
tokens, experts = logits.shape; choices = probabilities.argmax(axis=1)
capacity = int(np.ceil(capacity_factor*tokens/experts))
occupied = np.zeros(experts,dtype=int); accepted = np.zeros(tokens,dtype=bool)
for token, expert in enumerate(choices):
if occupied[expert] < capacity:
accepted[token] = True; occupied[expert] += 1
return probabilities, choices, accepted, occupied, capacity
def balance(probabilities, fractions):
p, f = np.asarray(probabilities,dtype=float), np.asarray(fractions,dtype=float)
tokens, experts = p.shape
loss = float(experts*np.sum(f*p.mean(axis=0)))
gradient = experts/tokens*p*(f-(p*f).sum(axis=1,keepdims=True))
return loss, gradient
def dispatch(x, logits, capacity_factor=1.0):
x = np.asarray(x,dtype=float)
p, choices, accepted, occupied, capacity = route(logits,capacity_factor)
if x.shape != (len(p),) or not np.isfinite(x).all():
raise ValueError('Use one finite scalar feature per token.')
output = x.copy(); evaluations = 0
for i in np.flatnonzero(accepted):
e = choices[i]
output[i] += p[i,e]*(e+1)*x[i]; evaluations += 1
fractions = np.bincount(choices,minlength=p.shape[1])/len(p)
return output, fractions, balance(p,fractions)[0], (choices,accepted,occupied,capacity,evaluations)
def example_logits():
return np.array([[3,1,0],[4,0,0],[2,1,0],[1,0,0],[0,3,1],[0,1,3]],dtype=float)
if __name__ == '__main__':
for name, logits in [('uneven',example_logits()),('tied uniform',np.zeros((6,3)))]:
output,f,aux,state = dispatch(np.arange(1,7),logits)
choice,accepted,occupied,capacity,calls = state
print(name,'assigned',np.bincount(choice,minlength=3).tolist(),'accepted',occupied.tolist(),'capacity',capacity)
print('dropped contribution rows',np.flatnonzero(~accepted).tolist(),'expert evaluations',calls,'balance loss',round(aux,9))
print('residual outputs',output.round(9).tolist())
Actual output:
uneven assigned [4, 1, 1] accepted [2, 1, 1] capacity 2
dropped contribution rows [2, 3] expert evaluations 4 balance loss 1.283458966
residual outputs [1.843794734, 3.929326312, 3.0, 4.0, 13.437947345, 21.188305221]
tied uniform assigned [6, 0, 0] accepted [2, 0, 0] capacity 2
dropped contribution rows [2, 3, 4, 5] expert evaluations 2 balance loss 1.0
residual outputs [1.333333333, 2.666666667, 3.0, 4.0, 5.0, 6.0]
The uneven case assigns (4,1,1) tokens but executes only (2,1,1). Rows 2 and 3 retain residual values 3 and 4. The tied-uniform case assigns all six tokens to expert zero and drops four expert contributions, despite balance loss one. Changing token order can change which overflowing tokens are accepted under this first-come policy.
This implementation stores the T-by-E probability matrix. Scoring and normalizing it require work proportional to TE; top-1 assignment adds a scan across the token rows. Real distributed systems also pack buffers, move representations between devices and combine outputs. Raising capacity reduces some overflow but increases reserved slots and potential padding cost.
When the method fails
Do not report accepted-token fractions as if they were the pre-capacity assignment fractions in the displayed loss. Rejected tokens would disappear from the statistic and hide a congested expert. Also distinguish skipped expert computation from deleting a token from the sequence.
The original papers use particular balancing coefficients, grouping and dispatch conventions. Our rounding, tie-breaking and first-come acceptance are declared teaching choices, not a universal router specification. A learned router needs task-loss evaluation, utilization measurements and checks for systematic overflow. This example verifies semantics and a fixed-f gradient; it neither trains a Switch model nor measures network communication.
Exercises with answers
- With six tokens, three experts and capacity factor one, what is each capacity?
Answer 1: Two. Total reserved capacity equals six, but uneven assignment can still overflow one expert.
- What reaches the next layer for a dropped contribution in this example?
Answer 2: The original residual x, with no expert addition.
- Does balance loss one prove assignments are uniform?
Answer 3: No. Uniform probability rows with deterministic ties can send every token to one expert while producing that value.
- Why keep f fixed when differentiating the auxiliary loss?
Answer 4: Hard argmax counts are nondifferentiable; the displayed training surrogate differentiates the probability averages P.
Sources and next steps
Switch physical pages 4–6 define retained gate weights, capacity, residual bypass and the f/P auxiliary loss. GShard physical pages 6–7 show a contrasting top-2 grouped design. The six-token traces, tied-uniform counterexample and derivative tests are original. Revisit mixture of experts for the difference between full-softmax weighting and selected-set renormalization.
Make a prediction, then check
What must be checked besides a scalar balance loss?
Learning objectives
- Trace assignment, acceptance, overflow and residual semantics.
- Derive the fixed-assignment balance gradient and interpret its limits.
Prerequisites & connections
Explore related knowledge →References
- Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity
William Fedus; Barret Zoph; Noam Shazeer · 2022 - GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding — arXiv v1
Dmitry Lepikhin et al. · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity · Physical pages 4–6, Equations 2–6: gate-weighted top-1 output, capacity factor, residual overflow bypass and nondifferentiable f / differentiable P balance loss.
- GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding — arXiv v1 · Physical pages 6–7, capacity and auxiliary-loss discussion plus Algorithm 1: contrasting grouped top-2 dispatch, counters and overflow.
Related topics