Algorithm Search⌘K

Algorithmintro

Fast gradient sign method

Also called FGSM.

Builds an adversarial example in one step by moving each input coordinate by epsilon in the sign of the loss gradient, then clipping to the valid range.

Time
O(g + d) worst
Space
Θ(d) extra
Where
d = the input dimension; g = the cost of one input gradient of the loss
Properties
deterministicnot exactofflineiterative
Origin
Ian J. Goodfellow, Jonathon Shlens, Christian Szegedy, 2014

The fast gradient sign method (FGSM) builds an adversarial example with one gradient. It computes the gradient g=∇xL(θ,x,y)g = \nabla_x L(\theta, x, y) of the loss in the input, and moves every coordinate of xx by ϵ\epsilon in the direction of the sign of gg: x′=clip⁡[0,1](x+ϵsign⁡(g))x' = \operatorname{clip}_{[0,1]}(x + \epsilon \operatorname{sign}(g)). The step maximizes the first-order model of the loss over the ℓ∞\ell_\infty ball of radius ϵ\epsilon, so on a linear model it is the exact worst case. Goodfellow, Shlens and Szegedy (2015) proposed it to support their claim that adversarial examples come from the near-linear behavior of networks. FGSM is the one-step special case of the PGD attack and the classic inner step of adversarial training.

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 B∞(x,ϵ)∩[0,1]dB_\infty(x, \epsilon) \cap [0,1]^d.

In plain words

A model gives each input a score of how wrong it is, the loss. The gradient tells, for each part of the input, whether making that part a bit larger raises the loss or lowers it.

FGSM asks this question one time. Then it moves every part of the input by the same small amount, up where that raises the loss and down where it lowers the loss. It does not care how strong the effect of each part is, only its direction. Each part stays in its valid range, for example a pixel stays between black and white.

