Simple Algorithm
Artificial Intelligence · Deep Layer · 28 min

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 R=σ2(Φ−1(pA)−Φ−1(pB))R=\tfrac\sigma2\big(\Phi^{-1}(p_A)-\Phi^{-1}(p_B)\big) 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 max⁡j≠yzj−zy\max_{j\neq y}z_j-z_y 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:

DerivationSteepest ascent and dual norms
  1. max⁡∥δ∥p≤αg⊤δ=α∥g∥q,1p+1q=1\max_{\norm{\boldsymbol\delta}_p\le\alpha}\mathbf g^\top\boldsymbol\delta=\alpha\norm{\mathbf g}_q,\qquad \tfrac1p+\tfrac1q=1

    To first order L(x+δ)≈L(x)+g⊤δ\loss(\mathbf x+\boldsymbol\delta)\approx\loss(\mathbf x)+\mathbf g^\top\boldsymbol\delta with g=∇xL\mathbf g=\nabla_{\mathbf x}\loss. The best step of size α\alpha maximizes a linear function over a norm ball, and by Hölder's inequality (tight) its value is the dual norm:

  2. p=∞: αsign⁡(g);p=2: αg∥g∥2;p=1: αsign⁡(gi∗) ei∗,  i∗=arg max⁡i∣gi∣p=\infty:\ \alpha\sign(\mathbf g);\qquad p=2:\ \alpha\frac{\mathbf g}{\norm{\mathbf g}_2};\qquad p=1:\ \alpha\sign(g_{i^*})\,\mathbf e_{i^*},\ \ i^*=\argmax_i\abs{g_i}

    The maximizers spend the budget differently: evenly on every coordinate for ℓ∞\ell_\infty, in proportion to the gradient for ℓ2\ell_2, all on the single steepest coordinate for ℓ1\ell_1:

  3. δt+1=ΠBp(0,ε)(δt+α arg max⁡∥v∥p≤1∇δL(x+δt,y)⊤v)\boldsymbol\delta_{t+1}=\Pi_{B_p(\mathbf 0,\varepsilon)}\Big(\boldsymbol\delta_t+\alpha\,\operatorname*{arg\,max}_{\norm{\mathbf v}_p\le1}\nabla_{\boldsymbol\delta}\loss(\mathbf x+\boldsymbol\delta_t,y)^\top\mathbf v\Big)

    PGD alternates such steps with projection onto Bp(x,ε)B_p(\mathbf x,\varepsilon), 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 ∥δ∥22\norm{\boldsymbol\delta}_2^2 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 ℓp\ell_p 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.

python
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 xadv\mathbf x_{\text{adv}}.

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, ℓ∞\ell_\infty-robust generalization provably needs on the order of d\sqrt d 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 βmax⁡x′DKL(f(x) ∥ f(x′))\beta\max_{\mathbf x'}\KL\big(f(\mathbf x)\,\|\,f(\mathbf x')\big), 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 2ε2\varepsilon 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 x′∈Bp(x,ε)\mathbf x'\in B_p(\mathbf x,\varepsilon) 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.

DerivationProof sketch: the worst base classifier is a half-space
  1. pY(z)pX(z)=exp⁡(δ⊤(z−x)σ2−∥δ∥222σ2)\frac{p_Y(\mathbf z)}{p_X(\mathbf z)}=\exp\Big(\frac{\boldsymbol\delta^\top(\mathbf z-\mathbf x)}{\sigma^2}-\frac{\norm{\boldsymbol\delta}_2^2}{2\sigma^2}\Big)

    Let X∼N(x,σ2I)X\sim\mathcal N(\mathbf x,\sigma^2I) and Y∼N(x+δ,σ2I)Y\sim\mathcal N(\mathbf x+\boldsymbol\delta,\sigma^2I). Their likelihood ratio depends on z\mathbf z only through δ⊤z\boldsymbol\delta^\top\mathbf z, and increases with it:

  2. A⋆={z: δ⊤(z−x)≤σ∥δ∥2 Φ−1(pA)}A^\star=\big\{\mathbf z:\ \boldsymbol\delta^\top(\mathbf z-\mathbf x)\le\sigma\norm{\boldsymbol\delta}_2\,\Phi^{-1}(p_A)\big\}

    The set {z:f(z)=A}\{\mathbf z:f(\mathbf z)=A\} has probability at least pAp_A under XX. By the Neyman–Pearson lemma (Evaluating Language Models), among all such sets the one with the least probability under YY is where the ratio is smallest, a half-space:

  3. Pr⁡[f(x+δ+η)=A] ≥ Pr⁡[Y∈A⋆]=Φ(Φ−1(pA)−∥δ∥2σ)\Pr\big[f(\mathbf x+\boldsymbol\delta+\boldsymbol\eta)=A\big]\ \ge\ \Pr[Y\in A^\star]=\Phi\Big(\Phi^{-1}(p_A)-\frac{\norm{\boldsymbol\delta}_2}{\sigma}\Big)

    Under XX, δ⊤(z−x)/(σ∥δ∥2)\boldsymbol\delta^\top(\mathbf z-\mathbf x)/(\sigma\norm{\boldsymbol\delta}_2) is standard normal, so Pr⁡[X∈A⋆]=pA\Pr[X\in A^\star]=p_A; under YY its mean shifts by ∥δ∥2/σ\norm{\boldsymbol\delta}_2/\sigma:

  4. Φ−1(pA)−∥δ∥2σ>Φ−1(pB)+∥δ∥2σ  ⟺  ∥δ∥2<σ2(Φ−1(pA)−Φ−1(pB))□\Phi^{-1}(p_A)-\frac{\norm{\boldsymbol\delta}_2}{\sigma}>\Phi^{-1}(p_B)+\frac{\norm{\boldsymbol\delta}_2}{\sigma}\iff\norm{\boldsymbol\delta}_2<\frac\sigma2\Big(\Phi^{-1}(p_A)-\Phi^{-1}(p_B)\Big)\qquad\square

    The same argument bounds every other class BB from above by Φ(Φ−1(pB)+∥δ∥2/σ)\Phi\big(\Phi^{-1}(p_B)+\norm{\boldsymbol\delta}_2/\sigma\big). Class AA still wins whenever

