Sub topic 3
Normalising and augmenting on the GPU
Prerequisites
This chapter assumes you know PyTorch tensors, Dataset and DataLoader, and uint8 image arrays in (C, H, W) layout. It builds on the decoding and batching stages covered earlier.
Normalising on the GPU
Send uint8 batches to the GPU, then convert to float and normalise there. A uint8 batch is one quarter the size of a float32 batch, so the transfer moves fewer bytes.
import torch
mean = torch.tensor([0.485, 0.456, 0.406], device="cuda").view(1, 3, 1, 1) * 255
std = torch.tensor([0.229, 0.224, 0.225], device="cuda").view(1, 3, 1, 1) * 255
for batch in loader: # uint8, shape (B, 3, H, W), pinned
x = batch.to("cuda", non_blocking=True).float()
x = (x - mean) / stdRandom horizontal flips can run on the GPU too. Draw one mask per sample with torch.rand and select with torch.where.
> Keep the mean and std scaled by 255 so the inputs stay in the 0 to 255 range.
Variable-size images: padding, bucketing, and resizing policy
Padding every image to the largest size in a batch wastes compute on empty pixels. Bucketing groups images of similar size, so each batch pads less. Choose one policy per project: resize to a fixed size, or pad within buckets. Record the original sizes if the loss needs to ignore padding.
Choosing a batch size for throughput and memory
Increase the batch size until throughput stops rising or GPU memory runs out. Measure images per second at each size. Check peak memory with torch.cuda.max_memory_allocated().
Hardware-accelerated decoding and when it helps
GPU decoders help when CPU decoding is the bottleneck and batches are large. For small images, the copy overhead can cancel the gain. Profile before switching.
Caching and sharded storage formats
Caching resized uint8 arrays trades storage for decode time. Caching at full size uses much more disk. Sharded formats store many images in a few files, which cuts the cost of opening each file.
Verifying the optimised pipeline matches the reference
Run both pipelines on the same files and compare the outputs.
import torch
def check_parity(ref_fn, fast_fn, paths, atol=1e-3):
for p in paths:
a = ref_fn(p).float()
b = fast_fn(p).float()
diff = (a - b).abs().max().item()
assert diff <= atol, f"{p}: max diff {diff:.5f}"
print("parity ok")Exercise
Why does the GPU normalisation code multiply the mean and std by 255?
Show answer
The uint8 input stays in the 0 to 255 range. Multiplying mean and std by 255 gives the same result as dividing the input by 255 first, so the input is not scaled separately.