Many small changes in the same harmful direction add up. In an image with thousands of pixels, a change too small to see can change the answer of the model. FGSM is fast because it needs only one gradient, and it is weak for the same reason.

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 and a radius ϵ≥0\epsilon \ge 0, find x′∈S=B∞(x,ϵ)∩[0,1]dx' \in S = B_\infty(x, \epsilon) \cap [0,1]^d with a large loss, ideally arg⁡max⁡x′∈SL(θ,x′,y)\arg\max_{x' \in S} L(\theta, x', y). If the result has a label other than yy, it is an adversarial example. FGSM solves the linearized problem max⁡x′∈Sg⊤(x′−x)\max_{x' \in S} g^\top (x' - x) exactly.

The algorithm

  1. FGSM(L, x, y, epsilon) ▷ x in [0, 1]^d with label y
  2. 1g ← ∇_x L(θ, x, y) ▷ one forward and one backward pass
  3. 2for i ← 1 to d do
  4. 3v ← x_i + epsilon · sign(g_i) ▷ sign(0) = 0
  5. 4x'_i ← min(max(v, 0), 1) ▷ stay in the valid range
  6. 5return x'

Line L1 is the only call of the model. Lines L2 to L4 work on each coordinate alone: a coordinate with a positive partial derivative goes up by ϵ\epsilon, one with a negative partial derivative goes down by ϵ\epsilon, and the clip of line L4 stops it at 00 or 11. Because xi∈[0,1]x_i \in [0,1], the clip never moves a coordinate by more than ϵ\epsilon from xix_i, so x′x' stays in SS.

For a targeted attack toward class tt, line L1 takes the gradient of L(θ,x,t)L(\theta, x, t) and line L3 uses −ϵ-\epsilon, so that the loss of the target label goes down.

Example

Take logistic regression with w=(1.5,−2,0.5,1,−0.5,3)w = (1.5, -2, 0.5, 1, -0.5, 3) and b=1b = 1, the logistic loss L=ln⁡(1+e−z)L = \ln(1 + e^{-z}) for the label y=1y = 1, and x=(0.2,0.9,0.5,0,1,0.4)x = (0.2, 0.9, 0.5, 0, 1, 0.4) with ϵ=0.1\epsilon = 0.1. The logit is z=w⊤x+b=0.45z = w^\top x + b = 0.45, so σ(z)=0.610639\sigma(z) = 0.610639 and L=0.493249L = 0.493249. The gradient of line L1 is g=(σ(z)−1) w=−0.389361 wg = (\sigma(z) - 1)\, w = -0.389361\, w.

ii xix_i wiw_i gig_i sign⁡(gi)\operatorname{sign}(g_i) line L3 line L4
1 0.2 1.5 -0.5840 -1 0.1 0.1
2 0.9 -2 0.7787 +1 1.0 1.0
3 0.5 0.5 -0.1947 -1 0.4 0.4
4 0 1 -0.3894 -1 -0.1 0
5 1 -0.5 0.1947 +1 1.1 1
6 0.4 3 -1.1681 -1 0.3 0.3

The result is x′=(0.1,1,0.4,0,1,0.3)x' = (0.1, 1, 0.4, 0, 1, 0.3). Its logit is z′=0.45−0.1(1.5+2+0.5+3)=−0.25z' = 0.45 - 0.1(1.5 + 2 + 0.5 + 3) = -0.25, so σ(z′)=0.437823\sigma(z') = 0.437823, the label is 00 and the loss is 0.8259390.825939. The clip of line L4 removed the moves of coordinates 4 and 5, which would have lowered the logit by another 0.150.15. Without the box the result would not be a valid input.

On this model FGSM is exact: no point of SS has a larger loss. At ϵ=0.05\epsilon = 0.05 the same step gives z′=0.1>0z' = 0.1 > 0, and so no adversarial example exists at that radius.

Correctness

Theorem. The output x′x' lies in S=B∞(x,ϵ)∩[0,1]dS = B_\infty(x, \epsilon) \cap [0,1]^d. It maximizes the linearized loss L(θ,x,y)+g⊤(x′−x)L(\theta, x, y) + g^\top (x' - x) over SS, with gain ϵ∥g∥1\epsilon \lVert g \rVert_1 when no coordinate is clipped. For logistic regression it maximizes the true loss over SS.

The key facts are that SS is a box ∏i[max⁡(xi−ϵ,0),min⁡(xi+ϵ,1)]\prod_i [\max(x_i - \epsilon, 0), \min(x_i + \epsilon, 1)] and that the linear objective is a sum of terms in one coordinate each, so each term is maximized at the end of its interval that the sign of gig_i picks; lines L3 and L4 compute exactly that end. For logistic regression the sign of gig_i is −ssign⁡(wi)-s \operatorname{sign}(w_i) with s=2y−1s = 2y - 1 at every point, and the loss is increasing in −s z-s\, z, so the linear argument applies to the true loss. The full proof is in proofs/correctness.md.

For a nonlinear model, FGSM is a heuristic: the linearization is valid only near xx, and a larger loss inside SS may exist.

Proof: FGSM stays in the allowed set and is the exact maximizer of a linearized lossfull

We write S=B∞(x,ϵ)∩[0,1]dS = B_\infty(x, \epsilon) \cap [0,1]^d for the allowed set, with x∈[0,1]dx \in [0,1]^d and ϵ≥0\epsilon \ge 0, and g=∇xL(θ,x,y)g = \nabla_x L(\theta, x, y) for the gradient that line L1 computes. FGSM returns x′x' with xi′=clip⁡[0,1](xi+ϵsign⁡(gi))x'_i = \operatorname{clip}_{[0,1]}(x_i + \epsilon \operatorname{sign}(g_i)) (lines L2 to L4), where sign⁡(0)=0\operatorname{sign}(0) = 0.

Lemma 1 (the set is a box). S=∏i[ℓi,ui]S = \prod_i [\ell_i, u_i] with ℓi=max⁡(xi−ϵ,0)\ell_i = \max(x_i - \epsilon, 0) and ui=min⁡(xi+ϵ,1)u_i = \min(x_i + \epsilon, 1), and ℓi≤xi≤ui\ell_i \le x_i \le u_i.

Proof. A point vv is in SS when ∣vi−xi∣≤ϵ|v_i - x_i| \le \epsilon and 0≤vi≤10 \le v_i \le 1 for every ii. These are two interval conditions on each coordinate, and their intersection is [ℓi,ui][\ell_i, u_i]. Because 0≤xi≤10 \le x_i \le 1 and ϵ≥0\epsilon \ge 0, xix_i is in both intervals. □\square

Lemma 2 (feasibility). x′∈Sx' \in S.

Proof. Take a coordinate ii. If gi>0g_i > 0, line L3 gives v=xi+ϵ≥0v = x_i + \epsilon \ge 0, so line L4 gives xi′=min⁡(xi+ϵ,1)=uix'_i = \min(x_i + \epsilon, 1) = u_i. If gi<0g_i < 0, then v=xi−ϵ≤1v = x_i - \epsilon \le 1 and xi′=max⁡(xi−ϵ,0)=ℓix'_i = \max(x_i - \epsilon, 0) = \ell_i. If gi=0g_i = 0, then xi′=xix'_i = x_i. In each case xi′∈[ℓi,ui]x'_i \in [\ell_i, u_i], so x′∈Sx' \in S by Lemma 1. □\square

Theorem 1 (exact for the linearized loss). Let L^(v)=L(θ,x,y)+g⊤(v−x)\hat L(v) = L(\theta, x, y) + g^\top (v - x) be the first-order model of the loss at xx. Then x′x' maximizes L^\hat L over SS. If no coordinate is clipped (that is, ϵ≤xi≤1−ϵ\epsilon \le x_i \le 1 - \epsilon wherever gi≠0g_i \ne 0), the maximum gain is L^(x′)−L^(x)=ϵ∥g∥1\hat L(x') - \hat L(x) = \epsilon \lVert g \rVert_1.