In practice pAp_A is estimated. Draw a few noisy samples to guess AA, then nn more; take a one-sided (1−α)(1-\alpha) Clopper–Pearson lower confidence bound pA‾\underline{p_A}; certify R=σΦ−1(pA‾)R=\sigma\Phi^{-1}(\underline{p_A}) if pA‾>12\underline{p_A}>\tfrac12, and abstain otherwise. With n=100,000n=100{,}000 and α=0.001\alpha=0.001, even a unanimous vote gives pA‾≈0.99993\underline{p_A}\approx0.99993, which caps certifiable radii near 3.8σ3.8\sigma. Training the base classifier on noisy inputs, Cohen et al. certified 49% top-1 accuracy on ImageNet within ℓ2\ell_2 radius 0.5 (127/255). Larger σ\sigma certifies larger radii at lower accuracy; adversarially training the base classifier against the smoothed model helps (Salman et al., 2019).

Predict before you look

A smoothed binary classifier uses σ=0.25\sigma=0.25, and the Monte Carlo lower bound is pA‾=0.9\underline{p_A}=0.9. What ℓ2\ell_2 radius does it certify? (Φ−1(0.9)≈1.28\Phi^{-1}(0.9)\approx1.28.)

Show the answer

0.32

R=σΦ−1(pA‾)=0.25×1.2816≈0.32R=\sigma\Phi^{-1}(\underline{p_A})=0.25\times1.2816\approx0.32, in units where pixel values lie in [0,1][0,1]. Raising the bound to 0.99 would give 0.25×2.33≈0.580.25\times2.33\approx0.58.

An ℓ2\ell_2 certificate of radius RR implies an ℓ∞\ell_\infty certificate only of radius R/dR/\sqrt d. On ImageNet (d=3⋅224⋅224=150,528d=3\cdot224\cdot224=150{,}528, d≈388\sqrt d\approx388) the radius 0.5 covers ℓ∞\ell_\infty perturbations of about 0.0013, a third of one intensity level, while changing every pixel by a single level (1/255) is an ℓ2\ell_2 perturbation of norm 1.52. Kumar et al. (2020) and Blum et al. (2020) showed that smoothing with independent noise cannot certify large ℓ∞\ell_\infty 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 EE to be a classifier's error set. With 1% error, a=Φ−1(0.01)≈−2.33a=\Phi^{-1}(0.01)\approx-2.33, so half of all inputs lie within ℓ2\ell_2 distance 2.33 of an error and 99% within 4.65, whatever the dimension, while typical inputs have norm about d\sqrt d. 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.

Check your understanding

A new defense reports 70% robust accuracy against white-box PGD at ε=8/255\varepsilon=8/255. A black-box random-search attack, which never sees gradients, succeeds more often than PGD. What should you conclude?

  1. The defense is robust; black-box attacks are noisier
  2. The gradients are probably masked or obfuscated, so the PGD evaluation is unreliable and the true robust accuracy is likely lower
  3. Random search is a stronger attack than PGD in general, so no conclusion follows
  4. 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 ε\varepsilon is bracketed by attacks (upper bounds) and certificates (lower bounds); steepest ascent in ℓp\ell_p is governed by the dual norm, so ℓ∞\ell_\infty 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 ℓ2\ell_2 radius σ2(Φ−1(pA)−Φ−1(pB))\tfrac\sigma2\big(\Phi^{-1}(p_A)-\Phi^{-1}(p_B)\big) through a Neyman–Pearson half-space argument; it scales to ImageNet, but its ℓ∞\ell_\infty guarantees shrink like 1/d1/\sqrt d.
  • Gaussian isoperimetry makes some vulnerability unavoidable in high dimension, non-robust features and local linearity explain much of the rest, and empirical ℓ∞\ell_\infty 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.

