Search

Search papers and lessons

Adversarial Training

Level 4 · 13 min read

Adversarial training teaches a model on deliberately perturbed inputs, so it learns to keep its answer when an attacker nudges the input within a small budget.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Linear algebra
  • Neural network basics
  • Losses & regularization
  • Probability
  • ReadReady to readNot yet

TL;DR

Adversarial training is a way to make a model harder to fool. At each training step, the method first finds, for each training input, the small change that hurts the model most, then updates the model so that it does well on the changed input as well as the original. The model gets better at keeping its answer under the attacks it was trained against, usually at a cost in accuracy on ordinary inputs and in training time.

Builds on: Adversarial Examples, Minimax Game, Backpropagation · Leads to: the fast gradient sign method as the cheap attack used in training, and robust training methods beyond it

Where it's used

Image classifiers in safety-sensitive settings. A vision model that reads road signs or pedestrians is checked by attacking it with small, targeted changes, and adversarial training is the most common way to improve its results under those attacks. The benefit is measured as accuracy on attacked inputs, not only on the clean test set.

Malware and spam detection. A detector that looks at file features or message text can be probed by an attacker who learns which features to change. Training the detector on attacked examples, produced with changes the attacker can really make, is one of the standard defences in this area.

Research benchmarks for robustness. Many papers report a model's accuracy under a fixed attack and budget, for example a small change to each pixel on a standard image dataset. Adversarially trained models are the baseline that new defences are compared against.

How it works

Take a tiny model that predicts a number: y^=wx\hat y = w x, with loss L=12(y^−y)2L = \tfrac{1}{2}(\hat y - y)^2. The current weight is w=1w = 1. One training example has input x=1x = 1 and target y=2y = 2. The attacker may change the input by at most ε=0.5\varepsilon = 0.5 in either direction. The learning rate is α=0.1\alpha = 0.1.

  1. Measure the clean loss. The prediction is 1×1=11 \times 1 = 1, and the error is 1−2=−11 - 2 = -1. The loss is 12(−1)2=0.5\tfrac{1}{2}(-1)^2 = 0.5. Check: the model is off by one unit, so the loss is half of 1.
  2. Find the worst change. The attacker may move xx anywhere in [0.5,1.5][0.5, 1.5]. Moving xx down makes the prediction smaller, which makes the error more negative and the loss larger. So the worst change is the largest move down, x′=1−0.5=0.5x' = 1 - 0.5 = 0.5. Check: the loss at x′=0.5x' = 0.5 is 12(0.5−2)2=1.125\tfrac{1}{2}(0.5 - 2)^2 = 1.125, larger than at x=1x = 1.
  3. Compute the gradient at the attacked input. The gradient of the loss with respect to ww is (y^−y)⋅x′(\hat y - y) \cdot x'. Here y^=1×0.5=0.5\hat y = 1 \times 0.5 = 0.5, so the gradient is (0.5−2)×0.5=−0.75(0.5 - 2) \times 0.5 = -0.75. Check: the sign is negative, so increasing ww lowers the loss on the attacked input.
  4. Step the weight. w←w−α×(−0.75)=1+0.075w \leftarrow w - \alpha \times (-0.75) = 1 + 0.075. The new weight is w=1.075w = 1.075. Check: the weight rose, which is the direction the gradient asked for.
  5. Look at the clean input again. The prediction is now 1.075×1=1.0751.075 \times 1 = 1.075, and the clean loss is 12(1.075−2)2=0.428\tfrac{1}{2}(1.075 - 2)^2 = 0.428. It fell from 0.50.5. Check: the model is closer to the target on the original input, as well as on the attacked one.
−0.4−0.200.20.400.511.5change to the inputloss
  • loss at change x
The attacker picks the point with the largest loss inside the budget. Here that is the left end, at change -0.5, with loss 1.125. The clean input (change 0) has loss 0.5.

The math

Setting

Let θ\theta be all the weights of the model, fθf_\theta the model, and L(θ,x,y)L(\theta, x, y) the Loss Function on input xx with label yy. The attacker's budget is an ε\varepsilon-ball in the infinity norm: a change δ\delta is allowed if every entry of δ\delta has size at most ε\varepsilon, written ∥δ∥∞≤ε\|\delta\|_\infty \le \varepsilon. The infinity norm ∥δ∥∞\|\delta\|_\infty is the largest absolute value among the entries (see Vector Norm). The training data is a distribution over pairs (x,y)(x, y).

