Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

Adversarial examples and robustness

P5.1740 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

A network can be right on every test picture and still be wrong on a picture that was changed in a way no person would care about. So test accuracy alone does not say how a model behaves when its input is not exactly the kind it was tested on.

  • The gradient of the loss with respect to the input pixels, the same quantity that a saliency map shows, is the whole of the FGSM attack. (P5.8: What do CNNs learn?)
  • Adversarial training adds the worst-case changed copy of each training image, so it is data augmentation with the changes chosen by the attacker. (P4.18: Data augmentation)
  • A deployed vision model meets noise, weather and new cameras as well as attackers, and watching for such shifts is part of monitoring. (P12.5: Monitoring and drift, coming soon)

Before this: Build a CNN, What do CNNs learn?, Backpropagation: step by step with numbers, Build an MLP from scratch (NumPy), Norms and distances

After this lesson you can

  • Define an adversarial example with a norm budget and say what the pixel scale of the budget is
  • Compute an FGSM step by hand for a small linear model and explain with numbers why the same budget moves a model with many inputs much further than a model with few
  • Write FGSM and PGD as short programs, and say what changes between untargeted and targeted, white-box and black-box attacks
  • Name what adversarial training costs, why many proposed defences turned out to be broken, and how robustness to ordinary corruptions differs from robustness to an attacker

The small network of P4.10 reads 8×88\times8 pictures of handwritten digits and is right on 264 of its 270 test digits. Take the first test digit, a 2. The network says “2” with 99.7% confidence. Now move every pixel by at most 0.050.05 on the scale from 0 (white) to 1 (full ink), in a direction chosen with the network’s own gradient. The network still says 2, but only 81% sure. At 0.100.10 it says 3, with 95.9% confidence. A person would most likely still read the picture as a 2 (the change is at most 1.6 ink levels of 16). Change the same pixels by the same amount in random directions, and the network stays at 2: in 2,000 random tries at 0.100.10 it never changed its answer.

This lesson is about that gap. A trained network can be very accurate and still fragile, and the fragility can be found with the tools you already have: backpropagation and the gradient.

What is an adversarial example?

A network ff classifies an input x\mathbf{x} correctly. An adversarial example is a nearby input x′\mathbf{x}' that the network classifies wrongly, although a person would still give x′\mathbf{x}' the same label as x\mathbf{x}. “Nearby” needs a number, so we pick a norm (P1.B4) and a budget ε\varepsilon:

∥x′−x∥∞≤ε\lVert\mathbf{x}'-\mathbf{x}\rVert_\infty\le\varepsilon

The L∞L_\infty norm is the largest absolute entry, so this says: no pixel may change by more than ε\varepsilon. It is the budget used in most of the work below. Other norms are used too: Szegedy et al. measured the total size of the change with the L2L_2 norm, and an L0L_0 budget limits how many pixels may change at all.

Say the pixel scale every time. A budget of “8” means nothing without it. In this lesson pixel values are floats from 00 to 11 (shape (N,C,H,W)(N,C,H,W) for batches in PyTorch, P5.1). A photograph stored as 8-bit integers from 0 to 255 and divided by 255 has ε=8/255≈0.031\varepsilon=8/255\approx0.031. The digit pictures here come as ink counts from 0 to 16, divided by 16, so ε=0.1\varepsilon=0.1 is 1.61.6 ink levels of 16.

A small ε\varepsilon is only a stand-in for “a person would not care”: ε=0.1\varepsilon=0.1 is faint but visible on an 8×88\times8 digit, while a change of 8 levels in 255 is usually hard to see on a 224×224224\times224 photograph.

Where it comes from. Szegedy et al. (“Intriguing properties of neural networks”, ICLR 2014) reported that a hardly perceptible change, found by optimising the input to maximise the network’s error, can make a trained network misclassify an image, and that the same change can fool a different network trained on a different subset of the data. Goodfellow, Shlens and Szegedy (“Explaining and harnessing adversarial examples”, ICLR 2015) gave FGSM and an explanation based on linearity. Both are below.