Proof. The gain g⊤(v−x)=∑igi(vi−xi)g^\top(v - x) = \sum_i g_i (v_i - x_i) is a sum of terms that each depend on one coordinate, and by Lemma 1 the coordinates of vv range over independent intervals. So the sum is largest when each term is largest. The term gi(vi−xi)g_i(v_i - x_i) is increasing in viv_i when gi>0g_i > 0, so its maximum is at vi=uiv_i = u_i; it is decreasing when gi<0g_i < 0, so its maximum is at vi=ℓiv_i = \ell_i; it is 00 for every viv_i when gi=0g_i = 0. The proof of Lemma 2 shows that xi′x'_i takes exactly these values. Without clipping, ui−xi=ϵu_i - x_i = \epsilon and ℓi−xi=−ϵ\ell_i - x_i = -\epsilon, so the gain is ∑i∣gi∣ϵ=ϵ∥g∥1\sum_i |g_i| \epsilon = \epsilon \lVert g \rVert_1. □\square

Theorem 2 (exact for logistic regression). Let the model be logistic regression with logit z(v)=w⊤v+bz(v) = w^\top v + b, label y∈{0,1}y \in \{0, 1\}, s=2y−1s = 2y - 1 and loss L(v)=ln⁡(1+e−sz(v))L(v) = \ln(1 + e^{-s z(v)}). Then x′x' maximizes the true loss LL over SS, not only its linearization.

Proof. The gradient is g=(σ(z(x))−y) wg = (\sigma(z(x)) - y)\, w. For y=1y = 1 the factor σ(z)−1\sigma(z) - 1 is negative, and for y=0y = 0 the factor σ(z)\sigma(z) is positive, so sign⁡(gi)=−ssign⁡(wi)\operatorname{sign}(g_i) = -s \operatorname{sign}(w_i) for every ii (both are 00 when wi=0w_i = 0). The function t↦ln⁡(1+et)t \mapsto \ln(1 + e^{t}) is increasing, so L(v)L(v) is an increasing function of −s z(v)=−s b+∑i(−s wi)vi-s\, z(v) = -s\, b + \sum_i (-s\, w_i) v_i. By the argument of Theorem 1 with the coefficients −s wi-s\, w_i in place of gig_i, the linear function −s z(v)-s\, z(v) is largest over SS at the point with vi=uiv_i = u_i when −s wi>0-s\, w_i > 0 and vi=ℓiv_i = \ell_i when −s wi<0-s\, w_i < 0. Since the coefficients have the signs of the gig_i, this point is x′x'. A maximizer of −s z-s\, z is a maximizer of LL. ■\blacksquare

Targeted variant. The function targeted_fgsm steps against the gradient of the loss of the target label. The same argument with −g-g in place of gg shows that it minimizes the linearized target loss over SS.

Complexity

  • Time. Line L1 costs one gradient, gg, which by backpropagation is a small constant times the cost of a forward pass. Lines L2 to L4 cost O(d)O(d). The total is O(g+d)O(g + d).
  • Space. Θ(d)\Theta(d) for gg and x′x', plus the memory of one backward pass.
  • Queries. One gradient, against hundreds or thousands of steps for the PGD attack, the Carlini-Wagner attack or a black-box attack.

Properties

  • Deterministic. The same model and input give the same output.
  • The perturbation is on a corner. Every unclipped coordinate of η=x′−x\eta = x' - x is ±ϵ\pm\epsilon, so ∥η∥∞=ϵ\lVert \eta \rVert_\infty = \epsilon and ∥η∥2\lVert \eta \rVert_2 is close to ϵd\epsilon \sqrt d.
  • Only the sign matters. Scaling the gradient, or the loss, by a positive number does not change the output. A gradient of exactly 00 leaves the input unchanged.
  • Exact on linear models. For a linear model the sign pattern of the gradient is the same at every point, so one step reaches the worst corner (theorem above).
  • An upper bound only. If x′x' is misclassified, xx is not robust at radius ϵ\epsilon. If it is not, xx may still have adversarial examples in SS.

Variants and improvements

  • Targeted FGSM. Step against the gradient of the loss of a target label tt (see the end of "The algorithm").
  • Fast gradient method in ℓ2\ell_2. Replace sign⁡(g)\operatorname{sign}(g) by g/∥g∥2g / \lVert g \rVert_2; this maximizes the linearized loss over the ℓ2\ell_2 ball before the clip.
  • Iterative FGSM. Repeat the step with a smaller size α\alpha and clip back to SS after each step. Kurakin, Goodfellow and Bengio (2017) call it the basic iterative method; with a random start it is the PGD attack of Madry et al. (2018).
  • FGSM with a random start. Start from a random point of SS and take one step of size somewhat above ϵ\epsilon. Wong, Rice and Kolter (2020) use it for fast adversarial training.
  • FGSM training. Goodfellow, Shlens and Szegedy (2015) trained on a mix of the clean loss and the loss at the FGSM point. Training on FGSM points alone can make the model hide its gradients (see Pitfalls).

When to use it

Use FGSM as a quick first check of a model, as the inner step of cheap adversarial training, or as a baseline in a paper. Do not use it alone to claim robustness: a model can resist FGSM and fail under the PGD attack. To measure robust accuracy, use the PGD attack with restarts and a minimal-distance attack, and to prove robustness, use a certificate such as randomized smoothing or interval bound propagation.

Pitfalls

  • No clip. If line L4 is left out, xi′=xi±ϵx'_i = x_i \pm \epsilon can leave [0,1][0,1], as coordinates 4 and 5 do in the example. The output is then not a valid input, and the success rate is too high. Keep the clip of line L4.
  • The wrong sign for a targeted attack. Using +ϵ+\epsilon in line L3 with the gradient of the target loss moves away from the target. The targeted step is xi−ϵsign⁡(gi)x_i - \epsilon \operatorname{sign}(g_i) with g=∇xL(θ,x,t)g = \nabla_x L(\theta, x, t).
  • A sign function with sign⁡(0)=1\operatorname{sign}(0) = 1. Some library functions, such as a copysign, return ±1\pm 1 for 00. Line L3 must leave a coordinate with gi=0g_i = 0 in place, or the output depends on rounding.
  • The predicted label in line L1. Using f(x)f(x) instead of the true yy is fine only when xx is correctly classified. For a misclassified xx the step makes the model more sure of its wrong label.
  • Gradient masking. A model trained only on FGSM points, or a model with a saturated softmax, can have gradients that point the wrong way near xx, so FGSM fails while the PGD attack or an attack from a random start succeeds. A low FGSM success rate is no proof of robustness (Athalye, Carlini and Wagner 2018; see evasion attack). Defensive distillation is a known case.

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 example table, that every output lies in B∞(x,ϵ)∩[0,1]dB_\infty(x, \epsilon) \cap [0,1]^d, that FGSM attains the maximum of the loss of a logistic model over all corners of the box on 500 random cases, that it attains the linearized optimum ϵ∥g∥1\epsilon \lVert g \rVert_1 on 500 random ReLU networks, and the helper mlkit.py itself.

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.

fast_gradient_sign_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-gradient-sign-method/. The authors are listed in prov/96QQ15.jsonl.

"""The fast gradient sign method of Goodfellow, Shlens and Szegedy (2015), 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.
"""

from typing import Callable, Sequence

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


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


