Gradient Accumulation
Definition
Gradient Accumulation — a neural network training technique where calculated gradients of several sequential microbatches are summed (or averaged) before performing one optimizer step. The effective batch size is defined as the product of the microbatch size and the number of accumulation steps.
It is used when the required batch size exceeds the available GPU or VRAM memory.
Mechanics
optimizer.zero_grad()
for i, batch in enumerate(loader):
loss = model(batch) / accumulation_steps
loss.backward()
if (i + 1) % accumulation_steps == 0:
optimizer.step()
optimizer.zero_grad()
Key parameters:
| Parameter | Influence |
|---|---|
accumulation_steps |
Number of microbatches per optimizer step |
micro_batch_size |
Size of one forward pass |
effective_batch_size |
Product of the two previous |
Normalization of loss by accumulation_steps is necessary for the correct gradient scale when averaging.
Limitations
- Does not proportionally reduce training time: the number of forward and backward passes remains the same.
- Incompatible with methods dependent on the true batch size (e.g., Batch Normalization).
- Requires coordination with Learning Rate Scheduler and Learning Rate Warmup.