Sub topic 10
Normalising and augmenting on the GPU
This chapter assumes you can write a PyTorch Dataset and DataLoader, know that image tensors are laid out as (batch, channels, height, width), and have read the earlier chapters on keeping data as uint8 and on pinned memory with asynchronous copies. Here you will move normalisation and some augmentations from CPU workers onto the GPU, and learn where that move helps and where it hurts.
Why move this work to the GPU
After decoding and resizing, a CPU worker would normally convert each image to float32, subtract the mean and divide by the standard deviation. Three costs follow from doing that on the CPU:
- The CPU does arithmetic on every pixel of every image. For a 224 x 224 RGB image that is 150,528 values.
- A
float32tensor takes four bytes per value. The same image asuint8takes one byte. Sending floats across the PCIe bus moves four times as many bytes. - The CPU worker processes must also pass those larger tensors back to the main process through shared memory.
A GPU does this elementwise arithmetic far faster than a CPU core. The cost on the GPU is tiny next to the model's forward and backward pass. So the plan is simple: workers return compact uint8 batches, the main process copies them to the device, and the device converts and normalises them.
Normalising on the GPU
The dataset from the earlier chapters returns uint8 tensors of shape 3 x H x W. The loop below copies each batch, then normalises it.
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: # batch: uint8, shape (B, 3, H, W)
x = batch.to("cuda", non_blocking=True).float()
x = (x - mean) / std
# x is ready to feed to the modelThree details matter here.
- Scale the statistics. The usual ImageNet mean and standard deviation assume pixel values in the range 0 to 1. Your tensor holds 0 to 255, so the code multiplies both statistics by 255. Forgetting this is a common error. The model then sees values around 100 to 200 instead of values near zero, and accuracy drops without any error message.
- Reshape for broadcasting. The
view(1, 3, 1, 1)shape lines the three channel values up with the channel axis of a (B, 3, H, W) tensor. Without it, PyTorch would try to broadcast against the width axis and either fail or give wrong results. - Create the constants once. Build
meanandstdoutside the loop. Creating small tensors on the device every step adds a host-to-device copy each time.
non_blocking=True only overlaps the copy with other work when the source tensor is in pinned memory, which pin_memory=True in the DataLoader provides. With pageable memory the call still works but is effectively synchronous.
Put it in a reusable object
A small class keeps the constants, the device and the conversion together, and makes the pipeline easier to test.
import torch
class GpuNormalizer:
def __init__(self, mean, std, device="cuda"):
self.device = device
self.mean = torch.tensor(mean, device=device).view(1, -1, 1, 1) * 255
self.std = torch.tensor(std, device=device).view(1, -1, 1, 1) * 255
@torch.no_grad()
def __call__(self, batch_uint8):
x = batch_uint8.to(self.device, non_blocking=True)
x = x.float()
return (x - self.mean) / self.std
if __name__ == "__main__":
norm = GpuNormalizer([0.485, 0.456, 0.406], [0.229, 0.224, 0.225],
device="cuda" if torch.cuda.is_available() else "cpu")
fake = torch.randint(0, 256, (8, 3, 224, 224), dtype=torch.uint8)
out = norm(fake)
print(out.shape, out.dtype, float(out.mean()), float(out.std()))The @torch.no_grad() decorator stops PyTorch from recording the operation for backpropagation. The input pixels do not need gradients, so recording them would waste memory.
Optional: use half precision and channels-last
If the model trains with mixed precision, you can convert straight to float16 or bfloat16 after normalising, so the first layer receives the type it expects. If the model uses the channels-last memory format, call x.contiguous(memory_format=torch.channels_last) at the end of the preprocessing step. Doing it here costs one fused kernel on the GPU. Doing it inside the model forward pass can add a hidden copy every step.
Augmenting on the GPU
Augmentations are random changes applied during training, such as flips, crops and brightness shifts. They multiply the effective size of the training set. When they run in CPU workers, each one adds time to the per-image budget. Simple augmentations are cheap on a GPU and work on a whole batch at once.
The key idea is to draw independent random parameters for each image in the batch, then apply them with batched tensor operations. Applying one random choice to the whole batch is a bug. Every image in the batch would get the same flip, which reduces the variety the model sees.
Random horizontal flip
import torch
def random_flip(x, p=0.5):
# x: float or uint8 tensor, shape (B, C, H, W)
flip = torch.rand(x.shape[0], device=x.device) < p # one decision per image
flipped = x.flip(dims=[3]) # flip along width
return torch.where(flip.view(-1, 1, 1, 1), flipped, x)torch.where picks, for each image, either the flipped or the original version. This computes the flipped copy of the whole batch even for images that stay unflipped. That wastes some work, but the operation is memory-bound and cheap, and it avoids a Python loop over images.
Random brightness and contrast
import torch
def random_brightness_contrast(x, brightness=0.2, contrast=0.2):
# x: float tensor in 0..1 or normalised range, shape (B, C, H, W)
b = x.shape[0]
shift = (torch.rand(b, 1, 1, 1, device=x.device) * 2 - 1) * brightness
scale = 1 + (torch.rand(b, 1, 1, 1, device=x.device) * 2 - 1) * contrast
mean = x.mean(dim=(1, 2, 3), keepdim=True)
return (x - mean) * scale + mean + shiftThe function draws one shift and one scale per image. The keepdim=True argument keeps the reduced axes as size 1, so the per-image mean broadcasts back over the image.
Order relative to normalisation
Photometric augmentations such as brightness assume a meaningful value range. Apply them before normalisation, on values scaled to 0 to 1 or 0 to 255, or choose their strengths with the normalised range in mind. Geometric augmentations such as flips do not change values, so they work at any point. A safe default order is:
- Copy
uint8to the device. - Apply geometric augmentations on
uint8, which moves a quarter of the bytes. - Convert to float and apply photometric augmentations.
- Normalise.
Random crops with per-image offsets
Cropping a different region for each image is harder to batch, because the slicing differs per image. When all crops have the same output size, you can loop over the batch on the GPU with slicing, which is cheap for moderate batch sizes.
import torch
def random_crop(x, out_h, out_w):
b, c, h, w = x.shape
tops = torch.randint(0, h - out_h + 1, (b,)).tolist()
lefts = torch.randint(0, w - out_w + 1, (b,)).tolist()
out = torch.empty(b, c, out_h, out_w, dtype=x.dtype, device=x.device)
for i, (t, l) in enumerate(zip(tops, lefts)):
out[i] = x[i, :, t:t + out_h, l:l + out_w]
return outThe offsets are generated on the CPU with .tolist() so that slicing does not force a device synchronisation for every image. For heavy geometric transforms such as rotation or scaling with interpolation, build an affine grid and use torch.nn.functional.grid_sample, which handles a different transform per image in one call.
Trade-offs and common errors
Moving work to the GPU is not free. Check these points before you commit to it.
| Concern | What happens | What to do |
|---|---|---|
| GPU is already the bottleneck | Preprocessing steals time from the model | Profile first. If the GPU is at full utilisation, keep preprocessing on the CPU |
| Wrong value range | Normalisation constants assume 0..1 but data is 0..255 | Scale the constants or divide the data by 255 once, and test it |
| Same random draw for every image | Batch loses augmentation diversity | Draw random values with a leading batch dimension |
| Reproducibility | GPU random numbers differ from CPU ones | Seed the generator on the device and accept different streams |
| Output differs from the reference | Interpolation or rounding differs from the CPU version | Compare on a sample batch; see the chapter on parity checks |
| Extra GPU memory | Float copy of a batch is four times larger than `uint8` | Account for it when choosing batch size |
When it helps most
GPU preprocessing pays off when your CPU cores are limited relative to the GPU, when images are small after resizing so transfer volume is modest, and when augmentation chains are long. It helps least when the model is large and slow, since the GPU is already busy, or when a few CPU cores can already keep the GPU fed. The profiling approach from the earlier chapter gives the answer: if the data loader wait time is near zero, further preprocessing work will not speed up training.
Exercise
A training job moves normalisation to the GPU. After the change, validation accuracy falls by several points, though throughput improves. The code is x = batch.to("cuda").float(); x = (x - mean) / std with mean = torch.tensor([0.485, 0.456, 0.406]) and std = torch.tensor([0.229, 0.224, 0.225]), both viewed as (1, 3, 1, 1) on the GPU. Batches are uint8. What is the most likely bug, and how do you fix it?
Show answer
The statistics are for pixel values in 0 to 1, but the batch holds 0 to 255 after .float(). The normalised values are roughly 255 times too large. Fix it by multiplying mean and std by 255, or by dividing x by 255 before subtracting the mean. Then compare the output with the CPU reference on a sample batch to confirm they match.
Exercise
You write flip = torch.rand(1) < 0.5 and then x = x.flip(dims=[3]) if flip else x for a training batch. What is wrong with this augmentation, and how would you change it?
Show answer
One random draw decides the flip for the entire batch, so all images are flipped together or none are. The model sees less variety than with per-image flips. Draw one value per image with torch.rand(x.shape[0], device=x.device) < 0.5 and combine the flipped and original batches with torch.where(flip.view(-1, 1, 1, 1), x.flip(dims=[3]), x).