Microbatch size and gradient semantics
Preserve the intended sample or token objective while changing accumulation, kernel shape, and schedule microbatches.
On this page
The question for today
What you’ll understand
- Derive weighted accumulation for unequal valid-token counts.
- Account for schedule scaling and data-parallel reduction conventions.
- Separate optimization equivalence from kernel efficiency and bitwise reproducibility.
Splitting a training batch changes its execution units, but it should not silently change which examples or tokens receive weight in the objective. Equal-sized microbatches with identical loss reductions are a convenient special case. Padding, masking, variable lengths, or a short final microbatch can break that shortcut. This lesson follows GPipe’s synchronous accumulation semantics and the explicit gradient-scaling contract in PyTorch 2.8 pipeline schedules.
Begin with the objective and its denominator
For a token-mean language-model objective, count the valid supervised tokens rather than padded positions or merely sequences. If microbatch m contains n_m valid tokens and reports its own token-mean gradient, its contribution to the whole-batch token mean is weighted by n_m. Averaging those means equally is correct only when the valid counts match. A microbatch with no valid targets needs an explicit handling policy that avoids division by zero while preserving the intended objective and collective participation. If the runtime expects static microbatch shapes, pad and mask a tail or use a supported batching policy rather than assuming a shorter final tensor is legal.
Keep the count and sum consistent across pipeline and data-parallel boundaries. A loss sum accumulated over microbatches can be divided by the complete valid-token count once, or each contribution can be normalized to the same global denominator. Those approaches require matching conventions in the communication layer. If a data-parallel reducer averages replica gradients, an already global-normalized local sum needs the corresponding compensation; blindly averaging again introduces another factor. Write the algebra before adding pipeline scheduling or mixed-precision loss scaling.
Match runtime scaling to the chosen reduction
PyTorch 2.8 pipeline schedules expose scale_grads, which by default scales accumulated gradients by the number of microbatches. That behavior matches a suitable equal-microbatch mean-loss setup; it does not automatically implement unequal token weighting. A sum-loss design can disable that averaging and apply the intended full-batch normalization exactly once. Check the version-specific schedule and loss implementation together, including any external training loop that rescales gradients. A default is not evidence that a particular masked objective is normalized correctly.
Accumulate all intended contributions before applying the logical optimizer update. Gradient clipping, weight decay, momentum updates, and learning-rate progression performed once per microbatch can define a different algorithm from performing them once per effective batch. Mixed-precision scaling and overflow handling must also agree across the ranks whose update is coupled. Even with mathematically equivalent sums, floating-point reduction order can cause small differences; state a justified numeric tolerance rather than promising bitwise identity merely because the global batch size matches.
Tune execution without changing the target accidentally
At fixed global example batch, increasing M reduces b and can reduce a modeled pipeline bubble while making matrix kernels less efficient. Smaller messages can also increase communication startup overhead relative to payload. Batch normalization computes statistics over its actual execution group, so microbatching can change the function itself even when gradient weighting is correct. Random masks and stateful operations likewise need a defined equivalence target. Validate both losses and gradients using unequal valid counts and a short final microbatch before evaluating throughput.
The Roofline lab isolates an assumed change in arithmetic intensity. Reset, set intensity to 2 and bandwidth to 80, predict the synthetic ceiling, then Step: 160 GFLOP/s. Compare a fresh Reset with both intensity at 8 and bandwidth at 80 before Step: 640 GFLOP/s. Its fixed compute ceiling is 1000. This is not a measured microbatch-size sweep and contains no gradient accumulation, token masks, pipeline bubbles, or optimizer semantics.
Work it through
Two microbatch means are not always equally weighted
Two microbatches contain two and six valid tokens. At the same parameter value, their scalar token-mean gradients are 10 and 2. Calculate the correct whole-batch token-mean gradient, compare an equal mean of means, and evaluate one declared global example count.
The weighted gradient numerator is 2 × 10 + 6 × 2 = 32, with eight valid tokens total. The intended gradient is 32/8 = 4.
An equal mean of the two means is (10 + 2)/2 = 6. It overweights the smaller microbatch and represents a different objective in this example.
Separately, D = 2 replicas, M = 4 microbatches, and b = 3 examples give 2 × 4 × 3 = 24 examples per update. That example count does not replace the valid-token denominator above.
Correct accumulation follows the objective’s units and denominator rather than the number of schedule chunks alone.
The living notebook
Explore the model
Interactive lab · roofline
An assumed kernel-intensity tradeoff
Reset, set I = 2 and B = 80, predict the synthetic ceiling, then Step: 160 GFLOP/s. Compare a fresh Reset with both I = 8 and B = 80 before Step: 640 GFLOP/s. The fixed compute ceiling is 1000; no actual microbatch kernels or gradients are executed.
- Attainable ceiling
- 640 GFLOP/s
- Ridge intensity
- 12.5 FLOP/byte
- Ceiling regime
- Memory-bound ceiling
Synthetic roofline ceiling min(1000, B·I), in GFLOP/s, with B in decimal GB/s and I in FLOP/byte. Playback traces the roof without changing the selected kernel. This upper-bound model is not a measured throughput prediction, hardware comparison or price model. 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 forExecution efficiency can change independently of the loss weighting required for an equivalent update.
Pause & reason
Check your understanding
Your turn
Try it yourself
Microbatches with three and one valid tokens have scalar token-mean gradients 2 and 10. Compute the correct token mean and the unweighted mean. Explain one condition besides normalization needed for synchronous reference equivalence.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Multiply each mean by its valid count before summing.
Compare with the solution
The correct gradient is (3 × 2 + 1 × 10)/4 = 4, while the equal mean is six. The reference also needs the intended common parameter version and update boundary, plus compatible batch-dependent operations, randomness, state, and numeric tolerance. Correct weighting alone cannot make microbatch batch-normalization statistics identical to statistics computed over a larger batch.
Keep the idea
Take it with you
- Weight gradient contributions by the objective’s actual sample or token count.
- Schedule averaging, replica reduction, and external loss scaling must be accounted for exactly once.
- Kernel efficiency, optimizer semantics, and numeric reproducibility are separate checks.
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.