AI Logic

Adversarial Attacks and Defenses

Fast Gradient Sign Method (FGSM)

Updated:

Diagram of FGSM. Left: the flow for creating an adversarial example (input and label, trained model, loss, gradient with respect to the input, take the sign and multiply by ε, add to the input). Right: a numerical example in which adding a ±ε perturbation to an abstract 6 × 6 input leaves it looking almost the same but changes a linear model's prediction from class A to B

What is FGSM

FGSM (Fast Gradient Sign Method) is a technique for creating inputs that make a model misclassify (adversarial examples) by adding small noise that is almost invisible to the human eye. It was proposed by Goodfellow, Shlens, and Szegedy in 2014 and presented at ICLR 2015.

The method takes only the "sign" of the gradient of the loss with respect to the input and shifts every pixel by the same amount ε\varepsilon in the direction that increases the loss.

x~=x+ε⋅sign(∇xJ(θ,x,y))\tilde{x} = x + \varepsilon \cdot \mathrm{sign}\big(\nabla_x J(\theta, x, y)\big)

Here, xx is the original input, yy is its label, θ\theta is the model's weights, JJ is the loss used for training (cross-entropy for classification), and ∇xJ\nabla_x J is the gradient of the loss with respect to the input xx. sign\mathrm{sign} is a function that returns +1+1 for positive values and −1-1 for negative values. ε\varepsilon is the upper bound on the size of the shift and is chosen by hand.

Computing the gradient takes only one pass of backpropagation, so, as the name says, adversarial examples can be created fast. The earlier method (the L-BFGS-based method of Szegedy et al., 2014) had to solve an optimization problem for each input and was slow.

In the paper, an image that GoogLeNet trained on ImageNet classified as "panda" with 57.7% confidence was classified as "gibbon" with 99.3% confidence after FGSM noise with ε=0.007\varepsilon = 0.007 was added, even though it looked unchanged. This ε\varepsilon corresponds to one brightness step of an 8-bit image.

How to create adversarial examples

The steps for creating an adversarial example with FGSM are as follows.

  1. Pass the input xx through the trained model and compute the loss J(θ,x,y)J(\theta, x, y) against the label yy.
  2. Compute the gradient of the loss with respect to the input xx, ∇xJ\nabla_x J, by backpropagation.
    • During training, the gradient is taken with respect to the weights θ\theta to update them; FGSM leaves the weights unchanged and changes the input instead.
  3. Take the sign of the gradient and multiply it by ε\varepsilon to obtain the perturbation (noise) η=ε⋅sign(∇xJ)\eta = \varepsilon \cdot \mathrm{sign}(\nabla_x J).
  4. Add the perturbation to the input. For images, the pixel values are usually clipped so that they stay within the valid range (for example, 0 to 1).

Each pixel of the perturbation has a magnitude of exactly ε\varepsilon, so no pixel changes by more than ε\varepsilon (∥η∥∞≤ε\|\eta\|_\infty \le \varepsilon, where ∥⋅∥∞\|\cdot\|_\infty is the maximum absolute value of the elements). FGSM finds the perturbation that maximizes the loss under this constraint by approximating the loss with a straight line.

The method assumes that the attacker knows the model's architecture and weights and can compute gradients (white-box). However, adversarial examples crafted on one model are known to often fool other models as well.

Why small noise fools models: the linearity explanation

The paper's main claim is that the primary cause of adversarial examples is not the complex nonlinearity of neural networks but their nearly linear behavior.

When an input with a perturbation η\eta added, x~=x+η\tilde{x} = x + \eta, is fed to a linear model with weights ww, the output changes as follows.

w⊤x~=w⊤x+w⊤ηw^\top \tilde{x} = w^\top x + w^\top \eta

To maximize w⊤ηw^\top \eta under the constraint that each element has magnitude at most ε\varepsilon, set η=ε⋅sign(w)\eta = \varepsilon \cdot \mathrm{sign}(w). The change in the output is then ε∑i∣wi∣\varepsilon \sum_i |w_i|. If the average magnitude of the weight elements is mm and the input dimension is nn, the change becomes εmn\varepsilon m n.

Even when ε\varepsilon is small, if the dimension nn is large, the small changes add up and the output changes greatly. For example, even with ε=0.01\varepsilon = 0.01 and m=0.01m = 0.01, a 224 × 224 color image (n=150,528n = 150{,}528) gives a change of about 15. Each pixel changes by an invisibly small amount, yet the output moves a lot.

