The Complementary Sequence-Wise Balance Loss, and the Batch-Wise Alternative
DeepSeek-V3 balances its experts mainly with the bias update, which looks at the load of a whole batch. A whole batch can be balanced while one sequence in it piles onto a few experts, so V3 adds a sequence-wise balance loss with a tiny weight (α=0.0001). The report then compares this sequence-wise scope with a batch-wise auxiliary loss that measures the same quantity over the whole batch. Compute both.
For a set of T tokens with sigmoid affinities si,t over N routed experts, each token routed to K experts:
fi=KTN∑t=1T1(token t is routed to expert i),si,t′=∑j=1Nsj,tsi,t,Pi=T1∑t=1Tsi,t′,L=α∑i=1NfiPi.
Write balance_losses(scores, idx, alpha).
scores: (B,L,N), the positive affinities of B sequences of L tokens. idx: (B,L,K) ints, the experts each token was routed to (distinct within a token).
- Return a dict:
"sequence": a list of B floats, L computed on each sequence alone (T=L);
"sequence_mean": their mean;
"batch": L computed once on all BL tokens together (T=BL).
Notes
- s′ normalises over all N experts, not only the selected ones.
- The report defines the loss per sequence and does not say how sequences are combined; the mean is our choice.