Step 1 in symbols: the objective is a minimax

Adversarial training solves

min⁡θ  E(x,y)[max⁡∥δ∥∞≤εL(θ,x+δ,y)].\min_{\theta} \; \mathbb{E}_{(x,y)} \left[ \max_{\|\delta\|_\infty \le \varepsilon} L(\theta, x + \delta, y) \right].

The inner maximum is the attacker: for each example, find the change that makes the loss largest. The outer minimum is the learner: choose θ\theta so that this worst-case loss is small. This is a Minimax Game in which the two players' gains are opposite.

Step 2 in symbols: the attack

Approximate the loss around xx with a first-order step, L(θ,x+δ,y)≈L(θ,x,y)+∇xL⋅δL(\theta, x + \delta, y) \approx L(\theta, x, y) + \nabla_x L \cdot \delta. To make this as large as possible inside the box, choose each entry of δ\delta to have the sign of the gradient and size ε\varepsilon:

xadv=x+ε sign(∇xL(θ,x,y)).x_{\text{adv}} = x + \varepsilon \, \mathrm{sign}\big(\nabla_x L(\theta, x, y)\big).

This is the Fast Gradient Sign Method. In the walkthrough, ∇xL=(y^−y)⋅w=(1−2)×1=−1\nabla_x L = (\hat y - y) \cdot w = (1 - 2) \times 1 = -1, so sign=−1\mathrm{sign} = -1 and xadv=1−0.5=0.5x_{\text{adv}} = 1 - 0.5 = 0.5. Check: this matches step 2 of the walkthrough.

A stronger attack takes several smaller steps and projects back into the box after each one. This is projected gradient descent, with KK steps of size η\eta:

x(k+1)=clip[x−ε, x+ε](x(k)+η sign(∇xL(θ,x(k),y))).x^{(k+1)} = \mathrm{clip}_{[x - \varepsilon, \, x + \varepsilon]}\Big( x^{(k)} + \eta \, \mathrm{sign}\big(\nabla_x L(\theta, x^{(k)}, y)\big) \Big).

Step 3 in symbols: the learner's update

Danskin's theorem, a standard result about maxima, says that under mild conditions the worst-case loss changes with θ\theta at the same rate as the loss at the worst input, so the gradient of the inner maximum with respect to θ\theta equals the gradient of the loss at the maximising input. So the learner can treat xadvx_{\text{adv}} as a fixed input and take an ordinary Gradient Descent step:

θ←θ−α ∇θL(θ,xadv,y).\theta \leftarrow \theta - \alpha \, \nabla_\theta L(\theta, x_{\text{adv}}, y).

In the walkthrough, ∇wL(w,0.5,2)=(0.5−2)×0.5=−0.75\nabla_w L(w, 0.5, 2) = (0.5 - 2) \times 0.5 = -0.75, and the step gives w=1+0.1×0.75=1.075w = 1 + 0.1 \times 0.75 = 1.075.

Step 4 in symbols: mixing clean and attacked losses

Many implementations train on a weighted mix of the two losses, with λ∈[0,1]\lambda \in [0, 1]:

Lmix=λ L(θ,x,y)+(1−λ) L(θ,xadv,y).L_{\text{mix}} = \lambda \, L(\theta, x, y) + (1 - \lambda) \, L(\theta, x_{\text{adv}}, y).

With λ=0.5\lambda = 0.5 and the numbers above, Lmix=0.5×0.5+0.5×1.125=0.8125L_{\text{mix}} = 0.5 \times 0.5 + 0.5 \times 1.125 = 0.8125. The mix keeps the model accurate on clean inputs while it learns the attacked ones.

Worked examples

Example
Example 1: one attack, one update

A model predicts y^=wx\hat y = w x with weight w=2w = 2. The input is x=1x = 1, the target is y=2.5y = 2.5, the budget is ε=0.5\varepsilon = 0.5, and the learning rate is α=0.2\alpha = 0.2.

  1. Clean prediction: 2×1=22 \times 1 = 2. Clean loss: 12(2−2.5)2=0.125\tfrac{1}{2}(2 - 2.5)^2 = 0.125.
  2. The loss as a function of the change δ\delta is 12(2(1+δ)−2.5)2=12(2δ−0.5)2\tfrac{1}{2}(2(1 + \delta) - 2.5)^2 = \tfrac{1}{2}(2\delta - 0.5)^2.
  3. On δ∈[−0.5,0.5]\delta \in [-0.5, 0.5], the largest value is at δ=−0.5\delta = -0.5, where 2δ−0.5=−1.52\delta - 0.5 = -1.5. Attacked loss: 12(1.5)2=1.125\tfrac{1}{2}(1.5)^2 = 1.125.
  4. The attacked input is xadv=0.5x_{\text{adv}} = 0.5. The gradient with respect to ww is (wxadv−y)⋅xadv=(1−2.5)×0.5=−0.75(w x_{\text{adv}} - y) \cdot x_{\text{adv}} = (1 - 2.5) \times 0.5 = -0.75.
  5. Update: w←2−0.2×(−0.75)=2.15w \leftarrow 2 - 0.2 \times (-0.75) = 2.15.
  6. New clean prediction: 2.152.15. New clean loss: 12(2.15−2.5)2=0.061\tfrac{1}{2}(2.15 - 2.5)^2 = 0.061. It fell from 0.1250.125.

Interpretation: the update made the model better at the original input as well as the attacked one. Here the attacked and clean inputs pulled the weight in the same direction, which is not always the case.

Example
Example 2: a robust decision needs a large enough margin

A linear classifier with weights ww and bias 00 predicts positive when s(x)=w⋅x>0s(x) = w \cdot x > 0. The input x=(3,1)x = (3, 1) is positive and correct. The budget is ε=0.5\varepsilon = 0.5 per value. Compare two models.

  1. Model A has w=(1,−2)w = (1, -2). Clean score: 1×3−2×1=11 \times 3 - 2 \times 1 = 1, which is positive.
  2. The worst change for model A pushes the score down by ε∥w∥1=0.5×3=1.5\varepsilon \|w\|_1 = 0.5 \times 3 = 1.5. Attacked score: 1−1.5=−0.51 - 1.5 = -0.5, which is negative. Model A fails under attack.
  3. Model B has w=(2,−1)w = (2, -1). Clean score: 2×3−1=52 \times 3 - 1 = 5.
  4. The worst change for model B pushes the score down by 0.5×(2+1)=1.50.5 \times (2 + 1) = 1.5. Attacked score: 5−1.5=3.55 - 1.5 = 3.5, which is positive. Model B keeps its answer.
  5. Check: the change for B is δ=−0.5⋅sign(w)=(−0.5,0.5)\delta = -0.5 \cdot \mathrm{sign}(w) = (-0.5, 0.5), and w⋅δ=−1−0.5=−1.5w \cdot \delta = -1 - 0.5 = -1.5, as step 4 says.

Interpretation: both models are correct on the clean input, but only B has a margin larger than the total budget effect. Adversarial training pushes the model toward B-like weights, where the margin on the training data is big compared with the budget.

Example
Example 3: the cost of an attack in every step

A training run for an image model takes 3 hours on clean data per full pass over the dataset. The adversarial version uses a 7-step attack inside each training step.

  1. Each clean training step needs one forward and one backward pass.
  2. Each attack step needs one more forward and backward pass to compute the gradient with respect to the input, so a 7-step attack adds 7 passes.
  3. Total passes per training step: 1+7=81 + 7 = 8.
  4. Compute ratio against clean training: 88.
  5. Adversarial training time: 3×8=243 \times 8 = 24 hours per pass over the dataset.
  6. Try it: if the attack is cut to 3 steps, what is the ratio and the time? Answer: the ratio is 1+3=41 + 3 = 4, and the time is 3×4=123 \times 4 = 12 hours.

Interpretation: the price of a stronger attack is paid in training time, and this is one reason a cheaper one-step attack is used in many experiments. The attack is part of the training loop, so its cost compounds across every step.

Common mistakes and tradeoffs

It is tempting to think that adversarial training makes a model robust to every attack. In fact it helps against the attacks it was trained on, and its robustness can be weaker against a different or stronger attack. Robustness claims must be tested with attacks the defender did not use in training.

