AI Logic

Data Augmentation

Fast AutoAugment

Updated:

Diagram of Fast AutoAugment. The left side shows the policy search flow: split the training data into K folds, split each fold into D_M and D_A, train a model θ on D_M, try B policies with Bayesian optimization and keep the top N; merge the policies from all folds, apply them to the whole training set, and retrain. The right side compares how a single policy is evaluated with AutoAugment (training a child model from scratch and measuring validation accuracy), together with a table of the GPU hours spent on the search

What is Fast AutoAugment?

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.

DatasetAutoAugmentFast AutoAugment
CIFAR-105,000 GPU hours3.5 GPU hours
SVHN1,000 GPU hours1.5 GPU hours
ImageNet15,000 GPU hours450 GPU hours

(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 DtrainD_{\text{train}} is split into DMD_M, used to train the model, and DAD_A, used to try policies. Denoting the parameters of the model trained on DMD_M as θ∗\theta^* and the set of images in DAD_A augmented with policy T\mathcal{T} as T(DA)\mathcal{T}(D_A), the policy to find is:

T∗=argmax⁡T  R(θ∗∣T(DA))\mathcal{T}^* = \operatorname*{argmax}_{\mathcal{T}} \; \mathcal{R}(\theta^* \mid \mathcal{T}(D_A))

R\mathcal{R} is accuracy. If a model trained only on DMD_M classifies the augmented DAD_A well, the images produced by the policy do not stray from the distribution of DMD_M; 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).

  1. Split the training data into KK folds: Split it into KK folds while keeping the class proportions (stratified), and make each into a pair of DMD_M and DAD_A.
  2. Train a model on DMD_M: For each fold, train a model θ\theta without applying any policy. This is the only training. The KK folds can be processed in parallel.
  3. Search for policies with Bayesian optimization: Try BB candidate policies, looking for policies that make the loss L(θ∣T(DA))\mathcal{L}(\theta \mid \mathcal{T}(D_A)) on the augmented DAD_A small. θ\theta is not changed.
  4. Keep the top NN: Of the BB policies tried, keep the NN with the smallest losses. Repeat steps 3 and 4 TT times.
  5. Merge the policies from all folds: Combine the policies kept for each fold into the final set of policies T∗\mathcal{T}^*.
  6. Retrain: Apply T∗\mathcal{T}^* to all of DtrainD_{\text{train}} 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)]\mathrm{EI}(\mathcal{T}) = \mathbb{E}\left[\min\left(\mathcal{L}(\theta \mid \mathcal{T}(D_A)) - \mathcal{L}^{\dagger},\ 0\right)\right]

L†\mathcal{L}^{\dagger} 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.

SymbolMeaningValue
KKNumber of training data folds5
TTNumber of "search and keep" iterations2
BBNumber of policies tried per iteration200
NNNumber of policies kept per iteration10
NτN_\tauNumber of operations in a sub-policy2
NTN_{\mathcal{T}}Number of sub-policies in a policy5

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.

ModelStandardCutoutAutoAugmentPBAFast AA (transfer / direct)
Wide-ResNet-40-25.34.13.7−3.6 / 3.7
Wide-ResNet-28-103.93.12.62.62.7 / 2.7
Shake-Shake (26 2×96d)2.92.62.02.02.0 / 2.0
Shake-Shake (26 2×112d)2.82.61.92.02.0 / 1.9
PyramidNet + ShakeDrop2.72.31.51.51.8 / 1.7

Test error rates (%) on CIFAR-100 are as follows.

ModelStandardCutoutAutoAugmentPBAFast AA (transfer / direct)
Wide-ResNet-40-226.025.220.7−20.7 / 20.6
Wide-ResNet-28-1018.818.417.116.717.3 / 17.3
Shake-Shake (26 2×96d)17.116.014.315.314.9 / 14.6
PyramidNet + ShakeDrop14.012.210.710.911.9 / 11.7

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.

ModelStandardAutoAugmentFast AutoAugment
ResNet-5023.7 / 6.922.4 / 6.222.4 / 6.3
ResNet-20021.5 / 5.820.0 / 5.019.4 / 4.7

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 DMD_M 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).

MethodHow policies are foundSearch time (CIFAR-10)CIFAR-10ImageNet
AutoAugmentTrain a child model per policy and search with reinforcement learning5,000 GPU hours1.522.4
Fast AutoAugmentMeasure the loss with a trained model and search with Bayesian optimization3.5 GPU hours1.7 (direct)22.4
PBAChange the policy during training with Population Based Training−1.5−
RandAugmentNo search (grid search only over the number of operations NN and magnitude MM)Not needed1.522.4
TrivialAugmentNo search (no values to tune either)Not needed1.421.9

Rough guidelines for choosing are as follows.

  • 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))\mathcal{L}(\theta \mid \mathcal{T}(D_A)) on the augmented DAD_A can be computed by prediction alone, keeping the model θ\theta trained on DMD_M 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.

References

  1. S. Lim, I. Kim, T. Kim, C. Kim, and S. Kim, "Fast AutoAugment," NeurIPS, 2019.
  2. kakaobrain/fast-autoaugment (implementation by the paper's authors)
  3. E. D. Cubuk, B. Zoph, D. Mané, V. Vasudevan, and Q. V. Le, "AutoAugment: Learning Augmentation Strategies from Data," CVPR, 2019.
  4. J. Bergstra, R. Bardenet, Y. Bengio, and B. Kégl, "Algorithms for Hyper-Parameter Optimization," NeurIPS, 2011.