Sub topic 11
Automated Policies: AutoAugment, RandAugment, TrivialAugment
This chapter assumes you can build a torchvision.transforms.Compose pipeline, know the difference between PIL images and tensors, and have trained a classifier in PyTorch. Earlier chapters covered individual geometric, photometric, and occlusion transforms. Here you will see how automated policies pick and combine those transforms for you, and when that is better than a hand-built pipeline.
Why automate the choice
A hand-built pipeline has many knobs: which transforms to include, the probability of each, and the magnitude of each. Ten transforms with a probability and a magnitude each give twenty settings, and they interact. Tuning them by hand takes many training runs.
Automated policies reduce that search in different ways:
- AutoAugment searches for a fixed policy on a particular dataset, then reuses it.
- RandAugment drops the search and samples operations at random, with two settings to tune.
- TrivialAugment removes the settings almost entirely.
All three work from the same idea. They keep a pool of label-preserving operations such as rotate, shear, translate, color, contrast, brightness, posterize, solarize, and equalize. Each training image receives a random choice from that pool.
AutoAugment: a searched policy
AutoAugment (Cubuk et al., 2019) treats augmentation as a search problem. A controller network proposes policies, a child model trains with each one, and the validation accuracy becomes the reward. The search is expensive, because it needs thousands of training runs on a proxy task.
A policy is a list of sub-policies. Each sub-policy contains two operations. Each operation has a probability of being applied and a magnitude. For each image, the pipeline picks one sub-policy at random and applies its two operations in order.
Here is an illustrative sub-policy, written as plain data. The values are made up to show the structure and are not the published ones.
# Each operation: (name, probability, magnitude)
sub_policy = [
("Posterize", 0.4, 8),
("Rotate", 0.6, 9),
]Torchvision ships the published policies for three datasets. You pick one with AutoAugmentPolicy:
from torchvision import transforms
from torchvision.transforms import AutoAugment, AutoAugmentPolicy
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
AutoAugment(AutoAugmentPolicy.IMAGENET),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])The available policies are IMAGENET, CIFAR10, and SVHN. The weakness is transfer. A policy found on ImageNet photographs may help on other natural photographs, but it can hurt on X-rays, satellite tiles, or document scans. Running the search again on your own data usually costs far more than the training you wanted to do.
RandAugment: two numbers instead of a search
RandAugment (Cubuk et al., 2020) removes the search. It uses a uniform pool of operations and two integer settings:
num_ops(N): how many operations to apply to each image.magnitude(M): one shared strength for every operation.
For each image, it samples N operations from the pool, with replacement, and applies them in sequence at magnitude M. There are no per-operation probabilities. The search space shrinks from a large policy to a grid of two values, so a short sweep can cover it.
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),
])Torchvision's defaults are num_ops=2 and magnitude=9, with num_magnitude_bins=31. The magnitude is an index into a table of per-operation ranges. Magnitude 9 of 31 bins is therefore a moderate setting, and magnitude 30 is the strongest. The same number means different physical amounts for different operations. For rotation it is an angle, for brightness it is a multiplier change, and for posterize it is a bit depth.
Note that the same magnitude is applied to every operation. This is simple, but it means one operation that is too strong for your data cannot be softened without changing the pool.
TrivialAugment: no settings to tune
TrivialAugment (Müller and Hutter, 2021) goes further. For each image it picks one operation at random, and it also draws the magnitude at random from the full range of that operation. Strength therefore varies from image to image, from nearly no change to the maximum.
The result is a parameter-free method. Despite the simplicity, the authors reported accuracy comparable to or better than AutoAugment and RandAugment on several benchmarks. In torchvision it is called TrivialAugmentWide:
from torchvision import transforms
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.TrivialAugmentWide(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])The "Wide" suffix refers to the magnitude ranges, which are wider than in the earlier variant, so the strongest settings are more aggressive.
Comparing the three
| Method | Operations per image | Magnitude | Settings to tune | Search cost |
|---|---|---|---|---|
| AutoAugment | 2 (from one sub-policy) | Fixed per sub-policy | Which published policy | Very high if rerun |
| RandAugment | `num_ops` | Shared, `magnitude` | 2 | None |
| TrivialAugment | 1 | Random per image | 0 | None |
Where they go in the pipeline
These transforms operate on PIL images or on uint8 tensors. They do not belong after ToTensor and Normalize, because operations such as posterize, solarize, and equalize assume integer pixel values from 0 to 255. After normalization the data is floating point and centered near zero, so those operations either raise an error or give meaningless results.
A safe order is:
- Resizing and cropping, which fix the output size and cut the cost of later steps.
- Flip.
- The automated policy.
ToTensorandNormalize.- Tensor-only transforms such as
RandomErasing.
If your pipeline already works on uint8 tensors, for example when decoding with torchvision.io, you can apply the policy there and skip PIL. Make sure the dtype is torch.uint8.
Choosing and tuning
Use these rules as a starting point and verify them with an experiment.
- Start with TrivialAugmentWide when you have no budget for tuning. It has no settings and a strong track record.
- Use RandAugment when you want a single "strength" dial. Sweep
num_opsin {1, 2, 3} andmagnitudein a few steps such as {5, 9, 15}. Larger models and longer training schedules usually tolerate more. - Use a published AutoAugment policy when your data resembles its source and you want to reproduce a published baseline.
- Avoid all three, or restrict the pool, when the default operations can change the label.
The last point matters in practice. The default pool includes color operations such as solarize, posterize, and equalize, plus shear and rotation. These are wrong for tasks where color carries the label, such as ripeness grading or traffic-light state, and for tasks where orientation matters, such as digit recognition where 6 and 9 differ under a 180-degree turn. Torchvision's classes do not expose the operation list, so a restricted pool means writing a small custom transform or using a library that lets you choose operations, such as Albumentations or timm.
Interactions with other regularizers
Strong augmentation changes how much other regularization you need.
- Policies combine with mixup and CutMix, which are applied per batch after the policy. The combination is common in modern training recipes, but the total strength adds up. If accuracy on the training set stays low and validation accuracy does not improve, lower the policy magnitude first.
- Policies reduce the benefit of dropout and heavy weight decay. If you add a strong policy, you may need to relax them.
- Strong augmentation needs longer training. A model that trains for 10 epochs may not have time to fit augmented data, and the policy then lowers final accuracy.
Reproducibility
Each of these transforms draws from torch's random number generator. Under a DataLoader with several workers, each worker gets its own seed derived from the base seed, so runs are repeatable when you set the seed and the worker count. Policy sampling is in the data path, not the model path, so it adds CPU load. If the GPU sits idle waiting for batches, raise num_workers before you change the policy.
Check a sample of augmented images by eye, as covered in the chapter on inspecting augmentation. Automated policies can produce images that look strange at high magnitude, and a quick grid of 16 outputs catches problems that metrics will not.
Common mistakes
- Placing the policy after
Normalize. - Evaluating with the policy still active. Validation and test pipelines must be deterministic.
- Comparing methods with a single run. Differences between policies are often under one percentage point, which is within seed-to-seed noise. Repeat each setting with several seeds.
- Treating magnitude as portable. The same
magnitudevalue in a different library maps to different ranges. - Applying the policy to segmentation or detection inputs without transforming the targets. Geometric operations in the pool move pixels, so masks and boxes must move with them. The built-in classification transforms handle only the image.
Exercise
You train a classifier for handwritten digits (0 to 9) and add RandAugment(num_ops=2, magnitude=9) after ToTensor() and Normalize(). Training fails with an error, and you also suspect that the policy could hurt accuracy even after you fix the order. Give the fix for the order and name one reason the default pool may be a poor fit for digits.
Show answer
Move RandAugment before ToTensor() and Normalize() so it receives a PIL image or a uint8 tensor, since its operations assume integer pixel values from 0 to 255. For digits, the default pool includes rotation and shear, and a large rotation can make one digit look like another (a 6 turned by 180 degrees resembles a 9). A smaller magnitude or a restricted pool without large rotations is safer.
Exercise
A teammate says AutoAugment is the best choice because it was searched, so it must beat TrivialAugment on any dataset. Respond with two points that argue against this.
Show answer
First, the AutoAugment policy was searched on specific datasets (ImageNet, CIFAR-10, SVHN), and it can transfer poorly to data that looks different, such as medical or satellite images. Rerunning the search is very costly. Second, TrivialAugment has no tunable settings and was reported to match or beat AutoAugment and RandAugment on several benchmarks, so a searched policy gives no guarantee of better results. Only a controlled experiment with several seeds on your own data can decide.