◆ AI All-in-One

Level 3 In-Depth AI · Safety, Ethics and Society

Adversarial Examples

Tiny, carefully chosen changes to an input can make a well-trained model confidently wrong. This chapter shows why that happens, builds the classic FGSM attack in a few lines, and covers the defences, from adversarial training to the jailbreak defences used for chatbots.

Level
●●●●● Intermediate
Reading
13 min
To learn it well
1 hour to read, an hour to try the code
↗ Plan a path here

Read first

Neural NetworksGradient Descent

This leads to

—
The full path from zero — 14 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Linear Regression
  12. The Perceptron
  13. Logistic Regression
  14. Neural Networks
  15. Adversarial Examples

Read them roughly in this order. See it on the concept map →

Why it matters

In 2014, researchers took a photo of a panda that an image classifier recognised with 57.7% confidence, added a faint pattern of noise invisible to the human eye, and the classifier then said "gibbon" with 99.3% confidence. The changed image is an adversarial example: an input deliberately modified so that a model gets it wrong, while a human sees no meaningful difference.

This is not a quirk of one model. Almost every neural network trained in the ordinary way is vulnerable, in images, audio, text and tabular data. It matters for three reasons:

  • Security. Any system that makes decisions from inputs an attacker can influence (spam and malware filters, content moderation, face recognition, self-driving perception, and now chatbots and AI agents) can be attacked this way.
  • Reliability. Adversarial examples show that models can be accurate without "seeing" things the way we do. That is a warning about how they will behave on unusual inputs.
  • Language models. The same idea, an input crafted to make a model misbehave, underlies jailbreaks of chatbots and, in a different form, Prompt Injection and LLM Security.

This chapter explains the attack conceptually and in code on a toy digit classifier, then focuses on what defends against it.

The intuition

A classifier draws decision boundaries: surfaces in input space that separate "panda" from "gibbon", or "8" from "4". A photo with a million pixel values is a point in a space with a million dimensions. Training places most natural photos far enough from the boundary on the correct side. But in a million dimensions, "far" in every direction you happen to look doesn't mean far in every direction. There is almost always some direction in which the boundary is very close.

Random noise wanders in random directions, and in high dimensions a random direction is almost perpendicular to the one that matters, so random noise rarely changes the prediction. An attacker doesn't move randomly. They use the model's own gradient, the direction in which the loss rises fastest, to step straight towards the boundary.

+ = original image 8 × 8 pixels perturbation each pixel ±0.1 (ε), from the gradient adversarial image still clearly the same digit model says: 8 confidence 96.9% red = add ink, blue = remove ink (pixels run from 0 = blank to 1 = full ink) model says: 4 confidence 99.3% A real example from this chapter's code: an MLP trained on scikit-learn digits, attacked with FGSM at ε = 0.1
Fig. 1 A real adversarial example from this chapter's code. An 8 × 8 handwritten 8 is classified correctly with 96.9% confidence. Adding a perturbation of at most 0.1 per pixel, chosen using the gradient, makes the model say "4" with 99.3% confidence, though the image barely changes.

Key idea Training uses the gradient to change the weights so the loss goes down. An adversarial attack uses the gradient to change the input so the loss goes up. Same calculus, opposite purpose.

How it works

Why linear models are already vulnerable

You might guess that adversarial examples come from the complicated, nonlinear shapes of deep networks. Goodfellow and colleagues argued in 2014 that the opposite is closer to the truth: they come from models being too linear in high dimensions.

Take a linear score z=w⋅x+bz = \mathbf{w} \cdot \mathbf{x} + b, where x\mathbf{x} is the input, w\mathbf{w} the weights and bb a bias. Suppose we may change each input value by at most a small amount ϵ\epsilon ("epsilon"). To push zz up as much as possible, nudge every input in the direction of its weight's sign: up where the weight is positive, down where it is negative. Then the score changes by

Δz=ϵ∑i=1n∣wi∣\Delta z = \epsilon \sum_{i=1}^{n} |w_i|

Each input moves only by ϵ\epsilon, but the effects add up across all nn inputs.

A worked example. Four pixels, weights w=(2,−1,3,−2)\mathbf{w} = (2, -1, 3, -2), bias b=−2b = -2, and input x=(0.5,0.2,0.4,0.1)\mathbf{x} = (0.5, 0.2, 0.4, 0.1). The score is 1−0.2+1.2−0.2−2=−0.21 - 0.2 + 1.2 - 0.2 - 2 = -0.2, which is negative, so the model says class 0. Now move each pixel by ϵ=0.1\epsilon = 0.1 in the direction of its weight's sign: x′=(0.6,0.1,0.5,0.0)\mathbf{x}' = (0.6, 0.1, 0.5, 0.0). The score rises by 0.1×(2+1+3+2)=0.80.1 \times (2 + 1 + 3 + 2) = 0.8 to +0.6+0.6, and the prediction flips to class 1.

