The interview problem
A training job fits 16 examples per GPU but needs an effective batch of 256 on four GPUs. Explain how to accumulate gradients correctly. The last microbatch is smaller and sequence lengths vary. Demonstrate when accumulation matches a large batch and when it does not.
Original fundamentals practice, not a reported interview. Numerical examples are hypothetical. Primary technical documentation retrieved September 27, 2026.
Quick answer
Gradient accumulation adds gradients from several microbatches before an optimizer step. Equal-sized microbatches can reproduce a larger batch’s mean gradient when normalization and model behavior match. Unequal token counts require a global denominator; averaging each microbatch mean equally is generally wrong.
1. State the mathematical condition
Let the desired objective be the mean of N per-example losses at one fixed parameter vector θ. Its gradient is the sum of those N loss gradients divided by N. Split the examples into microbatches, compute each contribution at the same θ and add those gradients before taking one optimizer step. Linearity gives the same mathematical gradient when the loss decomposes over examples and the forward computations are equivalent.
This does not mean taking an optimizer step after each microbatch. Those later gradients would be evaluated at changed parameters, and momentum or adaptive optimizer state would also change multiple times. Keep weights fixed across the accumulation window, then perform one update using the combined gradient.
In floating-point arithmetic, summation order and kernel choices can produce small numerical differences even with the same mathematical objective. Test closeness with a justified tolerance rather than demanding identical bits.
2. Calculate the effective batch
With four data-parallel workers, 16 examples per microbatch per worker and four accumulation rounds, the effective batch contains 4 × 16 × 4 = 256 examples, assuming distinct data and no dropped examples. Each worker processes 64 examples before the shared update.
For equally sized microbatches and a distributed reducer that averages gradients across workers, scaling each local mean loss by 1/4 across the four rounds gives the desired global mean gradient. Verify your framework's actual reduction convention: a sum reducer requires different scaling.
The final incomplete window needs its actual denominator. If only two full rounds remain, dividing by the configured four halves the intended mean gradient. Either deliberately drop that window or normalize by its real number of examples; document the choice and count discarded data.
3. Work through unequal microbatches
On one worker, suppose the first microbatch has three examples, each with scalar gradient 2, while the second has one example with gradient 10. The full-batch mean gradient is (3 × 2 + 10) / 4 = 4.
Averaging the two microbatch means produces (2 + 10) / 2 = 6. It overweights the single-example microbatch. Correct weights are 3/4 and 1/4, or accumulate summed loss gradients and divide by the total count once before the update.
For language-model training, define whether the objective weights tokens or sequences equally. If valid-token counts differ, averaging per-microbatch token means gives the wrong global token mean. Exclude masked tokens from both numerator and denominator. A microbatch with no valid targets needs an explicit zero-contribution path rather than division by zero.
4. Normalize across workers, not just locally
Suppose worker A contributes a summed gradient of 6 from three targets, and worker B contributes 10 from one target. The correct global mean remains 16/4 = 4. Averaging their local means gives (2 + 10)/2 = 6, even if each worker's own accumulation is internally correct.
If the reducer averages local summed gradients over W workers, its result is the global sum divided by W. Multiply that result by W/N_global to obtain the mean over all valid targets. In this example, the average of sums is 8 and W/N_global is 2/4, yielding 4. Alternatively, normalize local loss sums with the corresponding factor before backward when the global denominator is known.
All workers must agree on the window boundary, denominator and reduction schedule. Suppressing intermediate synchronization can reduce communication, but it does not change the required final normalization. Test uneven target counts explicitly; equal-length synthetic examples can hide this bug.
5. Apply nonlinear operations at the intended boundary
Gradient clipping is nonlinear. With two gradient contributions (2, 0) and (0, 2), clipping each to norm 1 and adding gives (1, 1). Adding first gives (2, 2); clipping that combined vector to norm 1 gives approximately (0.7071, 0.7071). They are different update directions or magnitudes in general. Normalize the accumulated objective gradient, then clip once if the intended algorithm clips the effective batch.
With mixed-precision scaling, retain one scale throughout the window. Unscale only after accumulation completes, then apply clipping and the optimizer step. Update the loss scale at the effective-update boundary. Mixing gradients produced under different scale factors corrupts the sum unless each contribution is explicitly converted consistently.
Define scheduler and weight-decay semantics per optimizer update. Four microbatch backward calls are not four Adam updates. If numerical overflow causes the optimizer to skip an update, decide whether the learning-rate schedule advances; keep logging and checkpoint counters consistent with the chosen policy.
6. Identify non-equivalent forward passes
Batch-dependent computations can violate the decomposable-loss assumption. Training-mode batch normalization uses statistics from the current forward batch. Several small forwards therefore need not reproduce one large forward. Synchronizing statistics across workers still does not automatically combine separate accumulation rounds.
Contrastive losses with in-batch negatives change when each example sees only its microbatch peers. Accumulating gradients cannot invent the missing cross-microbatch comparisons. A specialized approach that retains or recomputes representations may address this, but it has its own memory and gradient-correctness requirements.
Random operations such as dropout may use different random draws when the batch is split. Equivalent distributions do not guarantee identical realized gradients. For a clean equivalence test, start with a deterministic model without batch-dependent layers, identical weights and fixed input data, then introduce these complications separately.
7. Explain what memory is saved
Accumulation usually reduces peak activation storage because each microbatch can complete backward before the next forward. Parameters, optimizer state and accumulated gradient buffers still exist. It does not make an oversized parameter set fit merely by choosing a smaller microbatch.
Assume fixed model/optimizer/gradient memory is 12 GB and activations require 0.25 GB per example. A 16-example microbatch uses roughly 12 + 4 = 16 GB; a physical 64-example batch on that worker uses roughly 12 + 16 = 28 GB. Four accumulation rounds keep the activation estimate near the smaller peak, not four times it, provided old computation graphs are released.
These estimates omit allocator overhead and temporary workspaces. Smaller microbatches may reduce accelerator utilization, so measure examples or valid tokens per second as well as peak memory. Accumulation trades execution pattern for memory; it is not free parallelism.
8. Validate the training loop
Compare a single large-batch update with accumulated updates from the same initial state on a tiny deterministic model. Check gradients before stepping and weights after stepping. Include unequal microbatches, an incomplete final window, masked targets and unequal target counts across workers. Verify that zeroing gradients happens once per window rather than after every microbatch.
Checkpoint at update boundaries for simplicity. If mid-window recovery is required, save the usual weights and optimizer state plus partial gradients, denominator, data position, random state and scaling state, or deliberately replay the whole window from a consistent earlier checkpoint. Resuming only weights halfway through accumulation changes the update.
Foundation: derive 256 effective examples. Senior: explain why the correct gradient is 4 rather than 6. Staff: validate distributed token weighting and recovery from an interrupted window.
Score 0–2 each for mathematical equivalence, loss weighting, distributed normalization, update ordering and limitations.
Normalize tokens across workers
Suppose two workers accumulate 100 and 300 valid tokens. For one scalar parameter, their summed token gradients are 200 and 1,200. The desired global token-mean gradient is (200 + 1,200) / (100 + 300) = 3.5.
If distributed data parallel averages the workers’ summed gradients, the reduced gradient is 700. Multiply by world_size/global_token_count = 2/400 to obtain 3.5. Averaging local means instead gives (2 + 4)/2 = 3, which weights workers equally rather than tokens. This example assumes the objective is a mean over valid tokens and no additional loss terms.
Count valid tokens across the whole accumulation window and all workers. Keep loss scaling consistent across that window, synchronize the intended final backward pass, unscale before clipping, and step once. Skip an all-padding window coherently across workers instead of dividing by zero. Sequence-level weighting, custom communication hooks and auxiliary losses require their own normalization contract.
Sources and next steps
- PyTorch: Automatic Mixed Precision examples — accumulation boundaries, consistent scaling and unscaling before clipping.
The numerical counterexamples and memory model are original derivations. Framework-specific execution behavior must be checked against the version used in an implementation.
Continue your preparation
Choose a connected learning path or browse more ML fundamentals questions. Read our editorial method and attribution policy.