AI Logic

Adversarial Attacks and Defenses

PGD Attack and Adversarial Training

Updated:

Diagram of PGD. Left: one step of adversarial training (mini-batch, random start inside the ε-ball, K repetitions of gradient with respect to the input, step α along the sign, and projection onto x + S, adversarial example, SGD weight update). Right: a 2D sketch of PGD stepping by α inside a square ℓ∞ ball, projecting back whenever it leaves, as it heads toward a high-loss point, alongside the FGSM point reached with a single ε step

What are the PGD attack and adversarial training

The PGD (Projected Gradient Descent) attack builds adversarial examples by repeatedly moving the input a little in the direction that increases the loss and, whenever it leaves the allowed region, pulling it back inside (projecting it). Adversarial training with PGD trains a model on adversarial examples built by this PGD attack to make it resistant (robust) to attacks. Madry, Makelov, Schmidt, Tsipras, and Vladu proposed it in 2017, and it was presented at ICLR 2018.

The core of the paper is that it frames attack and defense as a single min-max (saddle point) problem.

min⁡θ ρ(θ),ρ(θ)=E(x,y)∼D[max⁡δ∈SL(θ, x+δ, y)]\min_{\theta} \ \rho(\theta), \qquad \rho(\theta) = \mathbb{E}_{(x, y) \sim \mathcal{D}} \Big[ \max_{\delta \in \mathcal{S}} L(\theta,\, x + \delta,\, y) \Big]

Here, θ\theta is the model's weights, LL is the loss (cross-entropy for classification), and S\mathcal{S} is the set of perturbations the attacker is allowed. The paper mainly deals with S={δ:∥δ∥∞≤ε}\mathcal{S} = \{\delta : \|\delta\|_\infty \le \varepsilon\} (the ℓ∞ ball), which limits each pixel's change to at most ε\varepsilon.

  • Inner maximization: Search within the allowed region for the perturbation that makes the loss largest. This is the attack.
  • Outer minimization: Train the weights so that the loss stays small even under that worst-case perturbation. This is adversarial training.

From this viewpoint, FGSM approximates the inner maximization with a single step, while PGD repeats the step many times to solve it more accurately. The left side of the header figure shows one step of adversarial training; the right side sketches PGD moving toward a high-loss point inside the ℓ∞ ball (a square in two dimensions).

As an analogy, it is a match between someone who writes exam questions (the attack) and someone who solves them (the model). Practicing only on questions written half-heartedly (FGSM) leaves one helpless against serious questions (PGD). The paper's idea is that practicing on serious questions also makes one strong against other questions drawn from the same range.

How the PGD attack and adversarial training work

The PGD attack solves the inner maximization by repeating the following update.

xt+1=Πx+S(xt+α⋅sgn(∇xL(θ,xt,y)))x^{t+1} = \Pi_{x + \mathcal{S}} \Big( x^{t} + \alpha \cdot \mathrm{sgn}\big(\nabla_x L(\theta, x^{t}, y)\big) \Big)

α\alpha is the size of each step (the step size), sgn\mathrm{sgn} is the function that returns the sign, and Πx+S\Pi_{x + \mathcal{S}} is the operation that returns the point to the nearest point in the region x+Sx + \mathcal{S} (projection). For the ℓ∞ ball, this amounts to clipping each pixel to [xi−ε, xi+ε][x_i - \varepsilon,\ x_i + \varepsilon].

The PGD attack proceeds as follows.

  1. Choose a random point x0x^0 in the ℓ∞ ball around the original input xx (add uniform noise in [−ε,ε][-\varepsilon, \varepsilon] to each pixel).
  2. Compute the gradient ∇xL\nabla_x L of the loss at xtx^t with respect to the input by backpropagation.
  3. Take a step of size α\alpha in the direction of the gradient's sign.
  4. Project the result onto x+Sx + \mathcal{S}. For images, also keep it within the range of pixel values (for example, 0–1).
  5. Repeat steps 2–4 KK times, and take the final xKx^K as the adversarial example.

Adversarial training with PGD solves the outer minimization with SGD.

  1. Take a mini-batch (x,y)(x, y).
  2. Run the PGD attack against the current weights θ\theta to build adversarial examples xKx^K.
  3. Compute the loss L(θ,xK,y)L(\theta, x^K, y) on xKx^K instead of the original inputs, and update θ\theta with the gradient with respect to the weights.
  4. Repeat steps 1–3.

