Algorithm Search⌘K

Algorithmcore

Projected gradient descent attack

Also called PGD attack, iterative FGSM, basic iterative method.

Repeats small signed gradient steps on the loss and projects back onto the epsilon ball and the valid box, from a random start. The standard first-order attack for robust accuracy.

Time
O(T (g + d)) worst
Space
Θ(d) extra
Where
T = the number of steps; d = the input dimension; g = the cost of one input gradient of the loss
Properties
randomizednot exactofflineiterative
Origin
Aleksander Madry, Aleksandar Makelov, Ludwig Schmidt, Dimitris Tsipras, Adrian Vladu, 2017

The projected gradient descent attack (PGD attack) searches for an adversarial example inside a fixed set S=Bp(x,ϵ)∩[0,1]dS = B_p(x, \epsilon) \cap [0,1]^d by gradient ascent on the loss. It starts at a random point of SS, takes a step of size α\alpha in the steepest ascent direction for the norm, and projects the result back onto SS. It repeats this TT times and keeps the point with the largest loss. One step from xx with α=ϵ\alpha = \epsilon in ℓ∞\ell_\infty is the fast gradient sign method. Madry et al. (2018) showed that the local maxima that PGD finds from many random starts have similar loss values, and they made PGD the inner step of adversarial training. PGD is the standard attack for an upper bound on robust accuracy against an attacker with gradients.

Threat model. The goal is untargeted (a targeted variant is below). The knowledge is white box: the attacker computes the input gradient of the loss. The capability is a change at test time within Bp(x,ϵ)∩[0,1]dB_p(x, \epsilon) \cap [0,1]^d, here for p=∞p = \infty or p=2p = 2.

In plain words

FGSM looks at the slope of the loss one time and jumps to the edge of the allowed region. If the loss curves, that jump can land in the wrong place.

PGD walks instead. It takes many small steps uphill, and after each step it looks at the slope again. When a step leaves the allowed region, PGD pulls the point back to the nearest allowed point. When the walk is done, PGD returns the highest point that it saw.

Because the loss of a network has many hills, PGD often starts from a random point of the region, and an evaluation runs it several times from different starts. A model that keeps its label against all these walks is likely, but not proved, to be robust at that radius.

The problem

Given a model with loss L(θ,x,y)L(\theta, x, y), an input x∈[0,1]dx \in [0,1]^d with label yy, a norm p∈{2,∞}p \in \{2, \infty\} and a radius ϵ≥0\epsilon \ge 0, find

x′∈arg⁡max⁡v∈SL(θ,v,y),S=Bp(x,ϵ)∩[0,1]d.x' \in \arg\max_{v \in S} L(\theta, v, y), \qquad S = B_p(x, \epsilon) \cap [0,1]^d.

