How does one implement adversarial examples in pytorch?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Adversarial examples are inputs that look almost unchanged to a person but push a model toward the wrong prediction. In PyTorch, the core idea is simple: compute the gradient of the loss with respect to the input, then nudge the input in the direction that increases that loss.
The Simplest Attack: FGSM
The Fast Gradient Sign Method, usually shortened to FGSM, is the standard first attack to implement. It takes one gradient step on the input:
- run a forward pass
- compute the loss against the true label
- backpropagate into the input tensor
- add
epsilon * sign(gradient)to the input
For images, the final perturbed tensor is normally clamped back into the valid pixel range, such as 0 through 1.
A Runnable PyTorch Example
The example below trains a tiny classifier on synthetic two-dimensional data and then generates adversarial samples with FGSM. The data is simple, but the attack logic is the same pattern used for real models.
Even on this toy problem, some points that were classified correctly before the attack will flip after the perturbation is added.
Why requires_grad_ Matters
Normally, you optimize model weights, not inputs. For adversarial attacks, you temporarily mark the input tensor as differentiable so PyTorch can populate input.grad after loss.backward().
That is the critical shift in perspective. The model parameters stay fixed. The attack changes the data instead.
For image models, the attack function usually looks like this:
The torch.clamp call is important when the input space has known bounds.
Beyond FGSM
FGSM is a one-step attack. Stronger attacks usually repeat the update several times while projecting the sample back into an allowed perturbation region. Projected Gradient Descent, or PGD, is the classic next step because it often finds more reliable failures than one gradient step.
You can also switch from untargeted attacks to targeted ones. An untargeted attack only tries to make the model wrong. A targeted attack tries to push the model toward one specific incorrect class.
For defense experiments, people often combine these attacks with adversarial training, where the model sees perturbed samples during training rather than only at evaluation time.
Common Pitfalls
- Forgetting
requires_grad_(True)on the input means the attack has no gradient to use. - Calling the attack while the model is in training mode can introduce randomness through dropout or batch normalization updates.
- Choosing an
epsilonthat is too large makes the perturbation unrealistic and the evaluation less informative. - Not clamping image data back to the legal range creates invalid samples.
- Comparing attacks across models without normalizing input preprocessing can produce misleading results.
Summary
- Adversarial examples are created by perturbing the input, not the model weights.
- FGSM is the easiest PyTorch attack to implement because it needs only one backward pass.
- Mark the input tensor as requiring gradients, compute the loss, then step in the gradient-sign direction.
- Clamp attacked image tensors back to the valid input range.
- Use FGSM to learn the workflow, then move to stronger attacks such as PGD for more realistic robustness testing.
Related reading
- How does one move data to multiple GPU towers using Tensorflow's Dataset API
- How does one train multiple models in a single script in TensorFlow when there are GPUs present?
- How does one train multiple models in a single script in TensorFlow when there are GPUs present?
- How does one transfer CUDA constant memory in tensorflow's C API
- How does one use Pytorch cuda with an A100 GPU?
- How does pytorch backprop through argmax?
- How does one initialize a variable with tf.get_variable and a numpy value in TensorFlow?
- How does one inspect variables in a checkpoint file in TensorFlow when TensorFlow can't find the tools attribute?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.