PyTorch Gradient Accumulation with Unequal Microbatches
Normalize summed losses over the whole optimizer update. A PyTorch example shows why averaging unequal microbatch means changes the gradient.
For a mean loss over examples, sum the per-example losses in each microbatch and divide by the total number of examples in the optimizer update. Call backward for each scaled sum, then step once. If you already have a mean loss for each microbatch, multiply each mean by that microbatch’s share of the total examples. Dividing each microbatch mean by the number of microbatches gives unequal weights to individual examples when the microbatch sizes differ.
Use the denominator defined by your objective
Suppose one update groups a three-example microbatch and a one-example microbatch. Averaging their means gives each group half the total weight. Each example in the larger group receives one sixth of the weight, while the single example receives one half. A mean over all examples gives each one a quarter.
The recipe assumes the objective is a sum of independent loss terms normalized by a known count. In the scalar MSE example below, one example contributes one loss element. For a token-level objective that excludes padding, the denominator may instead be the total valid tokens. Work out what the loss reduces before choosing the count.
Source: Hugging Face Accelerate — Gradient accumulation with variable-size samples ↗
Compare a full batch and two accumulation rules
Train a one-parameter model that predicts the same scalar w for every example. Start at w = 0 and use SGD with a learning rate of 0.1. The first microbatch has targets 1, 2, and 3. The second has target 10. The four derivatives at zero are −2, −4, −6, and −20, so the full-batch mean gradient is −8 and the optimizer moves w to 0.80.
If you give each microbatch mean equal weight, the two gradients being averaged are −4 and −20. Their mean is −12 and the same optimizer moves w to 1.20. Both versions perform one step and both can run without error. Comparing against a concatenated batch is a small test that exposes the weighting difference.
import torch
import torch.nn.functional as F
microbatches = [torch.tensor([1., 2., 3.]), torch.tensor([10.])]
num_examples = sum(batch.numel() for batch in microbatches)
def update(mode):
w = torch.nn.Parameter(torch.tensor(0.))
optimizer = torch.optim.SGD([w], lr=0.1)
optimizer.zero_grad()
if mode == "full":
targets = torch.cat(microbatches)
F.mse_loss(w.expand_as(targets), targets).backward()
else:
for targets in microbatches:
predictions = w.expand_as(targets)
if mode == "weighted":
loss = F.mse_loss(predictions, targets, reduction="sum")
loss = loss / num_examples
else:
loss = F.mse_loss(predictions, targets) / len(microbatches)
loss.backward()
optimizer.step()
return w.item()
for mode in ("full", "weighted", "mean_of_means"):
print(f"{mode}: {update(mode):.2f}")
# full: 0.80
# weighted: 0.80
# mean_of_means: 1.20Handle a partial accumulation window at the end
Build the denominator from the batches actually in the current update. If the loop expects four microbatches but reaches the end after two, decide whether to perform that last update. If you do, use the actual total count for those two. Clear gradients once per update window and step after the last included backward call.
The equivalence test here uses independent squared errors and one parameter. Training with operations that depend on other examples in the forward batch, such as training-mode batch normalization, can still differ from one large forward pass. Use the concatenated-batch check first on a small model where the loss terms are independent and the forward pass is deterministic.
Source: Hugging Face Transformers — Gradient accumulation and optimizer timing ↗
Predict the update in a PTCA practice question
Before working through the arithmetic, write down the objective, the number of contributing loss terms, and where the optimizer steps. If the question asks for one mean over all examples, a shorter group contributes a smaller share of the total. Check whether any zero_grad call discards earlier gradients before the update.
Open the free PTCA practice sample below in Study mode. Its unequal-microbatch question uses a different update. Predict the printed weight and then compare your denominator and gradient against the explanation.
Source: Hugging Face Transformers — Gradient accumulation and optimizer timing ↗
Your next steps
- Use the total contributing loss terms in the current optimizer update.
- Weight microbatch means by their share of that total.
- Compare a small accumulated update against a full-batch reference.
Sources & official resources
Linked resources checked on 2026-11-26. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →