AI Logic

Adversarial Attacks and Defenses

DeepFool

Updated:

Diagram of DeepFool. Left: the procedure (input; repeat until the prediction changes: output and gradient differences for each class, choose the nearest class under linearized boundaries, step perpendicular to that boundary; finally push slightly past it; adversarial example). Right: a linear 4-class classifier, comparing the distances from x0 in the class 4 region to the three surrounding boundaries F1–F3 and dropping the perpendicular r* to the nearest one, F3

What is DeepFool

DeepFool finds the smallest perturbation needed to change a classifier's prediction by approximating the decision boundaries with straight lines (hyperplanes). Moosavi-Dezfooli, Fawzi, and Frossard proposed it in 2015, and it was presented at CVPR 2016.

Methods for building adversarial examples fall into two groups depending on their goal.

  • Cause as many errors as possible within a fixed size: Like FGSM and PGD, these fix the perturbation size Ξ΅\varepsilon in advance.
  • Find the smallest perturbation needed to cause an error: DeepFool belongs here. The size of the perturbation it finds serves as a measure of how robust the model is around the input xx.

The paper defines the robustness of a classifier k^\hat{k} at an input xx as the size of the smallest perturbation that changes its prediction.

Ξ”(x;k^)=min⁑rΒ βˆ₯rβˆ₯2subjectΒ tok^(x+r)β‰ k^(x)\Delta(x; \hat{k}) = \min_{r} \ \|r\|_2 \quad \text{subject to} \quad \hat{k}(x + r) \ne \hat{k}(x)

Robustness over the whole dataset is then measured as the average normalized by the input size, ρadv(k^)=Ex[Ξ”(x;k^)/βˆ₯xβˆ₯2]\rho_{\mathrm{adv}}(\hat{k}) = \mathbb{E}_x \big[ \Delta(x; \hat{k}) / \|x\|_2 \big]. DeepFool is a method for approximating this Ξ”\Delta quickly and accurately.

As an analogy, it is like a person inside a room (the region of the current predicted class) measuring the distance to the nearest wall (a decision boundary). If the wall is flat, walking perpendicular to it is the shortest path. Even if the wall is curved, treating the wall as flat from where one stands, walking to it, and measuring again on arrival gets one out of the room in just a few steps.

How DeepFool works

Start with a linear binary classifier. When classifying by the sign of f(x)=w⊀x+bf(x) = w^\top x + b, the smallest perturbation that changes the prediction is the perpendicular dropped from x0x_0 to the boundary hyperplane {x:f(x)=0}\{x : f(x) = 0\}.

rβˆ—(x0)=βˆ’f(x0)βˆ₯wβˆ₯22 wr^*(x_0) = -\frac{f(x_0)}{\|w\|_2^2}\, w

For a nonlinear classifier, this is repeated. Around the current point xix_i, ff is approximated by a first-order expression (f(xi)+βˆ‡f(xi)⊀rf(x_i) + \nabla f(x_i)^\top r), and the point moves by the perpendicular to the boundary of that approximation, ri=βˆ’f(xi)βˆ₯βˆ‡f(xi)βˆ₯22βˆ‡f(xi)r_i = -\dfrac{f(x_i)}{\|\nabla f(x_i)\|_2^2} \nabla f(x_i). The process stops when the prediction changes.

For a multiclass classifier (which predicts the class kk with the largest output fkf_k), consider the boundaries between the original prediction k^(x0)\hat{k}(x_0) and each other class kk. For a linear classifier, the region predicted as k^(x0)\hat{k}(x_0) is a polyhedron bounded by boundary hyperplanes, and dropping a perpendicular to the nearest face gives the smallest perturbation (right side of the header figure).