Question 1

An attacker has an ℓ1\ell_1 budget: the total absolute change summed over pixels is at most α\alpha. To first order, which step increases the loss fastest?

  1. αsign⁡(g)/d\alpha\sign(\mathbf g)/d spread over all pixels
  2. α g/∥g∥2\alpha\,\mathbf g/\norm{\mathbf g}_2
  3. αsign⁡(g)\alpha\sign(\mathbf g)
  4. All of α\alpha on the single pixel with the largest ∣gi∣\abs{g_i}, in the direction of sign⁡(gi)\sign(g_i)
Show the answer

D. All of α\alpha on the single pixel with the largest ∣gi∣\abs{g_i}, in the direction of sign⁡(gi)\sign(g_i)

The dual of ℓ1\ell_1 is ℓ∞\ell_\infty: max⁡∥δ∥1≤αg⊤δ=αmax⁡i∣gi∣\max_{\norm{\boldsymbol\delta}_1\le\alpha}\mathbf g^\top\boldsymbol\delta=\alpha\max_i\abs{g_i}, attained by spending everything on the steepest coordinate. ℓ1\ell_1 attacks are therefore sparse.

Question 2

During adversarial training, how should you compute the gradient of Φ(θ)=max⁡∥δ∥≤εL(θ;x+δ,y)\Phi(\theta)=\max_{\norm{\boldsymbol\delta}\le\varepsilon}\loss(\theta;\mathbf x+\boldsymbol\delta,y) when the maximizer δ∗\boldsymbol\delta^* is unique?

  1. Backpropagate through every PGD iteration that produced δ∗\boldsymbol\delta^*
  2. Use ∇θL(θ;x+δ∗,y)\nabla_\theta\loss(\theta;\mathbf x+\boldsymbol\delta^*,y), treating δ∗\boldsymbol\delta^* as a constant
  3. Average ∇θL\nabla_\theta\loss over random δ\boldsymbol\delta in the ball
  4. It is zero, because δ∗\boldsymbol\delta^* is a stationary point
Show the answer

B. Use ∇θL(θ;x+δ∗,y)\nabla_\theta\loss(\theta;\mathbf x+\boldsymbol\delta^*,y), treating δ∗\boldsymbol\delta^* as a constant

By Danskin's theorem the dependence of δ∗\boldsymbol\delta^* on θ\theta does not contribute to first order: at a maximizer, small changes of δ\boldsymbol\delta leave the loss unchanged to first order (an envelope theorem).

Question 3

A smoothed binary classifier uses σ=0.5\sigma=0.5, and at an input pA‾≈0.977\underline{p_A}\approx0.977, so that Φ−1(pA‾)≈2\Phi^{-1}(\underline{p_A})\approx2. What does randomized smoothing certify?

  1. ℓ2\ell_2 radius 1.0
  2. ℓ2\ell_2 radius 0.5
  3. ℓ2\ell_2 radius 2.0
  4. ℓ∞\ell_\infty radius 1.0
Show the answer

A. ℓ2\ell_2 radius 1.0

With pB=1−pAp_B=1-p_A, R=σΦ−1(pA)=0.5×2=1.0R=\sigma\Phi^{-1}(p_A)=0.5\times2=1.0. Gaussian smoothing certifies ℓ2\ell_2 balls; the implied ℓ∞\ell_\infty radius is only R/dR/\sqrt d.

Question 4

A CIFAR-10 model (d=3×32×32=3072d=3\times32\times32=3072) is certified within ℓ2\ell_2 radius 0.5 at some input. What ℓ∞\ell_\infty radius does this guarantee?

  1. 0.5
  2. 0.5/3072≈0.000160.5/3072\approx0.00016
  3. 0.53072≈27.70.5\sqrt{3072}\approx27.7
  4. 0.5/3072≈0.0090.5/\sqrt{3072}\approx0.009, about 2.3/255
Show the answer

D. 0.5/3072≈0.0090.5/\sqrt{3072}\approx0.009, about 2.3/255

∥δ∥2≤d ∥δ∥∞\norm{\boldsymbol\delta}_2\le\sqrt d\,\norm{\boldsymbol\delta}_\infty, so every δ\boldsymbol\delta with ∥δ∥∞<0.5/3072\norm{\boldsymbol\delta}_\infty<0.5/\sqrt{3072} lies inside the certified ℓ2\ell_2 ball. That is far below the common ℓ∞\ell_\infty 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).