Sub topic 12
Choosing a Batch Size for Throughput and Memory
Assume you know basic Python, NumPy shapes, and PyTorch Dataset and DataLoader. You should also know that an image batch usually has shape (B, C, H, W), where B is the batch size.
What batch size controls
Batch size is the number of images processed before the model updates its weights. It affects two competing goals:
- Larger batches often improve throughput because the accelerator performs more work per launch.
- Larger batches use more memory for input tensors, intermediate activations, gradients, and temporary workspaces.
- Larger batches can increase the time before each training update.
- Small batches may leave the GPU underused and make data-loading overhead more visible.
Memory does not always grow in a perfectly predictable way. Model parameters and optimizer state are mostly fixed, but activations usually grow approximately with B. Training therefore needs much more memory than inference.
| Workload | Main memory cost | Useful starting choice |
|---|---|---|
| Inference | Inputs and temporary activations | Largest batch that meets latency limits |
| Training | Inputs, activations, gradients, optimizer state | Largest batch that fits with safety margin |
| Variable-size images | Largest padded batch shape | Group similar image sizes |
The best batch size is the largest one that meets your memory and latency requirements while maintaining acceptable input throughput.
Measure instead of guessing
Test several batch sizes on representative images. Warm up the model first because the first iterations may include kernel selection and memory allocation. Synchronise CUDA before reading the clock; GPU operations are asynchronous.
import time
import torch
def benchmark(model, loader, device, steps=50, warmup=10):
model.eval()
batches = iter(loader)
with torch.inference_mode():
for _ in range(warmup):
try:
x = next(batches).to(device, non_blocking=True)
except StopIteration:
batches = iter(loader)
x = next(batches).to(device, non_blocking=True)
model(x)
if device.type == "cuda":
torch.cuda.synchronize()
start = time.perf_counter()
seen = 0
for _ in range(steps):
try:
x = next(batches).to(device, non_blocking=True)
except StopIteration:
batches = iter(loader)
x = next(batches).to(device, non_blocking=True)
model(x)
seen += x.shape[0]
if device.type == "cuda":
torch.cuda.synchronize()
elapsed = time.perf_counter() - start
return seen / elapsed, elapsed / steps
# Example:
# for batch_size in (16, 32, 64, 128):
# loader = make_loader(batch_size)
# images_per_second, seconds_per_batch = benchmark(model, loader, device)
# print(batch_size, images_per_second, seconds_per_batch)Record images per second, batch time, GPU memory, and any out-of-memory error. Include data loading in the measurement when your goal is end-to-end throughput. A model-only benchmark can hide a slow decoder or an undersized worker pool.
Find the memory limit safely
Start with a conservative batch size and increase it gradually. Leave room for variation in image sizes, temporary allocations, and other processes. During training, test the full forward and backward pass, not only inference.
For variable-size images, padding can make one batch much larger than the others. Bucketing images with similar dimensions reduces wasted padded pixels. Alternatively, resize images to a fixed shape before collation when the model and accuracy requirements allow it.
When a larger batch does not help
Throughput may stop improving when the GPU is saturated. At that point, increasing B only increases latency or memory use. If the GPU is idle, the bottleneck may be decoding, resizing, worker processes, or host-to-device transfer instead.
Gradient accumulation can simulate a larger optimization batch by processing several smaller batches before calling optimizer.step(). It reduces memory use, but it does not equal a true large batch in every detail. Batch-normalisation statistics, random augmentation, and optimizer behavior can differ.
Exercise
Your GPU fits batch sizes 32 and 64, but images per second rises from 32 to 64 only slightly. What should you check before choosing 64?
Show answer
Check GPU utilisation, data-loader wait time, host-to-device transfer time, and the memory safety margin. If the input pipeline is the bottleneck, tuning workers or preprocessing may help more than increasing the batch size.