The procedure for a nonlinear classifier (Algorithm 2 in the paper) is as follows.

  1. Set x0=xx_0 = x and compute the original prediction k^(x0)\hat{k}(x_0).
  2. For each class kk other than the original prediction, compute the output difference fkβ€²=fk(xi)βˆ’fk^(x0)(xi)f'_k = f_k(x_i) - f_{\hat{k}(x_0)}(x_i) and the gradient difference wkβ€²=βˆ‡fk(xi)βˆ’βˆ‡fk^(x0)(xi)w'_k = \nabla f_k(x_i) - \nabla f_{\hat{k}(x_0)}(x_i).
  3. Choose the class l^\hat{l} with the smallest distance ∣fkβ€²βˆ£/βˆ₯wkβ€²βˆ₯2|f'_k| / \|w'_k\|_2 to its linearized boundary.
  4. Step perpendicular to that boundary: ri=∣fl^β€²βˆ£βˆ₯wl^β€²βˆ₯22 wl^β€²r_i = \dfrac{|f'_{\hat{l}}|}{\|w'_{\hat{l}}\|_2^2}\, w'_{\hat{l}}, xi+1=xi+rix_{i+1} = x_i + r_i.
  5. Repeat steps 2–4 until the prediction changes from k^(x0)\hat{k}(x_0), and return r^=βˆ‘iri\hat{r} = \sum_i r_i.

So that the point does not stop exactly on the linearized boundary, the paper multiplies the final perturbation by (1+Ξ·)(1 + \eta) (Ξ·=0.02\eta = 0.02 in the experiments).

It works for distances other than β„“2. When measuring by the maximum change of any pixel (β„“βˆž), steps 3 and 4 are replaced with the following.