The right side of the figure at the top shows an example with a small 36-pixel input and a linear model. A shift of only ε=0.1\varepsilon = 0.1 changes the output by −0.1×15.4≈−1.54-0.1 \times 15.4 \approx -1.54, and the prediction flips from class A to B.

In neural networks too, ReLU, LSTM, and maxout are deliberately designed to behave nearly linearly so that they are easy to train. As a result, like linear models, they are fooled by small perturbations in the direction of the gradient's sign.

The error rates under FGSM reported in the paper are as follows (ε=0.25\varepsilon = 0.25 on MNIST with pixel values in 0 to 1, and ε=0.1\varepsilon = 0.1 on CIFAR-10).

DataModelError rate on adversarial examplesAverage confidence on errors
MNISTSoftmax regression (shallow model)99.9%79.3%
MNISTMaxout network89.4%97.6%
CIFAR-10Convolutional maxout network87.15%96.6%

The important point is that the models not only make mistakes but make mistakes with high confidence. This shows that defenses that flag suspicious inputs by their confidence are unlikely to work well.

Adversarial training with FGSM

The paper also proposes adversarial training, which mixes adversarial examples created by FGSM into training. The loss becomes a weighted sum of the loss on the original input and the loss on the FGSM adversarial example.

J~(θ,x,y)=α J(θ,x,y)+(1−α) J(θ,  x+ε⋅sign(∇xJ(θ,x,y)),  y)\tilde{J}(\theta, x, y) = \alpha\, J(\theta, x, y) + (1 - \alpha)\, J\big(\theta,\; x + \varepsilon \cdot \mathrm{sign}(\nabla_x J(\theta, x, y)),\; y\big)

Here, α\alpha is the ratio between the two losses; the paper uses α=0.5\alpha = 0.5 in all experiments. The adversarial examples are regenerated each time from the model at that point in training.

For a maxout network on MNIST (with dropout), the following results are reported.

  • Error rate on the original test data: dropped from 0.94% to 0.84%. With further changes such as a larger model, it dropped to 0.782%. This shows that adversarial training also works as regularization that suppresses overfitting.
  • Error rate on FGSM adversarial examples: dropped from 89.4% to 17.9%. However, the average confidence on errors remained high at 81.4%.

Being robust to FGSM does not mean being robust to adversarial examples in general. FGSM is a weak attack that takes only a single step in the gradient direction, and models adversarially trained only with FGSM have been reported to be robust to FGSM but vulnerable to iterative attacks that take many small steps (Kurakin et al., 2017; Wong et al., 2020). When checking a model's robustness, also evaluate it with iterative attacks such as PGD.

Comparison with other attacks and how to choose

The table below compares FGSM with attacks it is often compared against, from the same viewpoints.

MethodHow the perturbation is foundNumber of gradient computationsStrength and use
FGSMTake one step of size ε\varepsilon in the direction of the gradient's sign1Weak but fast. Material for adversarial training, quick checks
I-FGSM (BIM)Repeat FGSM with small steps and keep the result within ε\varepsilon (Kurakin et al., 2016)One per iterationStronger than FGSM
PGDStart from a random point and iterate as in I-FGSM (Madry et al., 2018)One per iterationStrong. The standard for robustness evaluation and adversarial training
DeepFoolFind the shortest distance to the decision boundary by repeated linear approximationOne per iterationMeasures the minimum perturbation size needed for misclassification
C&W attackSolve an optimization problem that seeks both a small perturbation and misclassificationManyVery strong but slow. Evaluating defenses

Rough guidelines for choosing are as follows.

  • To quickly check the effect of adversarial examples or to make adversarial training cheaper: use FGSM. It needs only one gradient computation.
  • To evaluate a model's robustness properly: use iterative attacks such as PGD.
  • To measure how small a perturbation causes misclassification: use DeepFool or the C&W attack.

Adversarial training with FGSM was once considered "fast but weak," but Wong et al. (2020) showed that with tricks such as starting FGSM from a random point, it achieves robustness comparable to adversarial training with PGD at a much lower computational cost. They also reported "catastrophic overfitting," in which the model suddenly loses its robustness to PGD during training while remaining robust to FGSM, so when doing adversarial training with FGSM it is important to keep evaluating with PGD.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

