AugMix is a data augmentation method that applies several randomly chosen chains of transformations to one image, mixes them with weights, and then mixes the result with the original image as well. It is used together with a Jensen-Shannon (JS) divergence loss that aligns the predictions on the mixed images with those on the original image. It was proposed by Hendrycks et al. in 2019 and presented at ICLR 2020.
The goal of AugMix is not so much to raise test accuracy as to make models robust to kinds of image corruption not seen during training (noise, blur, weather, compression, and so on) and to keep their confidence (uncertainty) properly calibrated. Even a model with high accuracy on clean images can see its error rate jump when test images are only slightly corrupted. According to the paper, ImageNet error rises from 22% on the clean test images to 64% on ImageNet-C, a collection of corrupted images.
AugMix combines the following three components (see the diagram at the top).
Diverse transformations: A "chain" is built by randomly composing 1 to 3 transformations such as rotation, shear, and translation.
Mixing: Several chains are created and summed pixel by pixel with weights, and the result is also mixed with the original image. Composing many transformations pushes an image too far from its original appearance, but mixing preserves the meaning of the original image while keeping diversity.
JS divergence loss: The model is trained so that its predicted distributions on the original image and on two AugMix images are close.
Mixup and CutMix mix in a different image and mix the labels as well, whereas AugMix mixes transformations of the same image and leaves the label unchanged. Figure 1 of the paper shows that AugMix images preserve the semantics and local features of the original image well.
Procedure
The process of applying AugMix to one image xorig (AugmentAndMix) is as follows (the pseudocode in the paper; right side of the diagram at the top).
Draw the mixing weights (w1,…,wk) from a Dirichlet distribution Dirichlet(α,…,α). The weights are non-negative and sum to 1.
For each i=1,…,k, randomly pick three operations op1,op2,op3, and uniformly choose one of op1, op2∘op1, or op3∘op2∘op1 (a chain of length 1 to 3). The strength of each operation is also sampled uniformly every time it is applied.
Sum the images produced by the chains pixel by pixel with weights wi to obtain xaug.
Draw a weight m from a Beta distribution Beta(α,α) and mix with the original image.
The paper's defaults are k=3 chains and α=1. The paper calls the mixing with the original image through m a "skip connection."
During training, AugmentAndMix is called twice on the same image to produce xaugmix1 and xaugmix2 (because the process is random, the two images differ). Denoting the model's predicted distributions on the three images as porig, paugmix1, and paugmix2, the loss is (left side of the diagram at the top):
L(porig,y)+λJS(porig;paugmix1;paugmix2)
L is a classification loss such as cross-entropy and is applied only to the prediction on the original image. The JS divergence is the average of the KL divergences between each of the three distributions and their mean M.
The weight λ is not stated in the main text of the paper, but the official implementation (CIFAR) uses λ=12. At evaluation and inference time, AugMix is not applied and only the original image is fed in.
Exclude transformation operations that overlap with the corruptions used for evaluation. Out of the AutoAugment operations, the paper removes contrast, color, brightness, sharpness, and Cutout, and does not use noise or blur either. This keeps the corrupted test data (the 15 corruption types of ImageNet-C and similar benchmarks) from being seen during training. The official implementation uses nine operations: autocontrast, equalize, posterize, rotate, solarize, shear_x, shear_y, translate_x, and translate_y.
Why it works
The paper breaks down the effect of AugMix into three factors: diversity, the JS divergence loss, and mixing (Wide ResNet-40-2, mean error % on corrupted images).
Method
CIFAR-10-C
CIFAR-100-C
Standard augmentation
26.9
53.3
AutoAugment* (operations overlapping with the corruptions removed)
23.9
49.6
One random chain (Random AutoAugment*)
17.0
43.6
+ JS divergence loss
14.7
40.8
Mixing chains (no JS loss)
13.1
39.8
AugMix (mixing + JS loss)
11.2
35.9
Diversity: Choosing a random chain every time gave more robustness to corruptions than AutoAugment*, which searches for and fixes a policy. Training only on fixed transformations is known to make the model memorize those transformations and generalize poorly to new corruptions.
Mixing: Simply composing long chains distorts an image and moves it far from its original appearance, but mixing several chains and also mixing with the original image keeps the meaning of the original image while preserving diversity.
JS divergence loss: The model is trained so that its predictions agree across various transformations of the same image. Adding it lowered the error rate at either stage.
As an everyday analogy, it is like practicing so that, even when several people each edit the same photo slightly differently and the results are overlaid semi-transparently, you can still give the same answer with the same confidence as for the original photo.
As a reason for using the JS divergence, the paper notes that, unlike the KL divergence between two distributions, it is bounded (by the logarithm of the number of classes). Using only the two-way JS(porig;paugmix1) hurt performance, while increasing the number of AugMix images to three gave only a small improvement.
In the Fourier analysis in the paper's appendix, models trained with standard augmentation or Cutout sometimes exceeded 80% error under small high-frequency perturbations, whereas models trained with AugMix were clearly more robust to mid- to high-frequency perturbations.
Results reported in the paper
On corrupted CIFAR images (CIFAR-10-C and CIFAR-100-C, mean error % over 15 corruption types × 5 severity levels), the results were as follows.
The error on corrupted images was roughly halved compared with standard augmentation. Meanwhile, the error on clean CIFAR-10 (mean of 4 models) was 5.1% for AugMix versus 5.4% for standard augmentation, so AugMix does not sacrifice accuracy on clean images. Adversarial training degraded it to 17.3%. The calibration error (RMS calibration error, mean on CIFAR-10-C) also dropped from 23.0% to 8.5%.
On corrupted ImageNet images (ResNet-50, mCE on ImageNet-C: the error normalized by AlexNet's error and averaged; lower is better), the results were as follows.
Method
Clean error (%)
mCE (%)
Standard
23.9
80.6
Patch Uniform
24.5
74.3
AutoAugment*
22.8
72.7
MaxBlur pooling
23.0
73.4
Stylized ImageNet (SIN)
27.2
73.3
AugMix
22.4
68.4
AugMix + SIN
25.2
64.9
AugMix achieved the highest robustness to corruptions while also lowering the clean error. Combining it with Stylized ImageNet makes it even more robust. On gradually changing videos (ImageNet-P), the rate at which predictions flip (mFR) also dropped from 57.2% to 37.4%. The paper also shows that the calibration error barely increases as corruptions become more severe.
Changing hyperparameters (the number of training epochs, α, the number of images used in the JS loss, the chain length, and the number of chains k) did not change the ImageNet-C mCE much.
Practical notes
Training compute increases. With the JS divergence loss, each image requires forward and backward passes for three images.
Stacking it with other mixing augmentations can make things worse. In the paper, applying AugMix on top of Mixup raised the CIFAR-10-C error from 11.2% to 13.3%. The paper suggests this may be because excessive mixing produces images that look like another class (manifold intrusion).
Choose transformations that do not change the label. The paper's appendix gives an example in which a transformation that swaps color histograms makes a bird look like a different species.
When evaluating robustness, do not let the training transformations overlap with the evaluation corruptions. If they overlap, the model is merely recognizing corruptions it has seen during training, and "robustness to unseen corruptions" cannot be measured.
When using torchvision's transforms.AugMix, keep the following in mind.
With the default all_ops=True, it also uses brightness, color, contrast, and sharpness, which the paper excluded. To use the same operations as the paper (nine types), pass all_ops=False. If you evaluate on CIFAR-10-C or ImageNet-C, you will be training on transformations that overlap with the evaluation corruptions unless you set all_ops=False.
The other arguments and their defaults are severity=3 (upper bound of operation strength, 1 to 10), mixture_width=3 (number of chains k), chain_depth=-1 (chain length; a negative value picks randomly from 1 to 3), and alpha=1.0 (α of the Dirichlet and Beta distributions).
The JS divergence loss is not included. One call to AugMix just returns one mixed image, so, as in the implementation example below, apply it twice to the same image to obtain three images and write the loss yourself.
Apply it to PIL images or uint8 tensors. Place it before ToTensor and Normalize.
Comparison with similar methods and how to choose
The table below compares data augmentation methods that transform or mix images from the same angles.
Method
What is mixed
Label
Main goal
Extra loss
AugMix
Chains of transformations of the same image, plus the original image
Unchanged
Robustness to unseen corruptions and correct confidence
Production images may differ from training images (corrupted by weather, cameras, compression, and so on): Use AugMix. In the paper, it roughly halved the error on corrupted images while maintaining accuracy on clean images.
You want to use the model's confidence for decisions: Use AugMix. Its calibration error barely increased even as corruptions became more severe.
Accuracy on standard test data is the top priority: Also compare TrivialAugment and RandAugment. In the TrivialAugment paper, TrivialAugment outperformed AugMix in ResNet-50 accuracy on ImageNet.
You do not want extra compute: You can drop the JS divergence loss and train only on the mixed images. In the paper's ablation, this still lowered the CIFAR-10-C error from 26.9% to 13.1% (11.2% with the JS loss).
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, Dataset
"""
CIFAR-10 image classification (trained with AugMix and the JS divergence loss)
"""
# Hyperparameters
batch_size = 128 # Batch size
epochs = 5 # Number of epochs
learning_rate = 1e-3 # Learning rate
jsd_weight = 12.0 # Weight λ of the JS divergence loss (CIFAR value in the paper's official implementation)
# Use '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)
preprocess = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std)])
base_transform = transforms.Compose([ # Standard augmentation (applied before AugMix)
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
])
augmix = transforms.AugMix( # Works on PIL or uint8 tensors, so place it before ToTensor
severity=3, # Upper bound of operation strength (1-10, default 3)
mixture_width=3, # Number of chains k to mix (default 3)
chain_depth=-1, # Chain length; a negative value picks randomly from 1-3 (default -1)
alpha=1.0, # α of Dirichlet and Beta (default 1.0)
all_ops=False, # Default is True. False uses the paper's 9 ops (excludes color ops that overlap with corruptions)
)
class AugMixDataset(Dataset):
# Returns 3 images from one image: the original and 2 AugMix images
def __init__(self, dataset):
self.dataset = dataset
def __len__(self):
return len(self.dataset)
def __getitem__(self, i):
img, label = self.dataset[i]
img = base_transform(img)
return (preprocess(img), preprocess(augmix(img)), preprocess(augmix(img))), label
train_dataset = AugMixDataset(datasets.CIFAR10(root='./data', train=True, download=True))
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=preprocess) # No AugMix for evaluation
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))
def jensen_shannon(logits_orig, logits_aug1, logits_aug2):
# JS(p_orig; p_aug1; p_aug2) = (KL[p_orig || M] + KL[p_aug1 || M] + KL[p_aug2 || M]) / 3, where M is the mean of the three
p_orig, p_aug1, p_aug2 = F.softmax(logits_orig, dim=1), F.softmax(logits_aug1, dim=1), F.softmax(logits_aug2, dim=1)
log_m = torch.clamp((p_orig + p_aug1 + p_aug2) / 3., 1e-7, 1).log()
return (F.kl_div(log_m, p_orig, reduction='batchmean') +
F.kl_div(log_m, p_aug1, reduction='batchmean') +
F.kl_div(log_m, p_aug2, reduction='batchmean')) / 3.
model = SmallCNN().to(device)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
for epoch in range(epochs):
model.train()
for (x_orig, x_aug1, x_aug2), labels in train_loader:
labels = labels.to(device)
# Predict all 3 images in one pass (shared weights)
logits = model(torch.cat([x_orig, x_aug1, x_aug2]).to(device))
logits_orig, logits_aug1, logits_aug2 = torch.split(logits, x_orig.size(0))
loss = F.cross_entropy(logits_orig, labels) # Classification loss only on the original image's prediction
loss = loss + jsd_weight * jensen_shannon(logits_orig, logits_aug1, logits_aug2) # Loss that aligns the predictions
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. What happens to the label of an AugMix image?
A.
It stays the same. AugMix mixes transformations of the same image with the original image, so the content of the image is assumed not to change. This is where it differs from methods like Mixup, which mix in a different image and mix the labels too. The classification loss is applied to the prediction on the original image porig, and the predictions on the AugMix images are aligned through the JS divergence loss.
Q. Is the JS divergence loss always necessary?
A.
AugMix helps without it, but it is stronger with it. In the paper's ablation (Wide ResNet-40-2), the CIFAR-10-C error dropped from 26.9% to 13.1% with mixing alone, and to 11.2% with the JS loss added. Because the loss requires computation for three images per sample, dropping it is an option when compute is tight.
Q. Does using torchvision's AugMix as is reproduce the paper?
A.
There are two differences. The default all_ops=True also uses brightness, color, contrast, and sharpness, which the paper excluded, so set all_ops=False to match the paper. Also, the JS divergence loss is not included, so you need to apply it twice to the same image to obtain three images and write the loss yourself.