l^=arg⁑min⁑kβ‰ k^(x0)∣fkβ€²βˆ£βˆ₯wkβ€²βˆ₯1,ri=∣fl^β€²βˆ£βˆ₯wl^β€²βˆ₯1 sign(wl^β€²)\hat{l} = \arg\min_{k \ne \hat{k}(x_0)} \frac{|f'_k|}{\|w'_k\|_1}, \qquad r_i = \frac{|f'_{\hat{l}}|}{\|w'_{\hat{l}}\|_1}\, \mathrm{sign}(w'_{\hat{l}})

In the binary case, DeepFool has the same form as Newton's method for solving the equation f(x)=0f(x) = 0 (in its variant for more unknowns than equations). It can also be viewed as gradient descent with an automatically chosen step size.

Why it finds small perturbations

DeepFool finds small perturbations because it sets both the direction and the size from the shape of the boundary.

  • Direction: It moves perpendicular to the boundary (along the gradient difference wkβ€²w'_k), so it approaches the boundary most efficiently for a given distance. Moving every pixel by the same amount, as FGSM does, spends perturbation on directions that have little to do with the boundary.
  • Size: Using the linear approximation, it moves "exactly" far enough to reach the boundary, so it does not overshoot. FGSM fixes Ξ΅\varepsilon in advance, so it moves by Ξ΅\varepsilon even for inputs whose boundary is much closer.

In the paper's experiments, the prediction changed in fewer than three iterations in most cases.

However, DeepFool is a greedy method that always heads for "the boundary that currently looks closest," and there is no guarantee it reaches the true minimal perturbation. The paper argues that it is a good approximation because the perturbations obtained in experiments are very small.

Experimental results

For the same classifiers, the paper compared the perturbation size ρ^adv\hat{\rho}_{\mathrm{adv}} (the average β„“2 norm of the perturbation divided by the norm of the input; smaller means errors were caused with smaller perturbations) found by DeepFool, FGSM, and the L-BFGS attack of Szegedy et al. FGSM's Ξ΅\varepsilon was set to the smallest value that misclassifies 90% of the data.

Classifier (data)Test errorDeepFoolFGSML-BFGS attack
LeNet (MNIST)1%0.20 (110 ms)1.0 (20 ms)0.25 (> 4 s)
Fully connected 500-150-10 (MNIST)1.7%0.11 (50 ms)0.39 (10 ms)0.12 (> 2 s)
NIN (CIFAR-10)11.5%0.023 (1100 ms)0.12 (180 ms)0.024 (> 50 s)
LeNet (CIFAR-10)22.6%0.030 (220 ms)0.13 (50 ms)0.039 (> 7 s)
CaffeNet (ImageNet)42.6%0.0027 (510 ms)0.035 (50 ms)―
GoogLeNet (ImageNet)31.3%0.0019 (800 ms)0.047 (80 ms)―

The values in parentheses are the time to build one adversarial example (GPU for the two ImageNet rows, CPU for the rest). DeepFool's perturbations were from a fraction to less than one tenth of FGSM's, slightly smaller than the L-BFGS attack's, and found far faster than with the L-BFGS attack. The ImageNet classifiers were misclassified with perturbations about 1/1000 the size of the image.

Fine-tuning on adversarial examples. Each classifier was fine-tuned for 5 epochs at half the learning rate using only DeepFool or FGSM adversarial examples. With DeepFool examples, robustness (ρ^adv\hat{\rho}_{\mathrm{adv}} measured by DeepFool) rose sharply from the first epoch, by about 50% for the MNIST networks and about 40% for NIN. With FGSM examples, robustness sometimes went down instead. Test error changed as follows.

ClassifierTuned with DeepFoolTuned with FGSMBefore tuning
LeNet (MNIST)0.8%4.4%1%
Fully connected 500-150-10 (MNIST)1.5%4.9%1.7%
NIN (CIFAR-10)11.2%21.2%11.5%
LeNet (CIFAR-10)20.0%28.6%22.6%

The paper attributes this to FGSM's perturbations being much larger than the minimal ones: overly large perturbations can change the actual class of a digit, so training on them backfires. Indeed, training with DeepFool perturbations deliberately enlarged by 2Γ— or 3Γ— reduced robustness, and in the paper's figure, an enlarged perturbation turns a "1" into an image that looks like a "7".

Caveats

A large perturbation from DeepFool does not mean the model is robust. DeepFool searches for boundaries using gradients, so it cannot find them in models whose gradients are nearly 0. Carlini and Wagner (2017) showed that in networks trained with defensive distillation, the output softmax sticks almost at 0 or 1, the gradient vanishes, and DeepFool and the L-BFGS attack fail. To evaluate defenses, also use attacks such as the C&W attack and PGD.

  • The target class cannot be chosen: DeepFool causes misclassification into the class beyond the nearest boundary. To cause misclassification into a specific class, use the C&W attack or a similar method.
  • One gradient per class: Each iteration computes gradients for every class other than the original prediction. The more classes there are, the heavier each iteration becomes.
  • The pixel range is not considered: The paper's procedure does not include the range of pixel values (for example, 0–1) as a constraint. When using the result as an image, clip it to the range at the end and check that the prediction is still changed.
  • Comparing robustness: Compare ρ^adv\hat{\rho}_{\mathrm{adv}} only between values measured with the same method. The paper shows examples where measuring robustness with FGSM overestimates the effect of training or misses a drop in robustness.

Comparison with other attacks and how to choose

The table below lines up DeepFool and the attacks it is often compared with along the same criteria.

MethodHow the perturbation is foundPerturbation sizeCostMain use
FGSMTake one step of size Ξ΅\varepsilon in the direction of the gradient's signFixed in advance (Ξ΅\varepsilon)Very lightQuick checks, material for adversarial training
PGDRepeatedly take small steps in the sign direction and project back into the rangeFixed in advance (Ξ΅\varepsilon)ModerateRobustness evaluation within a fixed range, adversarial training
L-BFGS attackMinimize perturbation size + loss with L-BFGS, searching over the coefficientSearches for the minimum (L2)HeavyHistorical method
DeepFoolRepeatedly step perpendicular to the linearized boundarySearches for the minimum (L2, β„“p)Fairly light (a few iterations)Measuring robustness by the minimal perturbation size
C&W attackOptimize the sum of perturbation size and a logit-difference term, searching over the coefficientSearches for the minimum (L0, L2, L∞)HeavyEvaluating defenses, targeted attacks

Rough guidelines for choosing:

  • To quickly quantify a model's robustness over many inputs: Use DeepFool. It needs only a few gradient computations and gives a more accurate size than FGSM.
  • To know how often the model errs within a fixed Ξ΅\varepsilon: Use PGD.
  • To evaluate defenses rigorously or cause misclassification into a specific class: Use the C&W attack. It is heavier than DeepFool, but its loss holds up even against defenses that make gradients vanish.
  • To train a robust model: Fine-tuning on DeepFool adversarial examples also improves robustness, but today PGD-based adversarial training and TRADES are more common.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
DeepFool (Algorithm 2 of Moosavi-Dezfooli et al., 2016, β„“2 case)
  f'_k = f_k(x_i) βˆ’ f_kΜ‚(x_i), w'_k = βˆ‡f_k(x_i) βˆ’ βˆ‡f_kΜ‚(x_i)
  lΜ‚ = argmin_k |f'_k| / β€–w'_kβ€–2, r_i = |f'_lΜ‚| / β€–w'_lΜ‚β€–2Β² Β· w'_lΜ‚
repeat until the prediction changes, then multiply by (1 + Ξ·) at the end (Ξ· = 0.02)
"""

def deepfool(model, x, num_classes=10, overshoot=0.02, max_iter=50):
  # x: [1, C, H, W]. model returns outputs f_k (pre-softmax logits)
  model.eval()  # put BatchNorm and Dropout in inference mode
  x = x.detach()
  with torch.no_grad():
    k0 = model(x).argmax(dim=1).item()  # original prediction kΜ‚(x0)
  r_tot = torch.zeros_like(x)
  for i in range(max_iter):
    # to avoid stopping on the boundary, check the prediction at the point scaled by (1 + Ξ·) too
    x_i = (x + (1 + overshoot) * r_tot).requires_grad_(True)
    out = model(x_i)[0]
    if out.argmax().item() != k0:
      break  # stop once the prediction changes
    grad_k0 = torch.autograd.grad(out[k0], x_i, retain_graph=True)[0]
    best_dist, best_r = None, None
    for k in range(num_classes):
      if k == k0:
        continue
      grad_k = torch.autograd.grad(out[k], x_i, retain_graph=True)[0]
      w_k = grad_k - grad_k0                       # w'_k
      f_k = (out[k] - out[k0]).detach()            # f'_k (negative, since it is below the original prediction)
      w_norm = w_k.norm() + 1e-8
      dist = f_k.abs() / w_norm                    # distance to the linearized boundary
      if best_dist is None or dist < best_dist:
        best_dist = dist
        best_r = (f_k.abs() + 1e-4) / w_norm ** 2 * w_k  # perpendicular to that boundary
    r_tot = r_tot + best_r.detach()
  x_adv = x + (1 + overshoot) * r_tot
  return x_adv.detach(), r_tot.norm().item(), i


# Usage example (assumes a trained classifier model and a single image x)
# x_adv, r_norm, n_iter = deepfool(model, x)
# rho = r_norm / x.norm().item()  # β€–rβ€–2 / β€–xβ€–2 for this input (averaged over the data, this is ρ̂_adv)
# x_adv = x_adv.clamp(0, 1)       # when used as an image, clip to the range and check the prediction is still changed

FAQ

Q. How does DeepFool differ from FGSM?
A.

FGSM fixes the perturbation size Ξ΅\varepsilon in advance and moves every pixel by the same amount in the direction of the gradient's sign. DeepFool does not fix a size; it repeatedly steps perpendicular to the boundary by exactly enough to reach it. In the paper, DeepFool's perturbations were from a fraction to less than one tenth the size of FGSM's.

Q. What are the values found by DeepFool used for?
A.

They serve as a yardstick for model robustness. The larger ρ^adv\hat{\rho}_{\mathrm{adv}}, the average of each input's perturbation size divided by the input size, the larger the perturbation needed to change the prediction, and the more robust the model. It can be used to compare how robustness changes across training methods or architectures.

Q. Can it cause misclassification into a specific class?
A.

DeepFool itself causes misclassification into the class beyond the nearest boundary, and the class cannot be chosen. To cause misclassification into a specific class, use the C&W attack or PGD with a specified target class.

References

  1. S.-M. Moosavi-Dezfooli, A. Fawzi, and P. Frossard, "DeepFool: a simple and accurate method to fool deep neural networks," CVPR, 2016.
  2. I. J. Goodfellow, J. Shlens, and C. Szegedy, "Explaining and Harnessing Adversarial Examples," ICLR, 2015.
  3. C. Szegedy, W. Zaremba, I. Sutskever, J. Bruna, D. Erhan, I. Goodfellow, and R. Fergus, "Intriguing properties of neural networks," ICLR, 2014.
  4. N. Carlini and D. Wagner, "Towards Evaluating the Robustness of Neural Networks," IEEE Symposium on Security and Privacy, pp. 39–57, 2017.