Why a network with many inputs is easy to push

Start with the smallest model that shows the effect: a linear score for one class, z=w⋅x+bz=\mathbf{w}\cdot\mathbf{x}+b, followed by a sigmoid (P3.A7). Let the input have 4 numbers:

w=(2, −1, 3, −2),b=−1.7,x=(0.8, 0.2, 0.7, 0.1),true class y=1.\mathbf{w}=(2,\,-1,\,3,\,-2),\qquad b=-1.7,\qquad \mathbf{x}=(0.8,\,0.2,\,0.7,\,0.1),\qquad \text{true class }y=1.

The score is z=1.6+(−0.2)+2.1+(−0.2)−1.7=1.6z=1.6+(-0.2)+2.1+(-0.2)-1.7=1.6, so σ(z)=0.832\sigma(z)=0.832: the model says “class 1” with probability 0.83. Which way should each input move to lower zz the most? Down where wiw_i is positive, up where it is negative. That is −sign(wi)-\mathrm{sign}(w_i). Move every input by ε=0.1\varepsilon=0.1 that way:

x′=x−0.1⋅sign(w)=(0.7, 0.3, 0.6, 0.2),z′=1.4−0.3+1.8−0.4−1.7=0.8.\mathbf{x}'=\mathbf{x}-0.1\cdot\mathrm{sign}(\mathbf{w})=(0.7,\,0.3,\,0.6,\,0.2),\qquad z'=1.4-0.3+1.8-0.4-1.7=0.8.

The score fell by 0.8=ε (∣2∣+∣−1∣+∣3∣+∣−2∣)=ε∥w∥10.8=\varepsilon\,(|2|+|-1|+|3|+|-2|)=\varepsilon\lVert\mathbf{w}\rVert_1, and the probability fell from 0.83 to 0.69. At ε=0.2\varepsilon=0.2 the score is 0 (a coin flip, probability 0.5), and at ε=0.25\varepsilon=0.25 it is −0.4-0.4 (probability 0.40, the wrong class). Each input moved by at most 0.25 of its range of 1, and the answer flipped.

The key fact is that the best change in the score is ε∥w∥1\varepsilon\lVert\mathbf{w}\rVert_1: every input contributes its full ∣wi∣ε|w_i|\varepsilon, because every input is pushed in the direction that helps. Now count what happens with more inputs. Give each weight the size ∣wi∣=0.1|w_i|=0.1 (a small weight) and take ε=0.03\varepsilon=0.03, about 8/2558/255:

  • n=4n=4 inputs: the aligned change is 0.03⋅0.1⋅4=0.0120.03\cdot0.1\cdot4=0.012.
  • n=64n=64 (this lesson’s digits): 0.190.19.
  • n=784n=784 (a 28×2828\times28 picture): 2.352.35.
  • n=3072n=3072 (a 32×3232\times32 colour picture): 9.229.22.

The aligned change grows in proportion to nn. Random signs behave differently: the pluses and minuses of ∑iwisi\sum_i w_i s_i partly cancel, and the typical size of the change is ε∥w∥2=ε⋅0.1n\varepsilon\lVert\mathbf{w}\rVert_2=\varepsilon\cdot0.1\sqrt n, which grows only with n\sqrt n. A simulation of 20,000 random sign patterns gives typical sizes of 0.0060.006, 0.0240.024, 0.0840.084 and 0.1660.166 for the four values of nn. At 3,072 inputs the aligned change is about 55 times the random one, and 9.2 is a very large change for one score, compared with the 1.6 of the 4-input example.

That paper argues that this linear behaviour is the primary cause of the vulnerability of neural networks, and that ReLU networks, which are made of linear pieces, are “too linear to resist” an aimed change. It is an explanation supported by experiments, not a theorem about every deep network. What it gives us for sure is a recipe.

FGSM: one step along the sign of the input gradient

The linear example had a special case where the best direction was −sign(w)-\mathrm{sign}(\mathbf{w}). A network is not linear, but near x\mathbf{x} it is almost linear, and the role of w\mathbf{w} is played by the gradient of the loss with respect to the input, g=∇xL(θ,x,y)\mathbf{g}=\nabla_{\mathbf{x}}L(\boldsymbol{\theta},\mathbf{x},y). The fast gradient sign method (FGSM) is

x′=clip(x+ε sign(g)),g=∇xL(θ,x,y).\mathbf{x}'=\mathrm{clip}\big(\mathbf{x}+\varepsilon\,\mathrm{sign}(\mathbf{g})\big),\qquad \mathbf{g}=\nabla_{\mathbf{x}}L(\boldsymbol{\theta},\mathbf{x},y).

Four points about it:

  • The gradient is with respect to the pixels, not the weights. Training asks how the loss changes with θ\boldsymbol{\theta} and steps downhill. The attack keeps θ\boldsymbol{\theta} fixed, asks how the loss changes with x\mathbf{x} and steps uphill (++, not −-). Backpropagation (P4.8) already computes it: it passes through the first layer and does not stop there. It is the same input gradient that P5.8 used for saliency maps, except that saliency took the absolute value of a class score, and FGSM keeps the sign of a loss.
  • Why the sign. To first order, L(x+δ)≈L(x)+g⋅δL(\mathbf{x}+\boldsymbol{\delta})\approx L(\mathbf{x})+\mathbf{g}\cdot\boldsymbol{\delta}. With each ∣δi∣≤ε|\delta_i|\le\varepsilon, the biggest value of g⋅δ\mathbf{g}\cdot\boldsymbol{\delta} is ε∥g∥1\varepsilon\lVert\mathbf{g}\rVert_1, reached at δ=ε sign(g)\boldsymbol{\delta}=\varepsilon\,\mathrm{sign}(\mathbf{g}). This is the same ε∥w∥1\varepsilon\lVert\mathbf{w}\rVert_1 as above.
  • Clip. The result must stay a valid picture, so values are clipped into 00 to 11. A pixel already at 00 whose gradient asks it to go lower cannot move: in the first test digit above, 16 of the 64 pixels were at that limit, so FGSM changed 48.
  • Only the sign is used. A loss gradient is tiny when the network is very sure and right (the softmax is saturated), so its size says little, but its direction still points uphill. For the first test digit the straight-line estimate of the loss at ε=0.1\varepsilon=0.1 is 0.030.03 and the real loss after the step is 3.23.2: the linear picture finds the direction, not how far the loss goes.

The loss here is the cross-entropy of the true label (P1.E3), so the attack is untargeted: it just wants to leave the true class. A targeted attack wants a chosen class tt, and steps downhill on the loss of that class instead: x′=clip(x−ε sign(∇xL(θ,x,t)))\mathbf{x}'=\mathrm{clip}(\mathbf{x}-\varepsilon\,\mathrm{sign}(\nabla_{\mathbf{x}}L(\boldsymbol{\theta},\mathbf{x},t))). On the digit network one such step towards the class 3 made 16.9% of the 242 correctly classified non-3 test digits read as 3 at ε=0.1\varepsilon=0.1, and 57.9% at 0.20.2. (Stepping downhill on the loss of the true class, the wrong sign, never flipped anything: 0% at both budgets.)

Try it: the epsilon slider

Pick a digit, move ε\varepsilon and watch the prediction. Then switch to random signs. The third picture is the first plus the second, clipped; the middle picture shows the change that was applied, orange when the change comes from the gradient (FGSM), grey for random signs. Everything is computed in your browser, by backpropagation to the pixels, on the 2,410 numbers of the P4.10 network.

Digit
ε = 0.10 moves each pixel by at most 1.6 of the 16 ink levels (26 of 255 if the picture were 8-bit).
Original
2 (99.7%)
+−++++++−+−++++−−+−++++++−+++++−−+++++−−−−++−−−−
Gradient signs
48 of 64 pixels
Perturbed
3 (95.9%)

Digit 2. Epsilon 0.10, worst-case signs. Before: predicted 2 with probability 99.7%. After: predicted 3 with probability 95.9%, so the prediction changed.

With these signs the prediction first changes at ε = 0.07 (checked on a grid of 0.005).

Score margin (the true digit's score minus the best other digit's score, before the softmax): 5.88 before, -3.16 after. A margin below 0 means the prediction is wrong.

0 0.0%
1 0.0%
2true 4.1%
3 95.9%◀
4 0.0%
5 0.0%
6 0.0%
7 0.0%
8 0.0%
9 0.0%
  • before (outline)
  • after (solid)
  • + pixel made darker (ink added)
  • − pixel made lighter
  • ◀ predicted class after

The network is the 64-32-10 network of P4.10. Perturbed pixels are clipped to 0 to 1, so a pixel already at the limit cannot move and the third picture can change by less than ε.

The 64-32-10 digit network of P4.10 attacked in the browser. Choose a test digit (all are classified correctly at ε = 0) and a budget ε on the scale 0 to 1. Worst-case signs are the signs of the loss gradient with respect to the pixels (FGSM, orange); random signs are one fixed random pattern. Shown: three pictures, ten probabilities before and after, the score margin, and the smallest ε that changes the prediction.

Things to try:

  • Start at ε=0\varepsilon=0 and raise it slowly for several digits. The smallest ε\varepsilon that changes the prediction differs a lot between digits.
  • Switch to random signs and slide ε\varepsilon to 0.50.5, and compare with the worst-case direction. Watch the score margin: the prediction changes exactly when it goes below 0.

How often does it work?

The widget shows single digits. Here is the whole test set. Setup: the 264 test digits that the network classifies correctly, pixels in 00 to 11, every perturbed picture clipped; “random” is the average over 20 random sign patterns per digit.

Budget ε\varepsilonPrediction changed by FGSMBy random signs
0.0515.2%1.2%
0.1045.1%2.4%
0.1575.4%4.1%
0.2094.7%7.0%
0.30100%17.2%

The smallest FGSM budget on a grid of 0.0050.005 that changes the prediction has a median of 0.110.11 (middle half of the digits: 0.070.07 to 0.150.15), and every one of the 264 digits flips by ε=0.6\varepsilon=0.6. Among the digits whose prediction changed at ε=0.1\varepsilon=0.1 (119 of them), the network gave the wrong class on average 82% probability. So the network is not just wrong, it is confidently wrong.

These numbers belong to this network, these test digits and these budgets; what carries over is the shape: aimed changes are far more effective than random changes of the same size.

Stronger attacks and other settings

Iterative attacks. FGSM takes one big step and the loss surface is not a straight line, so a single step can overshoot or miss. Kurakin et al. (2016) repeated small steps (the “basic iterative method”). Projected gradient descent (PGD), used by Madry et al. (ICLR 2018), does the same and adds two things: it starts from a random point inside the budget, and after every step it projects back into the budget (here: clip each pixel to within ε\varepsilon of the original, and into 00 to 11):

xt+1=Π(xt+α sign(∇xL(θ,xt,y))),Π=projection into the ε-ball and [0,1].\mathbf{x}^{t+1}=\Pi\big(\mathbf{x}^{t}+\alpha\,\mathrm{sign}(\nabla_{\mathbf{x}}L(\boldsymbol{\theta},\mathbf{x}^{t},y))\big),\qquad \Pi=\text{projection into the }\varepsilon\text{-ball and }[0,1].

Madry et al. describe it as a strong first-order attack: it uses only gradient information. On the digit network, 10 steps with α=2.5ε/10\alpha=2.5\varepsilon/10 changed the prediction for 15.2%, 50.4%, 82.2% and 98.9% of the digits at ε=0.05\varepsilon=0.05, 0.100.10, 0.150.15 and 0.200.20, against FGSM’s 15.2%, 45.1%, 75.4% and 94.7%. It is stronger, not dramatically so on this small network, and it costs 10 gradients instead of one.

White-box and black-box. A white-box attacker knows the weights and can compute ∇xL\nabla_{\mathbf{x}}L directly. A black-box attacker can only send inputs and read outputs, and relies on transfer: examples made on one model often fool another. Szegedy et al. and Goodfellow et al. reported this across models trained on different subsets of the data or with different architectures, and Papernot et al. (2017) attacked a remotely hosted classifier by training a local substitute on the labels it returned. Transfer is partial: see the CIFAR-10 measurement below.

Defences

Adversarial training. If an attacker will move each training image to the worst point inside its ball, train on that point. Madry et al. write the goal as a min-max problem:

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

The inner maximum is found with PGD, then the weights take an ordinary gradient step on those worst-case images. Costs:

  • Computation. Each training step needs the attack first. With a kk-step PGD that is kk extra forward-and-backward passes per batch before the training step, so about k+1k+1 times the work of normal training (before any savings).
  • Clean accuracy and capacity. Madry et al. trained a ResNet made 10 times wider on CIFAR-10 with ε=8\varepsilon=8 (pixels from 0 to 255), using 7-step PGD. It reached 87.3% on clean test images and 45.8% on test images attacked by 20-step PGD (white-box, ε=8\varepsilon=8). The same wide network trained normally reaches 95.2% on clean images (the paper’s figure). They found that robust training needs more capacity than normal training, and called the robustness achieved “still far from satisfactory”.
  • Training on FGSM examples alone overfits to that single-step attack (known as label leaking, Kurakin et al.; Madry et al. also observed it). Goodfellow et al.’s adversarial training of a maxout MNIST network at ε=0.25\varepsilon=0.25 took its error rate on FGSM examples from 89.4% to 17.9%.

Gradient masking. A tempting shortcut is a defence that makes the gradient useless, so that gradient attacks fail: a step that is not differentiable, random choices at test time, or a very deep chain of operations. The defence then looks strong against the attacks that were tried and is not. Athalye, Carlini and Wagner (ICML 2018) named this obfuscated gradients, in three kinds: shattered gradients (missing or wrong), stochastic gradients (random at test time) and vanishing or exploding gradients. Of 9 non-certified white-box defences accepted at ICLR 2018, they found that 7 relied on obfuscated gradients, and their new attacks circumvented 6 of them completely and 1 partially. The adversarial training of Madry et al. was not one of the seven.

Warning signs listed in the paper include single-step attacks doing better than iterative ones and black-box attacks doing better than white-box ones. A defence is only as good as the strongest attack it has faced, so test with attacks designed for it (adaptive attacks), at several budgets.

Certified defences prove that no change within a given budget can change the answer; randomized smoothing (Cohen, Rosenfeld and Kolter, ICML 2019) does so for L2L_2 changes of a smoothed classifier. They are named here, not taught.

Robustness is more than defending against an attacker

Most failures in practice come from ordinary changes, not from a person with a gradient. Hendrycks and Dietterich (ICLR 2019) built ImageNet-C: 15 types of algorithmically generated corruption (noise, blur, weather and digital effects), each at 5 severity levels, applied to ImageNet validation images. They report negligible changes in relative corruption robustness (how much worse a classifier is on corrupted images than on clean ones) from AlexNet classifiers to ResNet classifiers. Robustness to an attacker and robustness to such corruptions are different properties, and fixing one does not fix the other.

The same worry appears when the world changes between training and use (a new camera, a new hospital). A pretrained model also inherits the gaps and biases of its training data (P5.10), so evaluate it on pictures like your own, split by the groups that matter. Monitoring after deployment is P12.5.

The physical world. Kurakin et al. (2016) printed adversarial pictures, photographed them with a phone camera and found that a large fraction were still classified wrongly by an ImageNet Inception model. Eykholt et al. (CVPR 2018) reported high targeted-misclassification rates against road-sign classifiers they had built, using stickers and posters on a real stop sign; these are results for specific classifiers, not for every deployed vehicle.

Responsibility. Adversarial examples matter most where a wrong answer costs something: driving, medical imaging, security checks. Use this knowledge to test your own models, never systems you do not own or have permission to test. Everything here targets small models trained for the lesson.

Depth: three ways to see it

Intuition

Think of the loss as a landscape over the 64 pixel values. A correct, confident picture sits in a flat valley. A random step across the valley floor changes little. The gradient points straight up the nearest slope, and with many directions to choose from, a small aimed step in each adds up to a big climb, while random steps cancel.

Math

FGSM from the first-order change. For a small change δ\boldsymbol{\delta}, L(x+δ)≈L(x)+g⊤δ,g=∇xL.L(\mathbf{x}+\boldsymbol{\delta})\approx L(\mathbf{x})+\mathbf{g}^\top\boldsymbol{\delta},\qquad \mathbf{g}=\nabla_{\mathbf{x}}L. Over ∥δ∥∞≤ε\lVert\boldsymbol{\delta}\rVert_\infty\le\varepsilon: g⊤δ=∑igiδi≤∑i∣gi∣ε=ε∥g∥1\mathbf{g}^\top\boldsymbol{\delta}=\sum_i g_i\delta_i\le\sum_i|g_i|\varepsilon=\varepsilon\lVert\mathbf{g}\rVert_1, with equality at δi=ε sign(gi)\delta_i=\varepsilon\,\mathrm{sign}(g_i). For an L2L_2 budget the best direction is the gradient itself, scaled to length ε\varepsilon, with first-order gain ε∥g∥2\varepsilon\lVert\mathbf{g}\rVert_2.

Linear score. For z=w⊤x+bz=\mathbf{w}^\top\mathbf{x}+b: Δz=w⊤δ≤ε∥w∥1\Delta z=\mathbf{w}^\top\boldsymbol{\delta}\le\varepsilon\lVert\mathbf{w}\rVert_1. If ∣wi∣=m|w_i|=m for all nn inputs, ∥w∥1=mn\lVert\mathbf{w}\rVert_1=mn. For random signs si=±1s_i=\pm1, Δz=ε∑wisi\Delta z=\varepsilon\sum w_is_i has mean 0 and standard deviation ε∥w∥2=εmn\varepsilon\lVert\mathbf{w}\rVert_2=\varepsilon m\sqrt n.

Adversarial training (Madry et al.). min⁡θ E[max⁡∥δ∥∞≤εL(θ,x+δ,y)],xt+1=Π(xt+α sign(∇xL)).\min_{\boldsymbol{\theta}}\ \mathbb{E}\Big[\max_{\lVert\boldsymbol{\delta}\rVert_\infty\le\varepsilon}L(\boldsymbol{\theta},\mathbf{x}+\boldsymbol{\delta},y)\Big],\qquad \mathbf{x}^{t+1}=\Pi\big(\mathbf{x}^t+\alpha\,\mathrm{sign}(\nabla_{\mathbf{x}}L)\big).

Code

On a batch of images in PyTorch (shape (N,C,H,W)(N,C,H,W), floats in 00 to 11), the input gradient is one call:

def input_grad(model, x, y):
    x = x.clone().requires_grad_(True)       # ask for the gradient of the pixels
    loss = F.cross_entropy(model(x), y)
    return torch.autograd.grad(loss, x)[0]   # same shape as x

def fgsm(model, x, y, eps):
    return (x + eps * input_grad(model, x, y).sign()).clamp(0, 1).detach()

def pgd(model, x, y, eps, steps=10):
    alpha = 2.5 * eps / steps
    z = (x + torch.empty_like(x).uniform_(-eps, eps)).clamp(0, 1)
    for _ in range(steps):
        z = z + alpha * input_grad(model, z, y).sign()
        z = torch.min(torch.max(z, x - eps), x + eps).clamp(0, 1)
    return z.detach()

Set the model to eval() first, so BatchNorm uses its stored statistics (P4.19) and the attack does not change them. The notebook below runs these on the CIFAR-10 CNN of P5.7.

eps (of 255)   random signs   FGSM
      1            0.8819   0.4640
      2            0.8798   0.2062
      4            0.8626   0.0605
      8            0.7672   0.0289
PGD 1 step:   0.0209
PGD 10 steps: 0.0000
PGD 20 steps: 0.0000

These are test accuracies (clean: 0.8822) of the P5.7 CNN trained normally, in the notebook run described below.

Try it in Python

The cells below share one namespace, like cells in a notebook. The first trains the P4.10 network again (the same seeds and the same plain SGD, so the weights are the ones in the widget) and computes the gradient with respect to the pixels, checked against a finite difference (fd). The second attacks the first test digit and then the whole test set; its table is the one above.

Step 1: train the network, get the input gradient

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
test accuracy: 264 of 270
pixel 27: backprop 0.00769, fd 0.00769

The two numbers agree: backpropagation passes through the whole network down to the pixels. The next cell turns that gradient into FGSM.

Step 2: FGSM and random signs

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
true digit: 2
clean:       2 (99.7%)
FGSM 0.05: 2 (81.0%) changed: 48
FGSM 0.10: 3 (95.9%) changed: 48
FGSM 0.20: 3 (100.0%) changed: 48
eps   FGSM   random signs
0.05   15.2%    1.2%
0.10   45.1%    2.4%
0.15   75.4%    4.1%
0.20   94.7%    7.0%
0.30  100.0%   17.2%

The first lines are the hook of this lesson, and the table is the one above. The cell clips to 00 to 11, which is why 48 pixels and not 64 changed. Challenge. In Step 2, change + eps * np.sign(...) in fgsm to a minus sign and rerun the table. What fraction changes, and why? (The loss then goes down, away from the wrong classes: 0% of the predictions change at ε=0.1\varepsilon=0.1 and at 0.20.2.) PGD is in the Colab notebook.

Colab notebook

The notebook P5.17-adversarial-examples-fgsm-pgd.ipynb (source on GitHub) trains the small CNN of P5.7 on CIFAR-10 (about 170 MB of data; about 13 minutes per 20-epoch network on the laptop GPU used here, and the notebook trains two; PyTorch 2.9.1; use a GPU runtime), then runs random signs, FGSM and PGD on the 10,000 test images and a transfer test between two networks with different seeds. The numbers below are from one run (seeds 0 and 1) and will differ a little on your machine.

Results on the 10,000 test images (budget in grey levels of 255): clean accuracy 88.2%. Random signs of 8/2558/255 lower it to 76.7%. FGSM at 1/2551/255, one grey level, already lowers it to 46.4%, and at 22, 44 and 88 to 20.6%, 6.0% and 2.9%. PGD at 8/2558/255 gives 2.1% after one step and 0.0% after 10 or 20 steps. This network was not trained against attacks.

Transfer. A second copy of the network, trained with seed 1 (clean accuracy 88.2%), was attacked with white-box FGSM and 10-step PGD at 8/2558/255, and the resulting images were given to the first network. The first network’s accuracy was 20.5% under FGSM images and 3.2% under PGD images made on the second network, against 2.9% and 0.0% for attacks made on itself. So transfer was strong here but weaker than a direct attack. This is one pair of networks of the same design and data, not a general rate.

Common mistakes

Quiz

Check your understanding

  1. A photograph is stored as 8-bit integers from 0 to 255. An attack is allowed an L∞L_\infty budget of 8 on this scale. What does that allow?

  2. In FGSM, with respect to what is the gradient of the loss taken?

  3. A linear model has 3,072 inputs, each with a weight of size about 0.1. Random changes of ±0.03\pm0.03 rarely move its score much, yet the sign of the weights moves it a lot. Why?

  4. A new defence stops every gradient attack that its authors tried, but an attack that uses a substitute model, with no gradient from the defended model, gets through. What is the most likely conclusion?

