Count the tokens that actually contribute to each update
Derive global valid-token batches and loss normalization across ranks and accumulation microbatches without silently weighting short batches more heavily.
On this page
The question for today
What you’ll understand
- Distinguish padded token slots from valid targets and optimizer updates.
- Calculate a global token-weighted objective from unequal local batches.
- State the gradient-reduction assumptions behind accumulation scaling.
Training budgets often quote tokens and batch size as though those were unambiguous counters. In practice, allocated slots include padding and excluded transitions, microbatches can contain different numbers of valid targets, and one optimizer update can accumulate work from several ranks. A correct reduction must reflect the intended objective. Counting storage capacity as training exposure or averaging unequal local means can change that objective while leaving a familiar batch-size label in the configuration.
Keep separate counters for separate events
Let a microbatch contain a known number of eligible prediction targets after serialization, shifting, padding, and boundary masks. Sum those counts across the microbatches and ranks contributing to one optimizer update. This is the update's valid-token batch. A product of data-parallel ranks, accumulation steps, sequences, and sequence length equals that count only under additional full-occupancy and eligibility assumptions. Tensor-parallel replicas holding pieces of the same examples are not additional independently trained tokens.
Also separate attempted updates, successful applied updates, consumed data, and accepted checkpoint progress. An overflow-skipped step can consume data without changing weights; a restart can recompute work already performed but not preserved in the recovered trajectory. Those counters answer different resource and exposure questions. Log the conventions explicitly. A reported tokens-per-second number should identify whether it measures processed input slots, valid targets, or another quantity, and whether it includes recovery and skipped-update work.
Reduce numerators and denominators consistently
For an unsmoothed unweighted token objective, sum local negative log-likelihoods and divide by the global valid-token count. Averaging local means instead weights each local batch equally, even if one has twice as many scored targets. The same distinction applies to gradients at a fixed parameter state. If a data-parallel system averages rank gradients, each rank's local summed-loss gradient needs scaling consistent with that average and the global denominator. Framework-provided averaging and accumulation conventions must be accounted for once, not guessed.
For example, under an explicit average-over-R-ranks reduction, scaling each rank's accumulated loss sum by R/T gives the gradient of the global token mean. If a trainer already divides by accumulation count or uses a different reducer, that formula must be adapted. PyTorch 2.9 documents DDP's gradient behavior and mixed-precision accumulation requirements. Validate the chosen implementation against a small single-process concatenated-batch reference, including deliberately unequal valid counts and the final incomplete accumulation group.
A nominal batch does not promise equivalent learning dynamics
Even with the same global token count, changing sequence lengths, document mixture, dropout realization, or reduction order can alter gradients. Increasing the valid-token batch can reduce some sampling variation but does not imply a universal linear learning-rate scaling rule. Keep the actual objective, optimizer, schedule clock, and token-exposure ledger attached to any batch-size experiment. For remainder groups, choose a declared policy such as correct renormalization, carrying work forward, or dropping it; silently using the full-group denominator changes update magnitude.
The sampling lab isolates one variance relationship under independent identical Bernoulli observations. Reset, set both p=0.5 and n=20, predict mean 0.5 and sample-mean variance 0.0125, then Play or Step. Reset and set both p=0.5,n=100 for variance 0.0025. The bars are exact binomial masses, and playback only highlights outcomes. Tokens and gradients in a document are correlated and heterogeneous, so this instrument does not infer an effective independent sample size or an optimizer scaling law for language-model training.
Work it through
Expose an average-of-means error
Two data-parallel ranks each accumulate two microbatches. Rank 0 has 1,000 valid targets in each, with mean loss two nats per token. Rank 1 has 500 in each, with mean loss four. All losses use the same declared objective.
Rank 0 contributes 2,000 tokens and 4,000 nats of summed loss. Rank 1 contributes 1,000 tokens and 4,000 nats. The global count is 3,000, not four equal local batches' nominal capacity.
The global mean is (4,000+4,000)/(2,000+1,000)=8/3≈2.6667 nats per token. Averaging the rank means gives (2+4)/2=3 and overweights the shorter rank's targets.
Use summed losses and valid counts, with gradient scaling matched to the actual reducer. Compare against a concatenated reference before assuming distributed accumulation implements the intended token-weighted objective.
The correct descriptive global loss is approximately 2.6667, not three. Equal accumulation counts do not make unequal valid-token counts equally weighted.
The living notebook
Explore the model
Interactive lab · sampling
Inspect a limited independent-sample variance model
Fresh Reset → set both p=0.5,n=20 predicts variance 0.0125; Reset → set both p=0.5,n=100 predicts 0.0025. Play or Step highlights exact binomial outcomes rather than generating samples. This is not a gradient, token-correlation, or learning-rate scaling simulator.
- Mean sample proportion
- 0.5
- Sample-mean variance
- 0.0125
- Uniform CDF error bound
- ≤ 0.1062
Exact binomial masses for the mean of n independent Bernoulli trials, compared with normal mass between adjacent half-count boundaries; normal tails outside the finite support remain outside the bars. Playback highlights outcomes, not random samples. The Berry–Esseen bound applies to standardized CDFs, not individual bars or continuity-corrected errors. At p = 0 or 1, normal comparison and that bound are disabled. Normal-CDF evaluation uses a numerical approximation with absolute error below 7.5×10⁻⁸ (at most 1.5×10⁻⁷ per interval, before rounding). 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 forA counted token batch and a justified independent sample size are different quantities.
Pause & reason
Check your understanding
Your turn
Try it yourself
Three microbatches contain 800, 800, and 400 valid targets, all with loss two nats per token. The final one is an incomplete accumulation group. What is the total valid-token mean, and what happens if its sum of 800 nats is divided by an assumed 800-token count?
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Separate the correct combined objective from the normalization of the incomplete group's own update.
Compare with the solution
The combined loss sum is 1,600+1,600+800=4,000 nats over 2,000 targets, giving two nats per token. The final group's own mean is 800/400=2. Dividing that sum by 800 instead gives one and halves its intended mean-loss gradient scale at a fixed parameter state. A remainder policy must therefore use the actual count or explicitly implement another documented objective; an unchanged nominal accumulation setting is not enough.
Keep the idea
Take it with you
- Valid target tokens, input slots, update attempts, and accepted progress need separate counters.
- Unequal microbatches require normalization matched to the global objective and reducer.
- Matching token counts alone does not guarantee matching gradients or learning dynamics.
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.