def fast_gradient_sign_method(grad: Gradient, x: Sequence[float], y: int, epsilon: float) -> Vector:
    """One FGSM step: x' = clip01(x + epsilon sign(grad(x, y))).

    grad(x, y) returns the gradient in the input of the loss L(theta, x, y) of a fixed
    model. Precondition: x in [0, 1]^d and epsilon >= 0. The result lies in
    B_inf(x, epsilon) intersected with [0, 1]^d. Cost: one gradient call and O(d).
    """
    g = grad(list(x), y)  # @line L1
    out: Vector = []
    for i in range(len(x)):  # @line L2
        v = x[i] + epsilon * sign(g[i])  # @line L3
        out.append(min(max(v, 0.0), 1.0))  # @line L4
    return out  # @line L5


def targeted_fgsm(grad: Gradient, x: Sequence[float], target: int, epsilon: float) -> Vector:
    """The targeted variant: x' = clip01(x - epsilon sign(grad(x, target))), a step down the loss of the target label."""
    g = grad(list(x), target)
    return [min(max(x[i] - epsilon * sign(g[i]), 0.0), 1.0) for i in range(len(x))]
mlkit.py 252 lines
# 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)
test_fast_gradient_sign_method.py 213 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-gradient-sign-method/. The authors are listed in prov/96QQ15.jsonl.

"""Tests of FGSM and of the shared helper mlkit, on seeded synthetic models only."""

import itertools
import math
import random

import mlkit as m
from fast_gradient_sign_method import fast_gradient_sign_method, sign, targeted_fgsm

TOL = 1e-9


def in_ball_and_box(xa: list[float], x: list[float], epsilon: float) -> bool:
    return m.norminf(m.sub(xa, x)) <= epsilon + TOL and all(-TOL <= a <= 1 + TOL for a in xa)


# ---------------------------------------------------------------- the helper


def central_difference(f, x: list[float], h: float = 1e-5) -> list[float]:
    out = []
    for j in range(len(x)):
        up, down = list(x), list(x)
        up[j] += h
        down[j] -= h
        out.append((f(up) - f(down)) / (2 * h))
    return out


def test_helper_vector_tools() -> None:
    u, v = [1.0, -2.0, 3.0], [0.5, 0.5, -1.0]
    assert m.dot(u, v) == 0.5 - 1.0 - 3.0
    assert m.add(u, v) == [1.5, -1.5, 2.0]
    assert m.sub(u, v) == [0.5, -2.5, 4.0]
    assert m.scale(2.0, v) == [1.0, 1.0, -2.0]
    assert m.norm1(u) == 6.0
    assert abs(m.norm2(u) - math.sqrt(14.0)) < TOL
    assert m.norminf(u) == 3.0
    assert m.norminf([]) == 0.0
    assert m.clip01([-0.5, 0.25, 1.5]) == [0.0, 0.25, 1.0]
    assert m.argmax([0.1, 0.7, 0.7, -1.0]) == 1
    p = m.softmax([1000.0, 1000.0])
    assert abs(p[0] - 0.5) < TOL
    assert abs(m.cross_entropy([0.0, 0.0], 1) - math.log(2.0)) < TOL
    assert abs(m.sigmoid(-800.0)) < 1e-300 and m.sigmoid(800.0) == 1.0


def test_helper_projections_land_in_ball_and_are_idempotent() -> None:
    rng = random.Random(7101)
    for _ in range(500):
        d = rng.randint(1, 8)
        c = [rng.uniform(-1, 1) for _ in range(d)]
        v = [rng.uniform(-3, 3) for _ in range(d)]
        r = rng.uniform(0, 2)
        p2 = m.project_l2(v, c, r)
        assert m.norm2(m.sub(p2, c)) <= r + TOL
        assert all(abs(a - b) < TOL for a, b in zip(m.project_l2(p2, c, r), p2))
        pi = m.project_linf(v, c, r)
        assert m.norminf(m.sub(pi, c)) <= r + TOL
        assert m.project_linf(pi, c, r) == pi
        # the l2 projection is the closest point of the ball: no sampled ball point is closer
        best = m.norm2(m.sub(v, p2))
        for _ in range(5):
            q = [rng.gauss(0, 1) for _ in range(d)]
            q = m.add(c, m.scale(rng.uniform(0, r) / max(m.norm2(q), 1e-12), q))
            assert m.norm2(m.sub(v, q)) >= best - 1e-9
        b = m.clip01(v)
        assert m.clip01(b) == b


