Sub topic 10
Normalising and Augmenting on the GPU
This chapter assumes you know basic PyTorch tensors, Dataset, and DataLoader, and that your loader returns image batches shaped (B, C, H, W). The examples assume images are stored as uint8 values from 0 to 255.
Moving preprocessing to the GPU can reduce CPU work and reduce the amount of data transferred. Keep images compact as uint8 while they are in the worker processes. Copy them to the GPU first, then convert them to floating point and normalise them there.
Transfer compact data, then convert it
A uint8 pixel uses one byte. A float32 pixel uses four bytes. Sending uint8 data across the host-to-device connection can therefore reduce transfer volume by about four times. The GPU conversion is usually cheaper than transferring the larger representation.
Scaling changes pixel values from [0, 255] to [0, 1]. Normalisation then subtracts a channel mean and divides by a channel standard deviation. These statistics must match the values used when the model was trained.
import torch
MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
def preprocess_on_gpu(batch, device="cuda", training=True):
# batch is uint8 with shape (B, 3, H, W)
x = batch.to(device, non_blocking=True).float()
x = x / 255.0
if training:
# Use an independent random decision for each image.
flip = torch.rand(x.shape[0], device=device) < 0.5
x = torch.where(
flip[:, None, None, None],
x.flip(dims=(-1,)),
x,
)
mean = MEAN.to(device)
std = STD.to(device)
return (x - mean) / stdThe non_blocking=True argument allows an asynchronous copy when the source tensor is in pinned memory. Pinned memory is a page of host memory that the operating system keeps available for faster device transfers. It does not make every copy asynchronous by itself, so configure the DataLoader with pin_memory=True.
Put augmentation in the correct place
Random augmentation belongs in training, not validation or inference. A validation image should receive deterministic preprocessing so that evaluation measures the model rather than random changes to its inputs.
GPU augmentation works best when the operation is already expressed as tensor operations. Flips, crops, colour changes, and normalisation can often run this way. Complex operations may still be faster on the CPU, especially when GPU work is small or the operation requires decoding.
Avoid common ordering errors
Convert to floating point before division by 255.0. Integer division or arithmetic can discard information. Apply spatial augmentation before normalisation when the augmentation operates on pixel values. For a deterministic validation path, set training=False and use the same resize and normalisation rules as training.
GPU preprocessing also consumes accelerator time. If the model already saturates the GPU, moving more work there may reduce throughput. Measure images per second and GPU utilisation after each change.
Exercise
Why should a training pipeline transfer a uint8 batch before converting it to float32?
Show answer
uint8 uses one byte per pixel instead of four, so the host-to-device transfer moves less data. The GPU can then perform the conversion and normalisation.