AI Logic

Adversarial Attacks and Defenses

Adversarial Examples (L-BFGS Attack)

Updated:

Diagram of the L-BFGS attack. Left: the flow for building an adversarial example (input and target label, objective function, optimizing the perturbation with box-constrained L-BFGS, line search over the coefficient c, adversarial example). Right: a sketch of the input space reduced to two dimensions, searching from the original input x for the nearest point across the decision boundary, where too large a c falls short and too small a c makes the perturbation large

What are adversarial examples

An adversarial example is an input built to make a model misclassify by adding a small perturbation, almost invisible to the human eye, to an input that is otherwise classified correctly. Szegedy, Zaremba, Sutskever, Bruna, Erhan, Goodfellow, and Fergus reported them in 2013 in the paper "Intriguing properties of neural networks," presented at ICLR 2014.

The paper found adversarial examples by using optimization to search for "an input as close as possible to the original that is classified as a specified class." Because the optimization uses box-constrained L-BFGS (a quasi-Newton method), this construction is called the L-BFGS attack.

The paper's main findings are these three:

  • They exist for every network: For every network examined (a fully connected network on MNIST, AlexNet on ImageNet, and QuocNet trained on YouTube images), adversarial examples close enough to be hard to tell apart could be built for every input.
  • They fool other models too: Many adversarial examples built for one model also caused misclassification in models with a different number of layers or different regularization, and in models trained on different training data.
  • They are not random noise: Random noise of about the same size barely makes the model err. Misclassification comes from perturbations aligned in specific directions.

The left side of the header figure shows the flow of the L-BFGS attack; the right side is a sketch of the input space reduced to two dimensions. Starting from the original input xx, the attack searches for the nearest point in the region of the target label ll.

How the L-BFGS attack works

For a classifier ff, an input x∈Rmx \in \mathbb{R}^m made of pixel values, and a target label ll (a class other than the true one), the paper considers the following problem.

min⁑rΒ βˆ₯rβˆ₯2subjectΒ tof(x+r)=l,x+r∈[0,1]m\min_{r} \ \|r\|_2 \quad \text{subject to} \quad f(x + r) = l,\quad x + r \in [0, 1]^m

In other words, it looks for the input closest to xx among those classified as ll. The paper writes this solution x+rx + r as D(x,l)D(x, l) (the minimum distortion). The second condition is a "box constraint" that keeps pixel values within the range [0,1][0, 1].

Since solving this problem directly is hard, the condition f(x+r)=lf(x + r) = l is replaced by a loss term, and the following problem is solved with box-constrained L-BFGS.

min⁑rΒ cβ€‰βˆ£r∣+lossf(x+r, l)subjectΒ tox+r∈[0,1]m\min_{r} \ c\,|r| + \mathrm{loss}_f(x + r,\, l) \quad \text{subject to} \quad x + r \in [0, 1]^m

Here, lossf\mathrm{loss}_f is the model's loss (cross-entropy for classification), which gets smaller the more likely x+rx + r is to be classified as ll. c>0c > 0 is a coefficient that sets the balance between keeping the perturbation small and achieving misclassification.

The procedure is as follows.

  1. Choose the target label ll and candidate values for the coefficient cc.
  2. Pick one cc, solve the problem above with box-constrained L-BFGS, and obtain the perturbation rr. The gradient is the derivative of the loss with respect to the input, computed by backpropagation. The weights are not changed.
  3. Check whether f(x+r)=lf(x + r) = l holds.
  4. Repeat steps 2–3 with different values of cc (a line search), and adopt the solution with the smallest perturbation among those classified as ll.

If cc is too large, keeping the perturbation small takes priority and the input never reaches ll. If it is too small, the input is classified as ll, but the perturbation becomes larger than necessary (right side of the header figure).