def test_helper_logistic_gradients_match_finite_differences() -> None:
    rng = random.Random(7102)
    for _ in range(200):
        d = rng.randint(1, 8)
        w = [rng.uniform(-2, 2) for _ in range(d)]
        b = rng.uniform(-1, 1)
        x = [rng.uniform(0, 1) for _ in range(d)]
        y = rng.randint(0, 1)
        gx = m.grad_x_logistic(w, b, x, y)
        fd = central_difference(lambda u: m.logistic_loss(w, b, u, y), x)
        assert all(abs(a - c) < 1e-6 for a, c in zip(gx, fd))
        gw, gb = m.grad_w_logistic(w, b, x, y)
        fdw = central_difference(lambda u: m.logistic_loss(u, b, x, y), w)
        assert all(abs(a - c) < 1e-6 for a, c in zip(gw, fdw))
        fdb = (m.logistic_loss(w, b + 1e-5, x, y) - m.logistic_loss(w, b - 1e-5, x, y)) / 2e-5
        assert abs(gb - fdb) < 1e-6


def test_helper_relu_net_gradients_match_finite_differences() -> None:
    rng = random.Random(7103)
    for _ in range(100):
        d, h, k = rng.randint(1, 6), rng.randint(1, 8), rng.randint(2, 4)
        net = m.tiny_relu_net(rng, d, h, k)
        x = [rng.uniform(0, 1) for _ in range(d)]
        label = rng.randrange(k)
        pre = [m.dot(row, x) + bi for row, bi in zip(net["W1"], net["b1"])]
        if min(abs(a) for a in pre) < 1e-3:
            continue  # too close to a kink of the ReLU for a finite difference
        g = m.input_gradient(net, x, label)
        fd = central_difference(lambda u: m.cross_entropy(m.forward(net, u), label), x)
        assert all(abs(a - c) < 1e-6 for a, c in zip(g, fd))
        jac = m.logits_jacobian(net, x)
        for c in range(k):
            fdc = central_difference(lambda u: m.forward(net, u)[c], x)
            assert all(abs(a - e) < 1e-6 for a, e in zip(jac[c], fdc))
        # the chain rule: input_gradient = J^T (softmax - onehot)
        p = m.softmax(m.forward(net, x))
        p[label] -= 1.0
        g2 = [math.fsum(p[c] * jac[c][j] for c in range(k)) for j in range(d)]
        assert all(abs(a - e) < 1e-9 for a, e in zip(g, g2))


def test_helper_make_blobs_and_train_logistic() -> None:
    rng = random.Random(7104)
    sigma = 0.1
    centers = [[0.5 - 0.2, 0.5], [0.5 + 0.2, 0.5]]  # distance 0.4 = 4 sigma
    train = m.make_blobs(rng, 200, 2, centers, sigma)
    test = m.make_blobs(rng, 200, 2, centers, sigma)
    assert [y for _, y in train[:4]] == [0, 1, 0, 1]
    w, b = m.train_logistic(train, 300, 1.0, 0.0)
    acc = m.accuracy(lambda x: 1 if m.dot(w, x) + b > 0 else 0, test)
    assert acc >= 0.95
    assert m.accuracy(lambda x: 0, []) == 0.0


# ---------------------------------------------------------------- FGSM


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 grad_logistic(w: list[float], b: float):
    return lambda u, t: m.grad_x_logistic(w, b, u, t)


def test_page_example() -> None:
    z = m.dot(W, X) + B
    assert abs(z - 0.45) < TOL
    xa = fast_gradient_sign_method(grad_logistic(W, B), X, 1, 0.1)
    assert all(abs(a - e) < TOL for a, e in zip(xa, [0.1, 1.0, 0.4, 0.0, 1.0, 0.3]))
    za = m.dot(W, xa) + B
    assert abs(za - (-0.25)) < TOL
    assert abs(m.logistic_loss(W, B, X, 1) - 0.493249) < 1e-6
    assert abs(m.logistic_loss(W, B, xa, 1) - 0.825939) < 1e-6


def test_edges() -> None:
    g = grad_logistic(W, B)
    assert fast_gradient_sign_method(g, X, 1, 0.0) == X
    assert fast_gradient_sign_method(lambda u, t: [], [], 1, 0.1) == []
    # a zero gradient coordinate does not move
    assert fast_gradient_sign_method(lambda u, t: [0.0, 1.0], [0.5, 0.5], 0, 0.25) == [0.5, 0.75]
    # a radius larger than the box sends each moved coordinate to a corner
    assert fast_gradient_sign_method(g, X, 1, 5.0) == [0.0, 1.0, 0.0, 0.0, 1.0, 0.0]
    assert sign(0.0) == 0.0 and sign(-3.0) == -1.0 and sign(2.0) == 1.0


