Sub topic 3
Offline versus online augmentation
This chapter assumes you can write a PyTorch Dataset and DataLoader, you know that images are arrays of shape (height, width, channels), and you have seen a train/validation split. Earlier chapters covered why augmentation helps and which transforms keep the label intact. This chapter covers when the transforms run: once before training, or on every sample draw during training.
The two models
Offline augmentation runs the transforms once, before training. You write the augmented images to disk (or to an in-memory array) and train on the enlarged dataset as if it were ordinary data. If you make five copies of each image, the dataset is six times larger, and those variants never change.
Online augmentation (also called on-the-fly augmentation) runs the transforms inside the data loading code. Each time the loader asks for sample i, the dataset reads the original image, applies freshly randomized transforms, and returns the result. The stored dataset does not grow. The model sees a different variant of the same image every epoch.
Comparing them
| Property | Offline | Online |
|---|---|---|
| Distinct variants per image | Fixed number you chose (for example 5) | Effectively unlimited across epochs |
| Disk or memory | Grows with the number of copies | Same as the original dataset |
| CPU cost per epoch | Only decoding the files | Decoding plus every transform, every epoch |
| Reproducibility | Exact: the files are the data | Depends on seeding and worker setup |
| Changing the policy | Regenerate the whole dataset | Edit the transform and rerun |
| Inspecting examples | Open the files | Need to dump samples from the loader |
| Fits expensive transforms | Yes, the cost is paid once | Only if workers keep the GPU fed |
Online augmentation is the default for image classification training because it gives the most variety for the least storage, and because changing the policy costs nothing. Offline augmentation still has real uses, covered below.
An offline generator
The sketch below writes several augmented copies of each training image. It operates on PIL images, so every transform in the list returns a PIL image that can be saved directly.
from pathlib import Path
import torch
from PIL import Image
from torchvision import transforms
def write_offline_copies(src_dir, dst_dir, copies=5, seed=0):
torch.manual_seed(seed) # torchvision random transforms draw from torch's RNG
tf = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.5, 1.0)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ColorJitter(brightness=0.2, contrast=0.2),
])
src_dir, dst_dir = Path(src_dir), Path(dst_dir)
for path in sorted(src_dir.rglob("*.jpg")):
img = Image.open(path).convert("RGB")
out_dir = dst_dir / path.parent.relative_to(src_dir)
out_dir.mkdir(parents=True, exist_ok=True)
for k in range(copies):
tf(img).save(out_dir / f"{path.stem}_aug{k}.jpg", quality=95)Run it on the training split only, never on the full dataset (see the leakage warning below). Even at quality=95, each copy is re-encoded as JPEG, which adds compression artifacts. If that matters, save as PNG and accept the larger files.
An online dataset
Online augmentation needs no generation step. The transform is simply called inside __getitem__. This example uses random in-memory images so it runs without any data on disk.
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
class InMemoryImages(Dataset):
def __init__(self, n=8, transform=None):
rng = np.random.default_rng(0)
self.images = [
Image.fromarray(rng.integers(0, 256, (64, 64, 3), dtype=np.uint8))
for _ in range(n)
]
self.labels = list(range(n))
self.transform = transform
def __len__(self):
return len(self.images)
def __getitem__(self, i):
img = self.images[i]
if self.transform is not None:
img = self.transform(img) # a new random draw on every call
return img, self.labels[i]
tf = transforms.Compose([
transforms.RandomResizedCrop(32, scale=(0.5, 1.0)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
])
ds = InMemoryImages(transform=tf)
loader = DataLoader(ds, batch_size=8, shuffle=False, num_workers=0)
epoch1, _ = next(iter(loader))
epoch2, _ = next(iter(loader))
print("same images, different pixels:", not torch.equal(epoch1, epoch2))Both batches contain the same eight source images in the same order, yet the tensors differ because each call to tf drew new crop boxes and flip decisions. That is the whole mechanism of online augmentation.
Where the randomness comes from
With online augmentation, reproducibility depends on how random number generators are handled across DataLoader workers.
- torch RNG.
DataLoaderdraws a base seed from torch's generator for each epoch's iterator and gives each workerbase_seed + worker_id. The torch and Pythonrandomstreams in the workers therefore differ from each other. Torchvision's random transforms use the torch RNG, so they are safe by default. - Reproducing a run. Call
torch.manual_seed(...)before creating the iterator, or passgenerator=torch.Generator().manual_seed(0)to theDataLoader. With a fixed seed and a fixed number of workers, the augmentation stream repeats. Changingnum_workerschanges which worker handles which sample, so the stream changes too. - Your own NumPy generator. If you create
np.random.default_rng(...)in the dataset's__init__, every worker receives a copy of the same state and produces identical "random" numbers. Seed a fresh generator inside each worker, for example fromtorch.initial_seed()in aworker_init_fn. - Multiprocessing start method. With
num_workers > 0on Windows and macOS (which spawn worker processes), put the loader code underif __name__ == "__main__":.
Cost: where the time goes
Online augmentation moves work into the data loader. Each epoch repeats JPEG decoding, resizing, and every transform. If the GPU waits on the loader, training slows down even though the model is fast. Signs of this problem are low GPU utilization and a training step time that shrinks when you raise num_workers.
Common ways to reduce the cost:
- Raise
num_workersuntil the GPU stays busy, and setpin_memory=Truewhen training on a GPU. - Put cheap, size-reducing transforms first. Cropping a large image before color operations means the later operations touch fewer pixels.
- Move deterministic work offline (the hybrid approach below).
- Run tensor-based transforms on the GPU if the CPU is the bottleneck. Torchvision's v2 transforms work on batched tensors, though per-sample randomness then needs care.
The hybrid approach
The two models can be combined. Anything deterministic can be computed once and cached. Anything random stays online. A common case is a dataset of very large photos where decoding and downscaling dominate the cost. You downscale each image once to a size slightly larger than the training size, store it, and apply random crops and flips online on the small images.
from pathlib import Path
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
def cache_resized(src_dir, dst_dir, short_side=256):
"""Offline, deterministic step: shrink once, keep aspect ratio."""
resize = transforms.Resize(short_side)
src_dir, dst_dir = Path(src_dir), Path(dst_dir)
for path in sorted(src_dir.rglob("*.jpg")):
out = dst_dir / path.relative_to(src_dir)
out.parent.mkdir(parents=True, exist_ok=True)
resize(Image.open(path).convert("RGB")).save(out, quality=95)
class CachedThenAugmented(Dataset):
"""Online, random step: runs on the small cached images."""
def __init__(self, paths_and_labels):
self.items = list(paths_and_labels)
self.tf = transforms.Compose([
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
])
def __len__(self):
return len(self.items)
def __getitem__(self, i):
path, label = self.items[i]
return self.tf(Image.open(path).convert("RGB")), labelThe split rule is: cache only operations that give the same output every time. Never cache a random transform and then reuse it, because that turns online augmentation back into offline augmentation with a single variant.
One consequence is that the cached images cap what later transforms can do. A RandomResizedCrop that zooms in on a 256-pixel cached image has fewer source pixels than the same crop on the original, so heavy zoom looks blurrier. Choose a cache size with that in mind.
When offline is the right choice
- Expensive transforms. Examples are synthetic rendering, style transfer, or generative inpainting, where one sample takes seconds. Generate them once and store them.
- Tiny datasets with tools that need files. Some annotation or labeling tools and some legacy training scripts only accept a folder of images.
- Auditing. If a reviewer must see exactly what the model trained on, a fixed folder is easier to inspect than a random stream.
- Class balancing. You may want exactly N extra variants of images from a rare class. Online sampling can do this too, using weighted sampling, but offline copies make the counts explicit.
The downside of offline copies is that variants of the same source image are strongly correlated. Ten augmented copies do not equal ten new photos. The model can still memorize each image's fixed variants after enough epochs, which limits the regularization benefit compared with online draws.
Common errors
- Augmenting before the train/validation split (the leakage described above).
- Applying random transforms to the validation set, which makes metrics noisy and not comparable between runs. The next chapters on pipelines cover evaluation transforms.
- Seeding a NumPy generator once in
__init__and getting identical augmentations in every worker. - Caching an already-augmented image, then augmenting it again online, which compounds the transforms (for example a crop of a crop) and changes the intended strength.
- Forgetting that offline copies inherit the label. If a transform can change the label (such as flipping an image of text), it is wrong in both modes.
Exercise
You have 2,000 photos and generate 10 offline augmented copies of each, giving 22,000 files. You then split 80/20 at random into train and validation folders and see 97% validation accuracy, but accuracy on a separately collected test set is 81%. What is the most likely cause, and how do you fix the process?
Show answer
Leakage. The random split put some augmented copies of a photo in training and other copies (or the original) in validation, so the model was evaluated on near-duplicates of images it trained on. Fix it by splitting the 2,000 original photos first (for example 1,600 train and 400 validation), then generating offline copies only from the training photos. Leave the validation photos unaugmented.
Exercise
Your online pipeline decodes 4000x3000 JPEGs, then applies RandomResizedCrop(224) and a flip. GPU utilization is 30% and raising num_workers does not help much. Describe a hybrid change that reduces loader cost without losing the random augmentation.
Show answer
Add an offline, deterministic step that resizes every image once to a smaller size such as a short side of 256 pixels and saves it. Train from these cached files, and keep the random crop and flip online. Decoding and resizing a 12-megapixel image every epoch is the dominant cost, and the cached small images are much cheaper to decode. The random transforms stay online, so each epoch still sees new variants. The trade-off is slightly less detail available when a crop zooms in.