AI Logic

Data Augmentation

TrivialAugment

Updated:

TrivialAugment diagram. Left: one pass on CIFAR (mini-batch, pick one operation uniformly, pick a magnitude uniformly from 0–30, apply only that one, standard augmentation, normalization, Cutout, model). Right: the list of 14 operations, examples of the same triangle image with Rotate, ShearX, TranslateY, and Identity applied at different magnitudes, and a table of differences from RandAugment

What is TrivialAugment

TrivialAugment is a data augmentation method that, for each image, picks one operation uniformly from a fixed list, picks its magnitude uniformly as well, and applies only that single operation. There are no hyperparameters to tune and no policy search stage. It was proposed by Müller and Hutter of the University of Freiburg in 2021 and presented at ICCV 2021.

Since AutoAugment, many methods have been proposed that determine augmentation policies automatically. All of them search for "which operations, at what magnitude, and how many to combine" to fit the data and model. The search costs tens of times the training compute even for RandAugment, and thousands of GPU hours for AutoAugment. The TrivialAugment paper showed that the simplest possible method, with no search at all, matches or exceeds the accuracy of these methods.

The name "Trivial" comes from this simplicity. The paper positions TrivialAugment as "the simplest baseline that should be compared against," one that had been overlooked in research on automated augmentation.

RandAugmentTrivialAugment
Operations applied per imageNNAlways 1
MagnitudeThe same MM for all imagesChosen uniformly per image
Values to tuneTwo, NN and MM (grid search)None
Extra training for searchUp to about 80 times the training costNone

TrivialAugment is not the same as RandAugment with N=1N = 1. RandAugment fixes the magnitude MM for all images, whereas TrivialAugment re-chooses the magnitude for each image. The paper concludes that this randomness in magnitude is important for performance.

Procedure

For each training image, the following is done (Algorithm 1 in the paper; the figure at the top).

  1. Pick one operation aa uniformly from the list of operations A\mathcal{A}.
  2. Pick the magnitude mm uniformly from the 31 levels {0,1,…,30}\{0, 1, \dots, 30\}.
  3. Apply a(x,m)a(x, m) to the image xx and return it. The label stays the same.

As a formula:

a∼U(A),m∼U{0,1,…,30},x~=a(x,m)a \sim \mathcal{U}(\mathcal{A}), \qquad m \sim \mathcal{U}\{0, 1, \dots, 30\}, \qquad \tilde{x} = a(x, m)

The list of operations is the same 14 as in RandAugment.

  • Identity, AutoContrast, Equalize, Rotate, Solarize, Color, Posterize
  • Contrast, Brightness, Sharpness, ShearX, ShearY, TranslateX, TranslateY

There are two magnitude ranges (the paper calls the combination of an operation list and magnitude ranges an augmentation space). The paper's main experiments and torchvision use the extended Wide space.

OperationRA rangeWide range
Rotate−30° to +30°−135° to +135°
ShearX, ShearY0 to 0.30 to 0.99
TranslateX, TranslateY0 to 10 pixels0 to 32 pixels
Color, Contrast, Brightness, Sharpness0.1 to 1.90.01 to 2.0
Posterize4 to 8 bits2 to 8 bits
Solarize0 to 2560 to 256

Magnitude m=30m = 30 corresponds to the maximum of each range and m=0m = 0 to the minimum.

In the CIFAR experiments, TrivialAugment is followed by the standard horizontal flip and padded crop, then normalization, and finally Cutout with a side of 16 pixels. On ImageNet, too, TrivialAugment is followed by the standard augmentation (random-resized crops, horizontal flips, color jitter, and so on).

Why it works despite being simple

The paper does not fully explain why TrivialAugment works so well. It does, however, offer the following two viewpoints along with experimental results.

1. The augmented distribution is an average of the per-operation distributions: since TrivialAugment applies only one operation per image, the augmented dataset can be viewed as "an equally weighted average of the 14 distributions obtained by applying each of the 14 operations to the whole dataset." Unlike other methods, it does not build complex distributions from combinations of operations.

2. Randomness in magnitude matters: comparing with fewer magnitude candidates gave the following (Wide-ResNet-28-10, RA space, test accuracy %).

Magnitude candidatesCIFAR-10CIFAR-100SVHN Core
{30}\{30\} (maximum only)97.4582.9898.16
{0,30}\{0, 30\}97.5183.4698.02
{0,15,30}\{0, 15, 30\}97.4683.4398.04
{0,…,30}\{0, \dots, 30\} (31 levels)97.4683.5498.05

On CIFAR-100, using only the maximum magnitude lowered accuracy considerably. On the other hand, using 2 or 3 levels was not much different from 31 levels. The paper suggests that a mix of strong and weak transformations is what matters. Only on SVHN (house-number digits) was the maximum magnitude best; the paper speculates that this is because many operations concern color, and digits remain readable even when the colors of the background and digits change drastically.

As an everyday analogy, it is like "drawing just one lottery ticket each time and applying whatever edit comes up at whatever strength comes up." Even without engineering the contents of the lottery, each draw applies a different edit, so a diverse set of images arises naturally.