With four pixels the shift is 0.8. With a 224 × 224 colour image there are about 150,000 inputs. If the average ∣wi∣|w_i| were 0.01, the same ϵ=0.1\epsilon = 0.1 would shift the score by about 150, far more than enough to cross any boundary, while each pixel moves by an amount nobody would notice. Deep networks built from ReLUs behave roughly linearly over small regions, so they inherit exactly this weakness.

The Fast Gradient Sign Method (FGSM)

That reasoning gives the simplest attack, the Fast Gradient Sign Method (FGSM). For a network with loss L(θ,x,y)L(\theta, \mathbf{x}, y), parameters θ\theta, input x\mathbf{x} and true label yy:

xadv=x+ϵ⋅sign⁡(∇xL(θ,x,y))\mathbf{x}_{\text{adv}} = \mathbf{x} + \epsilon \cdot \operatorname{sign}\big(\nabla_{\mathbf{x}} L(\theta, \mathbf{x}, y)\big)

In words: compute the gradient of the loss with respect to the input (not the weights), keep only its sign (+1 or −1 for each pixel), multiply by ϵ\epsilon and add it to the image. The ∇x\nabla_{\mathbf{x}} means "gradient with respect to x\mathbf{x}", which Backpropagation computes in one backward pass. The adversarial perturbation xadv−x\mathbf{x}_{\text{adv}} - \mathbf{x} has every entry equal to ±ϵ\pm\epsilon, so no pixel changes by more than ϵ\epsilon. Finally you clip the result to the valid pixel range.

Stronger attacks

FGSM takes one big step. Projected Gradient Descent (PGD; Madry and colleagues, 2017) takes many small FGSM-like steps, and after each one projects back into the allowed region (each pixel within ϵ\epsilon of the original). It finds much stronger adversarial examples and is the standard yardstick for testing defences. Other attacks minimise how large the change is (Carlini and Wagner, 2017), change only a few pixels, or produce physical objects: researchers have fooled sign classifiers with stickers on real stop signs (2018) and made a 3D-printed turtle that a classifier labelled "rifle" from most angles (2018).

What the attacker knows

  • In a white-box attack the attacker has the model's weights and can compute gradients, as in FGSM.
  • In a black-box attack they can only send inputs and see outputs. They can estimate gradients from many queries, or exploit transferability: adversarial examples crafted against one model often fool other models trained on similar data. Szegedy and colleagues noticed this in the 2013 paper that discovered adversarial examples. It means keeping your weights secret is not a defence.

Attacks at prediction time like these are called evasion attacks. A related threat is data poisoning: an attacker slips crafted examples into the training data so the model learns a hidden behaviour, such as a backdoor that triggers only when a particular pattern appears. Models trained on scraped web data are exposed to this risk.

In code

We train a small network on scikit-learn's digits (1,797 handwritten digits of 8 × 8 pixels), then attack the test set with FGSM at several sizes of ϵ\epsilon. For comparison we add random ±0.2 noise of the same size as the largest attack.

import torch, torch.nn as nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

torch.manual_seed(0)
X, y = load_digits(return_X_y=True)              # 1,797 images of 8x8 pixels, values 0..16
X = torch.tensor(X / 16.0, dtype=torch.float32)  # scale pixels to [0, 1]
y = torch.tensor(y)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)

model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10))
opt = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(100):                         # full-batch training, a second or two
    opt.zero_grad()
    loss_fn(model(X_tr), y_tr).backward()
    opt.step()

def accuracy(inputs):
    return (model(inputs).argmax(1) == y_te).float().mean().item()

def fgsm(x, labels, eps):
    x = x.clone().requires_grad_(True)
    loss_fn(model(x), labels).backward()         # gradient of the loss w.r.t. the INPUT
    x_adv = x + eps * x.grad.sign()              # step UP the loss, size eps per pixel
    return x_adv.clamp(0, 1).detach()            # stay a valid image

print(f"clean accuracy:       {accuracy(X_te):.3f}")
for eps in [0.05, 0.1, 0.2]:
    print(f"FGSM eps={eps:<4}  accuracy: {accuracy(fgsm(X_te, y_te, eps)):.3f}")
noise = (torch.rand_like(X_te).round() * 2 - 1) * 0.2   # random +-0.2 per pixel, same size
print(f"random noise 0.2   accuracy: {accuracy((X_te + noise).clamp(0, 1)):.3f}")

