Unequal token counts require one global denominator
Derive valid-token weighting across workers and accumulation windows, including zero-token cases and compatible count collectives.
On this page
The question for today
What you’ll understand
- Derive the global valid-token mean from local loss sums.
- Explain why equally averaging worker means biases unequal token batches.
- Coordinate zero-token and count-reduction behavior without changing collective participation.
A packed language-model batch can contain different numbers of valid target tokens on different workers. Averaging each worker’s mean loss gives every worker equal weight, not every valid token equal weight. That silently changes the objective when padding, masking, filtering, or sequence packing produces unequal counts. We assume fixed-world-size PyTorch 2.9 DDP default gradient averaging, a separable sum of eligible token losses, and token counts treated as data rather than differentiable model outputs. Weighted losses require the corresponding weight-sum denominator instead of a raw count.
Derive the objective before choosing a local scalar
Define a local sum over exactly the tokens included by the training objective. Exclude ignored targets and padding consistently, but do not remove examples merely because their current loss is inconvenient. Reduce the eligible counts across workers to obtain one positive global denominator. For an accumulation window, that denominator must cover the entire window, not whichever microbatch happened to finish last. Preserve the count and masks with the input fixture so that a single-process reference uses precisely the same token multiset.
The desired gradient is the sum of local loss-sum gradients divided by the global count. DDP adds its own division by world size, so one valid construction scales each local summed loss by world size divided by the global count before backward. Equivalently, a carefully controlled post-reduction rescaling can implement the same algebra, but it must occur before nonlinear transformations such as clipping. Do not divide by the global count and then accidentally leave DDP’s additional world-size division uncompensated.
Averaging worker means changes token weights
If a worker with two tokens and another with six tokens each contributes one local mean, a token on the smaller worker receives three times the weight of a token on the larger worker. The reducer cannot infer this mistake from tensor shape or successful communication. All ranks can agree perfectly on the wrong gradient. Equal local batch lengths are also insufficient when loss masks differ. Count the objective’s actual contributing targets and test an intentionally uneven fixture rather than rely on a balanced synthetic benchmark.
Zero eligible tokens need a coordinated policy. If the global count is positive but one rank has none, that rank still needs a compatible forward/backward and collective schedule, with a correctly connected zero contribution where required by the model and reducer configuration. It must not unilaterally skip backward. If the whole window has zero count, every rank must take the same defined skip or error path before division and keep optimizer, scaler, and scheduler state consistent. A divide-by-zero result is not a neutral contribution.
Count communication is part of the protocol
The count reduction is itself a collective with matching order and participation requirements. Every worker must execute it in the same intended window, including ranks whose local count is zero. DDP’s uneven-input join mechanism cannot automatically shadow arbitrary application collectives such as an extra token-count all-reduce. Use a supported coordinated protocol or terminate consistently when inputs are exhausted; do not insert a count collective on only the still-active ranks. Validate both the gradient values and the collective trace for the edge cases.
Use the function lab to isolate scalar weighting. Reset, explicitly set coefficient one and position two, predict y and slope, then Play or Step. For a separate run Reset and explicitly set coefficient 0.5 and position two before predicting again. The fixed parabola’s slope changes from four to two because scalar multiplication affects derivatives as well as loss values. This instrument contains no tokens, masks, global counts, DDP division, or distributed reductions. The numerical token fixture below supplies that accounting rather than asking the parabola to simulate it.
Work it through
The mean of two local means is the wrong objective
Two ranks have two and six eligible tokens. Their summed scalar gradient contributions at the same parameters are six and six. Compute the correct global token-mean gradient and compare with equal averaging of local means.
The global count is eight, and the total summed gradient is twelve. The desired token-mean gradient is therefore 12/8=1.5.
The local means are 6/2=3 and 6/6=1. Their equal average is two, which overweights the smaller rank’s tokens. Every rank could receive this same incorrect value without any communication error.
With world size two, scale each local summed loss by 2/8=0.25. Each scaled local gradient becomes 1.5, and DDP’s average of those two contributions is 1.5. This construction assumes the count covers exactly the objective’s valid tokens.
Global normalization gives 1.5; equal worker-mean averaging gives two. Successful replica agreement alone does not distinguish them.
The living notebook
Explore the model
Interactive lab · function
Loss scaling scales a derivative in a simpler model
For each independent run use Reset → explicitly set BOTH coefficient and position → predict → Play/Step. Compare (a,x)=(1,2), slope four, with (.5,2), slope two. The fixed y=ax² model has no token counts or DDP synchronization.
- y at chosen x
- 0.608
- Tangent slope · 2ax
- 1.35
- Signed area · ax³/3
- 0.182
This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forDerive the scalar multiplying each local loss before trusting the resulting global gradient.
Pause & reason
Check your understanding
Your turn
Try it yourself
Rank A has three valid tokens with summed gradient nine; rank B has one valid token with summed gradient one. Compute the global token mean, the equal-worker-mean result, and the local scaling factor for default two-rank DDP.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Use the same global count for both ranks and keep local sums separate from local means.
Compare with the solution
The global mean is (9+1)/(3+1)=2.5. The local means are three and one, whose equal average is two. The correct local-sum scaling factor is 2/4=0.5; scaled contributions 4.5 and 0.5 average to 2.5. If these microbatches belong to a longer accumulation window, replace four with the eligible count for that whole window and include all its loss sums. Do not add an extra division by the number of microbatches unless the chosen normalization algebra requires it.
Keep the idea
Take it with you
- Normalize the tokens or weights in the intended global objective.
- Compensate exactly once for the reducer’s divisor.
- Treat zero-count paths and count collectives as coordinated protocol steps.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.