Reducing the number of operations lowers performance only slowly. In an experiment on CIFAR-10 (Wide-ResNet-40-2) using only a random subset of the 14 operations, accuracy stayed close to the original even with 4 operations dropped. However, the fewer the operations, the larger the variance depending on which operations remained.

Results reported in the paper

Comparing published values for other automated augmentation methods under the same training setups gives the following (test accuracy %; TrivialAugment is the average of 10 runs, ImageNet of 5 runs).

DatasetModelBaselineAutoAugmentFast AAPBARandAugmentTrivialAugment (Wide)
CIFAR-10Wide-ResNet-28-1097.0397.497.397.497.397.46
CIFAR-10Shake-Shake (26 2x96d)97.5498.098.098.098.098.21
CIFAR-100Wide-ResNet-28-1082.2282.982.783.383.384.33
CIFAR-100Shake-Shake (26 2x96d)83.2885.785.484.7−86.19
SVHN (full data)Wide-ResNet-28-1098.6798.998.898.999.098.9
ImageNet (top-1)ResNet-5077.2077.677.6−77.678.07

In most settings, TrivialAugment was the best or indistinguishable from the best method. The exception is SVHN, where RandAugment was slightly higher. However, when the paper's authors reproduced RandAugment under the same training setup, this gap did not appear.

Comparisons reproduced under the same training setup gave the same picture. When each method was retrained with the same code using its published policy, TrivialAugment (Wide) achieved the highest accuracy on CIFAR-10, CIFAR-100, and SVHN Core with Wide-ResNet-28-10 (on CIFAR-100, 84.33% versus 82.91% for AutoAugment, 83.27% for Fast AutoAugment, and 83.1% for RandAugment).

It was also compared with RandAugment tuned exhaustively. For Wide-ResNet-40-2 on CIFAR-10, trying all 90 combinations of RandAugment's NN and MM and picking the best (the compute of 91 training runs) gave 96.42% accuracy. TrivialAugment (RA space), with a single training run, gave 96.62%.

On classification of occluded images (CIFAR-10 with a 14 × 14 square blacked out in every image) and on fine-grained car model classification (Stanford Cars), TrivialAugment also outperformed standard augmentation and RandAugment without any tuning.

Practical notes

  • Use it for image classification. The paper states that it could not find a setting where TrivialAugment fails in image classification, but that in object detection it did not work out of the box and needed tuning. Verify its effect before using it for tasks other than classification.
  • The augmentation space can be chosen to fit the data. In the paper, a larger space including blur and vertical flips (Full) lowered accuracy on CIFAR-10 and SVHN Core. Do not include operations, such as vertical flips, that change the meaning of the image in many classification tasks. Conversely, on SVHN the AutoAugment space, which includes Invert (reversing light and dark), worked well, while on CIFAR-10 excluding Invert gave better results.
  • Combine it with the standard augmentation. In the paper's CIFAR experiments, cropping, horizontal flipping, and Cutout are applied after TrivialAugment.