If the loss is convex, this substitution gives the exact solution of the original problem. Because neural network losses are not convex, the result is an approximation. Later, Carlini and Wagner (2017) reformulated this method as an attack that "minimizes c βˆ₯xβˆ’xβ€²βˆ₯22+lossF,l(xβ€²)c\,\|x - x'\|_2^2 + \mathrm{loss}_{F,l}(x') and tunes cc by binary search or similar."

Properties revealed by the paper

The paper's experiments were mainly run on fully connected networks for MNIST (pixel values in 0–1). The size of a perturbation is measured as the root mean square of the difference between the original image xx and the adversarial example xβ€²x', βˆ‘i(xiβ€²βˆ’xi)2/n\sqrt{\sum_i (x'_i - x_i)^2 / n} (n=784n = 784 pixels).

Small perturbations work for every model. The table below shows the average perturbation size needed to bring accuracy on the entire training set to 0%.

ModelTest errorAverage perturbation needed
Softmax regression (Weight Decay Ξ»=10βˆ’4\lambda = 10^{-4})7.4%0.062
Softmax regression (Ξ»=1\lambda = 1)20%0.14
Sigmoid network with 2 hidden layers (100-100-10)1.64%0.058
Sigmoid network with 2 hidden layers (200-200-10)1.54%0.065
Autoencoder features + softmax (AE400-10)1.9%0.086

With AlexNet on ImageNet as well, adversarial examples could be built so that randomly chosen images were all classified as "ostrich." The average perturbation size over 64 images is 0.006508.

They fool other models (transfer). Below are some of the error rates when adversarial examples built for one model are fed to another. For comparison, the value for random noise of about the same size is also listed.

Source model β†’ target modelError rate
Softmax regression (Ξ»=10βˆ’2\lambda = 10^{-2}) β†’ softmax regression (Ξ»=10βˆ’4\lambda = 10^{-4})87.1%
200-200-10 β†’ softmax regression (Ξ»=10βˆ’4\lambda = 10^{-4})38.2%
100-100-10 β†’ softmax regression (Ξ»=10βˆ’4\lambda = 10^{-4})28.9%
Random noise (standard deviation 0.1) β†’ 100-100-100%

They fool models trained on different data. The MNIST training data was split into two halves of 30,000 images each (P1 and P2), and models trained on each were tested. Adversarial examples built for a 100-100-10 model trained on P1 (perturbation size 0.062) caused 26.2% error on a model of a different shape (123-456-10) trained on P1, and 5.9% error on a 100-100-10 model trained on P2. Strengthening the perturbation to size 0.1 raised these to 98% and 43%, respectively. Random noise of the same size gave 2.2–2.8% for every model.

How much an input visibly changes and how much it affects the model do not match. In the paper, MNIST images with random noise of standard deviation 1, strong enough to make them unreadable, still kept 51% accuracy. Adversarial examples, on the other hand, look to people like nothing but the original digits, yet accuracy on them was 0%.

The paper also reports a preliminary experiment that mixes adversarial examples into training. For a 100-100-10 network, continually generating a pool of adversarial examples and mixing it with the original training data brought the test error below 1.2%. Weight Decay alone gave 1.6%, and careful use of dropout gave about 1.3%, so generalization improved. However, the effect appeared only when adversarial examples were generated not just for the input but also for the outputs of each layer. This idea leads to the later adversarial training with FGSM and PGD.

Why they occur: the paper's view and later explanations

In image classification, one usually expects that "changing the input only slightly does not change the classification" (the output is smooth near the input). Adversarial examples show that, in deep networks, places where this expectation fails exist near almost every input.

The paper reasoned about the cause as follows.

  • Low probability, but everywhere: Adversarial examples lie in "pockets" that are very unlikely to arise from the ordinary data distribution, so they are not found in test data. Even so, the view is that they exist right next to almost every input, just as rational numbers are found everywhere on the number line. This is why randomly perturbing inputs does not find them.
  • Each layer can greatly amplify its output: For each layer, the paper computed an upper bound LkL_k (a Lipschitz constant) on how much the output can change for an input change rr, using the operator norm (largest singular value) of the weights. For the whole network, βˆ₯Ο•(x)βˆ’Ο•(x+r)βˆ₯≀Lβˆ₯rβˆ₯\|\phi(x) - \phi(x + r)\| \le L \|r\| with L=∏kLkL = \prod_k L_k. For AlexNet, values greater than 1 appear, such as 2.75 for the first convolutional layer and 11 for the fifth, showing that instability can arise from the very first layer.

However, this is an upper bound, so a large value does not guarantee that adversarial examples exist. Conversely, a small bound guarantees that they do not arise, so the paper proposes regularization that penalizes this bound. The idea of constraining each layer's operator norm is also used later in Spectral Normalization.

The following year, Goodfellow and colleagues (Goodfellow was one of the same authors) re-explained the cause as the network's nearly linear behavior. Even if each pixel changes only slightly, when the input dimension is large, the small changes add up in the inner product with the weights and move the output a lot. From this explanation came FGSM, which builds an adversarial example in a single step using only the sign of the gradient.

Caveats

The L-BFGS attack is slow. For each input, it solves the L-BFGS optimization many times while varying the coefficient cc. It is unsuited to testing many inputs or to being built into training; today FGSM, PGD, and the C&W attack are used instead.

  • Results depend on the shape of the loss: Carlini and Wagner (2017) showed that in networks trained with defensive distillation, the output softmax sticks almost at 0 or 1, the loss gradient vanishes, and L-BFGS barely moves before stopping. A failed L-BFGS attack does not mean that no adversarial examples exist.
  • It assumes white-box access: Because it uses the gradient with respect to the input, the model's architecture and weights must be known. However, since the resulting adversarial examples transfer to other models, they can be built on a local model and used to test a different one.
  • It is a targeted attack: It specifies a label ll and causes misclassification into that class. If "anything but the true class" is enough, the attack is run several times with different labels and the one with the smallest perturbation is chosen.
  • How distance is measured: The L-BFGS attack measures the size of the perturbation with the L2 distance (square root of the sum of squared differences). FGSM and PGD constrain the maximum change of any pixel (the L∞ distance), so the same "small perturbation" is measured differently.

Comparison with other attacks and how to choose

The table below lines up the L-BFGS attack and the attacks that followed it along the same criteria.

MethodHow the perturbation is foundDistanceCostMain use
L-BFGS attackMinimize perturbation size + loss with box-constrained L-BFGS, and search over the coefficient ccL2HeavyShowing that adversarial examples exist (historical method)
FGSMTake a single step in the direction of the gradient's signL∞Light (1 gradient)Quick checks, material for adversarial training
PGDRepeatedly take small steps along the gradient and project back into the allowed regionL∞, etc.ModerateStandard for robustness evaluation and adversarial training
DeepFoolRepeatedly linearize the decision boundary and step to the nearest point on itL2, etc.Fairly lightMeasuring the minimum perturbation needed to misclassify
C&W attackOptimize the sum of perturbation size and a logit-difference termL0, L2, L∞HeavyEvaluating defenses

Rough guidelines for choosing:

  • To understand what adversarial examples are, or to reproduce the paper's experiments: Use the L-BFGS attack. Its definition, "the nearest input of a different class," maps directly onto an optimization problem.
  • To find a near-minimal perturbation in L2 distance: Use the C&W attack, which refines the idea of the L-BFGS attack, or DeepFool.
  • To evaluate model robustness or to do adversarial training: Use PGD. To tune the trade-off between robustness and accuracy, training methods such as TRADES are also available.

PyTorch example

Show code
python
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.optimize import fmin_l_bfgs_b

"""
L-BFGS attack of Szegedy et al. (2014):
  minimize c·|r| + loss_f(x + r, l)  subject to x + r ∈ [0, 1]^m
is solved with box-constrained L-BFGS (SciPy's L-BFGS-B); c is searched to pick the smallest r classified as l.
Here the squared L2 norm is used for the perturbation-size term so that it is easy to differentiate.
"""

def lbfgs_attack(model, x, target, c_values=(10.0, 3.0, 1.0, 0.3, 0.1, 0.03, 0.01), max_iter=100):
  # x: [1, C, H, W] (pixel values in 0-1), target: target label l (int)
  model.eval()  # put BatchNorm and Dropout in inference mode (weights are not changed)
  x_np = x.detach().cpu().numpy().astype(np.float64).ravel()
  target_t = torch.tensor([target], device=x.device)
  bounds = [(0.0, 1.0)] * x_np.size  # box constraint: keep each pixel of x + r within 0-1

  def objective(x_adv_flat, c):
    x_adv = torch.tensor(x_adv_flat.reshape(x.shape), dtype=x.dtype, device=x.device, requires_grad=True)
    r = x_adv - x
    loss = c * (r ** 2).sum() + F.cross_entropy(model(x_adv), target_t)
    grad = torch.autograd.grad(loss, x_adv)[0]  # gradient with respect to the input
    return loss.item(), grad.detach().cpu().numpy().astype(np.float64).ravel()

  best = None
  for c in c_values:  # try c from largest to smallest; keep the smallest r among solutions classified as l
    x_adv_flat, _, _ = fmin_l_bfgs_b(objective, x_np.copy(), args=(c,), bounds=bounds, maxiter=max_iter)
    x_adv = torch.tensor(x_adv_flat.reshape(x.shape), dtype=x.dtype, device=x.device)
    with torch.no_grad():
      success = model(x_adv).argmax(dim=1).item() == target
    if success:
      dist = (x_adv - x).norm().item()  # β€–rβ€–2
      if best is None or dist < best[1]:
        best = (x_adv, dist, c)
  return best  # (adversarial example, β€–rβ€–2, c used). None if not found


# Usage example (assumes a trained MNIST classifier model and a correctly classified image x)
# result = lbfgs_attack(model, x, target=3)
# if result is not None:
#   x_adv, dist, c = result
#   rms = dist / x.numel() ** 0.5  # perturbation size from the paper: sqrt(Ξ£(x'-x)^2 / n)
#   print(f"β€–rβ€–2 = {dist:.4f}, RMS = {rms:.4f}, c = {c}")

FAQ

Q. How do adversarial examples differ from random noise?
A.

They differ in direction. Random noise points in scattered directions, so even when it is made larger the model rarely errs. In the paper, noise with standard deviation 0.1 gave a 0% error rate on the 100-100-10 network. The perturbation of an adversarial example is aligned with the direction in which the loss increases (toward the target class), so it causes misclassification even when it is smaller than that.

Q. When should the L-BFGS attack be used instead of FGSM?
A.

The L-BFGS attack uses optimization to search for the nearest input classified as the target class, so its perturbations are small, but it is slow because it solves the optimization many times per input. FGSM only takes one step in the direction of the gradient's sign, so it is fast and well suited as material for adversarial training. To find a near-minimal perturbation, the usual choice is the C&W attack, which refines the L-BFGS attack.

Q. Are adversarial examples only a problem for images?
A.

The paper studied image classifiers, but for any model whose gradient with respect to the input can be computed, perturbations can be searched for in the same way. The paper's view is that the mapping from inputs to outputs in deep networks is not smooth near almost every input, which is not specific to any particular kind of data.

References

  1. C. Szegedy, W. Zaremba, I. Sutskever, J. Bruna, D. Erhan, I. Goodfellow, and R. Fergus, "Intriguing properties of neural networks," ICLR, 2014.
  2. I. J. Goodfellow, J. Shlens, and C. Szegedy, "Explaining and Harnessing Adversarial Examples," ICLR, 2015.
  3. N. Carlini and D. Wagner, "Towards Evaluating the Robustness of Neural Networks," IEEE Symposium on Security and Privacy, pp. 39–57, 2017.