In Goodfellow and colleagues’ example, a small computed perturbation changed GoogLeNet’s prediction for a panda image to gibbon. Under a per-coordinate budget, FGSM chooses the gradient signs that maximize the linearized loss increase. Whether the nonlinear model misclassifies an input must be tested at the stated input scale and budget.
This article explains the mathematics of gradient-based attacks (FGSM and PGD), provides PyTorch implementations for Red Teams, and discusses production pipelines for adversarial defense.
1. The Mathematical Boundaries of Threat Models
An adversarial evaluation needs a defined attacker feasible set. The threat model is parameterized by:
- Attacker Knowledge: White-box (full access to \( \theta \), architectures, and gradients \( \nabla_x J \)) vs. Black-box (query-based zeroth-order optimization or surrogate-model transfer).
- Perturbation Constraint (\( L_p \) Norm): The perturbation \( \delta \) is bounded by \( \|\delta\|_p \le \epsilon \). Common norms include \( L_\infty \) (maximum pixel change) and \( L_2 \) (Euclidean distance).
- Objective Function: Untargeted (\( \arg\max_\delta J(\theta, x+\delta, y) \)) vs. Targeted (\( \arg\min_\delta J(\theta, x+\delta, y_{target}) \)).
2. Fast Gradient Sign Method (FGSM)
FGSM is a single-step gradient-based attack that linearizes the loss function \( J \) around the input \( x \). Under a first-order Taylor approximation, it maximizes the increase in the linearized loss within the \( L_\infty \) budget.
The mathematical formulation is:
\[ \delta = \epsilon \cdot \text{sign}(\nabla_x J(\theta, x, y)) \]
\[ x_{adv} = \text{clip}(x + \delta, x_{min}, x_{max}) \]
The original PyTorch example is retained below. It assumes a floating leaf tensor, a scalar criterion, and inputs and epsilon expressed in raw [0,1] pixel coordinates. Put any required mean/standard-deviation normalization inside the differentiated model path, and choose eval/train mode explicitly. The original FGSM does not clear images.grad, so reusing an input with an existing gradient accumulates it. A separate correction follows the original PGD code.
PyTorch Implementation of FGSM
import torch
import torch.nn as nn
def fgsm_attack(model, images, labels, epsilon, criterion):
images.requires_grad = True
outputs = model(images)
loss = criterion(outputs, labels)
# Compute Jacobian / Gradients wrt input
model.zero_grad()
loss.backward()
data_grad = images.grad.data
# Create perturbation
sign_data_grad = data_grad.sign()
perturbed_images = images + epsilon * sign_data_grad
# Project back to valid input domain (e.g., [0, 1])
perturbed_images = torch.clamp(perturbed_images, 0, 1)
return perturbed_images
3. Projected Gradient Descent (PGD)
FGSM takes one step. PGD repeatedly computes gradients and projects into the feasible set, which can find higher-loss inputs without guaranteeing a global solution. The sign steps and coordinatewise clipping below specifically implement an L∞ attack with budget \( \epsilon \).
The update rule for step \( t+1 \) is:
\[ x^{t+1} = \Pi_{x+\mathcal{S}} \left( x^t + \alpha \cdot \text{sign}(\nabla_x J(\theta, x^t, y)) \right) \]
The parameter \( \alpha \) is the step size, and \( \Pi_{x+\mathcal{S}} \) projects into the allowed set centered at the original input. A general feasible set can be an \( L_p \) ball; this page’s code uses the intersection of an L∞ ball and the [0,1] input domain. An L2 attack needs the corresponding gradient normalization and projection.
PyTorch Implementation of PGD
def pgd_attack(model, images, labels, epsilon, alpha, iters, criterion):
perturbed_images = images.clone().detach()
# Random start within epsilon ball
perturbed_images = perturbed_images + torch.empty_like(perturbed_images).uniform_(-epsilon, epsilon)
perturbed_images = torch.clamp(perturbed_images, 0, 1)
for _ in range(iters):
perturbed_images.requires_grad = True
outputs = model(perturbed_images)
loss = criterion(outputs, labels)
model.zero_grad()
loss.backward()
with torch.no_grad():
adv_images = perturbed_images + alpha * perturbed_images.grad.sign()
eta = torch.clamp(adv_images - images, min=-epsilon, max=epsilon)
perturbed_images = torch.clamp(images + eta, 0, 1)
return perturbed_images
Independent correction (2026-11-07): This version creates a fresh input leaf and obtains its gradient with autograd.grad, avoiding any stored images.grad. It returns detached outputs without clearing or accumulating model-parameter gradients. It implements untargeted L∞ attacks with a scalar loss in raw [0,1] coordinates. The caller chooses model mode; randomized defenses require a separate EOT evaluation.
import math
import torch
def _budget(epsilon):
if not math.isfinite(epsilon) or epsilon < 0:
raise ValueError('epsilon must be finite and nonnegative')
def _clean(images):
clean = images.detach()
if not clean.is_floating_point() or not torch.isfinite(clean).all():
raise ValueError('finite floating inputs required')
if not ((clean >= 0) & (clean <= 1)).all():
raise ValueError('inputs must use raw [0,1] coordinates')
return clean
def fgsm_linf(model, images, labels, epsilon, criterion):
# Caller chooses model mode; any normalization belongs inside model.
_budget(epsilon)
clean = _clean(images)
x = clean.clone().requires_grad_(True)
loss = criterion(model(x), labels) # scalar loss from logits
grad, = torch.autograd.grad(loss, x)
return (clean + epsilon * grad.sign()).clamp(0, 1).detach()
def pgd_linf(model, images, labels, epsilon, alpha, iters, criterion):
_budget(epsilon)
if not math.isfinite(alpha) or alpha <= 0:
raise ValueError('alpha must be finite and positive')
if type(iters) is not int or iters < 1:
raise ValueError('iters must be a positive integer')
clean = _clean(images)
adv = (clean + torch.empty_like(clean).uniform_(-epsilon, epsilon)).clamp(0, 1)
for _ in range(iters):
x = adv.detach().requires_grad_(True)
loss = criterion(model(x), labels)
grad, = torch.autograd.grad(loss, x)
with torch.no_grad():
delta = (x + alpha * grad.sign() - clean).clamp(-epsilon, epsilon)
adv = (clean + delta).clamp(0, 1)
return adv.detach()
4. Red/Blue Team Post-Mortem: Production Architecture Defenses
For randomized defenses, Expectation Over Transformation (EOT) estimates the gradient of expected loss by repeated sampling. It tests whether randomness merely makes the attack gradient harder to estimate. Success depends on the transformations, sample count and budget; methods such as randomized smoothing can also provide certified radii under stated assumptions. Evaluate the actual implementation:
- Adversarial Training Logic: The empirical risk minimization is modified to a min-max saddle point problem: \[ \min_\theta \mathbb{E}_{(x,y)\sim \mathcal{D}} \left[ \max_{\|\delta\|_p \le \epsilon} J(\theta, x+\delta, y) \right] \] Training approximates the inner maximization with an attack such as PGD, then updates the model. Report clean and attacked accuracy together: their tradeoff depends on the data, budget and training method. Reduced curvature requires its own measurement.
- Gradient Masking & Obfuscation (A Warning): Nondifferentiable preprocessing can make gradients unusable. Backward Pass Differentiable Approximation (BPDA) can support an attack adapted to that preprocessing; transfer and gradient-free attacks check additional failure modes. Failure of a finite attack suite is not a robustness certificate.
- Inference Abstention & Out-of-Distribution (OOD) Detection: One option estimates class means and covariance from training features and forms a Mahalanobis distance score. Check thresholds, false positives, false negatives and adaptive attacks on separate evaluation data. It does not identify every evasion input.
5. Robust Evaluation Reporting Standards
A production security audit must yield an evaluation matrix:
- Clean Accuracy vs. PGD-100 (100 iterations) Accuracy across a spectrum of \( \epsilon \) budgets.
- Evaluation of gradient-free attacks (e.g., SPSA) to check whether unusable gradients conceal successful attack paths.
- System latency overhead introduced by dynamic OOD detection modules.
6. Robustness Audit Matrix
An adversarial evaluation report should record both attack strength and defense side effects. A model should not be called robust unless the evaluation records the attack budget, adaptive checks, and production impact.
| Audit dimension | Required measurement | Interpretation | Red flag |
|---|---|---|---|
| Attack budget | \( \epsilon \), norm type, PGD steps, step size, random restarts | Defines what the adversary is actually allowed to do | Only reporting one weak FGSM result and claiming broad robustness |
| Adaptive attack | BPDA/EOT or gradient-free transfer checks when preprocessing is non-differentiable | Separates real robustness from gradient masking | Robust accuracy is high for white-box gradients but low for black-box transfer |
| Clean accuracy trade-off | Clean, FGSM, PGD-20, PGD-100, and OOD accuracy in the same report | Shows whether the defense is useful for normal traffic | Robustness improves only by making the model reject or misclassify clean data |
| Runtime cost | Median and p95 latency with OOD detection or input purification enabled | Connects security controls to deployability | Defense requires many forward passes and cannot meet service latency budgets |
FGSM failure followed by PGD success first shows that the one-step attack was weaker. Transfer outperforming a well-debugged white-box attack is a signal to investigate gradient masking. Record input scale, norm, budget, step size, iterations, restarts, preprocessing and model mode, then aggregate attacks on the same examples. State the denominator for attacked accuracy separately from attack success calculated only among clean-correct examples.