Course contents 12 / 14

12 / 14 · Robustness and Deployment

Adversarial examples

Why tiny, deliberately chosen input changes flip the predictions of accurate networks, the linearity explanation, the FGSM and PGD attacks, targeted and black-box attacks that transfer between models, adversarial training as a min–max problem, and what robustness costs in accuracy.

On this page 10

The previous note completed the toolbox for vision: convolutional networks and Vision Transformers that reach high accuracy on held-out images. Every accuracy in the course so far was measured the same way, on test images drawn like the training images. This note measures something else: the accuracy on inputs chosen by someone who wants the network to fail. Accurate networks turn out to be fragile against such inputs. A change of a few grey levels in each pixel, chosen in the right direction, flips the prediction of almost every test image. The note explains why this happens, builds the two standard attacks, measures how attacks transfer from one model to another, and trains a network that resists them, at a price in clean accuracy.

Notation. An input x∈[0,1]dx \in [0, 1]^d has the true label yy. The network fθf_\theta outputs logits, and L(θ,x,y)L(\theta, x, y) is the cross-entropy of the prediction for xx; ∇xL\nabla_x L is its gradient with respect to the input, not the weights. A perturbation δ\delta gives the perturbed input x′=x+δx' = x + \delta. Its size is measured by the L∞L_\infty norm ∥δ∥∞=max⁡i∣δi∣\lVert \delta \rVert_\infty = \max_i \lvert \delta_i \rvert, the largest change to any one pixel, and the budget ε\varepsilon bounds it. sign⁡\operatorname{sign} acts elementwise, α\alpha is a step size, and tt is a target class.

Baseline: accuracy on data drawn like the training data#

A test accuracy estimates how often the network is right on a new example from the same distribution as the training set (validation). It says nothing about the worst input in a small neighbourhood of a test image. Szegedy et al. (2014) found that for state-of-the-art networks such worst inputs are close at hand: they could make the networks misclassify images by adding perturbations that were hardly perceptible, found by maximizing the network’s error. More surprisingly, the same perturbed images were often misclassified by other networks, trained with different architectures or on a different subset of the data.

Accuracy and robustness are different quantities. In the Code section a network 64→256→256→1064 \to 256 \to 256 \to 10 is trained on the bundled 8×88 \times 8 digits, 1257 images for training and 540 for testing, with pixel values scaled to [0,1][0, 1]. Its test accuracy is 0.9650.965. Adding random noise of ±0.1\pm 0.1 to every pixel, with independent random signs, leaves it at 0.9560.956. Adding ±0.1\pm 0.1 with signs chosen by an attack lowers it to 0.4300.430. The size of the change is the same; only the direction differs.

What counts as an adversarial example#

An adversarial example for xx is an input x′x' that the network classifies differently and that lies within the budget:

∥x′−x∥∞≤ε,x′∈[0,1]d,fθ(x′)≠y.\lVert x' - x \rVert_\infty \le \varepsilon, \qquad x' \in [0, 1]^d, \qquad f_\theta(x') \ne y .

The set of allowed perturbations is the threat model: here an L∞L_\infty ball, a box of half-width ε\varepsilon around xx, intersected with the valid pixel range. The L∞L_\infty ball is the standard choice because a bound on every pixel is a simple stand-in for “too small to notice”; other threat models bound the L2L_2 norm, the number of changed pixels, or allow rotations and patches. The robust accuracy at budget ε\varepsilon is the fraction of test images for which no adversarial example exists. No one can search the whole box, so it is estimated by running an attack: the accuracy under an attack is an upper bound on the robust accuracy, and a stronger attack gives a tighter bound.

The budgets used in the literature are ε=0.3\varepsilon = 0.3 for MNIST digits and ε=8/255\varepsilon = 8/255 for CIFAR-10 photographs, with pixels in [0,1][0, 1] (Madry et al., 2018, section 5). The digits of this note have only 17 grey levels, from 0 to 16, so ε=0.1\varepsilon = 0.1 moves a pixel by at most 1.61.6 levels, and ε=0.2\varepsilon = 0.2 by 3.23.2; the digit stays clearly recognizable.

Why linear models already have adversarial examples#

Take one linear unit, the logit of a linear classifier, at a perturbed input:

w⊤x′=w⊤x+w⊤δ.w^\top x' = w^\top x + w^\top \delta .

The perturbation shifts the logit by w⊤δw^\top \delta. How large can that shift be within the budget?

  max⁡∥δ∥∞≤εw⊤δ=ε∥w∥1,attained at δ=εsign⁡(w)  \boxed{\; \max_{\lVert \delta \rVert_\infty \le \varepsilon} w^\top \delta = \varepsilon \lVert w \rVert_1, \quad \text{attained at } \delta = \varepsilon \operatorname{sign}(w) \;}

The bound and the choice that attains it, term by term:

w⊤δ=∑i=1dwiδi≤∑i=1d∣wi∣ ∣δi∣≤ε∑i=1d∣wi∣=ε∥w∥1.w^\top \delta = \sum_{i=1}^d w_i \delta_i \le \sum_{i=1}^d \lvert w_i \rvert\, \lvert \delta_i \rvert \le \varepsilon \sum_{i=1}^d \lvert w_i \rvert = \varepsilon \lVert w \rVert_1 .

The first inequality replaces each product by its absolute value; the second uses ∣δi∣≤ε\lvert \delta_i \rvert \le \varepsilon. Both become equalities when every δi\delta_i has the sign of wiw_i and the full size ε\varepsilon, that is, δi=εsign⁡(wi)\delta_i = \varepsilon \operatorname{sign}(w_i). If the weights have average magnitude mm, the shift is εmd\varepsilon m d. The budget ∥δ∥∞=ε\lVert \delta \rVert_\infty = \varepsilon does not depend on the dimension, but the shift grows linearly with it.

Worked example. A colour image of 224×224224 \times 224 pixels has d=150,528d = 150{,}528 inputs. Let ε=1/255\varepsilon = 1/255, one step of an 8-bit pixel, and let the weights average m=0.01m = 0.01. The logit moves by εmd=150,528⋅0.01/255=5.9\varepsilon m d = 150{,}528 \cdot 0.01 / 255 = 5.9. A change of 5.9 in a logit flips all but the most confident predictions, and it comes from changing each pixel by the smallest amount an image file can store. On the 64 pixels of a digit, the same ε\varepsilon and mm give only 0.00250.0025; a low-dimensional linear model needs a large budget to be fooled.

A network is not linear, but its loss is differentiable, and to first order around xx

L(θ,x+δ,y)≈L(θ,x,y)+δ⊤∇xL(θ,x,y).L(\theta, x + \delta, y) \approx L(\theta, x, y) + \delta^\top \nabla_x L(\theta, x, y) .

The right side is a linear function of δ\delta with weight vector ∇xL\nabla_x L, so by the boxed result it is maximized over the box by δ=εsign⁡(∇xL)\delta = \varepsilon \operatorname{sign}(\nabla_x L), with gain ε∥∇xL∥1\varepsilon \lVert \nabla_x L \rVert_1. The approximation is only as good as the network is linear inside the box. Goodfellow et al. argued that standard networks are linear enough: ReLU networks are piecewise linear, LSTMs and maxout units were designed to behave linearly so that they are easy to optimize, and sigmoid networks are tuned to stay in their nearly linear range. Adversarial examples, in this view, are a result of models being “too linear, rather than too nonlinear” (sections 4 and 10). The experiment of this note agrees: one linear step is almost as damaging as twenty careful steps.

FGSM: one step to a corner of the box#

The fast gradient sign method (FGSM) takes the maximizer of the linear approximation as the attack:

  x′=clip⁡[0,1](x+εsign⁡(∇xL(θ,x,y)))  \boxed{\; x' = \operatorname{clip}_{[0, 1]}\big( x + \varepsilon \operatorname{sign}\big(\nabla_x L(\theta, x, y)\big) \big) \;}

It costs one forward and one backward pass. Every pixel moves by the full ε\varepsilon, up or down, so x′x' is a corner of the box; the clip keeps it a valid image. The gradient is taken with the network in evaluation mode, so that dropout and batch normalization behave as at test time.

Worked example. One logistic unit with w=(2,−1,0.5)w = (2, -1, 0.5), no bias, the input x=(0.5,0.2,0.4)x = (0.5, 0.2, 0.4) with label 1, and ε=0.3\varepsilon = 0.3. The logit is z=w⊤x=1−0.2+0.2=1.0z = w^\top x = 1 - 0.2 + 0.2 = 1.0, the predicted probability σ(1)=0.731\sigma(1) = 0.731 and the loss −log⁡0.731=0.313-\log 0.731 = 0.313. The gradient of the logistic loss with respect to the input is (σ(z)−1) w=−0.269 w=(−0.538,0.269,−0.134)(\sigma(z) - 1)\, w = -0.269\, w = (-0.538, 0.269, -0.134): increasing the loss means decreasing zz. Its sign is (−1,1,−1)(-1, 1, -1), so x′=(0.2,0.5,0.1)x' = (0.2, 0.5, 0.1). The new logit is z′=0.4−0.5+0.05=−0.05z' = 0.4 - 0.5 + 0.05 = -0.05, exactly z−ε∥w∥1=1−0.3⋅3.5z - \varepsilon \lVert w \rVert_1 = 1 - 0.3 \cdot 3.5, the probability of class 1 falls to 0.48750.4875 and the loss rises to 0.7180.718: the prediction flips, while no input moved by more than 0.30.3.

Goodfellow, Shlens and Szegedy (2015) report that FGSM with ε=0.25\varepsilon = 0.25 on MNIST makes a shallow softmax classifier wrong on 99.9% of the test set, with an average confidence of 79.3%, and a maxout network wrong on 89.4%, with an average confidence of 97.6% (section 4). The network is not only wrong but sure of itself.

PGD: many small steps, projected back#

FGSM trusts the linear approximation over the whole box. Projected gradient descent (PGD) trusts it only for small steps and corrects the direction as it goes. It maximizes the loss over the box by repeated sign steps of size α<ε\alpha < \varepsilon, each followed by a projection Π\Pi back onto the allowed set:

xk+1=Π(xk+αsign⁡(∇xL(θ,xk,y))),Π(u)i=min⁡(max⁡(ui, xi−ε, 0), xi+ε, 1).\begin{aligned} x^{k+1} &= \Pi\Big( x^k + \alpha \operatorname{sign}\big(\nabla_x L(\theta, x^k, y)\big) \Big), \\ \Pi(u)_i &= \min\big(\max(u_i,\ x_i - \varepsilon,\ 0),\ x_i + \varepsilon,\ 1\big) . \end{aligned}

For the box, the projection is a clip of each coordinate to [xi−ε,xi+ε]∩[0,1][x_i - \varepsilon, x_i + \varepsilon] \cap [0, 1]. Madry et al. (2018) start from a random point x0x^0 inside the box, which keeps the attack from always starting where the gradient may be uninformative, and run tens of steps; the same iteration started at x0=xx^0 = x is the basic iterative method of Kurakin, Goodfellow and Bengio (2017). The Code section uses 20 steps of size α=2.5ε/20\alpha = 2.5\varepsilon/20, large enough to cross the box and then move along its faces.

Worked example: the projection. Take ε=0.1\varepsilon = 0.1 and α=0.025\alpha = 0.025. A pixel with xi=0.5x_i = 0.5 whose gradient sign stays +1+1 moves to 0.5250.525, 0.550.55, 0.5750.575, 0.60.6; the next step would give 0.6250.625, and the projection returns it to 0.6=xi+ε0.6 = x_i + \varepsilon. A pixel with xi=0.95x_i = 0.95 moves to 0.9750.975, then 1.01.0, and the next step, 1.0251.025, is clipped to 1.01.0 by the pixel range, before it reaches its budget bound of 1.051.05. A pixel whose gradient sign changes moves back, which FGSM can never do.

Figure

FGSM and PGD inside the box of allowed perturbations

FGSM and PGD inside the box of allowed perturbationsThe square of allowed inputs around x, the decision boundary and, in the bottom right, the red region where the network is wrong. FGSM reaches the top-right corner in one step, where the loss is 0.287 and the class is still correct. PGD, in steps of a quarter of ε, goes right and up, then down along the right side of the square, and ends at the bottom-right corner with loss 0.744, across the boundary.wrong‖x′ − x‖∞ ≤ ε∇ₓL1FGSM2PGD345xallowed inputsnetwork is wrongcontours of the lossx: loss 0.201FGSM: 0.287, still correctPGD, 8 steps: 0.744, wrongFGSM and PGD inside the box of allowed perturbationsThe square of allowed inputs around x, the decision boundary and, in the bottom right, the red region where the network is wrong. FGSM reaches the top-right corner in one step, where the loss is 0.287 and the class is still correct. PGD, in steps of a quarter of ε, goes right and up, then down along the right side of the square, and ends at the bottom-right corner with loss 0.744, across the boundary.wrong‖x′ − x‖∞ ≤ ε∇ₓL1FGSM2PGD345xallowed inputsnetwork is wrongcontours of the lossx: loss 0.201FGSM: 0.287, still correctPGD, 8 steps: 0.744, wrong
A two-pixel toy: the input x at the centre, the budget ε, the allowed inputs a square (blue). The margin of the true class is m(u) = 1.5 − u₁ − 0.3u₂ + 0.9u₁u₂ and the loss L = log(1 + e^(−m)); where m < 0 the network is wrong. Dashed: contours of the loss through x, through the FGSM corner and through the fourth PGD point. FGSM trusts the linear approximation over the whole square and jumps to the corner given by the gradient’s sign at x. PGD takes 8 steps of size α = ε/4 from x (no random start, for clarity), recomputes the gradient at every step, and finds the corner with the highest loss.
  1. At xx the gradient of the loss points mostly to the right and slightly up.
  2. FGSM moves every coordinate by ε\varepsilon in the direction of the gradient’s sign: the top-right corner, where the loss is higher but the class is still correct.
  3. PGD takes steps of size α\alpha; once it is to the right, the curved loss surface makes the vertical gradient change sign, and the steps turn downwards.
  4. A step that leaves the box is projected back onto it.
  5. PGD ends at the bottom-right corner, across the decision boundary.

On the digits, both attacks were run against the network of the baseline at seven budgets (Code section, one training run; a different seed moves these numbers by a few points):

ε\varepsilon00.050.10.150.20.250.3
random signs0.9650.9720.9560.9390.9300.8690.806
FGSM0.9650.8150.4610.1200.0130.0020.002
PGD, 20 steps0.9650.8070.4300.0720.0020.0000.000

Random noise with the full budget in every pixel costs at most 16 points, even at ε=0.3\varepsilon = 0.3. The attacks bring the accuracy to almost 0 by ε=0.2\varepsilon = 0.2. PGD is stronger than FGSM at every budget, but only by a few points: the network is close enough to linear inside the box that one step finds most of the damage, as the linearity argument predicts.

Targeted and untargeted attacks#

The attacks so far are untargeted: any wrong class will do, so they climb the loss of the true class. A targeted attack wants a particular class tt and descends the loss of tt instead:

xk+1=Π(xk−αsign⁡(∇xL(θ,xk,t))).x^{k+1} = \Pi\Big( x^k - \alpha \operatorname{sign}\big(\nabla_x L(\theta, x^k, t)\big) \Big) .

Reaching one specific region of the input space is harder than leaving the correct one. On the digits, with t=y+1(mod10)t = y + 1 \pmod{10} for every test image, targeted PGD makes the network output the target for 15.2% of the images at ε=0.1\varepsilon = 0.1, 77.0% at ε=0.2\varepsilon = 0.2 and 99.8% at ε=0.3\varepsilon = 0.3. At ε=0.1\varepsilon = 0.1 the untargeted attack already makes 57.0% of the predictions wrong. With enough budget, an attacker can choose the answer.

White-box, black-box and transferability#

The attacks above are white-box: the attacker knows the weights and computes ∇xL\nabla_x L. A deployed model often exposes only its outputs. Black-box attacks come in two kinds:

  • Query-based attacks send many inputs and use the replies. With access to the scores, the input gradient can be estimated by finite differences (Chen et al., 2017); with access only to the predicted labels, a decision-based attack walks along the decision boundary (Brendel, Rauber and Bethge, 2018).
  • Transfer attacks need no queries to the target at all: they run a white-box attack on a surrogate model the attacker trained, and submit the result.

Transfer works surprisingly well. In the Code section the surrogate is a different network, 64→512→1064 \to 512 \to 10, trained from a different seed; FGSM computed on it, without any access to the target network, lowers the target’s accuracy to 0.5500.550 at ε=0.1\varepsilon = 0.1 and 0.0240.024 at ε=0.2\varepsilon = 0.2, against 0.4610.461 and 0.0130.013 for FGSM on the target itself. The linearity view explains why: models trained on the same task learn similar functions, so their input gradients point in similar directions, and a perturbation aligned with one is largely aligned with the other (Goodfellow, Shlens and Szegedy, 2015, section 8). Papernot et al. (2017) trained a surrogate on labels obtained by querying remote classification services and reported that 84.24%, 96.19% and 88.94% of the adversarial examples crafted on it were misclassified by the models of MetaMind, Amazon and Google. Untargeted examples transfer easily; targeted ones rarely keep their target label on another model unless they are crafted against an ensemble of surrogates (Liu et al., 2017). Transfer is weaker than a white-box attack: against an adversarially trained CIFAR-10 network, 7-step PGD computed on an independently trained copy left 64.2% accuracy, the same attack computed on the network itself 50.0% (Madry et al., 2018, Table 2).

Adversarial training as a min–max#

If a network fails on adversarial inputs, train it on them. Madry et al. (2018) state the goal as one optimization problem: minimize the expected loss of the worst perturbation of each example,

  min⁡θ E(x,y)[max⁡∥δ∥∞≤εL(θ,x+δ,y)]  \boxed{\; \min_\theta\ \mathbb E_{(x, y)} \Big[ \max_{\lVert \delta \rVert_\infty \le \varepsilon} L(\theta, x + \delta, y) \Big] \;}

The inner maximization is an attack; the outer minimization is training. It is a min–max problem like the GAN game, but here the inner player is not a network: it is a perturbation of one input, recomputed from scratch for every example. Each training step therefore has two parts:

  1. Inner step. For each example of the batch, run PGD for KK steps to find δ∗\delta^*, an approximate maximizer.
  2. Outer step. Take a gradient step on θ\theta for the loss at the perturbed inputs, L(θ,x+δ∗,y)L(\theta, x + \delta^*, y), treating δ∗\delta^* as a constant.

Why is the gradient at the maximizer the right descent direction for the max? Write ϕ(θ)=max⁡δL(θ,x+δ,y)\phi(\theta) = \max_\delta L(\theta, x + \delta, y) and let δ∗(θ)\delta^*(\theta) be the maximizer. Then

ϕ(θ)=L(θ,x+δ∗(θ),y),∇θϕ=∇θL(θ,x+δ∗,y)+(∂δ∗∂θ) ⁣⊤∇δL(θ,x+δ∗,y).\begin{aligned} \phi(\theta) &= L\big(\theta, x + \delta^*(\theta), y\big), \\ \nabla_\theta \phi &= \nabla_\theta L\big(\theta, x + \delta^*, y\big) + \Big(\frac{\partial \delta^*}{\partial \theta}\Big)^{\!\top} \nabla_\delta L\big(\theta, x + \delta^*, y\big) . \end{aligned}

The second line is the chain rule, through the direct dependence on θ\theta and through δ∗(θ)\delta^*(\theta). At an interior maximizer ∇δL=0\nabla_\delta L = 0. On a face of the box, a small change of θ\theta moves the maximizer only along the face, and at a constrained maximum ∇δL\nabla_\delta L is perpendicular to the face, so the product is again zero. Either way the second term drops out, and ∇θϕ=∇θL(θ,x+δ∗,y)\nabla_\theta \phi = \nabla_\theta L(\theta, x + \delta^*, y). This is Danskin’s theorem; its exact conditions, a unique maximizer and a smooth loss, do not hold for a ReLU network, but Madry et al. found that descending on the loss at PGD maximizers reliably lowers the adversarial loss in practice (section 3.3 and Appendix A).

The price is computation: KK steps of PGD cost KK extra forward and backward passes per batch, so adversarial training with K=7K = 7 is about eight times slower than standard training. The cheaper inner step, FGSM, was used by Goodfellow, Shlens and Szegedy (2015), with a loss that averages the clean and the FGSM example with weight 0.50.5 each; it lowered a maxout network’s error on FGSM examples from 89.4% to 17.9% (section 6). One-step training can also fail: the network can learn to make the FGSM direction uninformative while staying vulnerable to PGD, a failure called catastrophic overfitting, which a random start before the FGSM step largely prevents (Wong, Rice and Kolter, 2020).

Result on the digits. The same network trained with PGD at ε=0.2\varepsilon = 0.2 and 7 steps keeps 0.5390.539 accuracy against 20-step PGD at ε=0.2\varepsilon = 0.2, where the standard network keeps 0.0020.002, and 0.8240.824 at ε=0.1\varepsilon = 0.1, against 0.4300.430. Its clean accuracy drops from 0.9650.965 to 0.9440.944. At budgets beyond the one it was trained for, the protection fades: 0.1070.107 at ε=0.3\varepsilon = 0.3. Madry et al. (2018) report for MNIST with ε=0.3\varepsilon = 0.3: 98.8% clean accuracy and 89.3% against their strongest attack, PGD with 100 steps and 20 random restarts (Table 1).

Figure

Accuracy under attack: a standard and an adversarially trained network

Accuracy under attack: a standard and an adversarially trained networkTest accuracy against the budget ε from 0 to 0.3. Random noise barely hurts: 0.806 at 0.3. FGSM, PGD and transfer from another network bring the standard network close to zero by ε = 0.2. The network trained on PGD examples with ε = 0.2 keeps 0.539 at ε = 0.2 and 0.944 without attack.00.10.20.300.51.0budget εtest accuracytraining ε0.539random signsFGSMPGD, 20 stepstransfer from another netadversarially trained, PGDAccuracy under attack: a standard and an adversarially trained networkTest accuracy against the budget ε from 0 to 0.3. Random noise barely hurts: 0.806 at 0.3. FGSM, PGD and transfer from another network bring the standard network close to zero by ε = 0.2. The network trained on PGD examples with ε = 0.2 keeps 0.539 at ε = 0.2 and 0.944 without attack.00.10.20.300.51.0budget εtest accuracytraining ε0.539random signsFGSMPGD, 20 stepstransfer from another netadversarially trained, PGD
A 64 → 256 → 256 → 10 network on the 8 × 8 digits, 540 test images, one run of the Code section. Grey: random signs ±ε in every pixel; amber, red and blue: FGSM, 20-step PGD, and FGSM computed on another network, 64 → 512 → 10 (transfer). Green: PGD against the same architecture trained on PGD examples with ε = 0.2 (vertical line). Robustness costs 2.1 points of clean accuracy (0.944 against 0.965), and the protection fades beyond the training ε.

The robustness–accuracy trade-off#

The adversarially trained network lost 2.1 points of clean accuracy on the digits. On CIFAR-10 the loss is much larger: the wide residual network of Madry et al. reaches 95.2% clean accuracy with standard training (section 4); trained against PGD with ε=8/255\varepsilon = 8/255 it reaches 87.3% clean and 45.8% against a 20-step PGD attack (section 5 and Table 2). Robust accuracy is far below clean accuracy, and clean accuracy itself falls.

Tsipras et al. (2019) showed that the trade-off can be unavoidable, not a failure of training. In their example, a label y=±1y = \pm 1 comes with one robust feature x1x_1 that equals yy with probability pp, and dd non-robust features, each a Gaussian whose mean is ηy\eta y, too weakly correlated with the label to matter alone. Averaging the dd weak features classifies with accuracy close to 100% for large dd, but an L∞L_\infty adversary with ε≥2η\varepsilon \ge 2\eta can shift every one of them to look like the other class. Their Theorem 2.1: any classifier with standard accuracy at least 1−δ1 - \delta has robust accuracy at most p1−p δ\frac{p}{1 - p}\, \delta.

Worked example. With p=0.95p = 0.95 the bound is 19δ19\delta. A classifier that is 99% accurate (δ=0.01\delta = 0.01) has robust accuracy at most 0.190.19. To be robust it must rely on x1x_1 alone and accept an accuracy of p=0.95p = 0.95 on clean data, which the bound allows (δ=0.05\delta = 0.05 gives 19⋅0.05=0.9519 \cdot 0.05 = 0.95). High clean accuracy requires the non-robust features; robustness requires ignoring them.

In practice the trade-off is controlled by the training budget ε\varepsilon and by losses that weight the two goals explicitly. TRADES writes the robust error as the sum of the clean error and a boundary error, the probability that a correctly classified input lies within ε\varepsilon of the decision boundary, and minimizes a surrogate of the second term with a tunable weight (Zhang et al., 2019).

What changed#

Standard trainingAdversarial training
What is minimizedE L(θ,x,y)\mathbb E\, L(\theta, x, y)Emax⁡∥δ∥∞≤εL(θ,x+δ,y)\mathbb E \max_{\lVert \delta \rVert_\infty \le \varepsilon} L(\theta, x + \delta, y)
Cost per stepone forward and backward passK+1K + 1 of them (KK PGD steps)
Clean accuracy, digits0.9650.944
PGD accuracy at ε=0.1\varepsilon = 0.1 / 0.20.2, digits0.430 / 0.0020.824 / 0.539
Clean / PGD accuracy, CIFAR-10 (Madry et al.)95.2% / not reported87.3% / 45.8%

Limitations#

  • A threat model is not the world. A network robust in an L∞L_\infty ball can be fooled by a small rotation, an L2L_2 perturbation, a sticker or a change of lighting. Robustness is defined, trained and measured for one set of allowed perturbations at a time.
  • Attacks give upper bounds. The accuracy under an attack only bounds the robust accuracy from above. Defences that hide or scramble the gradient make attacks fail without making the model robust: Athalye, Carlini and Wagner (2018) found that 7 of 9 defences at one conference relied on such obfuscated gradients and broke most of them. Evaluations need strong attacks adapted to the defence, random restarts and black-box checks.
  • Guarantees need other methods. Certified defences, such as randomized smoothing (Cohen, Rosenfeld and Kolter, 2019), prove that no perturbation within a radius changes the prediction, at the cost of more computation and smaller certified radii.
  • Cost. Adversarial training multiplies the training cost by the number of attack steps, and the robust accuracy it reaches on natural images is still far below the clean accuracy.
  • Small scale here. The experiments use 8 × 8 digits, a small network and one training run; they show the effects, not their size on real images.

What you should remember#

  • An adversarial example lies within a budget ε\varepsilon of a correctly classified input and is misclassified; random noise of the same size does almost nothing.
  • For a linear unit the worst perturbation is εsign⁡(w)\varepsilon \operatorname{sign}(w) and shifts the logit by ε∥w∥1\varepsilon \lVert w \rVert_1, which grows with the dimension: many tiny changes add up.
  • FGSM: x′=clip⁡(x+εsign⁡∇xL)x' = \operatorname{clip}(x + \varepsilon \operatorname{sign} \nabla_x L), one gradient. PGD: repeated sign steps of size α\alpha, each clipped back to the box and the pixel range, from a random start.
  • Targeted attacks descend the loss of a chosen class. Black-box attacks use queries or transfer from a surrogate; untargeted examples transfer well.
  • Adversarial training solves min⁡θEmax⁡δL\min_\theta \mathbb E \max_\delta L by PGD inside every step; by Danskin’s theorem the outer gradient is the gradient at the attack’s result.
  • Robustness costs clean accuracy, sometimes unavoidably: 0.965 to 0.944 on the digits, 95.2% to 87.3% on CIFAR-10.

Code#

The linear worked example, FGSM and PGD against a network on the bundled digits, random noise and transfer from another network for comparison, a targeted attack, and adversarial training. Seeds are fixed; exact numbers can differ slightly across platforms and library versions. The script runs in about 5 seconds on a laptop CPU.

Data. Optical Recognition of Handwritten Digits, E. Alpaydin and C. Kaynak (1998), UCI Machine Learning Repository, CC BY 4.0. Loaded through scikit-learn; the transformations used in this example are specified in the code.

import torch
from torch import nn
import torch.nn.functional as F
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

# 1. the linear worked example: one logistic unit, w = (2, -1, 0.5), x = (0.5, 0.2, 0.4), label 1, eps = 0.3
w = torch.tensor([2.0, -1.0, 0.5])
x = torch.tensor([0.5, 0.2, 0.4], requires_grad=True)
loss = F.binary_cross_entropy_with_logits(w @ x, torch.tensor(1.0))
loss.backward()
x_adv = x.detach() + 0.3 * x.grad.sign()
r = lambda v: [round(a, 3) for a in v.tolist()]
print(r(x.grad), r(x_adv), round((w @ x).item(), 3), round((w @ x_adv).item(), 3),
      round(torch.sigmoid(w @ x_adv).item(), 4), round(loss.item(), 3),
      round(F.binary_cross_entropy_with_logits(w @ x_adv, torch.tensor(1.0)).item(), 3))
# [-0.538, 0.269, -0.134] [0.2, 0.5, 0.1] 1.0 -0.05 0.4875 0.313 0.718

# 2. digits in [0, 1]: 1257 training and 540 test images; two networks of different shapes
X, y = load_digits(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X / 16.0, y, test_size=0.3, random_state=0, stratify=y)
Xtr, Xte = torch.tensor(Xtr, dtype=torch.float32), torch.tensor(Xte, dtype=torch.float32)
ytr, yte = torch.tensor(ytr), torch.tensor(yte)

def fgsm(model, x, y, eps):
    x = x.clone().requires_grad_()
    g, = torch.autograd.grad(F.cross_entropy(model(x), y), x)
    return (x + eps * g.sign()).clamp(0, 1).detach()           # one step to a corner of the box, then stay a valid image

def pgd(model, x, y, eps, steps=20, target=None):
    alpha = 2.5 * eps / steps                                   # step size: enough to cross the box and move along its faces
    delta = (2 * torch.rand_like(x) - 1) * eps                  # random start inside the box
    for _ in range(steps):
        xa = (x + delta).clamp(0, 1).requires_grad_()
        if target is None:                                      # untargeted: ascend the loss of the true class
            g, = torch.autograd.grad(F.cross_entropy(model(xa), y), xa)
            delta = delta + alpha * g.sign()
        else:                                                   # targeted: descend the loss of the target class
            g, = torch.autograd.grad(F.cross_entropy(model(xa), target), xa)
            delta = delta - alpha * g.sign()
        delta = delta.clamp(-eps, eps)                          # project back onto the L-infinity ball
    return (x + delta).clamp(0, 1).detach()

def acc(model, x, y):
    with torch.no_grad():
        return round((model(x).argmax(1) == y).float().mean().item(), 3)

def fit(make, adv_eps=0.0, epochs=30, seed=0):
    torch.manual_seed(seed)                                     # seed before the weights are drawn
    model = make()
    opt = torch.optim.Adam(model.parameters(), lr=1e-3)
    for _ in range(epochs):
        for idx in torch.randperm(len(Xtr)).split(64):
            xb, yb = Xtr[idx], ytr[idx]
            if adv_eps:                                         # inner maximization: replace the batch by its PGD version
                xb = pgd(model, xb, yb, adv_eps, steps=7)
            opt.zero_grad()
            F.cross_entropy(model(xb), yb).backward()           # outer minimization on the perturbed batch
            opt.step()
    return model.eval()

mlp = lambda: nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 10))
net = fit(mlp)
other = fit(lambda: nn.Sequential(nn.Linear(64, 512), nn.ReLU(), nn.Linear(512, 10)), seed=1)
print(acc(net, Xte, yte), acc(other, Xte, yte))                # 0.965 0.98: clean test accuracy

