The small network of P4.10 reads 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 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 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 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 classifies an input correctly. An adversarial example is a nearby input that the network classifies wrongly, although a person would still give the same label as . “Nearby” needs a number, so we pick a norm (P1.B4) and a budget :
The norm is the largest absolute entry, so this says: no pixel may change by more than . 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 norm, and an 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 to (shape for batches in PyTorch, P5.1). A photograph stored as 8-bit integers from 0 to 255 and divided by 255 has . The digit pictures here come as ink counts from 0 to 16, divided by 16, so is ink levels of 16.
A small is only a stand-in for “a person would not care”: is faint but visible on an digit, while a change of 8 levels in 255 is usually hard to see on a 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, , followed by a sigmoid (P3.A7). Let the input have 4 numbers:
The score is , so : the model says “class 1” with probability 0.83. Which way should each input move to lower the most? Down where is positive, up where it is negative. That is . Move every input by that way:
The score fell by , and the probability fell from 0.83 to 0.69. At the score is 0 (a coin flip, probability 0.5), and at it is (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 : every input contributes its full , because every input is pushed in the direction that helps. Now count what happens with more inputs. Give each weight the size (a small weight) and take , about :
- inputs: the aligned change is .
- (this lesson’s digits): .
- (a picture): .
- (a colour picture): .
The aligned change grows in proportion to . Random signs behave differently: the pluses and minuses of partly cancel, and the typical size of the change is , which grows only with . A simulation of 20,000 random sign patterns gives typical sizes of , , and for the four values of . 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 . A network is not linear, but near it is almost linear, and the role of is played by the gradient of the loss with respect to the input, . The fast gradient sign method (FGSM) is
Four points about it:
- The gradient is with respect to the pixels, not the weights. Training asks how the loss changes with and steps downhill. The attack keeps fixed, asks how the loss changes with 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, . With each , the biggest value of is , reached at . This is the same as above.
- Clip. The result must stay a valid picture, so values are clipped into to . A pixel already at 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 is and the real loss after the step is : 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 , and steps downhill on the loss of that class instead: . 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 , and 57.9% at . (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 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.
Things to try:
- Start at and raise it slowly for several digits. The smallest that changes the prediction differs a lot between digits.
- Switch to random signs and slide to , 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 to , every perturbed picture clipped; “random” is the average over 20 random sign patterns per digit.
| Budget | Prediction changed by FGSM | By 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% | 17.2% |
The smallest FGSM budget on a grid of that changes the prediction has a median of (middle half of the digits: to ), and every one of the 264 digits flips by . Among the digits whose prediction changed at (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 of the original, and into to ):
Madry et al. describe it as a strong first-order attack: it uses only gradient information. On the digit network, 10 steps with changed the prediction for 15.2%, 50.4%, 82.2% and 98.9% of the digits at , , and , 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 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:
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 -step PGD that is extra forward-and-backward passes per batch before the training step, so about 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 (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, ). 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 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 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 , Over : , with equality at . For an budget the best direction is the gradient itself, scaled to length , with first-order gain .
Linear score. For : . If for all inputs, . For random signs , has mean 0 and standard deviation .
Adversarial training (Madry et al.).
Code
On a batch of images in PyTorch (shape , floats in to ), 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.0000These 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.
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.
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.
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.
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 to , 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 and at .) 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 lower it to 76.7%. FGSM at , one grey level, already lowers it to 46.4%, and at , and to 20.6%, 6.0% and 2.9%. PGD at 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 , 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
A photograph is stored as 8-bit integers from 0 to 255. An attack is allowed an budget of 8 on this scale. What does that allow?
The norm is the largest absolute entry, so the budget limits every pixel separately, by the same amount. Dividing by 255 puts it on the 0 to 1 scale. Limiting the total is a different norm (), counting pixels is , and a relative change is not what any of these norms measures.
In FGSM, with respect to what is the gradient of the loss taken?
FGSM changes the picture, not the network, so the gradient is with respect to the pixels. Backpropagation computes it by continuing past the first layer. The weights are held fixed; the probabilities are an intermediate value, not the variable of the gradient; and the learning rate is not something the loss depends on.
A linear model has 3,072 inputs, each with a weight of size about 0.1. Random changes of rarely move its score much, yet the sign of the weights moves it a lot. Why?
With every input pushed the helpful way each contributes its full , so the total is proportional to ; random signs cancel to a typical size proportional to . Clipping affects some pixels but cannot explain the gap, noise has no preference for unimportant inputs, and a sign never makes a change larger than .
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?
Athalye et al. list black-box attacks beating white-box ones among the signs of obfuscated gradients: the gradient had been made useless, but the model was not made robust. The other readings take the failed attacks as proof, call the successful attack wrong, or treat white-box and black-box as separate groups of defenders, when they describe what the attacker knows.
Exercises
- FGSM by hand. A linear model has , , input , true class 1 (a high score means class 1). What is the score , and what is it after the FGSM step with (no clipping needed)?
Show answer
. The step lowers the score the most: and . The change is , and the score is now negative, so the class has flipped. - Dimension. All 784 weights of a model have size and . What is the largest score change an aimed change can cause, and the typical size of the change from random signs?
Show answer
Aimed: . Random: , so aimed is times as large. - 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 answer
10 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). - Evaluation. A paper reports that its defended model resists every attack, including PGD, at . Name two checks you would run before believing it.
Show answer
Examples: attack with a method designed for this defence (an adaptive attack) instead of the standard one; raise 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).