Exercises

  1. FGSM by hand. A linear model has w=(1,−2,2)\mathbf{w}=(1,-2,2), b=−0.5b=-0.5, input x=(0.5,0.2,0.4)\mathbf{x}=(0.5,0.2,0.4), true class 1 (a high score means class 1). What is the score zz, and what is it after the FGSM step with ε=0.1\varepsilon=0.1 (no clipping needed)?
    Show answerz=0.5−0.4+0.8−0.5=0.4z=0.5-0.4+0.8-0.5=0.4. The step lowers the score the most: x′=x−0.1 sign(w)=(0.4, 0.3, 0.3)\mathbf{x}'=\mathbf{x}-0.1\,\mathrm{sign}(\mathbf{w})=(0.4,\,0.3,\,0.3) and z′=0.4−0.6+0.6−0.5=−0.1z'=0.4-0.6+0.6-0.5=-0.1. The change is −0.5=−ε∥w∥1=−0.1⋅5-0.5=-\varepsilon\lVert\mathbf{w}\rVert_1=-0.1\cdot5, and the score is now negative, so the class has flipped.
  2. Dimension. All 784 weights of a model have size 0.10.1 and ε=0.03\varepsilon=0.03. What is the largest score change an aimed change can cause, and the typical size of the change from random signs?
    Show answerAimed: 0.03⋅0.1⋅784=2.3520.03\cdot0.1\cdot784=2.352. Random: 0.03⋅0.1⋅784=0.0840.03\cdot0.1\cdot\sqrt{784}=0.084, so aimed is 784=28\sqrt{784}=28 times as large.
  3. Cost. Adversarial training uses a 10-step PGD attack for every batch. About how many forward-and-backward passes does one batch need, compared with normal training?
    Show answer10 passes to build the attack plus 1 for the weight update, so about 11 times as many (before any savings, such as skipping the weight gradients in the attack steps).
  4. Evaluation. A paper reports that its defended model resists every attack, including PGD, at ε=0.03\varepsilon=0.03. Name two checks you would run before believing it.
    Show answerExamples: attack with a method designed for this defence (an adaptive attack) instead of the standard one; raise ε\varepsilon and check that accuracy falls towards 0 (if it does not, the attack is failing and not the model resisting); compare a gradient-free or transfer attack with the gradient attacks (a better black-box result is a sign of masked gradients).

Key takeaways

  • An adversarial example is an input x′\mathbf{x}' within a small budget of a real input x\mathbf{x}, usually ∥x′−x∥∞≤ε\lVert\mathbf{x}'-\mathbf{x}\rVert_\infty\le\varepsilon (no pixel moves by more than ε\varepsilon), that the model classifies wrongly. Always say the pixel scale: ε=8/255≈0.031\varepsilon=8/255\approx0.031 on photographs in the range 00 to 11, and 0.10.1 on the digit pictures of this lesson.
  • FGSM (Goodfellow et al. 2015) takes one step of size ε\varepsilon along the sign of the gradient of the loss with respect to the pixels: x′=clip(x+ε sign(∇xL))\mathbf{x}'=\mathrm{clip}(\mathbf{x}+\varepsilon\,\mathrm{sign}(\nabla_{\mathbf{x}}L)). For a linear model the logit moves by ε∥w∥1\varepsilon\lVert\mathbf{w}\rVert_1, which grows with the number of inputs; random signs grow only with its square root.
  • On the 64-32-10 digit network of P4.10, FGSM changed the prediction for 45.1% of the 264 correctly classified test digits at ε=0.1\varepsilon=0.1, random signs of the same size for 2.4%, and 10-step PGD for 50.4%.
  • Defences that hide the gradient give a false sense of security: Athalye et al. (2018) found 7 of 9 ICLR 2018 defences relied on obfuscated gradients. Robustness to ordinary corruptions (ImageNet-C) is a different property from robustness to an adversary.
Found a mistake? Tell us