It is tempting to think that training on a weak one-step attack is enough. In fact a model can learn to hide its gradient, so the one-step attack finds a weak direction while a stronger attack still succeeds. This is called gradient masking, and it can make a model look robust when it is not. Multi-step attacks are the standard check.

It is tempting to think that the robust model will be as accurate as before. In fact there is usually a tradeoff: accuracy on clean inputs tends to fall, because the model must keep a larger margin. This is a version of the Bias-Variance Tradeoff: the model gives up some fit to the clean data to become less sensitive to small changes.

When to use it. Use adversarial training when inputs can be chosen by an adversary and a wrong answer has real costs, and when you can afford the extra training time. Test it with a range of attacks before trusting it.

When not to use it. If inputs are not chosen by anyone and the main risk is noise or distribution shift, it may cost accuracy for little benefit. In that case Data Augmentation, which applies ordinary transformations such as crops and flips, is cheaper and often enough.

Alternatives. Input preprocessing and detectors can be useful, but a determined attacker who knows the defence can often get around them. Certified defences give a guaranteed robust answer for a radius around each input, usually at a cost in accuracy and compute, but the guarantee holds for the stated budget only.

History

In 2013, Szegedy and colleagues showed that deep image networks could be fooled by small, carefully computed changes. In 2014 Goodfellow, Shlens and Szegedy proposed training on such changes as a regulariser, and introduced the Fast Gradient Sign Method to generate them cheaply. Their paper argued that the phenomenon is tied to the linear behaviour of models in high dimensions.

In 2017 Madry and colleagues framed adversarial training as the minimax problem above, and trained with a multi-step projected gradient attack. That made the training objective precise and gave a stronger benchmark, and it became the reference point for later robustness work. The field still struggles with the cost of training and with the gap between robustness to known attacks and robustness in general.

Recap

  • Adversarial training solves a minimax problem: the model minimises the loss an attacker can achieve inside a small budget.
  • Each step has two parts: find the worst change for each input, then update the model on the changed input, usually mixed with the clean loss.
  • The fast gradient sign method gives a one-step attack; projected gradient descent gives a stronger multi-step one.
  • Robustness is gained against the attacks used in training, usually at a cost in clean accuracy and in training time.
  • Gradient masking can make a weak attack look unsuccessful, so test with stronger attacks.
  • Read next: Fast Gradient Sign Method for the attack used in the inner loop, and Data Augmentation for a cheaper approach to variety in training data.

Check yourself

QuestionRecall: what is the inner maximisation in the adversarial training objective, and what is the outer minimisation?Show answer
The inner maximisation finds, for each training input, the change inside the budget that makes the loss largest. This is the attacker. The outer minimisation chooses the model weights so that this worst-case loss is small. This is the learner.
QuestionCompute: a model has w=1w = 1, input x=1x = 1, target y=2y = 2, budget ε=0.5\varepsilon = 0.5. The FGSM attack gives xadv=0.5x_{\text{adv}} = 0.5. What is the gradient of the loss with respect to ww at xadvx_{\text{adv}}, using L=12(wx−y)2L = \tfrac{1}{2}(wx - y)^2?Show answer
The gradient is (wxadv−y)⋅xadv=(0.5−2)×0.5=−0.75(w x_{\text{adv}} - y) \cdot x_{\text{adv}} = (0.5 - 2) \times 0.5 = -0.75.
QuestionWhy: why does a model trained only against a one-step attack sometimes look robust but fail under a multi-step attack?Show answer
The one-step attack uses the gradient at a single point, and the model can change its local shape so that this gradient points in a weak direction, while the loss still rises a lot a few steps away. This is gradient masking. A multi-step attack explores more of the budget and finds the points the model is weak against.
QuestionApplied: a company wants its document classifier to resist people who edit documents to fool it, and its clean accuracy is already close to the limit of its data. What should it weigh before adding adversarial training?Show answer
It should weigh the expected drop in clean accuracy against the benefit under realistic attacks, and check how much an attacker can really change the text while keeping its meaning. It should also budget the extra training time from the attack steps, and test against attacks it did not use in training, since the robustness gained may be narrow.

Sources

  • Goodfellow, Shlens and Szegedy, Explaining and Harnessing Adversarial Examples (arXiv:1412.6572).
  • Madry et al., Towards Deep Learning Models Resistant to Adversarial Attacks (arXiv:1706.06083).
  • Adversarial machine learning, Wikipedia.