Batch size, epochs and steps
9 min read
Three words, one calculation
- Batch. A group of examples processed together. Its size is the batch size.
- Step. One update of the weights, made after a batch, or after several if you use Gradient accumulationAdding up the gradients from several small batches before making one update, so a model trains as if it had a larger batch without needing the memory..
- Epoch. One full pass over the training set.
With 100 examples and 10 per batch, one epoch takes 10 steps. With three epochs, the run takes 30 steps. The learning rate schedule, the evaluation interval and the length of the run are all counted in steps, so it helps to compute them before you start.
Count the steps in code
The program below computes the plan for a run of 2,000 examples. It rounds up, because a last partial batch still takes a step in most data loaders. Some loaders drop it instead, so check yours.
import math
examples = 2000
per_device_batch = 8
accumulation = 4
epochs = 3
effective_batch = per_device_batch * accumulation
steps_per_epoch = math.ceil(examples / effective_batch)
total_steps = steps_per_epoch * epochs
print("effective batch size:", effective_batch)
print("steps per epoch:", steps_per_epoch)
print("total steps:", total_steps)
print("evaluate every", steps_per_epoch // 2, "steps for two checks per epoch")It prints:
effective batch size: 32
steps per epoch: 63
total steps: 189
evaluate every 31 steps for two checks per epochThe effective batch size is 32: 8 examples per forward pass, four passes before each update. The run takes 189 steps in total. You can now set the warm-up to about 10 steps and the evaluation interval to every 31 steps, which gives two checks per epoch. Record all of these numbers with the run.
What batch size changes
Batch size affects two things.
- Memory. A larger batch holds more activations at once, so it needs more GPU memory, as Fitting training into memory shows.
- The gradient. The update uses the average gradient of the batch. A larger batch gives a smoother, less noisy average, and fewer updates per epoch. A smaller batch gives a noisier signal and more updates.
There is no single best size. Common effective batch sizes for fine-tuning are from 8 to 64, and the right value depends on the data and the model. If you change the effective batch size, revisit the learning rate, because the two interact.
Gradient accumulation
If a batch of 32 does not fit in memory, run four batches of 8, add up their gradients and update once. The result is the same update as one batch of 32, for equal-sized batches, with a quarter of the activation memory. It costs speed, because the four passes run one after another.
The program below checks the equivalence on a made-up set of per-example gradients.
gradients = [0.9, -0.3, 0.4, 0.2, -0.1, 0.8, 0.5, -0.6]
def mean(values):
return sum(values) / len(values)
one_batch = mean(gradients)
micro = [gradients[i:i + 2] for i in range(0, len(gradients), 2)]
accumulated = mean([mean(part) for part in micro])
print(f"one batch of 8: {one_batch:.4f}")
print(f"four micro-batches of 2: {accumulated:.4f}")
print("same update:", abs(one_batch - accumulated) < 1e-12)It prints:
one batch of 8: 0.2250
four micro-batches of 2: 0.2250
same update: TrueThe accumulated gradient equals the one from the large batch, which is why a library can offer it as a single setting. In a real training setup, anything that depends on the batch as a whole, such as batch statistics in some layers, can differ slightly. Most transformer models do not use them.
Training on several GPUs multiplies the effective batch size again. With 4 GPUs, a per-device batch of 8 and accumulation of 4, the effective batch is 128.
How many epochs
More epochs give the model more passes over the same examples. For fine-tuning, one to three epochs is a common range, and small datasets sometimes use more. Too many lead to overfitting, as Overfitting and underfitting explains. The safe method is to evaluate at intervals during training, as Reading a training run showed, and keep the checkpoint with the best validation score. Leave the test set for the final check.
- CountExamples divided by the effective batch gives steps per epoch.
- MultiplySteps per epoch times epochs gives the total steps.
- Set the scheduleChoose warm-up and evaluation intervals in steps.
- TrialRun a few steps to measure time and memory.
How many steps per epoch?
2,000 examples, an effective batch size of 32.
2,000 divided by 32 is 62.5, so 63 steps cover the data once.
What does gradient accumulation give you?
A batch of 32 does not fit in memory.
Small batches are run in turn and their gradients are added before one update.
What does an extra epoch risk on a small dataset?
You train for 10 epochs on 500 examples.
Watch validation loss and stop when it stops improving.
Your reading position is saved
0 of 36 complete
Lesson complete
Batch size, epochs and steps
Up next