Sub topic 12
Choosing a batch size for throughput and memory
This chapter assumes you can write a PyTorch Dataset and DataLoader, and that you know what a uint8 image tensor of shape 3 x H x W is. It also assumes you have already profiled your pipeline (see the earlier chapter on profiling). Batch size interacts with every stage you have tuned so far, so it is worth choosing it deliberately instead of copying a number from a paper.
What batch size controls
The batch size is the number of images the model processes in one forward pass (and one backward pass, in training). Three things change when you change it:
- Accelerator utilisation. A GPU runs thousands of operations in parallel. A small batch leaves much of that hardware idle, and each kernel launch carries a fixed overhead. A larger batch spreads that overhead over more images.
- Memory use. Activations grow roughly linearly with batch size. Model weights and optimiser state do not.
- Pipeline behaviour. Each batch is a unit of work for the loader. A larger batch takes longer to assemble, occupies more pinned memory, and increases the burstiness of CPU work.
For training, batch size also affects optimisation (gradient noise, learning rate, generalisation). This chapter focuses on throughput and memory. Treat the optimisation side as a separate constraint that you must check, not ignore.
Throughput saturates
Throughput is images per second. As batch size grows, throughput rises quickly at first, then flattens. Past the flat point, a larger batch costs more memory and gives almost no extra speed. Your goal is to find the knee of that curve.
The numbers above are illustrative. Your curve depends on the model, the input resolution, the precision, and the GPU. Measure it instead of guessing.
Measuring the curve
The script below times the model alone, with synthetic data already on the GPU. This isolates the effect of batch size on the accelerator from the effect of the loader. It uses torch.cuda.synchronize() because CUDA calls are asynchronous, and without it you would time only the kernel launches.
import time
import torch
import torchvision
def measure(model, batch_size, size=(224, 224), steps=20, warmup=5):
x = torch.randn(batch_size, 3, *size, device="cuda")
torch.cuda.reset_peak_memory_stats()
with torch.no_grad():
for _ in range(warmup):
model(x)
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(steps):
model(x)
torch.cuda.synchronize()
dt = time.perf_counter() - t0
images_per_s = batch_size * steps / dt
peak_mb = torch.cuda.max_memory_allocated() / 2**20
return images_per_s, peak_mb
if __name__ == "__main__":
model = torchvision.models.resnet50().cuda().eval()
for bs in [1, 2, 4, 8, 16, 32, 64, 128]:
try:
ips, mb = measure(model, bs)
print(f"batch {bs:4d}: {ips:8.1f} img/s, peak {mb:8.0f} MiB")
except torch.cuda.OutOfMemoryError:
print(f"batch {bs:4d}: out of memory")
breakAlways include warmup iterations. The first calls pay for cuDNN autotuning, memory allocation, and lazy initialisation, and they would distort the result.
This measures inference. For training, run a forward and backward pass with an optimiser step, because activations must be kept for the backward pass and memory use is much higher.
Memory: what grows with the batch
GPU memory during training has four parts:
| Component | Grows with batch size? | Notes |
|---|---|---|
| Model weights | No | Fixed by the architecture. |
| Gradients | No | Same size as the weights. |
| Optimiser state | No | For Adam, two extra copies of the weights. |
| Activations | Yes, linearly | Saved for the backward pass. Usually the dominant term. |
At inference, with torch.no_grad(), activations are freed as soon as the next layer consumes them, so memory grows far more slowly with batch size.
Input memory also grows. A batch of 256 images at 3 x 224 x 224 is 256 × 150,528 bytes ≈ 36.8 MiB as uint8, but 147 MiB as float32. At higher resolutions this matters, and it is one reason to keep data as uint8 until the GPU (see the chapters on operation order and GPU preprocessing).
Host memory also matters. Each worker holds prefetch_factor batches in flight, and pinned memory is page-locked and cannot be swapped out. The host memory used by queued batches is roughly:
num_workers × prefetch_factor × batch_size × bytes_per_image
With 8 workers, prefetch_factor=2, batch size 256 and 150,528 bytes per image, that is about 590 MiB of queued uint8 data. At 1024 × 1024 resolution it would be about 12 GiB. Large batches with many workers can exhaust host RAM before they exhaust the GPU.
The out-of-memory boundary
The largest batch that fits is a hard upper limit. Do not run at that limit in production, for three reasons:
- Memory use can vary between steps. The CUDA caching allocator fragments, and a batch that fits at step 10 can fail at step 10,000.
- Variable-size inputs change the peak. If some batches are padded to larger shapes (see the chapter on variable-size images), the worst-case batch determines the limit, not the average.
- Evaluation, checkpointing, or mixed-precision loss scaling may need extra headroom.
A practical rule is to pick a batch size that uses 70 to 85 percent of the peak memory you measured at the largest working size, then test with the largest images your data contains.
Choosing: a decision procedure
- Find the maximum. Double the batch size until you get an out-of-memory error. The last size that works is your ceiling.
- Measure the curve below the ceiling, using the script above, and find where throughput gains drop below a few percent per doubling.
- Pick the smaller of the knee and a safe fraction of the ceiling. A batch beyond the knee wastes memory.
- Run the real loader. Check that the loader delivers batches at least as fast as the model consumes them. If the GPU waits, the batch size is not the problem. Return to the profiling and loading chapters.
- For training, check optimisation. If the best throughput batch is too large for good convergence, use the techniques below.
When the best batch does not fit or does not train well
If you want a large effective batch but memory is limited, use gradient accumulation: run several small batches, add up their gradients, and step the optimiser once. The result matches a large batch for most layers.
import torch
def train_epoch(model, loader, optimiser, loss_fn, accum_steps=4):
model.train()
optimiser.zero_grad(set_to_none=True)
for i, (x, y) in enumerate(loader):
x = x.cuda(non_blocking=True).float()
y = y.cuda(non_blocking=True)
loss = loss_fn(model(x), y) / accum_steps # keep the gradient scale
loss.backward()
if (i + 1) % accum_steps == 0:
optimiser.step()
optimiser.zero_grad(set_to_none=True)Two caveats. Batch normalisation computes statistics per micro-batch, not over the whole effective batch, so very small micro-batches can hurt accuracy. Also, when you scale the effective batch size, the learning rate usually needs adjusting. A common starting point is to scale it linearly with batch size and add a warmup period, but verify it on your task.
Other ways to fit more: mixed precision (torch.autocast) roughly halves activation memory, and activation checkpointing (torch.utils.checkpoint) trades extra compute for lower memory.
Batch size and the loader
Batch size changes how the loader behaves, in ways that are easy to miss:
- Latency to first batch. Each worker builds a whole batch before returning it. A large batch means a longer delay at the start of each epoch, unless
persistent_workers=Truekeeps workers alive. - Worker balance. With 4 workers and a dataset where the last batch is partial, small datasets can leave some workers idle. Set
drop_last=Truein training if uneven final batches cause trouble, for example with batch normalisation on a batch of 1. - Inference batching. For a service that handles requests one at a time, a large batch adds waiting time while requests accumulate. Choose a maximum batch size and a maximum wait time, and accept that latency and throughput pull in opposite directions.
Common errors
- Timing without synchronising. GPU calls return before the work is done. Without
torch.cuda.synchronize()you measure launch time, and every batch size looks equally fast. - Choosing the ceiling. A batch that barely fits will fail later on a larger image or after memory fragmentation.
- Raising batch size to fix a loader bottleneck. If the GPU is waiting for data, a larger batch makes each wait longer.
- Changing batch size without changing the learning rate. Training results may shift even though the pipeline is unchanged. Treat it as a hyperparameter change.
- Ignoring host memory. Large batches with many workers and a high
prefetch_factorcan cause the operating system to kill the process. - Powers of two as a rule. Multiples of 8 often suit tensor cores, but the exact best size is whatever your measurements show.
Exercise
A ResNet runs at 1,050 img/s at batch size 64, 1,120 img/s at 128, and 1,135 img/s at 256. Peak GPU memory is 6 GiB at 64, 11 GiB at 128, and 21 GiB at 256 on a 24 GiB card. Which batch size would you choose for training, and why? What else would you check before committing?
Show answer
Choose 128. Going from 64 to 128 gives about 7 percent more throughput, while 128 to 256 gives only about 1 percent for nearly double the memory. Batch 256 uses 21 of 24 GiB, which leaves too little headroom for fragmentation and larger inputs, while 128 leaves about half the card free. Before committing, check that the real DataLoader can supply 1,120 img/s (otherwise the GPU waits and the choice does not matter), that host memory can hold workers × prefetch_factor × 128 images, and that training at batch 128 converges well, adjusting the learning rate if needed. If memory headroom allows and you want an even larger effective batch, use gradient accumulation.