When using torchvision's transforms.TrivialAugmentWide, note the following.

  • Apply it to PIL images or uint8 tensors. Place it before ToTensor and Normalize.
  • As the name says, the magnitude ranges are Wide (Rotate up to 135°, ShearX and ShearY up to 0.99, and so on). They differ from the paper's RA space (Rotate up to 30°).
  • The maximum of TranslateX and TranslateY is 32 pixels regardless of image size. On 32 × 32 CIFAR images this can shift by the full image width, but on 224 × 224 ImageNet images it is only about 1/7 of the width.
  • The arguments are num_magnitude_bins (number of magnitude levels; default 31, corresponding to the paper's {0,…,30}\{0, \dots, 30\}), interpolation (interpolation for rotation and so on; default nearest), and fill (value for areas outside the image; default black). They are not hyperparameters to tune, so the defaults are normally used.
  • The direction (sign) of rotation, shear, translation, brightness, and so on is also chosen at random with 50% probability each.

Comparison with similar methods and how to choose

The table below compares augmentation methods that randomly select and apply image transformations from the same viewpoints.

MethodOperations applied per imageMagnitudeTuning / search
AutoAugmentTwo operations of a searched sub-policy (each applied with a probability)Searched valuesPolicy search with reinforcement learning (thousands of GPU hours)
Fast AutoAugmentTwo operations of a searched sub-policy (each applied with a probability)Searched valuesPolicy search with Bayesian optimization (a few GPU hours and up)
RandAugmentNN chosen uniformlyThe same MM for allGrid search over NN and MM
TrivialAugment1 chosen uniformlyUniform per imageNone
AugMixWeighted mix of several chains of transformationsFixed strength (severity)Choose severity, number of chains, etc.

Rules of thumb for choosing:

  • To try strong augmentation first on new data or a new model: use TrivialAugment. It needs no tuning, so a single training run is enough. The paper also recommends trying a tuning-free method like TrivialAugment on new data not covered in the automated augmentation literature.
  • For commonly used data and model combinations: the paper recommends using the method with the best published results for that combination (published policies or code).
  • When the data differs greatly from well-known benchmarks and there is compute to spare for tuning: the paper also mentions tuning a policy-search method such as PBA on one's own data.
  • To improve robustness to distribution shift and image corruptions: consider AugMix. AugMix aims mainly at robustness to corrupted images rather than test accuracy. In the TrivialAugment paper, TrivialAugment outperformed AugMix in ImageNet accuracy with ResNet-50.

PyTorch example

Show code
python
import random
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms.functional as TF
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

"""
CIFAR-10 image classification (trained with TrivialAugment)
"""

# The idea of the paper's Algorithm 1: pick one operation and one magnitude from 0-30, both uniformly, and apply
def trivial_augment(img, ops):
  op = random.choice(ops)          # pick an operation uniformly
  m = random.randint(0, 30)        # pick a magnitude uniformly from {0, ..., 30}
  return op(img, m)

# Example: some operations with Wide ranges (img is a PIL image)
example_ops = [
  lambda img, m: img,                                         # Identity
  lambda img, m: TF.rotate(img, random.choice([-1, 1]) * 135 * m / 30),   # Rotate (Wide: up to 135°)
  lambda img, m: TF.adjust_brightness(img, 1 + random.choice([-1, 1]) * 0.99 * m / 30),  # Brightness
]

# Hyperparameters (TrivialAugment itself has nothing to tune)
batch_size = 128      # batch size
epochs = 5            # number of epochs
learning_rate = 1e-3  # learning rate

# 'cuda' if available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

mean, std = (0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)
train_transform = transforms.Compose([
  transforms.TrivialAugmentWide(          # works on PIL images or uint8 tensors, so place it before ToTensor
    num_magnitude_bins=31,                # number of magnitude levels (default 31 = the paper's {0, ..., 30})
    interpolation=transforms.InterpolationMode.NEAREST,  # interpolation for rotation etc. (default)
    fill=None,                            # fill value for areas outside the image (default 0 = black)
  ),
  transforms.RandomCrop(32, padding=4),   # paper's CIFAR setup: crop and horizontal flip after TrivialAugment
  transforms.RandomHorizontalFlip(),
  transforms.ToTensor(),
  transforms.Normalize(mean, std),
  # the paper also applies Cutout with a 16-pixel side at the end (see the Cutout article's example)
])
test_transform = transforms.Compose([     # no augmentation for evaluation
  transforms.ToTensor(),
  transforms.Normalize(mean, std),
])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=test_transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)


class SmallCNN(nn.Module):
  def __init__(self, num_classes=10):
    super().__init__()
    self.features = nn.Sequential(
      nn.Conv2d(3, 32, kernel_size=3, padding=1),   # [B, 3, 32, 32] -> [B, 32, 32, 32]
      nn.BatchNorm2d(32),
      nn.ReLU(),
      nn.MaxPool2d(2),                              # -> [B, 32, 16, 16]
      nn.Conv2d(32, 64, kernel_size=3, padding=1),  # -> [B, 64, 16, 16]
      nn.BatchNorm2d(64),
      nn.ReLU(),
      nn.MaxPool2d(2),                              # -> [B, 64, 8, 8]
      nn.Flatten(),
    )
    self.classifier = nn.Linear(64 * 8 * 8, num_classes)

  def forward(self, x):
    return self.classifier(self.features(x))


model = SmallCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training: augmentation is applied while loading data. Labels are used as is
for epoch in range(epochs):
  model.train()
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    loss = criterion(model(images), labels)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# Evaluation: check on the original images
model.eval()
correct = 0
total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    predicted = model(images).argmax(dim=1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()

print(f"Test Accuracy: {100 * correct / total:.2f}%")

FAQ

Q. Is TrivialAugment the same as RandAugment with $N = 1$?
A.

No. RandAugment fixes the magnitude MM to the same value for all images and chooses that value by grid search. TrivialAugment re-chooses the magnitude from {0,…,30}\{0, \dots, 30\} for each image. The paper considers this randomness, which mixes strong and weak transformations, important for performance.

Q. What does "Wide" in torchvision's TrivialAugmentWide mean?
A.

It refers to an augmentation space with extended magnitude ranges. For example, rotation goes up to 135° instead of RandAugment's range (up to 30°), and shear up to 0.99. These are the same ranges as "TA (Wide)" in the paper's main experiments.

Q. Can it also be used for object detection or segmentation?
A.

The paper states that in object detection it did not work out of the box and needed tuning. For now, image classification is the only task for which it can be confidently recommended; for other tasks its effect needs to be verified.

References

  1. S. G. Müller and F. Hutter, "TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation," ICCV, 2021.
  2. automl/trivialaugment (implementation by the paper's authors)
  3. E. D. Cubuk, B. Zoph, J. Shlens, and Q. V. Le, "RandAugment: Practical automated data augmentation with a reduced search space," CVPR Workshops, 2020.
  4. PyTorch, torchvision.transforms.TrivialAugmentWide