Adversarial Training
Robust optimization with PGD, the robustness–accuracy tension and robust overfitting.
Of all the empirical defenses against adversarial examples, one has held up through years of ever-stronger attacks: at every training step, train on the worst perturbation you can find. It is also a regularizer of an unusual shape, a penalty on the input gradient that switches itself off for confidently classified points, and it overfits in ways ordinary training does not. Here you derive what adversarial training optimizes, why robust generalization needs more data than standard generalization, how to make training fast without breaking it, and how to tell a robust model from one that only hides its gradients.
What you’ll learn
- Set up adversarial training as a saddle-point problem, state Danskin's theorem and where its assumptions fail, and derive the exact robust loss of a linear classifier.
- Show that for small adversarial training penalizes the dual norm of the input gradient, and contrast it with Gaussian noise, which acts only at second order.
- Prove the decomposition of robust error behind TRADES, and explain from the Gaussian model of Schmidt et al. why robust generalization needs more data.
- Explain robust overfitting and catastrophic overfitting, and the fixes that work: early stopping, random initialization and gradient alignment.
- Evaluate a defense against adaptive attacks, recognize the signs of gradient masking, and state where empirical robustness stands as of the mid-2020s.
The saddle point, and the linear case
Madry, Makelov, Schmidt, Tsipras and Vladu (2018) wrote robust training as a single objective, with an attack nested inside the expected loss:
So training never differentiates through the attack: find the maximizer, then backpropagate at as usual. Madry et al. were explicit about the gap: ReLU and max-pooling networks are not continuously differentiable, and PGD returns only approximate maximizers. Their evidence that the recipe works anyway was empirical. Over random restarts of PGD, the final losses were tightly concentrated, without extreme outliers, and the adversarial loss fell steadily during training. They also found that capacity matters: to withstand strong attacks, networks needed more capacity than to classify clean examples correctly. For one model the inner problem can be solved exactly:
Take a linear score , labels , and a loss of the margin that decreases in , such as the logistic loss . Ignoring the clipping to valid pixels, the worst perturbation lowers the margin by the dual norm of :
Because decreases, maximizing the loss means minimizing the margin. The inner problem has a closed form, and adversarial training minimizes
Every margin shrinks by (by for an ball). That is an penalty, but placed inside the loss. Goodfellow, Shlens and Szegedy (2015) pointed out the difference from weight decay: once an example is classified with a large margin the loss flattens and the penalty fades, whereas weight decay never stops pulling. They also noted the other side: in the underfitting regime, adversarial training only makes the underfitting worse.
A logistic-regression model classifies a point with margin and has . What is its loss on the worst perturbation with , ignoring clipping? (Its clean loss is .)
Show the answer
0.47
The adversary removes of the margin, leaving , and : nearly four times the clean loss. A radius of would erase the margin entirely; margin over is this point's exact robustness radius.
A penalty on input gradients
For a network the inner maximum has no closed form, but for small it has an expansion. Write for . To first order, exactly as in the derivation of FGSM,
Compare training on random noise of the same size, the oldest input-space regularizer. Let have independent coordinates with mean zero and variance :
Expand to second order and take the expectation. The linear term averages away:
For a linear model under the squared loss, , the Hessian is and the expansion is exact: noise adds the ridge penalty (Bishop, 1995), as in Weight Decay, Dropout & Early Stopping. The adversary pays at first order instead:
Perturbations of a few percent of the pixel range have , which is why noise of the same size does little for robustness to attacks. And the adversarial penalty is data-dependent: it is large where the loss is steep in the input, near the decision boundary, and fades where margins are large, just like the shrunken margins of the linear case.
Simon-Gabriel et al. also proved that, at initialization, the norm of the input gradient grows like for most common architectures, and found that the growth persisted after both standard and adversarial training unless the regularization was strong: larger images invite larger first-order damage. A small input gradient at the data points is not the same as robustness, though. A model can make its gradients useless rather than small, and that gradient masking is the main trap in evaluating defenses (last step).
Training on Gaussian noise with per-pixel standard deviation improves robustness to attacks of size far less than adversarial training does. Which explanation matches the expansions above?
- Gaussian noise is too weak because it is not uniform; uniform noise would match the attack
- Noise changes the labels of the training examples
- The noise's first-order effect averages to zero, so it penalizes curvature at order ; the attack's first-order term does not average away, so it penalizes at order
- Adversarial training uses much larger perturbations than the noise
Show the answer
C. The noise's first-order effect averages to zero, so it penalizes curvature at order ; the attack's first-order term does not average away, so it penalizes at order
Random directions are uncorrelated with the gradient, so they move the loss only through curvature; the attack aligns with the gradient and moves the loss at first order. For small perturbations , so the noise's penalty is much weaker.
Robustness, accuracy and data
Robustness costs clean accuracy. Madry et al.'s CIFAR-10 network reached 95.2% accuracy with standard training; trained against PGD at , it reached 87.3% clean accuracy and about 46% robust accuracy. Tsipras et al. (2019) built distributions on which the tension is unavoidable, where high accuracy needs many weakly predictive features that an adversary can flip all at once. Whether natural images force such a trade-off is debated. Zhang et al. (2019) made the trade-off explicit, starting from an exact decomposition of the robust error of a binary classifier :
Split the robust-error event by whether the clean point is already misclassified. If , take . If , a point in the ball with exists exactly when changes sign within of , that is when . The two cases are disjoint, so their probabilities add:
Now bound each 0–1 term by a surrogate loss . The boundary term needs no label: it asks whether and disagree. That gives the TRADES objective, with a trade-off parameter :
Zhang et al. proved that for a nonnegative, classification-calibrated with , is at most of the excess surrogate risk plus this robustness term, where is the calibration function of and the best achievable natural error, and that the bound is tight up to an arbitrarily small constant. For many classes, the robustness term compares the two softmax outputs, . The code uses the KL divergence , which differs from the cross-entropy between the two outputs only by the entropy of , with .
import torch
import torch.nn.functional as F
def trades_loss(model, x, y, eps=8/255, alpha=2/255, steps=10, beta=6.0):
model.eval() # attack with fixed batch-norm statistics
p_clean = F.softmax(model(x), dim=1).detach()
x_adv = (x + 0.001 * torch.randn_like(x)).detach() # at x itself the KL gradient is zero
for _ in range(steps): # maximize KL(f(x) || f(x')) in the box
x_adv.requires_grad_(True)
kl = F.kl_div(F.log_softmax(model(x_adv), dim=1), p_clean, reduction='batchmean')
g, = torch.autograd.grad(kl, x_adv)
x_adv = x + (x_adv.detach() + alpha * g.sign() - x).clamp(-eps, eps)
x_adv = x_adv.clamp(0, 1)
model.train()
logits = model(x)
robust = F.kl_div(F.log_softmax(model(x_adv), dim=1), F.softmax(logits, dim=1),
reduction='batchmean') # KL(f(x) || f(x_adv))
return F.cross_entropy(logits, y) + beta * robustWith on CIFAR-10 at (8/255), Zhang et al. reported 84.92% clean and 56.61% robust accuracy under a 20-step PGD attack, against 87.30% and 47.04% for Madry et al.'s model under the same attack, and the method won the NeurIPS 2018 Adversarial Vision Challenge. A small favors clean accuracy, a large one robustness.
Robust generalization needs more data. Schmidt, Santurkar, Tsipras, Talwar and Mądry (2018) proved a gap in a model where standard learning is easy. Draw uniformly and in , with and noise level for a small constant .
With samples, with . A new point's score has signal and noise of standard deviation about , which for is about . That is small next to when is small, so one sample is enough for standard accuracy.
The adversary subtracts from every margin, and the norm adds up the estimation noise of all coordinates. Once the noise per coordinate, , exceeds the signal per coordinate, 1,
This stays below the signal only if , that is . The robust classifier must estimate every coordinate of well, because the adversary exploits all the errors at once; the standard classifier only needs their sum to point the right way.
In this model, at fixed and ignoring constants and the logarithm, how many times more samples does robust learning need if the input dimension grows 16-fold?
Show the answer
4
The robust sample complexity scales like , so 16 times the dimension needs times the data, while standard learning still needs a single sample. In practice extra data is the strongest lever: adding 500,000 unlabeled images to CIFAR-10, with robust self-training, beat the previous best robust accuracy by more than 5 points (Carmon et al., 2019), and images generated by diffusion models took it further (Gowal et al., 2021; Wang et al., 2023).
Overfitting, twice
In standard deep learning, training longer rarely hurts much. In adversarial training it does. Rice, Wong and Kolter (2020) found that robust test error drops sharply right after the first learning-rate decay and then climbs for the rest of training, while robust training error keeps falling: robust overfitting. For a Wide ResNet on CIFAR-10 at , the best checkpoint had 43.2% robust test error against a 10-step PGD attack and the final ones 51.4%. Simply stopping early on a robust validation set matched the gains of virtually all the algorithmic improvements published since PGD training. Explicit and penalties, cutout and mixup reduced the overfitting but, trained to convergence, never beat early stopping; only semi-supervised data combined with early stopping did better. Double descent appears in adversarial training too, but it does not explain the effect (Early Stopping & Regularization by Time).
Fast training and catastrophic overfitting. PGD training multiplies the cost of every step. Wong, Rice and Kolter (2020) showed that a single FGSM step can do most of the job, if it starts from a random point of the ball and uses a step of : on CIFAR-10 at , with fast-training tricks, it reached 46.06% accuracy against PGD in about 12 minutes; 7-step PGD training with the same tricks took about 69 minutes and reached 50.69%. From a zero start, or with a step of , the same recipe ended at 0% accuracy against PGD. This is catastrophic overfitting: during training, robustness to multi-step attacks suddenly collapses, and the model ends up resisting only the one-step attack it was trained on.
import torch
import torch.nn.functional as F
def fgsm_rs_step(model, opt, x, y, eps=8/255):
delta = torch.empty_like(x).uniform_(-eps, eps).requires_grad_(True) # random start
g, = torch.autograd.grad(F.cross_entropy(model(x + delta), y), delta)
delta = (delta + 1.25 * eps * g.sign()).clamp(-eps, eps) # one step, alpha = 1.25 eps
x_adv = (x + delta).clamp(0, 1).detach()
loss = F.cross_entropy(model(x_adv), y)
opt.zero_grad(); loss.backward(); opt.step()
return loss.item()Single-step adversarial training costs about two forward and backward passes per step. Monitor accuracy against a multi-step PGD attack on a small batch of training data, as Wong et al. did: a sudden collapse is the signature of catastrophic overfitting, and stopping just before it salvages much of the run.
Why does it happen? Andriushchenko and Flammarion (2020) found that the random start does not cure it: with it only extended the working range on CIFAR-10 from to , and at training again ended at 0% accuracy against PGD. Its main effect is to shrink the average size of the perturbation. They also found that catastrophic overfitting occurs even in a single-layer convolutional network with a few filters, and that it coincides with a loss of local linearity: once the input gradient varies inside the ball, the one-step linearization finds poor perturbations, and training on them no longer covers the rest of the ball. Their GradAlign regularizer keeps the gradients aligned across the ball:
Evaluating defenses, and what robust models learn
A defense is only as credible as the strongest attack tried against it. The recurring failure is gradient masking: the defense makes gradients useless to the attacker without removing the adversarial examples. Athalye, Carlini and Wagner (2018) found that seven of the nine white-box defenses accepted at ICLR 2018 relied on obfuscated gradients, and circumvented six of them completely and one partially. Adaptive attacks designed against each defense broke many later ones (Tramèr, Carlini, Brendel & Madry, 2020). AutoAttack (Croce & Hein, 2020), a parameter-free ensemble of two improved PGD variants and two complementary attacks, lowered the reported robust accuracy of all but one of more than 50 published models, often by more than 10 points, and became the standard evaluation, with public leaderboards in RobustBench (Croce et al., 2021).
What robust models learn. Ilyas et al. (2019) argued that adversarial examples exploit non-robust features: patterns in the data that genuinely predict the label but flip under tiny perturbations, and that standard training has every reason to use. Adversarial training makes a model give them up. That costs accuracy, but it changes the representation in ways that look like features rather than bugs: the representations of robust models align better with salient image structure and with human perception (Tsipras et al., 2019), a single robust classifier can be used to synthesize and edit images (Santurkar et al., 2019), and robust ImageNet models, though less accurate, often transfer better to downstream tasks (Salman et al., 2020).
Key takeaways
- Adversarial training solves . By Danskin's theorem the gradient at a unique inner maximizer is the outer gradient, but nonsmooth networks and approximate PGD maximizers make this a well-tested heuristic rather than a theorem.
- For a linear model the inner maximum is exact: margins shrink by . For any network and small , the adversarial loss is the clean loss plus , a first-order, data-dependent gradient penalty, while Gaussian noise acts only at second order.
- Robust error equals natural error plus boundary error, and TRADES penalizes the second with a label-free term. In a Gaussian model robust learning needs about times more samples than standard learning, and extra unlabeled or generated data is the strongest lever in practice.
- Robust overfitting makes early stopping on robust validation accuracy essential. Single-step training works at moderate radii from a random start with a moderate step; catastrophic overfitting goes with a loss of local linearity, which GradAlign penalizes directly.
- Accuracy under an attack only bounds robust accuracy from above: evaluate defenses with adaptive attacks and AutoAttack, and treat the signs of gradient masking as alarms.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
For a linear classifier with the logistic loss, what does adversarial training at radius minimize (ignoring pixel clipping)?
- : the clean loss plus an penalty
- : the loss of every margin shrunk by
- The clean loss, since a linear model has no adversarial examples
Show the answer
B. : the loss of every margin shrunk by
The worst perturbation of a linear score lowers every margin by exactly , the dual norm of , and the loss decreases in the margin, so that perturbation also maximizes the loss. Unlike weight decay, the penalty sits inside the loss and fades for large margins.
TRADES rests on the decomposition robust error = natural error + boundary error. What does the boundary error count?
- Misclassified points that lie near the decision boundary
- All points within of some training example
- Correctly classified points that lie within of the decision boundary, so that some perturbation in the ball flips their prediction
- Points whose true label changes under the perturbation
Show the answer
C. Correctly classified points that lie within of the decision boundary, so that some perturbation in the ball flips their prediction
The robust-error event splits into points that are already misclassified and correctly classified points that a perturbation can push across the boundary. The second part needs no label to evaluate, which is why the robustness term of TRADES compares with instead of with .
During PGD adversarial training of a CIFAR-10 network, robust test accuracy peaks soon after the first learning-rate decay and then declines while robust training accuracy keeps rising. What did Rice, Wong and Kolter find works best against this?
- Stronger weight decay, trained to convergence
- Early stopping on robust accuracy measured on held-out data
- Cutout or mixup augmentation, trained to convergence
- Training longer, since the decline reverses as in double descent
Show the answer
B. Early stopping on robust accuracy measured on held-out data
Robust overfitting is a large generalization gap in robust error: the best checkpoint beat the final ones by about 8 points (43.2% against 51.4% robust test error for a Wide ResNet at ). Explicit penalties and augmentation reduced the problem but, trained to convergence, did not beat early stopping; only semi-supervised data combined with early stopping did better.
Single-step FGSM adversarial training on CIFAR-10 at , from a zero start, gives a model with 85% clean accuracy and 0% accuracy against PGD. What happened, and what helps?
- Catastrophic overfitting: the model resists only the one-step attack it was trained on; a random start with a moderate step (), or a gradient-alignment penalty, prevents it
- The model is robust, and PGD must be a broken attack
- The learning rate was too low for adversarial training to have any effect
- Single-step training can never produce robust models
Show the answer
A. Catastrophic overfitting: the model resists only the one-step attack it was trained on; a random start with a moderate step (), or a gradient-alignment penalty, prevents it
From a zero start every training perturbation sits on a corner of the box, and the network learns to defeat that one linearization while becoming nonlinear inside the ball. At this radius, the random start of Wong, Rice and Kolter (2020) and the GradAlign penalty of Andriushchenko and Flammarion (2020) both restore robustness to PGD; at larger radii the random start alone fails, while GradAlign kept working in Andriushchenko and Flammarion's experiments.
Further reading
- A. Madry, A. Makelov, L. Schmidt, D. Tsipras & A. Vladu, "Towards deep learning models resistant to adversarial attacks," ICLR (2018).
- H. Zhang, Y. Yu, J. Jiao, E. P. Xing, L. El Ghaoui & M. I. Jordan, "Theoretically principled trade-off between robustness and accuracy," ICML (2019).
- L. Schmidt, S. Santurkar, D. Tsipras, K. Talwar & A. Mądry, "Adversarially robust generalization requires more data," NeurIPS (2018).
- L. Rice, E. Wong & J. Z. Kolter, "Overfitting in adversarially robust deep learning," ICML (2020).
- E. Wong, L. Rice & J. Z. Kolter, "Fast is better than free: revisiting adversarial training," ICLR (2020).