# 3. accuracy of `net` against eps: random signs of the same size, FGSM and PGD (white-box),
#    and FGSM computed on `other` (black-box transfer)
torch.manual_seed(0)
print(' eps   noise  FGSM   PGD   transfer')
for eps in (0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3):
    noise = (Xte + eps * (2 * torch.randint(0, 2, Xte.shape) - 1)).clamp(0, 1)
    print(f'{eps:4.2f} {acc(net, noise, yte):6.3f} {acc(net, fgsm(net, Xte, yte, eps), yte):6.3f} '
          f'{acc(net, pgd(net, Xte, yte, eps), yte):6.3f} {acc(net, fgsm(other, Xte, yte, eps), yte):6.3f}')
#  eps   noise  FGSM   PGD   transfer
# 0.00  0.965  0.965  0.965  0.965
# 0.05  0.972  0.815  0.807  0.833
# 0.10  0.956  0.461  0.430  0.550
# 0.15  0.939  0.120  0.072  0.169
# 0.20  0.930  0.013  0.002  0.024
# 0.25  0.869  0.002  0.000  0.000
# 0.30  0.806  0.002  0.000  0.000

# 4. targeted PGD: push every test image towards the class y + 1 (mod 10)
target = (yte + 1) % 10
for eps in (0.1, 0.2, 0.3):
    x_adv = pgd(net, Xte, yte, eps, target=target)
    with torch.no_grad():
        pred = net(x_adv).argmax(1)
    print(eps, round((pred == target).float().mean().item(), 3))   # fraction classified as the target
# 0.1 0.152 | 0.2 0.77 | 0.3 0.998

# 5. adversarial training: the same network trained on PGD examples with eps = 0.2 (7 steps);
#    clean accuracy, then accuracy under 20-step PGD at eps = 0.05, ..., 0.3
robust = fit(mlp, adv_eps=0.2)
torch.manual_seed(0)
print([acc(robust, pgd(robust, Xte, yte, eps) if eps else Xte, yte) for eps in (0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3)])
# [0.944, 0.9, 0.824, 0.715, 0.539, 0.311, 0.107]

Next#

An adversarially trained network is more expensive to train, but at deployment it costs the same as any other: its size and its speed are those of its architecture. Deployment brings its own constraints. A phone has limited memory and a battery, and a server answering millions of requests pays for every multiply-add. The next note makes a trained network smaller and faster: by pruning its weights, by distilling it into a smaller student, and by factorizing its layers, measuring each time what is lost in accuracy and what is really gained in speed.

References#