# clean accuracy:       0.970
# FGSM eps=0.05  accuracy: 0.769
# FGSM eps=0.1   accuracy: 0.365
# FGSM eps=0.2   accuracy: 0.006
# random noise 0.2   accuracy: 0.870

At ϵ=0.2\epsilon = 0.2, FGSM takes accuracy from 97% to under 1%. Random noise of exactly the same size per pixel leaves 87%. The size of the change is not what matters. Its direction is.

Defence: adversarial training

The most reliable defence found so far is adversarial training: generate adversarial examples against the current model during training and train on them too, so the model learns to resist. Formally, Madry and colleagues framed it as a min-max problem: minimise the loss on the worst-case input within ϵ\epsilon of each training example. Continuing from the code above:

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10))
opt = torch.optim.Adam(model.parameters(), lr=0.01)
for epoch in range(200):
    x_adv = fgsm(X_tr, y_tr, 0.1)                # attack the current model
    opt.zero_grad()                              # (fgsm left gradients in the weights)
    loss = loss_fn(model(X_tr), y_tr) + loss_fn(model(x_adv), y_tr)
    loss.backward()
    opt.step()

print(f"robust model, clean:      {accuracy(X_te):.3f}")
for eps in [0.1, 0.2]:
    print(f"robust model, FGSM {eps}: {accuracy(fgsm(X_te, y_te, eps)):.3f}")

# robust model, clean:      0.976
# robust model, FGSM 0.1: 0.794
# robust model, FGSM 0.2: 0.256
0 0.05 0.1 0.15 0.2 0.25 0.3 0% 25% 50% 75% 100% random ±ε noise standard model FGSM attack standard model FGSM attack adversarially trained ε: maximum change allowed per pixel (pixels range 0 to 1) test accuracy Same size of change, very different damage: direction is what matters.
Fig. 2 Test accuracy against the size of the change ε. Random noise barely hurts the standard model. FGSM destroys it by ε = 0.2. Adversarial training at ε = 0.1 keeps accuracy much higher, but robustness still falls off for larger changes than it was trained on.

Accuracy under attack at ϵ=0.1\epsilon = 0.1 rises from 37% to 79%. Two caveats. On large datasets, adversarial training usually costs some clean accuracy and several times the compute. And it only protects against roughly the kind and size of attack it was trained on. A stronger attack such as PGD would push the robust model's numbers lower than FGSM does, which is why serious evaluations always use strong, adaptive attacks.

Defences, honestly assessed

  • Adversarial training (with PGD) is the most dependable empirical defence for images. On the RobustBench leaderboard for CIFAR-10 images, the best models' accuracy under strong attack at the standard ϵ=8/255\epsilon = 8/255 remains far below their clean accuracy.
  • Certified defences give a mathematical guarantee that no change within a given ϵ\epsilon can flip the prediction. Randomised smoothing (Cohen and colleagues, 2019) classifies many noisy copies of the input and takes a vote. Guarantees hold only for small ϵ\epsilon and cost accuracy and compute.
  • Input preprocessing and detection (compressing, denoising or flagging suspicious inputs) often look good against simple attacks and fail against attackers who know about them. In 2018, Athalye, Carlini and Wagner bypassed most of the defences published at that year's ICLR conference, many of which worked by hiding the gradient rather than by fixing the model.
  • System design usually matters most in practice: don't let a single model's output trigger a high-stakes action, combine independent signals, rate-limit queries, and keep a human in the loop for consequential decisions.

Watch out A defence evaluated only against FGSM, or against attacks that don't know about the defence, proves very little. The standard of evidence is an adaptive attack: one designed by someone who knows exactly how the defence works.

Jailbreaks: adversarial examples for language models

Chatbots are trained with RLHF and Preference Optimization and similar methods to refuse harmful requests. A jailbreak is an input crafted to make a model ignore that training. Conceptually, jailbreaks are adversarial examples for language models, though the input is discrete text rather than continuous pixels. Wei, Haghtalab and Steinhardt (2023) identified two root causes:

  • Competing objectives. The model is trained both to be helpful and to be harmless. Inputs that frame a harmful request as role-play, fiction or an urgent task set the two goals against each other.
  • Mismatched generalisation. Safety training covers less ground than the model's capabilities. A request in an unusual language, an encoding or an odd format may be understood by the model but fall outside what safety training covered.

Zou and colleagues (2023) made the link to this chapter explicit. They used a gradient-guided search over tokens to find nonsense-looking suffixes that, appended to a request, made open models comply, and found that many of these suffixes transferred to closed commercial models. Transferability again.