If f(x′)≠yf(x') \ne y, then x′x' is an adversarial example. This is the inner maximization of the saddle point problem min⁡θE[max⁡ηL(θ,x+η,y)]\min_\theta \mathbb{E}[\max_{\eta} L(\theta, x + \eta, y)] of Madry et al. (2018). For a network the objective is not concave, so PGD is a local method: it gives a feasible point with a large loss, not a certified maximum.

The algorithm

Write PSP_S for the map of line L5 into SS. For p=∞p = \infty it clips coordinate ii to [max⁡(xi−ϵ,0),min⁡(xi+ϵ,1)][\max(x_i - \epsilon, 0), \min(x_i + \epsilon, 1)]; this is the Euclidean projection onto the box SS. For p=2p = 2 it rescales v−xv - x to length at most ϵ\epsilon and then clips to [0,1]d[0,1]^d. The step direction u(g)u(g) is sign⁡(g)\operatorname{sign}(g) for p=∞p = \infty and g/∥g∥2g / \lVert g \rVert_2 for p=2p = 2, the direction of steepest ascent of a linear function for that norm.

  1. PGD(L, x, y, epsilon, alpha, T) ▷ x in [0, 1]^d with label y
  2. 1x^0 ← P_S(x + random point of B_p(0, epsilon)) ▷ or x^0 ← x without a random start
  3. 2best ← x^0; bestloss ← L(θ, x^0, y)
  4. 3for t ← 0 to T - 1 do
  5. 4g ← ∇_x L(θ, x^t, y) ▷ one forward and one backward pass
  6. 5x^{t+1} ← P_S(x^t + alpha · u(g)) ▷ step, then project
  7. 6if L(θ, x^{t+1}, y) > bestloss then best ← x^{t+1}; bestloss ← L(θ, x^{t+1}, y)
  8. 7return best

Line L1 draws the start uniformly from the ℓ∞\ell_\infty box or from the ℓ2\ell_2 ball and maps it into SS. Lines L4 and L5 are one step of projected gradient descent on −L-L, with the normalized direction uu in place of the raw gradient. Line L6 keeps the best iterate, because a step of fixed size can overshoot a maximum and lower the loss.

For a targeted attack toward class tt, use the loss −L(θ,v,t)-L(\theta, v, t), so that the walk lowers the loss of the target label. Madry et al. also run PGD on the margin loss of the Carlini-Wagner attack, max⁡k≠yzk(v)−zy(v)\max_{k \ne y} z_k(v) - z_y(v), in place of the cross-entropy.

Parameters. The step size α\alpha and the step count TT must satisfy αT≥2ϵ\alpha T \ge 2\epsilon in ℓ∞\ell_\infty, so that a walk can cross the whole box. Madry et al. used ϵ=0.3\epsilon = 0.3, T=40T = 40 and α=0.01\alpha = 0.01 on MNIST, and ϵ=8\epsilon = 8 on the pixel scale 0 to 255, T=7T = 7 and α=2\alpha = 2 on CIFAR10, with T=20T = 20 for their hardest test. For the sweeps of their Figure 6 they used T=100T = 100 and α=2.5 ϵ/100\alpha = 2.5\,\epsilon / 100. These are choices of the paper, not rules.

Example

A linear model. Take the logistic model of the FGSM page: w=(1.5,−2,0.5,1,−0.5,3)w = (1.5, -2, 0.5, 1, -0.5, 3), b=1b = 1, x=(0.2,0.9,0.5,0,1,0.4)x = (0.2, 0.9, 0.5, 0, 1, 0.4), y=1y = 1, the logistic loss, ℓ∞\ell_\infty with ϵ=0.1\epsilon = 0.1 and α=0.025\alpha = 0.025, and the start x0=xx^0 = x. The gradient is (σ(z)−1) w(\sigma(z) - 1)\,w at every point, so its sign pattern (−,+,−,−,+,−)(-, +, -, -, +, -) never changes.

tt xtx^t logit zz loss
0 (0.2, 0.9, 0.5, 0, 1, 0.4) 0.45 0.493249
1 (0.175, 0.925, 0.475, 0, 1, 0.375) 0.275 0.565071
2 (0.15, 0.95, 0.45, 0, 1, 0.35) 0.1 0.644397
3 (0.125, 0.975, 0.425, 0, 1, 0.325) -0.075 0.731350
4 (0.1, 1, 0.4, 0, 1, 0.3) -0.25 0.825939
5 (0.1, 1, 0.4, 0, 1, 0.3) -0.25 0.825939

Coordinates 4 and 5 never move: the box holds them at 00 and 11. Each other coordinate moves by 0.0250.025 per step until the projection stops it at xi±0.1x_i \pm 0.1, after 44 steps. From then on the iterate is fixed at the FGSM point, which is the exact maximum of the loss over SS. The label changes at step 3.

In ℓ2\ell_2 with ϵ=0.1\epsilon = 0.1 and the same α\alpha, each step moves along −w/∥w∥2-w / \lVert w \rVert_2 with ∥w∥2=4.0927\lVert w \rVert_2 = 4.0927, and the clip to the box removes the part of the step on coordinates 4 and 5. After 1, 2 and 4 steps the logit is 0.35530.3553, 0.26060.2606 and 0.07130.0713, and after 8 steps it is 0.05690.0569, so the label is still 11. Without the box the best logit in the ball would be 0.45−0.1⋅4.0927=0.04070.45 - 0.1 \cdot 4.0927 = 0.0407, still positive. So no ℓ2\ell_2 adversarial example exists at radius 0.10.1, while in ℓ∞\ell_\infty one does: the ℓ∞\ell_\infty ball of the same radius is much larger.

A network where one step fails. Take the network of mlkit.tiny_relu_net with seed 2744, d=2d = 2 inputs, h=4h = 4 hidden ReLU units and K=2K = 2 classes. Its first layer has the rows (1.188,−1.941)(1.188, -1.941), (−0.523,−0.003)(-0.523, -0.003), (−0.188,1.168)(-0.188, 1.168) and (1.157,0.158)(1.157, 0.158) with biases (0.106,0.001,0.078,0.038)(0.106, 0.001, 0.078, 0.038), and its output layer has the rows (−1.175,0.061,0.208,0.244)(-1.175, 0.061, 0.208, 0.244) and (1.592,−0.171,0.257,−0.354)(1.592, -0.171, 0.257, -0.354) with biases (−0.142,−0.110)(-0.142, -0.110) (rounded to three places). The input is x=(0.63,0.46)x = (0.63, 0.46) with label 00, and ϵ=0.1\epsilon = 0.1 in ℓ∞\ell_\infty.

At xx the gradient is (−0.274,−0.015)(-0.274, -0.015), so FGSM moves to (0.53,0.36)(0.53, 0.36). There the logits are (0.070,−0.199)(0.070, -0.199), and the label is still 00. PGD with α=0.025\alpha = 0.025 and T=10T = 10 from xx gives:

tt xtx^t logits (z0,z1)(z_0, z_1) gradient
0 (0.63, 0.46) (0.166, -0.280) (-0.274, -0.015)
2 (0.58, 0.41) (0.140, -0.269) (-0.280, -0.015)
3 (0.555, 0.385) (0.105, -0.234) (1.076, -2.249)
4 (0.58, 0.36) (0.012, -0.127) (1.203, -2.516)
6 (0.63, 0.36) (-0.046, -0.056) (1.286, -2.690)
7 (0.655, 0.36) (-0.074, -0.020) (1.328, -2.777)
10 (0.73, 0.36) (-0.161, 0.088) (1.452, -3.038)

At step 3 the first hidden unit, with pre-activation 1.188x1−1.941x2+0.1061.188 x_1 - 1.941 x_2 + 0.106, turns on, and the sign of the first partial derivative flips. FGSM saw only the slope at xx and moved x1x_1 the wrong way. PGD saw the new slope, turned around, and reached class 11 at step 7. The final point (0.73,0.36)(0.73, 0.36) is the opposite corner in the first coordinate from the FGSM point.

Correctness

Theorem 1 (feasibility). Every iterate lies in SS, and the output is an iterate with the largest loss among x0,…,xTx^0, \dots, x^T.

Theorem 2 (linear model, ℓ∞\ell_\infty). For logistic regression and αT≥2ϵ\alpha T \ge 2\epsilon, from any start in SS the last iterate agrees with the FGSM point on every coordinate with wi≠0w_i \ne 0, and the output maximizes the loss over SS.

Theorem 3 (linear model, ℓ2\ell_2). For logistic regression with w≠0w \ne 0, start xx and αT≥ϵ\alpha T \ge \epsilon, if the point x−s ϵ w/∥w∥2x - s\,\epsilon\, w / \lVert w \rVert_2 with s=2y−1s = 2y - 1 lies in [0,1]d[0,1]^d, then it is the last iterate and the maximizer of the loss over SS.

Theorem 1 holds because both forms of PSP_S land in SS: the clip of the ℓ2\ell_2 case moves each coordinate toward [0,1][0,1], which contains xix_i, so it cannot leave the ball. Theorems 2 and 3 hold because the sign, or the direction, of the gradient of a logistic model is the same at every point, so the walk is a straight line that the projection stops at the optimal face. The full proofs are in proofs/correctness.md.

For a network, nothing more is proved. PGD can stop at a local maximum, and a failure of PGD is no proof of robustness. Madry et al. give experimental evidence, not a theorem, that the local maxima have similar losses (their Section 3.1, with 10510^5 restarts on a few MNIST and CIFAR10 points).

Proof: The PGD attack stays in the allowed set and reaches the optimum on a linear modelfull

We write Sp=Bp(x,ϵ)∩[0,1]dS_p = B_p(x, \epsilon) \cap [0,1]^d for p∈{2,∞}p \in \{2, \infty\}, with x∈[0,1]dx \in [0,1]^d, ϵ≥0\epsilon \ge 0 and α>0\alpha > 0. The map PP of line L5 is the function project: for p=∞p = \infty it clips coordinate ii to [ℓi,ui]=[max⁡(xi−ϵ,0),min⁡(xi+ϵ,1)][\ell_i, u_i] = [\max(x_i - \epsilon, 0), \min(x_i + \epsilon, 1)]; for p=2p = 2 it rescales v−xv - x onto the ball, v↦x+min⁡(1,ϵ/∥v−x∥2)(v−x)v \mapsto x + \min(1, \epsilon / \lVert v - x \rVert_2)(v - x), and then clips to [0,1]d[0,1]^d.

Lemma 1. P(v)∈SpP(v) \in S_p for every v∈Rdv \in \mathbb{R}^d. For p=∞p = \infty, PP is the Euclidean projection onto S∞S_\infty.

Proof. For p=∞p = \infty, S∞=∏i[ℓi,ui]S_\infty = \prod_i [\ell_i, u_i], since each coordinate must satisfy ∣vi−xi∣≤ϵ|v_i - x_i| \le \epsilon and 0≤vi≤10 \le v_i \le 1. Clipping each coordinate to its interval gives a point of the product, and it is the nearest point because the squared distance is a sum of one term for each coordinate. For p=2p = 2, the rescaled point rr satisfies ∥r−x∥2≤ϵ\lVert r - x \rVert_2 \le \epsilon. Clipping to [0,1][0,1] moves each coordinate rir_i toward the interval [0,1][0,1], which contains xix_i, so ∣clip⁡(ri)−xi∣≤∣ri−xi∣|\operatorname{clip}(r_i) - x_i| \le |r_i - x_i| for each ii. Hence the clipped point is in [0,1]d[0,1]^d and still within distance ϵ\epsilon of xx. □\square

Theorem 1 (feasibility and monotone record). Every iterate xtx^t lies in SpS_p, and the returned point x⋆x^\star is an iterate with L(x⋆)=max⁡0≤t≤TL(xt)L(x^\star) = \max_{0 \le t \le T} L(x^t), where TT is the number of steps.

Proof. The start of line L1 is x∈Spx \in S_p or the image under PP of a random point, so it lies in SpS_p by Lemma 1. Each later iterate is an image under PP (line L5), so it lies in SpS_p too. Lines L2 and L6 keep the iterate with the largest loss seen so far, and line L7 returns it. □\square

So the returned point is always a valid perturbation of xx, and its loss is at least the loss of the start. This is what an attack needs to give an upper bound on robust accuracy: if x⋆x^\star is misclassified, then xx is not robust at radius ϵ\epsilon.

Theorem 2 (the linear model, p=∞p = \infty). Let the model be logistic regression with logit z(v)=w⊤v+bz(v) = w^\top v + b and label y∈{0,1}y \in \{0,1\}, and let s=2y−1s = 2y - 1. Assume αT≥2ϵ\alpha T \ge 2\epsilon. Then, from any start in S∞S_\infty, the last iterate xTx^T is the point xFx^{\mathrm{F}} returned by FGSM, and x⋆x^\star maximizes the loss over S∞S_\infty.

Proof. The input gradient is g(v)=(σ(z(v))−y) wg(v) = (\sigma(z(v)) - y)\, w. The scalar factor is negative for y=1y = 1 and positive for y=0y = 0, at every vv, so sign⁡(gi(v))=−ssign⁡(wi)\operatorname{sign}(g_i(v)) = -s \operatorname{sign}(w_i) does not depend on vv. Fix a coordinate ii with wi≠0w_i \ne 0, and say −s wi>0-s\, w_i > 0 (the other sign is symmetric). Each step adds α\alpha to coordinate ii and clips it to [ℓi,ui][\ell_i, u_i]. So the coordinate is min⁡(xi0+tα,ui)\min(x^0_i + t\alpha, u_i) after tt steps. Since ui−xi0≤ui−ℓi≤2ϵ≤αTu_i - x^0_i \le u_i - \ell_i \le 2\epsilon \le \alpha T, it equals uiu_i after TT steps. A coordinate with wi=0w_i = 0 has a step of 00 and keeps its start value; it does not change the loss. FGSM sets coordinate ii to uiu_i when −s wi>0-s\, w_i > 0 and to ℓi\ell_i when −s wi<0-s\, w_i < 0 (see the proof page of fast-gradient-sign-method), so xTx^T and xFx^{\mathrm{F}} agree on all coordinates that affect the loss, and L(xT)=L(xF)L(x^T) = L(x^{\mathrm{F}}). That proof also shows that xFx^{\mathrm{F}} maximizes the loss over S∞S_\infty. By Theorem 1, L(x⋆)≥L(xT)L(x^\star) \ge L(x^T), and L(x⋆)L(x^\star) cannot be larger than the maximum, so x⋆x^\star is a maximizer too. □\square

Theorem 3 (the linear model, p=2p = 2). Under the same model, assume that the point xL2=x−s ϵ w/∥w∥2x^{\mathrm{L2}} = x - s\, \epsilon\, w / \lVert w \rVert_2 lies in [0,1]d[0,1]^d, that w≠0w \ne 0, and that the start is xx. If αT≥ϵ\alpha T \ge \epsilon, the last iterate is xL2x^{\mathrm{L2}}, and xL2x^{\mathrm{L2}} maximizes the loss over S2S_2.

Proof. The normalized ascent direction is g/∥g∥2=−s w/∥w∥2=:eg / \lVert g \rVert_2 = -s\, w / \lVert w \rVert_2 =: e at every point, a fixed unit vector. Starting from xx, the iterates stay on the ray x+τex + \tau e with τ≥0\tau \ge 0: a step adds α\alpha to τ\tau, the rescaling caps τ\tau at ϵ\epsilon, and the clip does nothing because the whole segment from xx to xL2x^{\mathrm{L2}} lies in the convex set [0,1]d[0,1]^d. After TT steps τ=min⁡(Tα,ϵ)=ϵ\tau = \min(T\alpha, \epsilon) = \epsilon. For optimality, the loss is increasing in −s z(v)=−s b−s w⊤v-s\, z(v) = -s\,b - s\, w^\top v, and by the Cauchy-Schwarz inequality −s w⊤(v−x)≤∥w∥2∥v−x∥2≤ϵ∥w∥2-s\, w^\top (v - x) \le \lVert w \rVert_2 \lVert v - x \rVert_2 \le \epsilon \lVert w \rVert_2 on S2S_2, with equality at v=xL2v = x^{\mathrm{L2}}. ■\blacksquare

What is not claimed. For a nonlinear model the loss is not concave in vv, and PGD can stop at a local maximum. Theorem 1 still holds, so the output is a valid perturbation, but a failure of PGD is no proof of robustness. Only a verifier or a certificate gives a lower bound on robust accuracy.

Complexity

  • Time. Each step costs one gradient, gg, by backpropagation, one loss value (at most a forward pass, so O(g)O(g)), and O(d)O(d) for the step and the projection. The total is O(T(g+d))O(T (g + d)). With RR restarts the cost is RR times larger.
  • Space. Θ(d)\Theta(d) for the iterate, the gradient and the best point, plus the memory of one backward pass.
  • Model. These counts are in the real-ram model, with one gradient as a unit of work.

Properties

  • Randomized. With a random start, two runs give different outputs. With the start xx the method is deterministic.
  • Anytime. The best loss never goes down from one step to the next, so the run can stop at any step with a valid point.
  • An upper bound only. A misclassified output proves that xx is not robust at radius ϵ\epsilon. A correct output proves nothing.
  • Agrees with FGSM on linear models. On a linear model with αT≥2ϵ\alpha T \ge 2\epsilon, PGD ends at the FGSM point (Theorem 2). The two differ only when the gradient changes sign inside SS, as in the network example.

Variants and improvements

  • Basic iterative method. Kurakin, Goodfellow and Bengio (2017) start at xx, take steps of size α\alpha and clip after each step. It is PGD without the random start.
  • Targeted PGD and the margin loss. Descend on the loss of a target label, or ascend on the margin max⁡k≠yzk−zy\max_{k \ne y} z_k - z_y, which does not saturate like the cross-entropy.
  • Restarts. Run RR walks from different random starts and keep the best. Madry et al. report robust accuracy that goes down a little as steps and restarts grow (their Table 1).
  • Step size schedules. A step size that shrinks over time, or one that adapts to the progress of the loss, removes the need to tune α\alpha. The AutoAttack suite of Croce and Hein (2020) uses such a variant.
  • Other norms. For ℓ1\ell_1, the steepest ascent direction moves only the largest coordinates of gg, and the projection onto the ℓ1\ell_1 ball needs a sort.
  • PGD for training. Adversarial training runs PGD on each training batch and trains on the result.

When to use it

Use PGD with restarts as the first strong attack in a robustness evaluation, and as the inner step of adversarial training. Report the norm, ϵ\epsilon, α\alpha, TT, the number of restarts and the loss. Add a minimal-distance attack, such as the Carlini-Wagner attack or DeepFool, to see how far the decision boundary is. For a defense that changes the gradients, adapt the attack (BPDA, EOT). To prove robustness, use a certificate such as randomized smoothing or interval bound propagation.

Pitfalls

  • Too few steps. If αT<2ϵ\alpha T < 2\epsilon, part of the box cannot be reached, and the robust accuracy is too high. Check that a larger TT does not lower it further.
  • Only the last iterate. A fixed step size can overshoot. Keep the best iterate, as line L6 does, or the result can be worse than FGSM.
  • No clip to the box. Without the clip of PSP_S to [0,1]d[0,1]^d, the output is not a valid input.
  • Clip in the wrong order for ℓ2\ell_2. Clip after the rescaling, not before. The clip after the rescaling cannot leave the ball (Theorem 1); a rescaling after the clip can leave the box.
  • Gradient masking. Defenses with saturated softmax outputs, random input transformations or non-differentiable steps can make PGD fail while the model is not robust. Athalye, Carlini and Wagner (2018) broke 7 of 9 ICLR 2018 defenses in this way. A check: an unbounded attack with a large ϵ\epsilon must reach 100 percent success (Carlini et al. 2019).
  • The cross-entropy saturates. When the softmax gives the true label a probability near 11, the gradient of the cross-entropy is tiny. The margin loss avoids this.

Implementations

The code of this page is an abstract model on synthetic data. The attack runs only on models that the tests build from a fixed seed: a logistic regression with given weights, or a two-layer ReLU network from mlkit.tiny_relu_net, on seeded random inputs. It never reads real data or touches a real system. The tests check the trace of the linear example, the network example where FGSM fails and PGD succeeds, that one step from xx with α=ϵ\alpha = \epsilon equals FGSM, that PGD from a random start reaches the maximum over all corners of the box on random logistic models, that it reaches the closed-form ℓ2\ell_2 optimum, that every iterate stays in SS on 500 random networks for both norms, and that the ℓ2\ell_2 random start is uniform in the disc.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

mlkit.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small vector tools, synthetic data and two tiny models for the adversarial machine learning pages.

Vectors are lists of floats. Every model here is synthetic: it is built from a seeded
random.Random and never from real data. The helper holds no attack loop, no
certification and no defense; those live in the slug files of the pages.
"""

import math
import random
from typing import Callable, Sequence

Vector = list[float]
Matrix = list[list[float]]
Net = dict[str, list]
Data = list[tuple[Vector, int]]


def dot(u: Sequence[float], v: Sequence[float]) -> float:
    """Inner product of two vectors of the same length. Cost O(d)."""
    return math.fsum(a * b for a, b in zip(u, v, strict=True))


def add(u: Sequence[float], v: Sequence[float]) -> Vector:
    """Coordinatewise sum u + v. Cost O(d)."""
    return [a + b for a, b in zip(u, v, strict=True)]


def sub(u: Sequence[float], v: Sequence[float]) -> Vector:
    """Coordinatewise difference u - v. Cost O(d)."""
    return [a - b for a, b in zip(u, v, strict=True)]


def scale(c: float, v: Sequence[float]) -> Vector:
    """The vector c v. Cost O(d)."""
    return [c * a for a in v]


def norm1(v: Sequence[float]) -> float:
    """The l1 norm, the sum of |v_i|. Cost O(d)."""
    return math.fsum(abs(a) for a in v)


def norm2(v: Sequence[float]) -> float:
    """The Euclidean norm. Cost O(d)."""
    return math.sqrt(math.fsum(a * a for a in v))


def norminf(v: Sequence[float]) -> float:
    """The l_infinity norm, max |v_i|, and 0 for the empty vector. Cost O(d)."""
    return max((abs(a) for a in v), default=0.0)


def project_l2(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
    """Euclidean projection of v onto the l2 ball of the given center and radius >= 0.

    A point inside the ball is returned unchanged; a point outside is moved along the
    segment to the center until it is on the sphere. Cost O(d).
    """
    diff = sub(v, center)
    r = norm2(diff)
    if r <= radius:
        return list(v)
    return add(center, scale(radius / r, diff))


def project_linf(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
    """Euclidean projection of v onto the l_infinity ball: clip each coordinate to [c_i - r, c_i + r]. Cost O(d)."""
    return [min(max(a, c - radius), c + radius) for a, c in zip(v, center, strict=True)]


def clip01(v: Sequence[float]) -> Vector:
    """Euclidean projection onto the box [0, 1]^d. Cost O(d)."""
    return [min(max(a, 0.0), 1.0) for a in v]


def make_blobs(rng: random.Random, n: int, d: int, centers: Sequence[Sequence[float]], sigma: float) -> Data:
    """n synthetic points in R^d from Gaussian blobs N(center, sigma^2 I).

    Point i gets the label i mod len(centers) and is drawn around that center, so the
    classes are balanced. The points are not clipped. Cost O(n d) and n d draws of rng.
    """
    for c in centers:
        if len(c) != d:
            raise ValueError("each center must have d coordinates")
    data: Data = []
    for i in range(n):
        label = i % len(centers)
        x = [c + rng.gauss(0.0, sigma) for c in centers[label]]
        data.append((x, label))
    return data


def sigmoid(t: float) -> float:
    """The logistic function 1 / (1 + e^(-t)), computed without overflow. Cost O(1)."""
    if t >= 0:
        return 1.0 / (1.0 + math.exp(-t))
    e = math.exp(t)
    return e / (1.0 + e)


def _softplus(t: float) -> float:
    """ln(1 + e^t) without overflow."""
    return max(t, 0.0) + math.log1p(math.exp(-abs(t)))


def logistic_loss(w: Sequence[float], b: float, x: Sequence[float], y: int) -> float:
    """Logistic loss of the linear model z = w.x + b on a label y in {0, 1}.

    The loss is ln(1 + e^(-s z)) with s = 2 y - 1. Cost O(d).
    """
    s = 2 * y - 1
    return _softplus(-s * (dot(w, x) + b))


def grad_x_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> Vector:
    """Gradient of logistic_loss in the input x: (sigmoid(z) - y) w. Cost O(d)."""
    g = sigmoid(dot(w, x) + b) - y
    return scale(g, w)


def grad_w_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> tuple[Vector, float]:
    """Gradient of logistic_loss in the parameters: ((sigmoid(z) - y) x, sigmoid(z) - y). Cost O(d)."""
    g = sigmoid(dot(w, x) + b) - y
    return scale(g, x), g


def train_logistic(data: Data, steps: int, lr: float, l2: float) -> tuple[Vector, float]:
    """Full-batch gradient descent on the mean logistic loss plus (l2 / 2) ||w||^2.

    Labels are in {0, 1}. The weights start at zero, so the result is deterministic.
    The bias has no penalty. Returns (w, b). Cost O(steps n d).
    """
    d = len(data[0][0])
    n = len(data)
    w = [0.0] * d
    b = 0.0
    for _ in range(steps):
        gw = [0.0] * d
        gb = 0.0
        for x, y in data:
            g = sigmoid(dot(w, x) + b) - y
            for j in range(d):
                gw[j] += g * x[j]
            gb += g
        w = [w[j] - lr * (gw[j] / n + l2 * w[j]) for j in range(d)]
        b -= lr * gb / n
    return w, b


def tiny_relu_net(rng: random.Random, d: int, h: int, k: int) -> Net:
    """A fixed-seed two-layer ReLU network with d inputs, h hidden units and k logits.

    The weights are drawn from N(0, 1/d) in the first layer and N(0, 1/h) in the second,
    and the biases from N(0, 0.01). The dict has the keys W1 (h rows of d), b1 (h),
    W2 (k rows of h) and b2 (k). Cost O(h d + k h).
    """
    s1, s2 = 1.0 / math.sqrt(d), 1.0 / math.sqrt(h)
    return {
        "W1": [[rng.gauss(0.0, s1) for _ in range(d)] for _ in range(h)],
        "b1": [rng.gauss(0.0, 0.1) for _ in range(h)],
        "W2": [[rng.gauss(0.0, s2) for _ in range(h)] for _ in range(k)],
        "b2": [rng.gauss(0.0, 0.1) for _ in range(k)],
    }


def _hidden(net: Net, x: Sequence[float]) -> tuple[Vector, Vector]:
    """Pre-activations and activations of the hidden layer."""
    pre = [dot(row, x) + bi for row, bi in zip(net["W1"], net["b1"], strict=True)]
    return pre, [max(a, 0.0) for a in pre]


def forward(net: Net, x: Sequence[float]) -> Vector:
    """Logits z(x) = W2 relu(W1 x + b1) + b2 of a tiny_relu_net. Cost O(h d + k h)."""
    _, act = _hidden(net, x)
    return [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]


def argmax(z: Sequence[float]) -> int:
    """The first index of a largest entry. Cost O(k)."""
    best = 0
    for i in range(1, len(z)):
        if z[i] > z[best]:
            best = i
    return best


def softmax(z: Sequence[float]) -> Vector:
    """The softmax of a logit vector, shifted by the maximum to avoid overflow. Cost O(k)."""
    m = max(z)
    e = [math.exp(a - m) for a in z]
    s = math.fsum(e)
    return [a / s for a in e]


def cross_entropy(z: Sequence[float], label: int) -> float:
    """Cross-entropy loss -ln softmax(z)[label], computed as logsumexp(z) - z[label]. Cost O(k)."""
    m = max(z)
    return m + math.log(math.fsum(math.exp(a - m) for a in z)) - z[label]


def logits_jacobian(net: Net, x: Sequence[float]) -> Matrix:
    """The k by d Jacobian of the logits in the input, W2 diag(relu'(pre)) W1.

    The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
    Cost O(k h d).
    """
    pre, _ = _hidden(net, x)
    d = len(x)
    rows = []
    for w2 in net["W2"]:
        row = [0.0] * d
        for i, a in enumerate(pre):
            if a > 0 and w2[i] != 0.0:
                c = w2[i]
                w1 = net["W1"][i]
                for j in range(d):
                    row[j] += c * w1[j]
        rows.append(row)
    return rows


def input_gradient(net: Net, x: Sequence[float], label: int) -> Vector:
    """Gradient in x of cross_entropy(forward(net, x), label), by backpropagation.

    The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
    Cost O(h d + k h).
    """
    pre, act = _hidden(net, x)
    z = [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
    p = softmax(z)
    p[label] -= 1.0
    back = [0.0] * len(pre)
    for c, row in zip(p, net["W2"], strict=True):
        for i in range(len(pre)):
            back[i] += c * row[i]
    g = [0.0] * len(x)
    for i, a in enumerate(pre):
        if a > 0:
            w1 = net["W1"][i]
            for j in range(len(x)):
                g[j] += back[i] * w1[j]
    return g


def accuracy(predict: Callable[[Vector], int], data: Data) -> float:
    """Fraction of the pairs (x, y) of data with predict(x) == y. Cost: n calls of predict."""
    if not data:
        return 0.0
    return sum(1 for x, y in data if predict(x) == y) / len(data)
pgd_attack.py 79 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pgd-attack/. The authors are listed in prov/YAKX8W.jsonl.

"""The projected gradient descent attack of Madry et al. (2018), on synthetic models only.

The tests run it on a seeded logistic model and a seeded two-layer ReLU network from
mlkit. Nothing here reads real data or touches a real system.
"""

import math
import random
from typing import Callable, Sequence

Vector = list[float]
Gradient = Callable[[Vector, int], Vector]
Loss = Callable[[Vector, int], float]


def sign(t: float) -> float:
    """The sign function with sign(0) = 0."""
    return 1.0 if t > 0 else (-1.0 if t < 0 else 0.0)


def project(v: Sequence[float], x: Sequence[float], epsilon: float, norm: str) -> Vector:
    """Map v into B_p(x, epsilon) intersected with [0, 1]^d, for norm "inf" or "2".

    For "inf" this is the exact Euclidean projection: the set is a box, so clip each
    coordinate to [max(x_i - epsilon, 0), min(x_i + epsilon, 1)]. For "2" it rescales
    v - x onto the ball and then clips to [0, 1]; the clip cannot leave the ball
    because it moves each coordinate toward x_i in [0, 1]. Cost O(d).
    """
    if norm == "inf":
        return [min(max(a, c - epsilon, 0.0), c + epsilon, 1.0) for a, c in zip(v, x, strict=True)]
    diff = [a - c for a, c in zip(v, x, strict=True)]
    r = math.sqrt(math.fsum(t * t for t in diff))
    f = 1.0 if r <= epsilon else epsilon / r
    return [min(max(c + f * t, 0.0), 1.0) for c, t in zip(x, diff)]


def ascent_direction(g: Sequence[float], norm: str) -> Vector:
    """The steepest ascent step of unit size for the norm: sign(g) for l_inf, g / ||g||_2 for l2."""
    if norm == "inf":
        return [sign(t) for t in g]
    r = math.sqrt(math.fsum(t * t for t in g))
    return [0.0] * len(g) if r == 0 else [t / r for t in g]


def random_start(rng: random.Random, x: Sequence[float], epsilon: float, norm: str) -> Vector:
    """A random point of the ball: uniform in the l_inf box, or uniform in the l2 ball; then mapped into [0, 1]^d."""
    d = len(x)
    if norm == "inf":
        u = [rng.uniform(-epsilon, epsilon) for _ in range(d)]
    else:
        u = [rng.gauss(0.0, 1.0) for _ in range(d)]
        r = math.sqrt(math.fsum(t * t for t in u)) or 1.0
        rad = epsilon * rng.random() ** (1.0 / d) if d else 0.0
        u = [rad * t / r for t in u]
    return project([a + b for a, b in zip(x, u)], x, epsilon, norm)


def pgd_attack(grad: Gradient, loss: Loss, x: Sequence[float], y: int, epsilon: float, alpha: float,
               steps: int, norm: str = "inf", rng: random.Random | None = None) -> Vector:
    """PGD on the loss over B_p(x, epsilon) cap [0, 1]^d. Returns the iterate with the largest loss.

    grad(x, y) and loss(x, y) are the input gradient and the loss of a fixed model.
    With rng the start is a random point of the ball; without it the start is x.
    Precondition: x in [0, 1]^d, epsilon >= 0, alpha > 0, steps >= 0.
    Cost: steps gradient calls, steps + 1 loss calls and O(steps d) more.
    """
    xt = random_start(rng, x, epsilon, norm) if rng is not None else list(x)  # @line L1
    best, best_loss = xt, loss(xt, y)  # @line L2
    for _ in range(steps):  # @line L3
        g = grad(xt, y)  # @line L4
        step = ascent_direction(g, norm)
        xt = project([a + alpha * s for a, s in zip(xt, step)], x, epsilon, norm)  # @line L5
        lt = loss(xt, y)  # @line L6
        if lt > best_loss:
            best, best_loss = xt, lt
    return best  # @line L7
test_pgd_attack.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pgd-attack/. The authors are listed in prov/YAKX8W.jsonl.

"""Tests of the PGD attack, on seeded synthetic models only."""

import itertools
import math
import random

import mlkit as m
from pgd_attack import ascent_direction, pgd_attack, project, random_start

TOL = 1e-9
W = [1.5, -2.0, 0.5, 1.0, -0.5, 3.0]
B = 1.0
X = [0.2, 0.9, 0.5, 0.0, 1.0, 0.4]


def logistic(w, b):
    return (lambda u, t: m.grad_x_logistic(w, b, u, t)), (lambda u, t: m.logistic_loss(w, b, u, t))


def feasible(xa, x, eps, norm) -> bool:
    dist = m.norminf(m.sub(xa, x)) if norm == "inf" else m.norm2(m.sub(xa, x))
    return dist <= eps + TOL and all(-TOL <= a <= 1 + TOL for a in xa)


def test_page_example() -> None:
    g, f = logistic(W, B)
    xa = pgd_attack(g, f, X, 1, 0.1, 0.025, 10)
    assert all(abs(a - e) < TOL for a, e in zip(xa, [0.1, 1.0, 0.4, 0.0, 1.0, 0.3]))
    assert abs(m.dot(W, xa) + B + 0.25) < TOL
    # after 2 steps of 0.025 each moved coordinate is 0.05 from x
    x2 = pgd_attack(g, f, X, 1, 0.1, 0.025, 2)
    assert all(abs(a - e) < TOL for a, e in zip(x2, [0.15, 0.95, 0.45, 0.0, 1.0, 0.35]))


def test_page_network_example() -> None:
    # the seeded network of the page: FGSM keeps label 0, PGD reaches label 1 at step 7
    net = m.tiny_relu_net(random.Random(2744), 2, 4, 2)
    g = lambda u, t: m.input_gradient(net, u, t)
    f = lambda u, t: m.cross_entropy(m.forward(net, u), t)
    x = [0.63, 0.46]
    one = pgd_attack(g, f, x, 0, 0.1, 0.1, 1)
    assert all(abs(a - e) < TOL for a, e in zip(one, [0.53, 0.36]))
    assert m.argmax(m.forward(net, one)) == 0
    xa = pgd_attack(g, f, x, 0, 0.1, 0.025, 10)
    assert all(abs(a - e) < TOL for a, e in zip(xa, [0.73, 0.36]))
    assert m.argmax(m.forward(net, xa)) == 1
    assert m.argmax(m.forward(net, pgd_attack(g, f, x, 0, 0.1, 0.025, 6))) == 0
    assert m.argmax(m.forward(net, pgd_attack(g, f, x, 0, 0.1, 0.025, 7))) == 1


def test_edges() -> None:
    g, f = logistic(W, B)
    assert pgd_attack(g, f, X, 1, 0.1, 0.025, 0) == X
    assert pgd_attack(g, f, X, 1, 0.0, 0.025, 5) == X
    assert project([2.0, -1.0], [0.5, 0.5], 0.25, "inf") == [0.75, 0.25]
    assert project([0.5, 0.5], [0.5, 0.5], 0.25, "2") == [0.5, 0.5]
    assert ascent_direction([0.0, 0.0], "2") == [0.0, 0.0]


def test_one_step_from_x_is_fgsm() -> None:
    rng = random.Random(7201)
    for _ in range(500):
        d, h, k = rng.randint(1, 5), rng.randint(2, 8), rng.randint(2, 4)
        net = m.tiny_relu_net(rng, d, h, k)
        x = [rng.uniform(0, 1) for _ in range(d)]
        y = rng.randrange(k)
        eps = rng.uniform(0, 0.4)
        g = lambda u, t: m.input_gradient(net, u, t)
        f = lambda u, t: m.cross_entropy(m.forward(net, u), t)
        gx = g(x, y)
        fgsm = [min(max(a + eps * (1 if s > 0 else -1 if s < 0 else 0), 0.0), 1.0) for a, s in zip(x, gx)]
        one = pgd_attack(g, f, x, y, eps, eps, 1)
        if f(fgsm, y) > f(x, y):
            assert all(abs(a - b) < TOL for a, b in zip(one, fgsm))
        assert f(one, y) >= f(x, y) - TOL


def test_linear_model_reaches_the_vertex_optimum_from_a_random_start() -> None:
    # For a linear model the loss is convex in x, so its maximum over the box
    # B_inf(x, eps) cap [0, 1]^d is at a vertex; enumerate the 2^d vertices.
    rng = random.Random(7202)
    for _ in range(500):
        d = rng.randint(1, 4)
        w = [rng.choice([-1, 1]) * rng.uniform(0.1, 3) for _ in range(d)]
        b = rng.uniform(-1, 1)
        x = [rng.choice([0.0, 1.0, rng.uniform(0, 1)]) for _ in range(d)]
        y = rng.randint(0, 1)
        eps = rng.uniform(0.01, 0.5)
        alpha = eps / 4
        g, f = logistic(w, b)
        xa = pgd_attack(g, f, x, y, eps, alpha, 9, "inf", rng)
        assert feasible(xa, x, eps, "inf")
        lo = [max(a - eps, 0.0) for a in x]
        hi = [min(a + eps, 1.0) for a in x]
        best = max(f(list(v), y) for v in itertools.product(*zip(lo, hi)))
        assert abs(f(xa, y) - best) < 1e-9


def test_l2_linear_model_reaches_the_closed_form() -> None:
    # Inside the box, the l2 maximum of a loss that grows along g is x + eps g / ||g||.
    rng = random.Random(7203)
    for _ in range(500):
        d = rng.randint(1, 6)
        w = [rng.uniform(-2, 2) for _ in range(d)]
        b = rng.uniform(-1, 1)
        x = [rng.uniform(0.35, 0.65) for _ in range(d)]
        y = rng.randint(0, 1)
        eps = rng.uniform(0.01, 0.3)
        g, f = logistic(w, b)
        xa = pgd_attack(g, f, x, y, eps, eps / 3, 5, "2")
        assert feasible(xa, x, eps, "2")
        gx = g(x, y)
        target = m.add(x, m.scale(eps / m.norm2(gx), gx))
        assert m.norm2(m.sub(xa, target)) < 1e-9


def test_iterates_stay_feasible_on_relu_nets() -> None:
    rng = random.Random(7204)
    for _ in range(500):
        d, h, k = rng.randint(1, 4), rng.randint(2, 8), rng.randint(2, 3)
        net = m.tiny_relu_net(rng, d, h, k)
        x = [rng.uniform(0, 1) for _ in range(d)]
        y = rng.randrange(k)
        eps = rng.uniform(0, 0.3)
        norm = rng.choice(["inf", "2"])
        g = lambda u, t: m.input_gradient(net, u, t)
        f = lambda u, t: m.cross_entropy(m.forward(net, u), t)
        start = random_start(random.Random(rng.random()), x, eps, norm)
        assert feasible(start, x, eps, norm)
        xa = pgd_attack(g, f, x, y, eps, eps / 4, 6, norm, rng)
        assert feasible(xa, x, eps, norm)


def test_l2_random_start_is_inside_the_ball() -> None:
    rng = random.Random(7205)
    radii = []
    for _ in range(2000):
        u = random_start(rng, [0.5, 0.5], 0.2, "2")
        radii.append(math.dist(u, [0.5, 0.5]))
    assert max(radii) <= 0.2 + TOL
    # uniform in a disc: P(r <= 0.1) = 1/4; 2000 draws give a standard error of about 0.01
    frac = sum(r <= 0.1 for r in radii) / len(radii)
    assert abs(frac - 0.25) < 0.05

History

Kurakin, Goodfellow and Bengio (2016) proposed the basic iterative method, which repeats the FGSM step with clipping, and used it on photos of printed adversarial images. Madry, Makelov, Schmidt, Tsipras and Vladu posted their paper in June 2017 (ICLR 2018). They stated robustness as a saddle point problem, added the random start, called the inner method projected gradient descent and argued that it is a "universal" first-order adversary. Their PGD-trained models reached more than 89 percent accuracy on MNIST against their strongest white-box attack at ϵ=0.3\epsilon = 0.3, and 45.8 percent on CIFAR10 against PGD with 20 steps at ϵ=8/255\epsilon = 8/255 (measurements in their Section 5). They also published the models as open challenges. Later evaluations with stronger variants, such as AutoAttack, lowered such numbers a little but did not break PGD training.

References

  1. Aleksander Madry, Aleksandar Makelov, Ludwig Schmidt, Dimitris Tsipras and Adrian Vladu, Towards deep learning models resistant to adversarial attacks, ICLR 2018, Section 2 (the saddle point problem, equation 2.1, and the PGD step), Section 3.1 (the landscape of local maxima over random restarts), Section 3.2 (first-order adversaries), Section 5 (the attack settings on MNIST and CIFAR10 and Tables 1 and 2)
  2. Alexey Kurakin, Ian Goodfellow and Samy Bengio, Adversarial examples in the physical world, ICLR 2017 workshop, the basic iterative method, which repeats the FGSM step and clips to the epsilon box after each step
  3. Ian J. Goodfellow, Jonathon Shlens and Christian Szegedy, Explaining and harnessing adversarial examples, ICLR 2015, Section 4 (the one-step method that PGD repeats)
  4. Anish Athalye, Nicholas Carlini and David Wagner, Obfuscated gradients give a false sense of security, circumventing defenses to adversarial examples, ICML 2018, the defenses that made PGD fail through obfuscated gradients, and the adapted attacks that broke them
  5. Nicholas Carlini, Anish Athalye, Nicolas Papernot, Wieland Brendel, Jonas Rauber, Dimitris Tsipras, Ian Goodfellow, Aleksander Madry and Alexey Kurakin, On evaluating adversarial robustness, arXiv 2019, the advice on step counts, restarts, the loss to use and the checks of an evaluation
  6. Francesco Croce and Matthias Hein, Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks, ICML 2020, the PGD variant with an adaptive step size (APGD) and the AutoAttack suite
  7. Battista Biggio and Fabio Roli, Wild patterns: Ten years after the rise of adversarial machine learning, Pattern Recognition 84, pages 317 to 331, 2018, the threat model in three parts used on this page

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example