Fast AutoAugment is a method that searches far faster for data augmentation policies of the same form as AutoAugment (which operations to apply, with what probability and magnitude) by evaluating them without retraining a model. It was proposed by Lim et al. at Kakao Brain in 2019 and presented at NeurIPS 2019.
AutoAugment trained a small model (child model) from scratch for every candidate policy it tried and measured validation accuracy. Repeating this about 15,000 times took 5,000 GPU hours for the CIFAR-10 search alone. Fast AutoAugment prepares one trained model and evaluates a policy simply by measuring the prediction loss on images augmented with it (right side of the diagram at the top). Because each evaluation changes from "training" to "prediction," search time drops dramatically.
(Note that the GPU types differ: AutoAugment's times are on Tesla P100 and Fast AutoAugment's on Tesla V100.)
Even so, the error rates of models trained with the policies found were almost the same as with AutoAugment.
The policy structure (5 sub-policies, each sub-policy being 2 operations, each operation a triple of type, probability, and magnitude) and the 16 operations are the same as in AutoAugment. What differs is how policies are searched, and that probabilities and magnitudes are searched as continuous values in 0 to 1 rather than in discrete steps. The policy structure and the list of operations are summarized in the AutoAugment article.
Idea: do augmented images look "like the training data"?
Fast AutoAugment considers a good policy to be one whose augmented images can be classified correctly by a model trained only on the training data. The paper formulates this as a density matching problem of aligning the distributions (densities) of two sets of data.
The training data Dtrain is split into DM, used to train the model, and DA, used to try policies. Denoting the parameters of the model trained on DM as θ∗ and the set of images in DA augmented with policy T as T(DA), the policy to find is:
T∗=TargmaxR(θ∗∣T(DA))
R is accuracy. If a model trained only on DM classifies the augmented DA well, the images produced by the policy do not stray from the distribution of DM; that is, the policy produces "images that could plausibly be in the training data but are not yet included." The paper builds on the idea of Bayesian DA, which regards augmented images as "missing points of the training data."
As an everyday analogy, it is a selection that keeps only the photo edits after which someone used to photos can still tell at a glance what the photo shows. Policies that produce implausible images (such as images where the object's shape is broken) have large losses and are not selected.
This evaluation has the same form as test-time augmentation, which augments images at test time before predicting. By moving only the policy while keeping the trained model fixed, the paper removes the need for backpropagation or training in each evaluation.
Search procedure
The search proceeds in the following order (Algorithm 1 in the paper; left side of the diagram at the top).
Split the training data into K folds: Split it into K folds while keeping the class proportions (stratified), and make each into a pair of DM and DA.
Train a model on DM: For each fold, train a model θ without applying any policy. This is the only training. The K folds can be processed in parallel.
Search for policies with Bayesian optimization: Try B candidate policies, looking for policies that make the loss L(θ∣T(DA)) on the augmented DA small. θ is not changed.
Keep the top N: Of the B policies tried, keep the N with the smallest losses. Repeat steps 3 and 4 T times.
Merge the policies from all folds: Combine the policies kept for each fold into the final set of policies T∗.
Retrain: Apply T∗ to all of Dtrain and train the production model.
The Bayesian optimization in step 3 uses the Tree-structured Parzen Estimator (TPE). It chooses the next policy to try based on the losses of the policies tried so far. The selection criterion is the following Expected Improvement.
EI(T)=E[min(L(θ∣T(DA))−L†,0)]
L† is a threshold set by a quantile of the losses of the policies tried so far. The policy with the largest expected reduction of the loss below the threshold (the most negative value of the expression) is tried next. The implementation uses the HyperOpt library and runs Bayesian optimization in parallel.
The settings of the paper's experiments are as follows.
Symbol
Meaning
Value
K
Number of training data folds
5
T
Number of "search and keep" iterations
2
B
Number of policies tried per iteration
200
N
Number of policies kept per iteration
10
Nτ
Number of operations in a sub-policy
2
NT
Number of sub-policies in a policy
5
The production model to be retrained may differ from the model used for the search. The paper's CIFAR experiments include two variants: "direct," which searches directly with the production model and full data, and "transfer," which brings over policies found with a small model (Wide-ResNet-40-2) and CIFAR-10 reduced to 4,000 images. However, the paper states that the gap between transfer and direct widens as the production model gets larger, because policies found with a small model are limited in how much they can improve the generalization of a large model.
Results reported in the paper
Test error rates (%) on CIFAR-10 are as follows. "Standard" is each model's standard preprocessing, Fast AA is Fast AutoAugment, and "transfer / direct" are the results of the two search variants above.
For every model, it clearly outperformed standard augmentation and Cutout, and on CIFAR-10 it was almost the same as AutoAugment. On CIFAR-100, it fell slightly short of AutoAugment and PBA for models other than Wide-ResNet-40-2. The paper suggests this may be due to insufficient search or overtraining of the model used for the search.
Validation error rates (%, top-1 / top-5) on ImageNet are as follows. The search used 6,000 images selected from 120 ImageNet classes.
On SVHN (Wide-ResNet-28-10), Fast AutoAugment achieved 1.1%, the same as AutoAugment, compared with 1.5% for standard augmentation and 1.3% for Cutout.
The effect of the number of sub-policies was also examined. When retraining with a subset of the 400 sub-policies found in the search, the validation error on CIFAR-10 and CIFAR-100 kept decreasing as the number of sub-policies was increased up to 100 to 125.
Practical notes
Train the model used for the search without data augmentation. The method assumes that the model trained on DM represents "the distribution of the original images." The TrivialAugment paper also summarizes Fast AutoAugment as "a method that searches for good test-time augmentations for a network trained on non-augmented images."
On data with many classes, such as CIFAR-100, it may fall slightly short of AutoAugment. In the paper's results, the gap was about 0.2 to 1.0 points.
Use a fairly large number of policies. In the paper's experiments, the error kept decreasing as the number of sub-policies used for retraining was increased up to 100 to 125.
Compare with methods that need no search before using it. The later TrivialAugment paper reproduced the published Fast AutoAugment policies under the same training setup and reported that TrivialAugment, which does no search, achieved the same or higher accuracy (84.33% versus 83.27% on CIFAR-100 with Wide-ResNet-28-10).
Neither PyTorch nor torchvision has a built-in Fast AutoAugment (torchvision provides AutoAugment, RandAugment, TrivialAugmentWide, and AugMix). Search with the paper authors' implementation (kakaobrain/fast-autoaugment), or load the policies published there. To search yourself, combine a function that measures the loss on augmented images with a Bayesian optimization library, as in the implementation example below.
Comparison with similar methods and how to choose
The table below compares methods that automatically determine data augmentation policies from the same angles. Error rates (%) are for PyramidNet + ShakeDrop on CIFAR-10 and ResNet-50 top-1 on ImageNet, taken from each paper (TrivialAugment's ImageNet settings, such as image width, differ slightly).
You want to find a policy tailored to your data with little computation: Use Fast AutoAugment. It can find policies of the same form as AutoAugment in a few GPU hours.
You want to eliminate the search stage altogether: Use RandAugment or TrivialAugment. In the TrivialAugment paper, these search-free methods achieved the same or higher accuracy than Fast AutoAugment.
You want to use a published policy as is: For data close to CIFAR, SVHN, or ImageNet, AutoAugment's policies (torchvision's AutoAugment) are the easiest option.
PyTorch example
▶Show code
python
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms.functional as TF
import optuna # Bayesian optimization with TPE (Tree-structured Parzen Estimator) (the paper uses HyperOpt)
"""
A small implementation of the Fast AutoAugment policy search (one fold of Algorithm 1 in the paper).
model is a model trained on D_M (without any policy); x_a and y_a are the D_A images ([N, 3, H, W] in 0-1) and labels.
"""
# List of operations (the paper uses the same 16 as AutoAugment; only some here). Magnitude m is continuous in 0-1
def shear_x(img, m): return TF.affine(img, angle=0.0, translate=[0, 0], scale=1.0, shear=[m * 0.3 * 180 / np.pi, 0.0])
def translate_x(img, m): return TF.affine(img, angle=0.0, translate=[int(m * 0.45 * img.shape[-1]), 0], scale=1.0, shear=[0.0, 0.0])
def rotate(img, m): return TF.rotate(img, m * 30)
def auto_contrast(img, m): return TF.autocontrast(img)
def invert(img, m): return TF.invert(img)
def brightness(img, m): return TF.adjust_brightness(img, 0.1 + 1.8 * m)
def contrast(img, m): return TF.adjust_contrast(img, 0.1 + 1.8 * m)
def solarize(img, m): return TF.solarize(img, 1.0 - m)
OPS = [shear_x, translate_x, rotate, auto_contrast, invert, brightness, contrast, solarize]
N_SUB, N_OP = 5, 2 # Policy = 5 sub-policies, sub-policy = 2 operations (paper's setting)
def apply_subpolicy(img, subpolicy):
# Apply the sub-policy's operations in order, each with its probability p (Eq. (1))
for op_idx, p, m in subpolicy:
if random.random() < p:
img = OPS[op_idx](img, m)
return img
@torch.no_grad()
def policy_loss(model, policy, x_a, y_a):
# Loss on the augmented D_A, L(θ | T(D_A)). θ is unchanged (no backpropagation, no training)
model.eval()
imgs = torch.stack([apply_subpolicy(img, random.choice(policy)) for img in x_a])
return F.cross_entropy(model(imgs), y_a).item()
def search(model, x_a, y_a, T=2, B=200, N=10):
found = []
for t in range(T):
def objective(trial):
# Operation types are categorical; probabilities and magnitudes are searched as continuous values in 0-1
policy = [[(trial.suggest_categorical(f"op_{i}_{j}", list(range(len(OPS)))),
trial.suggest_float(f"p_{i}_{j}", 0.0, 1.0),
trial.suggest_float(f"m_{i}_{j}", 0.0, 1.0)) for j in range(N_OP)] for i in range(N_SUB)]
trial.set_user_attr("policy", policy)
return policy_loss(model, policy, x_a, y_a) # Smaller is a better policy
study = optuna.create_study(direction="minimize", sampler=optuna.samplers.TPESampler(seed=t))
study.optimize(objective, n_trials=B) # Try B policies
best = sorted(study.trials, key=lambda tr: tr.value)[:N] # Keep the top N
found += [tr.user_attrs["policy"] for tr in best]
return found
class FastAAPolicy:
# Use the set of found policies T* as data augmentation when retraining (place after ToTensor and before Normalize)
def __init__(self, policies):
self.subpolicies = [sp for policy in policies for sp in policy]
def __call__(self, img):
return apply_subpolicy(img, random.choice(self.subpolicies))
if __name__ == "__main__":
# A small example to check that it runs (in practice, use a model trained on D_M and D_A)
model = nn.Sequential(nn.Conv2d(3, 8, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(8, 10))
x_a, y_a = torch.rand(64, 3, 32, 32), torch.randint(0, 10, (64,))
policies = search(model, x_a, y_a, T=1, B=20, N=2) # Paper's setting is T=2, B=200, N=10 (and for each of K=5 folds)
augment = FastAAPolicy(policies)
print(len(augment.subpolicies), augment(x_a[0]).shape)
FAQ
Q. Can Fast AutoAugment be used in torchvision?
A.
It is not built into torchvision. torchvision provides AutoAugment, RandAugment, TrivialAugmentWide, and AugMix. To use Fast AutoAugment, search with the paper authors' implementation (kakaobrain/fast-autoaugment) or load the policies published there.
Q. Why can policies be evaluated without retraining the model?
A.
Because a good policy is defined as "one whose augmented images can still be classified correctly by a model trained only on the original images." With this criterion, the loss L(θ∣T(DA)) on the augmented DA can be computed by prediction alone, keeping the model θ trained on DM fixed. Each evaluation needs no training or backpropagation, so the search becomes very fast.
Q. Is accuracy lower than with AutoAugment?
A.
In the paper's results, it was almost the same on CIFAR-10, SVHN, and ImageNet, and with ResNet-200 on ImageNet its top-1 error of 19.4% beat AutoAugment's 20.0%. On CIFAR-100, however, it fell short of AutoAugment by about 0.2 to 1.0 points for many models.