'''
Train a small CNN on MNIST and check its accuracy on adversarial examples created with FGSM
(pixel values are kept in 0-1, and adversarial examples are also clipped to 0-1)
'''

# Hyperparameters
batch_size = 64       # Batch size
epochs = 3            # Number of epochs
learning_rate = 1e-3  # Learning rate
epsilons = [0.0, 0.05, 0.1, 0.2, 0.25]  # Perturbation size ε (0 means the original images)

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

transform = transforms.ToTensor()  # Scale pixel values to 0-1
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)


class SmallCNN(nn.Module):
  def __init__(self, num_classes=10):
    super().__init__()
    self.features = nn.Sequential(
      nn.Conv2d(1, 32, kernel_size=3, padding=1),   # [B, 1, 28, 28] -> [B, 32, 28, 28]
      nn.ReLU(),
      nn.MaxPool2d(2),                              # -> [B, 32, 14, 14]
      nn.Conv2d(32, 64, kernel_size=3, padding=1),  # -> [B, 64, 14, 14]
      nn.ReLU(),
      nn.MaxPool2d(2),                              # -> [B, 64, 7, 7]
      nn.Flatten(),
    )
    self.classifier = nn.Linear(64 * 7 * 7, num_classes)

  def forward(self, x):
    return self.classifier(self.features(x))


def fgsm(model, images, labels, epsilon):
  # x̃ = x + ε · sign(∇x J(θ, x, y)). Keep the weights θ fixed and compute only the gradient w.r.t. the input
  images = images.clone().detach().requires_grad_(True)
  loss = F.cross_entropy(model(images), labels)
  grad = torch.autograd.grad(loss, images)[0]
  adv = images + epsilon * grad.sign()
  return adv.clamp(0, 1).detach()  # Keep pixel values within 0-1


# Training (standard training, no adversarial training)
model = SmallCNN().to(device)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
for epoch in range(epochs):
  model.train()
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad()
    loss = F.cross_entropy(model(images), labels)
    loss.backward()
    optimizer.step()

# Evaluation: compare accuracy on adversarial examples for different ε
model.eval()
for epsilon in epsilons:
  correct = 0
  total = 0
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    adv = fgsm(model, images, labels, epsilon)
    with torch.no_grad():
      predicted = model(adv).argmax(dim=1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()
  print(f"epsilon = {epsilon:.2f}: Accuracy {100 * correct / total:.2f}%")

FAQ

Q. How large should ε be?
A.

Choose it based on the range of pixel values and on a size at which people do not notice the change. The paper uses 0.25 for MNIST with values in 0 to 1, and 0.007, which corresponds to one step of an 8-bit image, in the ImageNet example. When comparing results, compare them at the same ε.

Q. Can it be used without knowing the model's weights?
A.

FGSM itself uses gradients, so it is a method for when the weights are known (white-box). However, adversarial examples crafted on a different local model are known to often fool the target model as well, and some attacks exploit this.

Q. Can it make the model misclassify into a specific class?
A.

FGSM shifts the input in the direction that increases the loss for the correct label, so it cannot choose which class the model mistakes it for. A variant that shifts the input in the direction that decreases the loss for a target class can aim to make the model misclassify into a specific class (Kurakin et al., 2016).

References

  1. I. J. Goodfellow, J. Shlens, and C. Szegedy, "Explaining and Harnessing Adversarial Examples," ICLR, 2015.
  2. C. Szegedy, W. Zaremba, I. Sutskever, J. Bruna, D. Erhan, I. Goodfellow, and R. Fergus, "Intriguing properties of neural networks," ICLR, 2014.
  3. A. Kurakin, I. Goodfellow, and S. Bengio, "Adversarial examples in the physical world," arXiv:1607.02533, 2016 (ICLR Workshop, 2017).
  4. A. Kurakin, I. Goodfellow, and S. Bengio, "Adversarial Machine Learning at Scale," ICLR, 2017.
  5. A. Madry, A. Makelov, L. Schmidt, D. Tsipras, and A. Vladu, "Towards Deep Learning Models Resistant to Adversarial Attacks," ICLR, 2018.
  6. E. Wong, L. Rice, and J. Z. Kolter, "Fast is better than free: Revisiting adversarial training," ICLR, 2020.