It is not obvious that "updating the weights with the gradient at the maximizing point" is valid. The paper shows, using a classical optimization theorem (Danskin's theorem), that for functions satisfying its conditions, the gradient at the solution of the inner maximization is a descent direction for the outer problem. Networks with ReLU or Max Pooling do not strictly satisfy the conditions, but in experiments the adversarial loss decreased steadily over training.

Why PGD works: the loss landscape and first-order adversaries

The inner maximization is usually hard to solve because a network's loss is not concave in the input. The paper examined the loss landscape of MNIST and CIFAR-10 models by restarting PGD many times from random points in the ℓ∞ ball.

  • It plateaus quickly: From any starting point, the loss rose consistently within a few steps and then plateaued.
  • The local maxima have similar values: Even after 10510^5 restarts, the loss values at the local maxima reached were concentrated in a narrow range, and no outstandingly large value was found. The local maxima are distinct points far apart from one another, yet their loss values are similar.

From this, the paper conjectures that a model robust to PGD is robust to attacks in general that use only the gradient with respect to the input (first-order information), and treats PGD as the representative "first-order adversary." This is a conjecture based on experiments rather than a proof, but the evaluation in Section 5 shows that PGD-trained models are robust to PGD with different numbers of iterations and restarts, to attacks using the loss of the C&W attack, and to attacks transferred from other models.

Another finding is that robust models need large capacity. Even if the boundary separating ordinary data is simple, separating the data together with the ε-ball around each point requires a more complex boundary.

Experimental results

Below are results on CIFAR-10 comparing ResNet (Simple) and a version with each layer widened 10× (Wide) under different training methods (Figure 4 in the paper; ℓ∞ with ε=8\varepsilon = 8 on the 0–255 pixel scale). Each cell is the "Simple / Wide" accuracy.

Training methodOriginal test dataFGSM attackPGD attack
Standard training92.7% / 95.2%27.5% / 32.7%0.8% / 3.5%
Adversarial training with FGSM87.4% / 90.3%90.9% / 95.1%0.0% / 0.0%
Adversarial training with PGD79.4% / 87.3%51.7% / 56.1%43.7% / 45.8%

Models trained with FGSM become robust to FGSM, but score 0% against PGD. The paper explains that FGSM produces only a limited variety of adversarial examples, and the model overfits to them (a phenomenon called label leaking). Training with PGD lowers accuracy on the original data but keeps over 40% accuracy even under the PGD attack.

Below are some results of evaluating PGD-trained models against various attacks (Tables 1 and 2 in the paper). "White-box" attacks use the gradients of the attacked model itself; "transfer" attacks feed in adversarial examples built on an independently trained model of the same architecture.

DataAttackAccuracy
MNIST (ε=0.3\varepsilon = 0.3)No attack98.8%
MNISTPGD, 40 steps (white-box)93.2%
MNISTPGD, 100 steps, 20 restarts (white-box)89.3%
MNISTPGD, 40 steps (transfer)96.0%
CIFAR-10 (Wide, ε=8\varepsilon = 8)No attack87.3%
CIFAR-10PGD, 7 steps (white-box)50.0%
CIFAR-10PGD, 20 steps (white-box)45.8%
CIFAR-10PGD, 7 steps (transfer)64.2%

On MNIST, a network with two convolutional layers (32 and 64 filters) and a fully connected layer of 1024 units was trained with 40 steps of PGD at step size 0.01. The same network trained normally reaches 99.2% on the original data but drops to 6.4% on FGSM adversarial examples. On CIFAR-10, training used 7 steps of PGD at step size 2.

Caveats

Computation is several times that of standard training. Every weight update adds KK forward and backward passes for PGD (40 for MNIST and 7 for CIFAR-10 in the paper's setup). Also, robustness to PGD means robustness within the chosen ε\varepsilon and distance (such as ℓ∞); robustness to other perturbations is not guaranteed.

  • Accuracy on the original data drops: For the CIFAR-10 Wide model, it fell from 95.2% with standard training to 87.3%. To tune the trade-off between robustness and accuracy, methods such as TRADES are available.
  • Training collapses for low-capacity models: In the paper, training a small network with PGD made it always output the same class. Robustness requires a larger model than standard training does.
  • Robustness can drop sharply beyond the training ε: The MNIST model's accuracy fell sharply for perturbations slightly larger than the ε=0.3\varepsilon = 0.3 used in training.
  • Hidden gradients lead to overestimated robustness: For the paper's MNIST model, ℓ2 PGD found no adversarial examples even with very large perturbations, but gradient-free attacks revealed the model to be much weaker. This is thought to be because the learned first layer acted like a threshold on pixels, so the gradient gave the attack no useful signal. For evaluation, use not only PGD but also the C&W attack, gradient-free attacks, and others.
  • Make evaluation PGD stronger than training PGD: The paper also evaluates with PGD using more iterations and restarts. Evaluating only with the same weak settings as training overestimates robustness.

Comparison with other methods and how to choose

First, PGD as an attack, alongside other attacks.

MethodHow the perturbation is foundNumber of gradient computationsMain use
FGSMTake one step of size ε\varepsilon in the direction of the gradient's sign1Quick checks, lightweight adversarial training
PGDFrom a random point, step by α\alpha and project, KK timesKKStandard for robustness evaluation and adversarial training
DeepFoolRepeatedly linearize the decision boundary and step to the nearest point on itNumber of iterations (per class)Measuring the minimum perturbation needed to misclassify
C&W attackOptimize the sum of perturbation size and a logit-difference termManyEvaluating defenses (especially L2)

Next, methods for adversarial training.

MethodTraining lossCostCharacteristics
Adversarial training with FGSM (Goodfellow et al., 2015)Weighted sum of the losses on the original input and the FGSM adversarial exampleLightTends to be weak against PGD at large ε
Adversarial training with PGDLoss on PGD adversarial examplesHeavy (about KK times)The reference method for robustness
TRADESLoss on the original input + difference (KL) between outputs on the original input and the adversarial exampleHeavyA coefficient tunes the trade-off between accuracy and robustness

Rough guidelines for choosing:

  • To evaluate model robustness properly: Use PGD with more iterations and restarts than in training. Combine it with other kinds of attacks.
  • To build a model robust to perturbations in an ℓ∞ range: Adversarial training with PGD is the starting point. Use a high-capacity model.
  • To avoid losing much accuracy on the original data: Consider methods like TRADES that can tune the trade-off between accuracy and robustness.
  • To reduce computation: Combine adversarial training with FGSM with tricks such as random starts, and keep evaluating with PGD (see the FGSM article for details).

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

"""
Adversarial training with PGD on MNIST (MNIST setup of Madry et al., 2018: ε = 0.3, step size 0.01, 40 steps)
  inner maximization: x^{t+1} = Π_{x+S}(x^t + α·sgn(∇x L)), starting from a random point in the ε-ball
  outer minimization: update the weights with the loss on PGD adversarial examples
"""

# Hyperparameters
batch_size = 64       # batch size
epochs = 3            # number of epochs (the paper trains much longer)
learning_rate = 1e-3  # learning rate
epsilon = 0.3         # upper bound ε on perturbation size (pixel values in 0-1)
alpha = 0.01          # PGD step size α
steps = 40            # number of PGD iterations K

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_loader = DataLoader(datasets.MNIST('./data', train=True, download=True, transform=transform), batch_size=batch_size, shuffle=True)
test_loader = DataLoader(datasets.MNIST('./data', train=False, download=True, transform=transform), batch_size=batch_size)


class SmallCNN(nn.Module):
  # the paper's MNIST network: conv with 32 and 64 filters (each followed by 2×2 Max Pooling) + fully connected 1024
  # (the paper does not state the kernel size, so 5×5 is used here)
  def __init__(self, num_classes=10):
    super().__init__()
    self.features = nn.Sequential(
      nn.Conv2d(1, 32, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(2),   # -> [B, 32, 14, 14]
      nn.Conv2d(32, 64, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(2),  # -> [B, 64, 7, 7]
      nn.Flatten(),
      nn.Linear(64 * 7 * 7, 1024), nn.ReLU(),
    )
    self.classifier = nn.Linear(1024, num_classes)

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


def pgd_attack(model, images, labels, epsilon, alpha, steps, random_start=True):
  images = images.clone().detach()
  adv = images.clone()
  if random_start:  # start from a random point in the ε-ball
    adv = adv + torch.empty_like(adv).uniform_(-epsilon, epsilon)
    adv = adv.clamp(0, 1)
  for _ in range(steps):
    adv.requires_grad_(True)
    loss = F.cross_entropy(model(adv), labels)
    grad = torch.autograd.grad(loss, adv)[0]          # gradient with respect to the input (weights are not changed)
    adv = adv.detach() + alpha * grad.sign()           # step α in the sign direction
    adv = torch.min(torch.max(adv, images - epsilon), images + epsilon)  # project onto x + S (ℓ∞ ball)
    adv = adv.clamp(0, 1)                              # keep within the pixel value range
  return adv.detach()


model = SmallCNN().to(device)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

for epoch in range(epochs):
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    # inner maximization: build adversarial examples against the current weights
    # (this model has no BatchNorm or Dropout, so train/eval give the same result.
    #   when it does, model.eval() is commonly used for the attack and model.train() for the update)
    model.eval()
    adv = pgd_attack(model, images, labels, epsilon, alpha, steps)
    # outer minimization: update the weights with the loss on adversarial examples
    model.train()
    optimizer.zero_grad()
    loss = F.cross_entropy(model(adv), labels)
    loss.backward()
    optimizer.step()

# evaluation: accuracy on the original test data and under PGD (100 steps, stronger than in training)
model.eval()
clean_correct = adv_correct = total = 0
for images, labels in test_loader:
  images, labels = images.to(device), labels.to(device)
  adv = pgd_attack(model, images, labels, epsilon, alpha, steps=100)
  with torch.no_grad():
    clean_correct += (model(images).argmax(1) == labels).sum().item()
    adv_correct += (model(adv).argmax(1) == labels).sum().item()
  total += labels.size(0)
print(f"clean: {100 * clean_correct / total:.2f}%, PGD-100: {100 * adv_correct / total:.2f}%")

FAQ

Q. How do PGD and I-FGSM (BIM) differ?
A.

Both repeatedly take small steps in the direction of the gradient's sign and project back into the ε range. The difference is the starting point: I-FGSM starts from the original input xx, while PGD starts from a random point in the ε-ball. Madry et al. found that restarts from random points converge to similar loss values, and positioned PGD as the representative first-order attack.

Q. How should ε, the step size α, and the number of steps K be chosen?
A.

ε is the size of perturbation to defend against: 0.3 for MNIST (pixels 0–1) and 8 for CIFAR-10 (pixels 0–255) in the paper. α and K are chosen so that the attack can reach the edge of the ε-ball. For training, the paper uses α=0.01\alpha = 0.01, K=40K = 40 for MNIST and α=2\alpha = 2, K=7K = 7 for CIFAR-10; for evaluations with varying ε, it uses α=2.5⋅ε/100\alpha = 2.5 \cdot \varepsilon / 100 and K=100K = 100 so that the edge can be reached from any starting point.

Q. Does training with PGD make a model robust to every attack?
A.

No. It becomes robust to perturbations within the distance (such as ℓ∞) and ε chosen for training. In the paper as well, the MNIST model weakened sharply for perturbations slightly larger than the training ε, and gradient-free attacks showed it to be much weaker against ℓ2 perturbations. Evaluation should use several kinds of attacks.

References

  1. A. Madry, A. Makelov, L. Schmidt, D. Tsipras, and A. Vladu, "Towards Deep Learning Models Resistant to Adversarial Attacks," ICLR, 2018.
  2. I. J. Goodfellow, J. Shlens, and C. Szegedy, "Explaining and Harnessing Adversarial Examples," ICLR, 2015.
  3. A. Kurakin, I. Goodfellow, and S. Bengio, "Adversarial examples in the physical world," arXiv:1607.02533, 2016.
  4. A. Kurakin, I. Goodfellow, and S. Bengio, "Adversarial Machine Learning at Scale," ICLR, 2017.
  5. N. Carlini and D. Wagner, "Towards Evaluating the Robustness of Neural Networks," IEEE Symposium on Security and Privacy, pp. 39–57, 2017.