Defences mirror those for images: adversarial training on known attack styles, input and output classifiers that screen for harmful content separately from the main model, monitoring for suspicious patterns at scale, and red-teaming, where people and automated systems deliberately try to break the model before release. As of late 2026 no model is jailbreak-proof, and developers treat robustness as an ongoing, measured property rather than a solved problem. See AI Risks and Safety for how this fits into safety evaluation.

Common pitfalls

  • Testing only on clean data. High test accuracy says nothing about robustness. If an adversary could ever touch your inputs, evaluate under attack.
  • Weak evaluation. Use strong, adaptive attacks (PGD with many steps and random restarts, or established suites) before claiming robustness.
  • Gradient masking. A defence that makes gradients useless (by adding randomness or non-differentiable steps) can stop gradient attacks without making the model robust. Black-box and transfer attacks often still work.
  • Wrong threat model. Small-ϵ\epsilon pixel changes are a research convenience. Real attackers may use stickers, rotations, different phrasing or completely new inputs. Decide what the attacker can actually do.
  • Forgetting the training data. Poisoned or backdoored data defeats defences that look only at test-time inputs. Know where your data comes from.

Where it leads

  • Prompt Injection and LLM Security covers the most important practical attack on LLM applications, where the adversarial text arrives inside documents and tool results.
  • Interpretability and Explainability uses the same input gradients to produce saliency maps. Ilyas and colleagues argued in 2019 that adversarial examples exploit "non-robust features": real, predictive patterns in data that humans don't perceive.
  • AI Risks and Safety places adversarial robustness among the broader evaluations done before releasing powerful models.
  • Data Augmentation is the gentle cousin of adversarial training: training on transformed inputs to improve robustness to natural variation.

A bit of history

Attacks on machine-learning spam filters were studied in the mid-2000s, and Biggio and colleagues demonstrated gradient-based evasion attacks in 2013. The same year, Szegedy and colleagues' "Intriguing properties of neural networks" showed that deep image classifiers could be fooled by imperceptible changes, and that the changes transferred between models. In 2014, Goodfellow, Shlens and Szegedy explained the phenomenon by local linearity and introduced FGSM and adversarial training. Madry and colleagues' PGD adversarial training (2017) became the standard defence, and Carlini and Wagner's attacks (2017) the standard test. A wave of broken defences in 2017–2018 established the norm of adaptive evaluation. From 2022, with chatbots in wide use, the focus widened to jailbreaks and prompt injection, and adversarial robustness became a core part of AI security and safety testing.

Try it

  1. Run the code and pick one test image that FGSM flips at ϵ=0.1\epsilon = 0.1. Print the model's top three classes and their probabilities before and after. Does the wrong class look plausible to you?
  2. Replace FGSM with a 10-step PGD attack: repeat x = x + 0.02 * grad.sign() ten times, clipping each time so no pixel moves more than 0.1 from the original. Is PGD stronger than FGSM against the adversarially trained model?
  3. Redo the worked example with ϵ=0.05\epsilon = 0.05. Does the prediction still flip?

Hint for 2: after each step, use torch.max(torch.min(x_adv, x0 + eps), x0 - eps) to stay within ϵ\epsilon of the original x0, then clamp to [0, 1].

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A linear model has weights (2, -1, 3, -2). Each input may move by at most ε = 0.1. By how much can an attacker raise the score at most?

  2. On the digits model, FGSM at ε = 0.2 drops accuracy to under 1%, but random ±0.2 noise leaves 87%. What does this show?

  3. Your team keeps the model's weights secret and concludes it is safe from gradient-based attacks. What is the main flaw in this reasoning?

  4. A new defence is reported to stop FGSM almost completely. What should you ask before trusting it?

  5. An attacker slips a few crafted images with a small sticker pattern into your scraped training data, so the model misbehaves whenever that sticker appears. What kind of attack is this?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Tutorial

Adversarial Robustness: Theory and Practice

Zico Kolter & Aleksander Madry · 2018 · Intermediate · Free

A free online tutorial with PyTorch code covering attacks (FGSM, PGD), adversarial training and certified defences, from two leading researchers.

Tutorial

Adversarial Example Generation

PyTorch · Beginner · Free

The official PyTorch tutorial that attacks an MNIST classifier with FGSM and plots accuracy against epsilon, very close to this chapter's code.

Paper

Intriguing properties of neural networks

Szegedy et al. · 2013 · Advanced · Free

The paper that discovered adversarial examples, showing that imperceptible perturbations fool image classifiers and transfer between models.

Tool

RobustBench

Croce, Andriushchenko et al. · Intermediate · Free

A standardised leaderboard of adversarial robustness for image classifiers, evaluated with strong attacks, plus a library of robust models.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/society/adversarial-examples.md