advanced28 min studyLesson 542 in Engineering

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

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.

G=∑r∇SrN,N=∑rNr>0G=\frac{\sum_r\nabla S_r}{N},\qquad N=\sum_r N_r>0
Sr is a local sum of eligible scalar token losses and Nr a nonnegative integer token count. N is shared and treated as constant with respect to parameters. G has gradient units per global mean token loss; weighted objectives need a matching positive weight sum.↔ Scroll wide equations horizontally.

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.

L~r=WNSr⟹1W∑r∇L~r=G\widetilde L_r=\frac{W}{N}S_r\quad\Longrightarrow\quad\frac1W\sum_r\nabla\widetilde L_r=G
This exact-arithmetic scaling cancels default DDP averaging for fixed positive W and N. It assumes ordinary compatible participation and no custom hook or join divisor change. It is an objective derivation, not a drop-in implementation for every model or runtime.↔ Scroll wide equations horizontally.

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.

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.

  1. The global count is eight, and the total summed gradient is twelve. The desired token-mean gradient is therefore 12/8=1.5.

  2. 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.

  3. 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.

The result

Global normalization gives 1.5; equal worker-mean averaging gives two. Successful replica agreement alone does not distinguish them.

Explore the model

Interactive lab

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.

Loss scaling scales a derivative in a simpler modelThis 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. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

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.

Check your understanding

With unequal valid-token counts and default DDP averaging, which construction targets the global valid-token mean?

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.

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.