def test_exact_for_linear_logistic_model_against_vertex_search() -> None:
    # The logistic loss of a linear model is convex in x, so its maximum over the box
    # B_inf(x, epsilon) cap [0, 1]^d is at a vertex. Enumerate all 2^d vertices.
    rng = random.Random(7105)
    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, 0.6)
        xa = fast_gradient_sign_method(grad_logistic(w, b), x, y, eps)
        assert in_ball_and_box(xa, x, eps)
        lo = [max(a - eps, 0.0) for a in x]
        hi = [min(a + eps, 1.0) for a in x]
        best = max(m.logistic_loss(w, b, list(v), y) for v in itertools.product(*zip(lo, hi)))
        assert abs(m.logistic_loss(w, b, xa, y) - best) < 1e-9


def test_linearized_loss_optimum_on_relu_net() -> None:
    # Away from the box faces, FGSM attains max over the l_inf ball of g . eta, which is
    # epsilon ||g||_1. Compare with a search over the 2^d sign vectors.
    rng = random.Random(7106)
    for _ in range(500):
        d, h, k = rng.randint(1, 4), rng.randint(2, 8), rng.randint(2, 4)
        net = m.tiny_relu_net(rng, d, h, k)
        x = [rng.uniform(0.3, 0.7) for _ in range(d)]
        label = rng.randrange(k)
        eps = rng.uniform(0.0, 0.3)
        grad = lambda u, t: m.input_gradient(net, u, t)
        xa = fast_gradient_sign_method(grad, x, label, eps)
        assert in_ball_and_box(xa, x, eps)
        g = grad(x, label)
        gain = m.dot(g, m.sub(xa, x))
        best = max(m.dot(g, [eps * s for s in signs]) for signs in itertools.product((-1, 1), repeat=d))
        assert abs(gain - best) < 1e-9
        assert abs(gain - eps * m.norm1(g)) < 1e-9


def test_targeted_variant_lowers_target_loss_on_linear_model() -> None:
    rng = random.Random(7107)
    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, 1) for _ in range(d)]
        t = rng.randint(0, 1)
        eps = rng.uniform(0, 0.3)
        xa = targeted_fgsm(grad_logistic(w, b), x, t, eps)
        assert in_ball_and_box(xa, x, eps)
        assert m.logistic_loss(w, b, xa, t) <= m.logistic_loss(w, b, x, t) + 1e-12

History

Szegedy et al. (2014) found adversarial examples of deep networks with a slow box-constrained L-BFGS search, and Biggio et al. (2013) had found test-time evasion of classifiers with gradient steps. Goodfellow, Shlens and Szegedy posted FGSM in December 2014, and it appeared at ICLR 2015. They argued that adversarial examples come from linearity in high dimension, not from overfitting or nonlinearity, and they showed that the one-step attack is enough: at ϵ=0.25\epsilon = 0.25 on MNIST, FGSM gave an error rate of 99.9 percent on a shallow softmax classifier and 89.4 percent on a maxout network (a measurement on those models). They also proposed adversarial training with FGSM. Kurakin, Goodfellow and Bengio (2017) made the step iterative, and Madry et al. (2018) added random starts and showed that the iterative attack is the right inner step for robust training.

References

  1. Ian J. Goodfellow, Jonathon Shlens and Christian Szegedy, Explaining and harnessing adversarial examples, ICLR 2015, Section 3 (the linear explanation), Section 4 (the fast gradient sign method and its error rates on MNIST at epsilon 0.25), Sections 5 and 6 (adversarial training of linear and deep models)
  2. Alexey Kurakin, Ian Goodfellow and Samy Bengio, Adversarial examples in the physical world, ICLR 2017 workshop, the basic iterative method and the iterative least-likely class method, which repeat the FGSM step with clipping
  3. Aleksander Madry, Aleksandar Makelov, Ludwig Schmidt, Dimitris Tsipras and Adrian Vladu, Towards deep learning models resistant to adversarial attacks, ICLR 2018, the discussion of FGSM as one step of projected gradient ascent on the l_infinity ball
  4. Eric Wong, Leslie Rice and J. Zico Kolter, Fast is better than free, revisiting adversarial training, ICLR 2020, FGSM training with a random start, and catastrophic overfitting
  5. 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