Sub topic 8
Composing a Randomized Augmentation Pipeline
This chapter assumes you know basic Python, can treat an image as an array of shape (height, width, channels), and have written a PyTorch training loop. It builds on the earlier chapters on geometric, photometric, and occlusion transforms. Here the question is how to combine them into one pipeline that runs correctly and cheaply on every sample.
What a pipeline is
A pipeline is an ordered list of transforms applied to one image. Each transform takes the output of the previous one. Most transforms have a probability p of being applied and random parameters, such as a crop location or a brightness factor. These are drawn fresh each time the sample is loaded.
Because the draw happens at load time, the same file produces a different tensor in every epoch. This is online augmentation. The dataset on disk stays unchanged, and the model sees a new variant each time.
In torchvision, transforms.Compose chains transforms. The following pipeline is a typical starting point for classification.
from torchvision import transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.5, 1.0)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
transforms.ToTensor(),
transforms.Normalize(mean=mean, std=std),
])Read it from top to bottom. The image is cropped and resized to 224 by 224, flipped half the time, and has its colors perturbed. Then it is converted to a float tensor and normalized.
Order matters
Order changes both correctness and cost. Four rules cover most cases.
- Crop or resize first. Later transforms then work on small images. Running a blur on a 4000-pixel photo and then cropping to 224 wastes time.
- Run geometric transforms before photometric ones. Interpolation during rotation or scaling can blend pixel values slightly. Doing color changes last keeps the final colors under your control. In practice either order works for mild settings, but pick one and keep it.
- Run PIL-based transforms before
ToTensor.ColorJitter,RandAugment, and similar transforms are designed for PIL images oruint8tensors in the range 0 to 255. - Normalize last among the deterministic steps.
Normalizesubtracts the mean and divides by the standard deviation. Transforms that assume pixel values in 0 to 1 or 0 to 255 will misbehave if they run after it.
Tensor-only transforms, such as RandomErasing, go after ToTensor. Erasing after Normalize is common, because the erased region then holds values near the dataset mean when filled with zeros.
The next pipeline shows both placements. It adds RandAugment before conversion and RandomErasing after normalization.
from torchvision import transforms
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.RandAugment(num_ops=2, magnitude=9),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
transforms.RandomErasing(p=0.25),
])A pipeline as a data flow
The diagram shows where each stage sits relative to the data type it expects.
How probabilities combine
Each random transform has its own chance of firing. The chance that a given image is modified at all is higher than any single p suggests.
Suppose a pipeline has a flip with p=0.5, a color jitter that always applies, and erasing with p=0.25. Flip and erasing are independent. The chance that neither fires is 0.5 × 0.75 = 0.375, so about 62.5% of images receive at least one of those two changes. Color jitter changes every image on top of that.
If you add many transforms, each at a modest probability, most images get several changes at once. That is often what you want. It also means the combined strength can grow unnoticed, so check it by looking at output (covered in a later chapter).
To control combinations, use transforms.RandomApply to group transforms under one probability, or transforms.RandomChoice to pick exactly one from a list.
from torchvision import transforms
blur_or_noise_group = transforms.RandomApply(
[transforms.GaussianBlur(kernel_size=5, sigma=(0.1, 2.0))],
p=0.3,
)
one_of = transforms.RandomChoice([
transforms.RandomRotation(15),
transforms.RandomAffine(degrees=0, translate=(0.1, 0.1)),
transforms.RandomPerspective(distortion_scale=0.3, p=1.0),
])
tf = transforms.Compose([
transforms.RandomResizedCrop(224),
one_of,
blur_or_noise_group,
transforms.ToTensor(),
])RandomChoice here applies exactly one geometric distortion per image. This keeps the amount of warping bounded, which a chain of three independent transforms would not.
Randomness, workers, and reproducibility
Random draws come from a random number generator. Where that generator lives affects your results.
- Per-sample draws. Each call to a transform draws new random values. Two samples in one batch get different crops and flips.
- Per-worker state. A
DataLoaderwithnum_workers > 0runs the pipeline in separate processes. PyTorch seeds each worker'storchrandom state differently, derived from a base seed. NumPy and Python'srandommodule are a known trap in older setups. If your custom transform usesnumpy.randomand you run an old PyTorch version, workers can share the same state and produce duplicated augmentations. Current PyTorch handles NumPy seeding for you in most cases, but verify this with your version. - Reproducibility. To repeat a run, seed everything and pass a
generatorandworker_init_fnto theDataLoader.
import random
import numpy as np
import torch
from torch.utils.data import DataLoader
def seed_worker(worker_id):
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
g = torch.Generator()
g.manual_seed(0)
dataset = torch.utils.data.TensorDataset(torch.zeros(8, 3, 32, 32))
loader = DataLoader(
dataset,
batch_size=4,
shuffle=True,
num_workers=2,
worker_init_fn=seed_worker,
generator=g,
)Even with seeds fixed, results can differ between runs if the number of workers changes. Each worker gets its own stream, and which sample lands in which worker depends on that count.
Writing a custom transform
When a built-in transform does not fit, write a callable class. It should take an image and return an image. Keep random draws inside __call__, not in __init__. If you draw in __init__, every sample gets the same value.
import numpy as np
from PIL import Image
class AddGaussianNoise:
def __init__(self, std_range=(0.0, 0.05), p=0.5):
self.std_range = std_range
self.p = p
def __call__(self, img):
if np.random.rand() >= self.p:
return img
std = np.random.uniform(*self.std_range)
arr = np.asarray(img, dtype=np.float32) / 255.0
arr = arr + np.random.normal(0.0, std, size=arr.shape)
arr = np.clip(arr, 0.0, 1.0)
return Image.fromarray((arr * 255).astype(np.uint8))
img = Image.new("RGB", (64, 64), color=(120, 120, 120))
noisy = AddGaussianNoise(p=1.0)(img)
print(noisy.size, noisy.mode)Note the clip before converting back to uint8. Without it, noise pushes values outside 0 to 255, and the cast wraps around, producing bright speckles where dark pixels should be.
Where the cost goes
Augmentation runs on the CPU in the default setup, inside the data loader workers. If the GPU sits idle waiting for batches, the pipeline is the bottleneck. Ways to reduce the load:
- Decode and resize large images to a smaller stored size ahead of time, then apply random crops from that.
- Raise
num_workersuntil GPU utilization stops improving. - Put cheap transforms first and shrink the image early.
- Move heavy tensor operations to the GPU, for example with batch-level transforms applied after the batch is transferred.
Measure before optimizing. Time a few hundred samples through the pipeline alone, without the model.
import time
from PIL import Image
from torchvision import transforms
tf = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
])
img = Image.new("RGB", (1024, 768), color=(90, 140, 200))
start = time.perf_counter()
for _ in range(200):
tf(img)
elapsed = time.perf_counter() - start
print(f"{elapsed / 200 * 1000:.2f} ms per image")Common composition mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `Normalize` before a PIL-only transform | Error, or wrong colors | Move `Normalize` after `ToTensor` and after color work |
| Random draw in `__init__` of a custom transform | Same "random" value for every sample | Draw inside `__call__` |
| Same random transform on image but not on its mask | Labels no longer match pixels | Apply paired transforms (covered in a later chapter) |
| Many independent transforms at moderate `p` | Combined distortion far stronger than intended | Group with `RandomApply` or `RandomChoice`, then inspect output |
| Using the training pipeline for validation | Noisy, non-reproducible metrics | Use a separate deterministic pipeline (next chapter) |
Summary of a working approach
- Start with a small pipeline: random resized crop and horizontal flip, if flipping preserves the label.
- Add one transform at a time and keep it only if validation results improve or stay equal.
- Keep the order consistent: geometry, color, tensor conversion, normalization, tensor-only transforms.
- Look at a grid of augmented samples before training.
Exercise
A pipeline is Compose([ToTensor(), Normalize(mean, std), ColorJitter(brightness=0.3), RandomResizedCrop(224)]). Name the problems with this order and give a corrected order.
Show answer
ColorJitter runs after Normalize, so it receives values that are no longer in the 0 to 1 range, and its brightness scaling and clamping give wrong results. The crop also runs last, so the color work is done on the full-size image, which is slow. A corrected order is RandomResizedCrop(224), ColorJitter(brightness=0.3), ToTensor(), Normalize(mean, std).
Exercise
A pipeline applies horizontal flip with p=0.5 and random erasing with p=0.25, independently. What fraction of images receive neither change?
Show answer
The two events are independent, so the probability of neither is 0.5 × 0.75 = 0.375. About 37.5% of images pass through unchanged by these two transforms.
Exercise
A custom transform draws self.angle = random.uniform(-10, 10) in __init__ and rotates by self.angle in __call__. Why is this wrong, and how do you fix it?
Show answer
The angle is drawn once when the transform object is created, so every image is rotated by the same angle and no variety is added. Move the random.uniform(-10, 10) call into __call__ so a new angle is drawn for each image.