Robustness & Distribution Shift
Adversarial examples, shortcuts and models that fail outside their training data.
A classifier that rivals people on its test set can be flipped by a change no person can see, lose more than ten points of accuracy on a careful copy of its own benchmark, and answer pure noise with near certainty. The test set measured one thing: accuracy on more data drawn exactly like the training data. Here you build the attacks that exploit everything else, measure what happens when the data drift, and meet the simplest way to notice an input the network was never trained for.
What you’ll learn
- Define a threat model and robust accuracy, derive the fast gradient sign method as the steepest first-order attack, and iterate it into projected gradient descent.
- Explain the linearity account of adversarial examples and of their transfer between models, and say what it leaves unexplained.
- Distinguish covariate, label and concept shift, and correct a classifier's probabilities for a known change in class frequencies.
- Measure robustness to synthetic corruptions (ImageNet-C) and to natural shifts (effective robustness), and say which interventions have helped.
- Flag out-of-distribution inputs with the maximum softmax probability, score a detector by AUROC, and explain why ReLU networks are confident far from their data.
Attacks are optimizers
Generalization asks how a model does on new inputs drawn like its training data. An adversarial example asks something else: what is the worst input within a small distance of a real one? For deep image classifiers, Szegedy et al. (2014) found the answer is often a misclassified image that looks unchanged. To make "small" precise, fix a threat model.
Finding the worst is a maximization, , over the input instead of the weights. Its first-order solution is the classic attack:
Write , computed by backpropagating all the way to the input. For a small perturbation the loss is nearly linear:
Under every coordinate can be chosen on its own: push each pixel by in the direction of its gradient's sign. This is the fast gradient sign method (FGSM; Goodfellow, Shlens & Szegedy, 2015):
Under , Cauchy–Schwarz picks the rescaled gradient instead, , with gain : in general, times the dual norm of the gradient. Now compare random signs of the same size, with independent :
So the attack beats noise by the ratio , which grows with the input dimension when the gradient is spread over many pixels: many changes far too small to see, all pointing the same way, add up. For a binary linear classifier the loss depends on the input only through a margin that is linear in it, so FGSM is the exact worst case in the box; for a network it is one step of an optimizer.
Suppose the input gradient of an ImageNet classifier, with inputs, had entries like independent Gaussian draws, so that . How many times larger is FGSM's first-order loss increase than the typical change caused by random signs of the same size?
Show the answer
310
: the attack's gain is about 310 standard deviations of the random perturbation's effect. For a MNIST digit the same ratio is about 22. Real gradients are not independent Gaussians, but this growth with is why high-dimensional inputs such as images are so easy to attack.
One step is only a linearization. Iterating it, and projecting back into the ball after every step, gives the standard strong attack, projected gradient descent (PGD) on the negative loss: start at a random point of the ball and repeat (Kurakin, Goodfellow & Bengio, 2017; Madry et al., 2018).
import torch
import torch.nn.functional as F
def fgsm(model, x, y, eps):
x = x.clone().requires_grad_(True)
g, = torch.autograd.grad(F.cross_entropy(model(x), y), x)
return (x + eps * g.sign()).clamp(0, 1).detach() # one steepest l_inf step
def pgd(model, x, y, eps, alpha, steps):
delta = torch.empty_like(x).uniform_(-eps, eps) # random start in the box
for _ in range(steps):
delta.requires_grad_(True)
g, = torch.autograd.grad(F.cross_entropy(model(x + delta), y), delta)
delta = (delta + alpha * g.sign()).clamp(-eps, eps) # ascend, then project
delta = ((x + delta).clamp(0, 1) - x).detach() # keep pixels in [0, 1]
return x + delta
# e.g. CIFAR-10: x_adv = pgd(model, x, y, eps=8/255, alpha=2/255, steps=10)Both attacks only need gradients with respect to the input. PGD is an optimizer, so the accuracy it leaves is only an upper bound on robust accuracy: a stronger attack can find what it missed. Evaluations that trusted weak attacks have repeatedly overstated robustness, as Adversarial Training shows.
Why they exist, and why they transfer
The most famous example: Goodfellow, Shlens and Szegedy took a photo that GoogLeNet labeled "panda" with 57.7% confidence and added an FGSM perturbation with , the size of the smallest bit of an 8-bit image after the network's preprocessing. The result looked identical and was labeled "gibbon" with 99.3% confidence.
Their explanation is not exotic nonlinearity but its opposite. ReLUs, maxout units and LSTMs are designed to behave nearly linearly, because that makes them easy to optimize, and in high dimension a linear function is exactly what the derivation shows to be fragile: a change of per input moves a linear score by up to , which grows with the number of inputs. The evidence is that one linearized step suffices. With on MNIST, FGSM gave a shallow softmax classifier a 99.9% error rate, with an average confidence of 79.3%, and made a maxout network misclassify 89.4% of the examples with an average confidence of 97.6%. Linear models are vulnerable too: this is not a peculiarity of deep networks.
Transfer. Szegedy et al. (2014) found that adversarial examples made for one network often fool others, trained with different architectures or on different subsets of the data. That turns a white-box attack into a black-box one: train a substitute model on similar data, attack it, and submit the result (Papernot, McDaniel & Goodfellow, 2016); attacking an ensemble of substitutes makes the examples transfer more reliably (Liu, Chen, Liu & Song, 2017). The linear view explains transfer too: what matters is the perturbation's direction, and models trained for the same task learn similar functions, so their gradients point in similar directions near the data.
What the linear view leaves open: adversarially trained networks are just as piecewise linear, yet far more robust, so linearity cannot be the whole story. Adversarial Training takes up the competing explanations, among them the idea that the perturbations exploit features of the data that genuinely predict the label but that people do not see.
Models A and B are trained separately for the same task. Why do PGD examples crafted against A often fool B too?
- A and B share their random initialization, so their weights are nearly identical
- Both learn similar functions from the same kind of data, so their loss gradients point in similar directions near the data, and a perturbation aligned with A's also hurts B
- Adversarial perturbations are random noise, and noise fools every model
- B must have been trained on A's adversarial examples
Show the answer
B. Both learn similar functions from the same kind of data, so their loss gradients point in similar directions near the data, and a perturbation aligned with A's also hurts B
Transfer is a property of what the models learned, not of how they were initialized. When two models compute similar functions, a perturbation aligned with one model's gradient is largely aligned with the other's. Black-box attacks exploit exactly this, with a substitute model playing the role of A.
When the data move
Adversarial examples are worst cases chosen by an opponent. Far more common is distribution shift: the data met in use simply differ from the training data. Write the joint distribution two ways, . The standard kinds of shift each change one factor and keep its partner:
- Covariate shift: changes, does not. A digit recognizer trained on one scanner's images meets another scanner's: the images look different, but any given image is labeled the same way. If the input densities overlap, weighting each training example by makes the training loss an unbiased estimate of the test loss (Shimodaira, 2000), though in high dimension the weights are hard to estimate and can have enormous variance.
- Label shift: changes, does not. A flu detector built in summer meets the winter: the share of patients with flu jumps, yet a case of flu presents the same way as before.
- Concept shift: itself changes, as when fraudsters adapt to a detector. No amount of unlabeled data reveals how; only new labels help.
Label shift has a clean fix that needs no new labels at all:
Mark the training (source) distribution by and the deployment (target) distribution by , with . Apply Bayes' rule in the target, then rewrite the shared class-conditional with Bayes' rule in the source:
The factors that depend only on cancel when the probabilities are normalized over classes, so the trained classifier's output only needs reweighting by the ratio of class frequencies (Saerens, Latinne & Decaestecker, 2002):
In logits, this adds to class 's logit: the same move as the post-hoc logit adjustment for imbalanced classes in Reshaping Cross-Entropy. When is unknown, it can be estimated from unlabeled target data, by expectation–maximization (Saerens et al., 2002) or by inverting the classifier's confusion matrix (Lipton, Wang & Smola, 2018).
A diagnostic classifier was trained on a balanced dataset, half positive. For one patient it outputs . In the clinic only 10% of patients are positive, and the disease looks the same as in training. What probability should it report, in percent?
Show the answer
31 %
Reweight by the prior ratios: positive , negative , so . In odds: the classifier's odds are multiplied by the change in prior odds, , giving odds and probability . A confident-looking 80% becomes less than one in three.
Corruptions and natural shifts
To measure robustness to everyday degradations, Hendrycks and Dietterich (2019) built ImageNet-C: 15 corruption types from four families (noise, blur, weather and digital), each at five severities, applied to ImageNet validation images that models must not train on. Fog is harder than brightness, so each corruption's error is normalized by AlexNet's:
Natural shifts. Corruptions are synthetic. The new CIFAR-10 and ImageNet test sets of Recht et al. (2019), met in the Activation lesson, are a natural shift, and they showed a striking regularity: across many models, accuracy on the new test set rose almost linearly with accuracy on the original. Taori et al. (2020) evaluated 204 ImageNet models under 213 test conditions. On logit-scaled axes the standard models fall close to a line , so robustness should be measured beyond that line, as effective robustness:
Robustness to synthetic shifts (corruptions, attacks) transferred little or not at all to natural ones, and most interventions bought no robustness to the natural shifts in their testbed. The main exception was training on larger and more diverse datasets, which helped in several cases without closing the gaps. Miller et al. (2021) found this "accuracy on the line" across architectures, hyperparameters, training-set sizes and training durations, for shifts of CIFAR-10, ImageNet and real-world datasets, with exceptions such as some synthetic CIFAR-10 corruptions and tissue images from new hospitals (Camelyon17).
The largest effective robustness so far came from changing the training data. Zero-shot CLIP classifiers, trained on image–text pairs from the internet rather than on ImageNet, shrank the gap between ImageNet accuracy and accuracy under natural shifts by up to 75% (Radford et al., 2021). Fitting a logistic-regression classifier to CLIP's features on ImageNet itself raised ImageNet accuracy by 9.2 points, yet average accuracy under the shifts fell slightly, leaving effective robustness close to that of the best earlier ImageNet models (Vision Transformers & Vision–Language Models).
On a natural-shift benchmark, the line fitted to standard models predicts 57% shifted accuracy for a model with 70% original accuracy, and 68% for one with 80%. Model A scores 70% and 59%; model B scores 80% and 68%. Which statement is right?
- B is the more robust model, because its accuracy under the shift is higher
- Neither has effective robustness, since both lose accuracy under the shift
- A and B are equally robust, since both lose about the same number of points
- A has 2 points of effective robustness and B has none, even though B is more accurate under the shift
Show the answer
D. A has 2 points of effective robustness and B has none, even though B is more accurate under the shift
Effective robustness is accuracy under shift beyond what the trend of standard models predicts from original accuracy: for A and for B. B is simply a more accurate model on the same line. Which model to deploy depends on what you need, but only A shows robustness that its accuracy does not already explain.
Shortcuts, and knowing when not to answer
Why do natural shifts hurt so much? One reason is shortcut learning: decision rules that work on test data drawn like the training data but fail out of distribution (Geirhos et al., 2020). If the cows in the training photos stand on grass, grass predicts "cow": an off-the-shelf image tagger that recognized cows in Alpine pastures failed to detect cows on a beach (Beery, Van Horn & Perona, 2018). On images whose shape says one class and whose texture says another, people chose by shape in 95.9% of the answers that matched either cue, while an ImageNet-trained ResNet-50 chose by texture in 77.9% (Geirhos et al., 2019). Training rewards any feature that predicts the label; Shortcut Learning & Spurious Correlations shows why gradient descent favors simple ones, and how to measure and limit the damage.
When shifts cannot be prevented, a model should at least notice them. The simplest detector of out-of-distribution inputs is the maximum softmax probability (MSP; Hendrycks & Gimpel, 2017): score and flag inputs that score below a threshold. Correctly classified in-distribution inputs tend to score higher than misclassified or out-of-distribution ones. A detector is summarized by its AUROC, the probability that a random in-distribution input outscores a random out-of-distribution one, so 0.5 is chance. The baseline works more often than one might expect, but in the same paper an MNIST classifier gave Gaussian noise a confidence of 91%, and for ReLU networks there is a reason it must fail somewhere:
The regions are convex polytopes. A ray that left a region could not come back to it (the segment between two of its points would stay inside), and there are finitely many regions, so beyond some the ray stays in one region :
For almost every the numbers , over the rows of , are all different: ties happen only on the finitely many hyperplanes . Let have the largest and write . The probability left for the other classes is at most the sum of their odds against , and each of those shrinks exponentially in :
A softmax temperature divides every exponent by and changes nothing in the limit, so no recalibration of the outputs fixes this. Images live in , so the theorem does not apply to them directly, but the same idea can be used to find high-confidence inputs, and Hein et al. proposed training that enforces low confidence far from the training data instead. A Gaussian posterior on the last layer's weights also bounds the confidence far away (the Machine Learning course's Uncertainty in Neural Networks).
Key takeaways
- A threat model fixes what the attacker may change, usually an ball; robust accuracy counts the test points whose prediction no allowed change can flip. Accuracy under any particular attack only bounds it from above.
- To first order the worst perturbation is (FGSM), with gain , up to times the typical effect of random signs; PGD iterates the step with projection and random starts.
- The linearity account explains how many tiny changes, all pushing the loss the same way, accumulate in high dimension, and why examples transfer between models, which enables black-box attacks; it does not explain why adversarially trained networks, equally piecewise linear, are robust.
- Under label shift, reweight predicted probabilities by and renormalize; covariate shift calls for importance weights on the training loss; concept shift needs new labels.
- On corruption and natural-shift benchmarks, robustness gains have mostly tracked clean accuracy, and only more diverse training data, as in zero-shot CLIP, has bought large effective robustness. The maximum softmax probability is the baseline detector of out-of-distribution inputs, but ReLU networks are confident far from their data.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
An attacker may change the input by a perturbation of norm at most . To first order, which perturbation increases the loss the most?
- , the FGSM step
- , the gradient rescaled to length
- Random signs of size per pixel
- All of on the pixel with the largest gradient entry
Show the answer
B. , the gradient rescaled to length
Maximizing over the ball is Cauchy–Schwarz: the best direction is the gradient itself, with gain . The sign step is optimal for the box, and spending everything on one pixel is optimal for an budget.
A model was trained where 20% of the examples belong to class A; at deployment 60% do, and the way each class looks has not changed. How should its predicted probabilities be corrected?
- They need no correction, since nothing about the inputs of each class changed
- Add 40 percentage points to class A's probability
- Multiply each class's probability by (by 3 for class A) and renormalize
- Retrain from scratch, since probabilities cannot be corrected without new labels
Show the answer
C. Multiply each class's probability by (by 3 for class A) and renormalize
This is label shift: the class-conditional distributions are fixed and only the class frequencies moved. Bayes' rule then gives the new posterior as the old one reweighted by the ratio of priors, which needs only the new class frequencies, and those can themselves be estimated from unlabeled data.
From AlexNet to ResNet, ImageNet-C's mean corruption error fell steadily, yet Hendrycks and Dietterich concluded that robustness to corruptions had barely changed. What did they see?
- The corruption error fell only because the newer models were trained on the corruptions
- The mean corruption error rose when measured at the highest severity alone
- Newer models were evaluated on easier corruptions
- The improvements tracked clean accuracy: the relative corruption error, which subtracts each model's clean error, was for many later models no better than AlexNet's
Show the answer
D. The improvements tracked clean accuracy: the relative corruption error, which subtracts each model's clean error, was for many later models no better than AlexNet's
The mean corruption error mixes two things, how accurate a model is and how much it degrades under corruption. The relative version isolates the degradation, and for many models after AlexNet it was worse than AlexNet's: better accuracy, not better robustness, drove the gains. Taori et al. made the same point for natural shifts with effective robustness.
A ReLU network's logits are piecewise linear in its input. Why can't dividing its logits by a temperature stop it from giving near-certain predictions on inputs far from the training data?
- Far away the input lies in one unbounded linear region, where the logits are along a ray ; their gaps grow linearly in , and a fixed only slows the growth
- Temperature scaling only works for sigmoid outputs
- Far from the data the logits become all equal, so the softmax is already uniform
- Temperature scaling changes which class is predicted, which makes it useless here
Show the answer
A. Far away the input lies in one unbounded linear region, where the logits are along a ray ; their gaps grow linearly in , and a fixed only slows the growth
Along a ray the network eventually stays in a single linear region, since there are finitely many and they are convex. There the top logit outgrows the others linearly in , so the softmax tends to 1 for every (Hein, Andriushchenko & Bitterwolf, 2019). Fixing this needs a different architecture or training that explicitly lowers confidence away from the data.
Go deeper
- Adversarial Training · Robust optimization with PGD, the robustness–accuracy tension and robust overfitting.
- Certified Robustness · Provable guarantees from bound propagation, Lipschitz networks and randomized smoothing.
- Shortcut Learning & Spurious Correlations · Texture bias, group robustness and models that are right for the wrong reasons.
Further reading
- I. J. Goodfellow, J. Shlens & C. Szegedy, "Explaining and harnessing adversarial examples," ICLR (2015).
- D. Hendrycks & T. Dietterich, "Benchmarking neural network robustness to common corruptions and perturbations," ICLR (2019).
- R. Taori, A. Dave, V. Shankar, N. Carlini, B. Recht & L. Schmidt, "Measuring robustness to natural distribution shifts in image classification," NeurIPS (2020).
- D. Hendrycks & K. Gimpel, "A baseline for detecting misclassified and out-of-distribution examples in neural networks," ICLR (2017).