Adversarial Examples & Robustness
Tiny perturbations, big mistakes, and defenses.
Any image classifier that has not been trained against attacks can be flipped by perturbations below the threshold of perception, and the perturbations often transfer between models. Defenses have a sobering record: most proposed ones were broken within months by stronger attacks. This lesson treats robustness as optimization: attacks as constrained maximization, adversarial training as a saddle-point problem, and certification as a proof that no attack within a radius exists.
What you’ll learn
- Define threat models and robust accuracy precisely, and derive steepest-ascent attack steps from dual norms.
- State Danskin's theorem, use it to justify adversarial training, and explain gradient masking, robust overfitting and the accuracy–robustness trade-off.
- Prove the randomized-smoothing certificate and compute certified radii from Monte Carlo estimates.
- Relate Gaussian isoperimetry to the inevitability of adversarial examples, and assess the state of empirical and certified robustness.
Threat models and attacks
Attacks are optimizers. The inner problem, maximizing the loss (or a margin such as over the logits) on the ball, is nonconvex for a network, but first-order methods work well. The building block is the steepest-ascent step:
To first order with . The best step of size maximizes a linear function over a norm ball, and by Hölder's inequality (tight) its value is the dual norm:
The maximizers spend the budget differently: evenly on every coordinate for , in proportion to the gradient for , all on the single steepest coordinate for :
PGD alternates such steps with projection onto , from random starts. For a linear model the loss is monotone in a linear score, so one full step is already optimal; for networks, more steps and restarts find higher losses.
The attack zoo extends this core. C&W (Carlini & Wagner, 2017) minimizes plus a weighted margin loss, with a change of variables that keeps pixels valid; it broke defensive distillation. Black-box attacks transfer examples from surrogate models (Papernot et al., 2017) or search randomly using only scores (Square Attack). AutoAttack (Croce & Hein, 2020) runs a parameter-free ensemble of four attacks (two step-size-adaptive PGD variants, FAB and Square) and became the standard evaluation; applied to published defenses, it lowered many reported robust accuracies, some by more than ten points.
Attacks also leave the ball. One universal perturbation can fool a network on most images (Moosavi-Dezfooli et al., 2017); stickers on a stop sign fooled a road-sign classifier in physical tests (Eykholt et al., 2018); a 3D-printed turtle was classified as a rifle from most viewpoints (Athalye et al., 2018). For language models, the GCG attack (Zou et al., 2023) searches token by token, guided by gradients with respect to one-hot token indicators, for suffixes that make aligned chat models comply with harmful requests, and the suffixes transferred to closed models.
Adversarial training as robust optimization
So adversarial training never differentiates through the attack: find (approximately) the maximizer, then take the ordinary gradient there. Madry et al. (2018) observed that PGD from many random starts reaches losses of very similar value, which is evidence, not proof, that a first-order attack approximates the inner maximum well enough.
import torch
import torch.nn.functional as F
def pgd(model, x, y, eps=8/255, alpha=2/255, steps=10):
delta = torch.empty_like(x).uniform_(-eps, eps) # random start
for _ in range(steps):
delta.requires_grad_(True)
loss = F.cross_entropy(model(x + delta), y)
g, = torch.autograd.grad(loss, delta)
delta = (delta + alpha * g.sign()).clamp(-eps, eps) # step, project
delta = ((x + delta).clamp(0, 1) - x).detach() # valid pixels
return x + delta
def adversarial_epoch(model, loader, opt):
for x, y in loader:
model.eval(); x_adv = pgd(model, x, y); model.train()
loss = F.cross_entropy(model(x_adv), y) # Danskin: gradient at the maximizer
opt.zero_grad(); loss.backward(); opt.step()PGD adversarial training. The attack runs with batch-norm statistics frozen; the update is plain backpropagation at .
Four phenomena complicate the picture.
- Obfuscated gradients. Athalye, Carlini & Wagner (2018) examined nine defenses accepted at ICLR 2018: seven relied on shattered, stochastic or vanishing gradients, and attacks that approximated or averaged the gradients (BPDA, expectation over transformation) circumvented six completely and one partially. Tramèr et al. (2020) broke thirteen more with adaptive attacks. Evaluate every defense with attacks designed against it.
- Catastrophic overfitting. Single-step training (FGSM from a random start) nearly matches PGD training at a fraction of the cost (Wong, Rice & Kolter, 2020), but robustness to PGD can suddenly collapse during training.
- Robust overfitting. Robust test accuracy peaks and then declines while robust training accuracy keeps rising; early stopping on a robust validation set recovers most of the best checkpoint (Rice, Wong & Kolter, 2020).
- Data hunger. In a Gaussian mixture model, -robust generalization provably needs on the order of times more samples than standard generalization (Schmidt et al., 2018). Extra unlabeled or generated data drives the strongest empirical results (Carmon et al., 2019; Gowal et al., 2021; Wang et al., 2023). TRADES (Zhang et al., 2019) separates the objective into a clean loss plus , making the trade-off explicit.
Whether natural data force such a trade-off is contested. Yang et al. (2020) measured that standard image datasets are well separated, with images of different classes farther apart than for commonly used radii, so a classifier that is both accurate and robust exists in principle; the observed gap may reflect training methods and data rather than an inherent limit.
Certification and randomized smoothing
A certificate proves that no changes the label. Exact verification of ReLU networks is NP-complete (Katz et al., 2017); complete solvers (SMT, mixed-integer programming, branch and bound) handle networks of modest size. Sound but incomplete methods push bounds through the layers, by interval bound propagation (Gowal et al., 2018), linear relaxations of each ReLU (Wong & Kolter, 2018) or Lipschitz constants, and training against these bounds yields certifiably robust small networks. Randomized smoothing scales to ImageNet by changing the classifier instead.
Let and . Their likelihood ratio depends on only through , and increases with it:
The set has probability at least under . By the Neyman–Pearson lemma (Evaluating Language Models), among all such sets the one with the least probability under is where the ratio is smallest, a half-space:
Under , is standard normal, so ; under its mean shifts by :
The same argument bounds every other class from above by . Class still wins whenever
In practice is estimated. Draw a few noisy samples to guess , then more; take a one-sided Clopper–Pearson lower confidence bound ; certify if , and abstain otherwise. With and , even a unanimous vote gives , which caps certifiable radii near . Training the base classifier on noisy inputs, Cohen et al. certified 49% top-1 accuracy on ImageNet within radius 0.5 (127/255). Larger certifies larger radii at lower accuracy; adversarially training the base classifier against the smoothed model helps (Salman et al., 2019).
A smoothed binary classifier uses , and the Monte Carlo lower bound is . What radius does it certify? (.)
Show the answer
0.32
, in units where pixel values lie in . Raising the bound to 0.99 would give .
An certificate of radius implies an certificate only of radius . On ImageNet (, ) the radius 0.5 covers perturbations of about 0.0013, a third of one intensity level, while changing every pixel by a single level (1/255) is an perturbation of norm 1.52. Kumar et al. (2020) and Blum et al. (2020) showed that smoothing with independent noise cannot certify large radii in high dimension without noise that swamps the image. Threat models are not interchangeable.
Why adversarial examples exist, and where the field stands
Three explanations, not mutually exclusive, have support. Local linearity (Goodfellow et al., 2015; Computer Vision) explains why small aligned changes add up in high dimension. Non-robust features: Ilyas et al. (2019) perturbed training images toward a target class and relabeled them as that class, producing a training set that looks mislabeled to people; models trained only on it still classified the clean test set well, so the perturbations encode features that genuinely predict labels and that people do not see. Geometry: in high dimension, most of the space lies close to any set of non-negligible probability.
Take to be a classifier's error set. With 1% error, , so half of all inputs lie within distance 2.33 of an error and 99% within 4.65, whatever the dimension, while typical inputs have norm about . For Gaussian data, or data concentrated on a high-dimensional sphere (Gilmer et al., 2018; Shafahi et al., 2019), every classifier with non-negligible error therefore has small-perturbation adversarial examples. The extremal set is the same half-space as in the smoothing proof. Real images are not Gaussian, though, and adversarial training raises robustness far above that of standard training on the same data, so geometry shows that some vulnerability can be unavoidable, not that today's level is.
A new defense reports 70% robust accuracy against white-box PGD at . A black-box random-search attack, which never sees gradients, succeeds more often than PGD. What should you conclude?
- The defense is robust; black-box attacks are noisier
- The gradients are probably masked or obfuscated, so the PGD evaluation is unreliable and the true robust accuracy is likely lower
- Random search is a stronger attack than PGD in general, so no conclusion follows
- The threat model must be wrong, because black-box attacks cannot beat white-box ones
Show the answer
B. The gradients are probably masked or obfuscated, so the PGD evaluation is unreliable and the true robust accuracy is likely lower
A white-box attacker can always do at least as well as a black-box one in principle, since it has strictly more information. When a gradient-free attack wins, the gradients are misleading the white-box attack: a hallmark of gradient masking (Athalye et al., 2018). Use adaptive attacks and AutoAttack before believing the 70%.
Key takeaways
- Robust accuracy at is bracketed by attacks (upper bounds) and certificates (lower bounds); steepest ascent in is governed by the dual norm, so attacks take sign steps.
- Adversarial training minimizes the robust risk, and Danskin's theorem justifies plain gradients at the attack's output; gradient masking, catastrophic and robust overfitting, and data hunger complicate it.
- Defenses must face adaptive attacks (with AutoAttack as the minimum): obfuscated gradients made many published evaluations far too optimistic.
- Randomized smoothing certifies the radius through a Neyman–Pearson half-space argument; it scales to ImageNet, but its guarantees shrink like .
- Gaussian isoperimetry makes some vulnerability unavoidable in high dimension, non-robust features and local linearity explain much of the rest, and empirical robustness on CIFAR-10 has plateaued near 70%.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
An attacker has an budget: the total absolute change summed over pixels is at most . To first order, which step increases the loss fastest?
- spread over all pixels
- All of on the single pixel with the largest , in the direction of
Show the answer
D. All of on the single pixel with the largest , in the direction of
The dual of is : , attained by spending everything on the steepest coordinate. attacks are therefore sparse.
During adversarial training, how should you compute the gradient of when the maximizer is unique?
- Backpropagate through every PGD iteration that produced
- Use , treating as a constant
- Average over random in the ball
- It is zero, because is a stationary point
Show the answer
B. Use , treating as a constant
By Danskin's theorem the dependence of on does not contribute to first order: at a maximizer, small changes of leave the loss unchanged to first order (an envelope theorem).
A smoothed binary classifier uses , and at an input , so that . What does randomized smoothing certify?
- radius 1.0
- radius 0.5
- radius 2.0
- radius 1.0
Show the answer
A. radius 1.0
With , . Gaussian smoothing certifies balls; the implied radius is only .
A CIFAR-10 model () is certified within radius 0.5 at some input. What radius does this guarantee?
- 0.5
- , about 2.3/255
Show the answer
D. , about 2.3/255
, so every with lies inside the certified ball. That is far below the common benchmark radius of 8/255.
Further reading
- B. Biggio & F. Roli, "Wild patterns: Ten years after the rise of adversarial machine learning," Pattern Recognition 84 (2018).
- A. Athalye, N. Carlini & D. Wagner, "Obfuscated gradients give a false sense of security: Circumventing defenses to adversarial examples," ICML (2018).
- J. Cohen, E. Rosenfeld & J. Z. Kolter, "Certified adversarial robustness via randomized smoothing," ICML (2019).
- A. Ilyas, S. Santurkar, D. Tsipras, L. Engstrom, B. Tran & A. Madry, "Adversarial examples are not bugs, they are features," NeurIPS (2019).
- F. Croce & M. Hein, "Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks," ICML (2020).