Algorithm Search⌘K

Algorithmadvanced

Universal adversarial perturbation

Also called image-agnostic perturbation.

Builds one small perturbation that changes the label of many inputs at once, by adding DeepFool steps over a data set and projecting the sum back onto a norm ball.

Time
O(P n T (g + K d)) worst
Space
Θ(K d) extra
Where
K = the number of classes; P = the number of passes; T = the DeepFool iterations per point; d = the input dimension; g = the cost of the logits and their Jacobian; n = the number of data points
Properties
deterministicnot exactofflineiterative
Origin
Seyed Mohsen Moosavi Dezfooli, Alhussein Fawzi, Omar Fawzi, Pascal Frossard, 2016

A universal adversarial perturbation is one vector vv, small in a norm, such that adding it to most inputs changes their label. It does not depend on the input. Moosavi-Dezfooli, Fawzi, Fawzi and Frossard (2017) gave an algorithm to build it: go through a data set, and each time x+vx + v still has the label of xx, add the DeepFool step that pushes x+vx + v across the nearest boundary, then project vv back onto the ball of radius ϵ\epsilon. Repeat until the fooling rate, the fraction of inputs whose label changes, is high enough. On ImageNet networks the paper found such vectors that fool most images and also fool other networks. That result shows that the decision boundaries of a network share directions across many inputs.

Threat model. The goal is untargeted, on a whole input distribution at once. The knowledge is white box: the attacker computes the logits and their Jacobian, and has samples of the inputs. The capability is one fixed change vv with ∥v∥p≤ϵ\lVert v \rVert_p \le \epsilon, p∈{2,∞}p \in \{2, \infty\}, added at test time to every input and clipped to [0,1]d[0,1]^d. The attacker does not need to see the input that the change is added to.

In plain words

A normal adversarial example is made for one input. A universal one is made once and used on every input.

The algorithm starts with v=0v = 0 and looks at the training inputs one at a time. If vv already changes the label of an input, it moves on. If not, it computes the smallest extra push that changes the label of x+vx + v, adds that push to vv, and shrinks vv back to the allowed size if it is too large.

The pushes for different inputs often point in similar directions, because the borders of the classes tend to have shared directions. So the sum does not cancel out, and one vector of the allowed size can change many labels.

The problem

Given logits zz on [0,1]d[0,1]^d with label k(u)=arg⁡max⁡jzj(u)k(u) = \arg\max_j z_j(u), data x1,…,xnx^1, \dots, x^n, a radius ϵ\epsilon and a norm pp, find vv with ∥v∥p≤ϵ\lVert v \rVert_p \le \epsilon that makes the fooling rate

R(v)=1n ∣{i:k(clip⁡(xi+v))≠k(xi)}∣R(v) = \frac{1}{n}\,\big|\{i : k(\operatorname{clip}(x^i + v)) \ne k(x^i)\}\big|

large. The paper asks for R(v)≥1−δR(v) \ge 1 - \delta on the data distribution for a given δ\delta. Maximizing RR is a hard combinatorial problem in general. The algorithm is a heuristic for it.

The algorithm

  1. UNIVERSAL(z, x^1..x^n, epsilon, p, target, P)
  2. 1v ← 0
  3. 2for pass ← 1 to P do
  4. 3for i ← 1 to n do
  5. 4if k(clip(x^i + v)) = k(x^i) then
  6. 5r ← DEEPFOOL step at clip(x^i + v), away from the class k(x^i)
  7. 6v ← the projection of v + r onto the ball ||v||_p ≤ epsilon
  8. 7rate ← R(v)
  9. 8if rate ≥ target then stop the loop
  10. 9return (v, rate)

Line L5 runs the iterations of DeepFool from the point clip⁡(xi+v)\operatorname{clip}(x^i + v), with an overshoot of 0.020.02 and at most 10 iterations in the code. It returns the total step. Line L6 projects onto the ball: for p=2p = 2 it scales vv down to length ϵ\epsilon, and for p=∞p = \infty it clips each coordinate to [−ϵ,ϵ][-\epsilon, \epsilon]. The paper visits the data in a new random order on each pass. The code uses the order of the data, so it is deterministic.

Example

A linear model. Take two classes in the plane with logits (0,f(u))(0, f(u)), f(u)=u1+u2−0.6f(u) = u_1 + u_2 - 0.6, so w=(1,1)w = (1, 1). Take five points, all of label 1:

point (0.5,0.3)(0.5, 0.3) (0.4,0.5)(0.4, 0.5) (0.6,0.5)(0.6, 0.5) (0.7,0.6)(0.7, 0.6) (0.5,0.6)(0.5, 0.6)
f(x)f(x) 0.2 0.3 0.5 0.7 0.5

Let ϵ=0.3\epsilon = 0.3 and p=2p = 2. The first pass goes as follows. At (0.5,0.3)(0.5, 0.3), f=0.2f = 0.2, the step is 1.02⋅0.1⋅(−1,−1)1.02 \cdot 0.1 \cdot (-1, -1), and v=(−0.102,−0.102)v = (-0.102, -0.102). At (0.4,0.5)(0.4, 0.5), f(x+v)=0.096f(x + v) = 0.096, the step is (−0.04896,−0.04896)(-0.04896, -0.04896), and v=(−0.15096,−0.15096)v = (-0.15096, -0.15096). At (0.6,0.5)(0.6, 0.5), f(x+v)=0.1981f(x + v) = 0.1981, the step makes v+r=(−0.25198,−0.25198)v + r = (-0.25198, -0.25198) of length 0.35640.3564, and line L6 scales it to v=(−0.21213,−0.21213)v = (-0.21213, -0.21213), of length 0.30.3. At the last two points vv is at the edge of the ball in the direction of −w-w, so the steps add to it and the projection gives the same vv again. The fooling rate is 2/5=0.42/5 = 0.4, and the second pass changes nothing.

This is the best rate for the ℓ2\ell_2 ball: any vv moves ff by at least −ϵ∥w∥2=−0.4243-\epsilon \lVert w \rVert_2 = -0.4243, so only the two points with f(x)≤0.4243f(x) \le 0.4243 can change label. For p=∞p = \infty the bound uses ∥w∥1=2\lVert w \rVert_1 = 2, so the best vv moves ff by −0.6-0.6. The algorithm ends the first pass at v=(−0.3,−0.3)v = (-0.3, -0.3) and fools four of the five points, a rate of 0.80.8. Only (0.7,0.6)(0.7, 0.6), with f=0.7f = 0.7, keeps its label.

A small network. Take the network of mlkit.tiny_relu_net with seed 26, d=4d = 4, h=8h = 8 and K=3K = 3. Draw 40 training points and 200 new points, uniform in [0,1]4[0,1]^4, from the same seeded generator. With ϵ=0.3\epsilon = 0.3 in ℓ2\ell_2, the algorithm stops changing vv after the first pass. The vector v=(−0.098,−0.144,−0.021,0.243)v = (-0.098, -0.144, -0.021, 0.243) has length 0.30.3 and fools 22 of the 40 training points (rate 0.550.55) and 116 of the 200 new points (rate 0.580.58). For comparison, 100 random directions of length 0.30.3 fool on average 31.731.7 percent of the new points, and a separate DeepFool run on each new point changes the label within 0.30.3 for 91 percent of them. So the universal vector is between the two: much better than a random direction, and worse than one attack per input.

Correctness

Theorem 1 (a valid output). The returned vv satisfies ∥v∥p≤ϵ\lVert v \rVert_p \le \epsilon, and the returned rate is R(v)R(v) on the data.

Theorem 2 (an upper bound). For a binary affine model f(u)=w⊤u+bf(u) = w^\top u + b, with all points of label 1 and no clip active, every vv in the ball has R(v)≤R⋆=∣{i:f(xi)≤ϵ∥w∥q}∣/nR(v) \le R^\star = |\{i : f(x^i) \le \epsilon \lVert w \rVert_q\}| / n, with q=2q = 2 for p=2p = 2 and q=1q = 1 for p=∞p = \infty.

Theorem 3 (optimal in ℓ2\ell_2 on binary affine models). Under the conditions of Theorem 2 with p=2p = 2, and with no f(xi)f(x^i) equal to ϵ∥w∥2\epsilon \lVert w \rVert_2, one pass gives R(v)=R⋆R(v) = R^\star.

Theorem 1 holds because vv starts at 00 and changes only by a projection onto the ball. Theorem 2 is Hölder's inequality: w⊤v≥−∥w∥q∥v∥pw^\top v \ge -\lVert w \rVert_q \lVert v \rVert_p. For Theorem 3, every DeepFool step is a positive multiple of −w-w, so vv stays on the ray of −w-w and its length only grows, up to ϵ\epsilon; once a point is fooled it stays fooled, and each point that the full ball can fool is fooled when the pass reaches it. The proofs are in proofs/correctness.md. For p=∞p = \infty the result can be below R⋆R^\star when the box clips some coordinates and not others, and for a network there is no optimality claim.

Proof: The universal perturbation stays in the ball and reaches the best rate on a binary linear modelfull

Let the data be x1,…,xn∈[0,1]dx^1, \dots, x^n \in [0,1]^d, let ϵ≥0\epsilon \ge 0, and let B={v:∥v∥p≤ϵ}B = \{v : \lVert v \rVert_p \le \epsilon\} with p∈{2,∞}p \in \{2, \infty\}. The map PBP_B of line L6 is project_ball. The fooling rate of vv is the fraction of the xix^i whose label at clip⁡(xi+v)\operatorname{clip}(x^i + v) differs from the label at xix^i.

Lemma 1. PBP_B is the Euclidean projection onto BB, so PB(u)∈BP_B(u) \in B for every uu.

Proof. For p=2p = 2, project_l2 keeps a point of the ball and moves any other point uu to ϵu/∥u∥2\epsilon u / \lVert u \rVert_2, the nearest point of the sphere. For p=∞p = \infty, BB is the box [−ϵ,ϵ]d[-\epsilon, \epsilon]^d, and clipping each coordinate gives the nearest point of a box. □\square

Theorem 1 (a valid output). The returned vv satisfies ∥v∥p≤ϵ\lVert v \rVert_p \le \epsilon, and the returned rate is the fooling rate of vv on the data.

Proof. Line L1 sets v=0∈Bv = 0 \in B. The only other assignment to vv is line L6, whose result is in BB by Lemma 1. Line L7 computes the rate of the current vv after each pass, and vv does not change between line L7 and the return in line L9: line L8 breaks right after line L7, and otherwise the loop ends after line L7 of the last pass. If there are no passes, v=0v = 0 and the rate is 00, the rate of 00. □\square

Theorem 2 (an upper bound for binary linear models). Let the logits be (0,f(u))(0, f(u)) with f(u)=w⊤u+bf(u) = w^\top u + b and w≠0w \ne 0, so the label is 11 when f(u)>0f(u) > 0 and 00 otherwise. Let every xix^i have label 11, and assume that no clip acts on the points that the algorithm visits. Then every v∈Bv \in B has fooling rate at most R⋆=∣{i:f(xi)≤ϵ∥w∥q}∣/nR^\star = |\{i : f(x^i) \le \epsilon \lVert w \rVert_q\}| / n, where q=2q = 2 for p=2p = 2 and q=1q = 1 for p=∞p = \infty.

Proof. A point xix^i is fooled by vv when f(xi+v)=f(xi)+w⊤v≤0f(x^i + v) = f(x^i) + w^\top v \le 0. By Hölder's inequality, w⊤v≥−∥w∥q∥v∥p≥−ϵ∥w∥qw^\top v \ge -\lVert w \rVert_q \lVert v \rVert_p \ge -\epsilon \lVert w \rVert_q. So a fooled point has f(xi)≤ϵ∥w∥qf(x^i) \le \epsilon \lVert w \rVert_q. □\square

Theorem 3 (the ℓ2\ell_2 rate is the best one). Under the assumptions of Theorem 2 with p=2p = 2, after one pass the fooling rate is R⋆R^\star, provided that no f(xi)f(x^i) is equal to ϵ∥w∥2\epsilon \lVert w \rVert_2.

Proof. For the logits (0,f)(0, f) and label 11, the only other class is 00, and its difference vector is w0=∇z0−∇z1=−ww_0 = \nabla z_0 - \nabla z_1 = -w. So each DeepFool step of line L5 is a positive multiple of −w-w, and the projection of line L6 multiplies vv by a positive number. By induction, v=−τ w/∥w∥2v = -\tau\, w / \lVert w \rVert_2 with 0≤τ≤ϵ0 \le \tau \le \epsilon at all times, and τ\tau never decreases: a step adds a positive amount to τ\tau and the projection caps τ\tau at ϵ\epsilon. The point xix^i is fooled by such a vv exactly when f(xi)≤τ∥w∥2f(x^i) \le \tau \lVert w \rVert_2, so a point once fooled stays fooled. Take a point xix^i with f(xi)<ϵ∥w∥2f(x^i) < \epsilon \lVert w \rVert_2 that is not fooled when line L4 reaches it. On an affine model the inner DeepFool reaches the far side of the boundary at its first step (see the proof page of deepfool), so v+rv + r fools xix^i. If the projection does not act, vv fools xix^i after line L6. If it acts, τ=ϵ\tau = \epsilon after line L6, and f(xi)<ϵ∥w∥2f(x^i) < \epsilon \lVert w \rVert_2 means xix^i is fooled. So at the end of the pass every point with f(xi)<ϵ∥w∥2f(x^i) < \epsilon \lVert w \rVert_2 is fooled, and no other point can be fooled by Theorem 2. ■\blacksquare

What is not claimed. For p=∞p = \infty the iterates stay on the line of ww only until a projection clips some coordinates, so the ℓ∞\ell_\infty result can be below R⋆R^\star; the test checks only the upper bound there. For a nonlinear model, the algorithm is a heuristic: the result depends on the order of the data, and no optimality holds. The fooling rate is a measurement on the given data, not a guarantee on new data.

Complexity

  • Time. Each pass checks nn labels and runs DeepFool on at most nn points, each at most TT iterations of cost g+O(Kd)g + O(K d), and line L7 costs nn more pairs of label calls. The total for PP passes is O(PnT(g+Kd))O(P n T (g + K d)).
  • Space. Θ(Kd)\Theta(K d) for one Jacobian, Θ(d)\Theta(d) for vv and the step. The data is read, not copied.
  • Model. These counts are in the real-ram model, with one call of the logits and Jacobian as a unit of work. The paper reports that a small part of the training set, much smaller than the full set, is enough on ImageNet (a measurement).

Properties

  • Input-agnostic. One vv for all inputs. It can be computed offline and applied without knowing the input.
  • Deterministic in this code. The paper shuffles the data on each pass, which makes it random.
  • In the ball. The output always satisfies the norm bound (Theorem 1).
  • Generalizes. A vector built on some inputs often fools new inputs at a similar rate, as in the network example. This is a measurement, not a guarantee.
  • Transfers. The paper reports that a vector built for one network also fools other networks at a lower rate (see adversarial transferability).

Variants and improvements

  • Other inner steps. Replace DeepFool by an FGSM or PGD step on the loss of the current batch. This gives a stochastic gradient method on the average loss over the data, projected onto the ball.
  • Data-free versions. Later work builds universal vectors without training data, by maximizing the activations of inner layers.
  • Generative models. A network can be trained to output universal perturbations, which gives many different ones quickly.
  • Universal adversarial training. Train the model against the current universal vector, which costs much less than adversarial training per input, and protects only against universal changes.
  • Patches. Replace the norm ball by a small region of the input, where any value is allowed.

When to use it

Use the algorithm on small models to study how much the boundaries of a model share directions, or to compare the risk of one fixed change with the risk of attacks per input. It is also a cheap test of a defense: if one fixed vector fools a defended model on many inputs, the defense is weak. Use PGD per input to measure robust accuracy, since a universal vector gives a weaker attack than one made for each input.

Pitfalls

  • Rate on the training points only. Report the rate on new points, as in the network example. A rate measured on the points used to build vv overstates the effect.
  • A universal vector is weaker than one attack per input. In the example, 58 percent against 91 percent at the same radius. Do not use the universal rate as a robust accuracy.
  • The clip. Inputs at the edge of the box absorb part of vv. The fooling rate uses clip⁡(x+v)\operatorname{clip}(x + v), so compute it in the same way as the algorithm.
  • Order of the data. On a network the result depends on the order of visits. Shuffle with a fixed seed and report it.
  • Compare with random noise. A fair report gives the rate of random vectors of the same size, which can be large on a small model, as the 31.7 percent in the example shows.

Implementations

The code of this page is an abstract model on synthetic data. The algorithm runs only on models and data that the tests build from a fixed seed: affine models with given or seeded weights, and two-layer ReLU networks from mlkit.tiny_relu_net, on seeded random points. It never reads real data or touches a real system. The tests check the two examples of the page, edge cases, the projection, that on 500 random binary affine models the rate never passes the Hölder bound and equals it in ℓ2\ell_2, and that on seeded networks the output stays in the ball and the reported rate is correct.

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)
universal_adversarial_perturbation.py 88 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/universal-adversarial-perturbation/. The authors are listed in prov/NQDGS5.jsonl.

"""The universal perturbation algorithm of Moosavi-Dezfooli et al. (2017), on synthetic models only.

One perturbation v with ||v||_p <= epsilon is grown over a data set, so that the label of
clip01(x + v) differs from the label of x for many x. The inner step is a small DeepFool.
The model is given as its logits and the Jacobian of its logits; the tests build both
from seeded affine models and seeded ReLU networks of mlkit. Nothing here reads real
data or touches a real system.
"""

import math
from typing import Callable, Sequence

import mlkit as m

Vector = list[float]
Logits = Callable[[Vector], Vector]
Jacobian = Callable[[Vector], list[Vector]]


def project_ball(v: Sequence[float], epsilon: float, norm: str) -> Vector:
    """Projection onto the ball of radius epsilon around 0, in the l2 or the l_infinity norm. Cost O(d)."""
    zero = [0.0] * len(v)
    if norm == "inf":
        return m.project_linf(v, zero, epsilon)
    return m.project_l2(v, zero, epsilon)


def minimal_step(logits: Logits, jac: Jacobian, p: Sequence[float], label: int, overshoot: float = 0.02,
                 max_iter: int = 10) -> Vector:
    """A DeepFool step r so that the label of clip01(p + r) differs from label, or the best try.

    Each iteration moves to the nearest boundary of the linearized model. The total step
    is scaled by 1 + overshoot. Cost: at most max_iter logits and Jacobian calls.
    """
    r = [0.0] * len(p)
    for _ in range(max_iter):
        q = m.clip01([a + (1.0 + overshoot) * t for a, t in zip(p, r)])
        z = logits(q)
        if m.argmax(z) != label:
            break
        jz = jac(q)
        best, best_ratio = None, math.inf
        for k in range(len(z)):
            if k == label:
                continue
            wk = m.sub(jz[k], jz[label])
            nk = m.norm2(wk)
            if nk > 0.0 and abs(z[k] - z[label]) / nk < best_ratio:
                best, best_ratio = (k, wk, nk), abs(z[k] - z[label]) / nk
        if best is None:
            break
        k, wk, nk = best
        r = m.add(r, m.scale((abs(z[k] - z[label]) + 1e-12) / (nk * nk), wk))
    return m.scale(1.0 + overshoot, r)


def fooling_rate(logits: Logits, data: Sequence[Sequence[float]], v: Sequence[float]) -> float:
    """Fraction of the points x of data whose label at clip01(x + v) differs from the label at x."""
    if not data:
        return 0.0
    fooled = sum(1 for x in data if m.argmax(logits(m.clip01(m.add(x, v)))) != m.argmax(logits(list(x))))
    return fooled / len(data)


def universal_perturbation(logits: Logits, jac: Jacobian, data: Sequence[Sequence[float]], epsilon: float,
                           norm: str = "2", target_rate: float = 0.8, max_passes: int = 10) -> tuple[Vector, float]:
    """Grow one perturbation over data. Returns (v, the fooling rate of v on data).

    The loop stops when the fooling rate reaches target_rate or after max_passes passes
    over the data. Preconditions: epsilon >= 0, norm is "2" or "inf", data is not empty.
    Cost per pass: n label calls and at most n DeepFool runs.
    """
    v = [0.0] * len(data[0])  # @line L1
    rate = 0.0
    for _ in range(max_passes):  # @line L2
        for x in data:  # @line L3
            label = m.argmax(logits(list(x)))
            p = m.clip01(m.add(x, v))
            if m.argmax(logits(p)) == label:  # @line L4
                r = minimal_step(logits, jac, p, label)  # @line L5
                v = project_ball(m.add(v, r), epsilon, norm)  # @line L6
        rate = fooling_rate(logits, data, v)  # @line L7
        if rate >= target_rate:  # @line L8
            break
    return v, rate  # @line L9
test_universal_adversarial_perturbation.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/universal-adversarial-perturbation/. The authors are listed in prov/NQDGS5.jsonl.

"""Tests of the universal perturbation algorithm, on seeded synthetic models only."""

import math
import random

import mlkit as m
from universal_adversarial_perturbation import fooling_rate, minimal_step, project_ball, universal_perturbation

# The worked example of the page: a linear two-class model in the plane and five points.
WE = [1.0, 1.0]
BE = -0.6
DATA = [[0.5, 0.3], [0.4, 0.5], [0.6, 0.5], [0.7, 0.6], [0.5, 0.6]]


def binary(w, b):
    """Two logits: 0 for class 0 and w.x + b for class 1."""
    return (lambda u: [0.0, m.dot(w, u) + b]), (lambda u: [[0.0] * len(w), w])


def test_page_example() -> None:
    lg, jac = binary(WE, BE)
    v, rate = universal_perturbation(lg, jac, DATA, 0.3, norm="2", target_rate=1.0, max_passes=3)
    s = 0.3 / math.sqrt(2)
    assert all(abs(a + s) < 1e-12 for a in v)
    assert rate == 0.4
    v, rate = universal_perturbation(lg, jac, DATA, 0.3, norm="inf", target_rate=1.0, max_passes=3)
    assert all(abs(a + 0.3) < 1e-12 for a in v)
    assert rate == 0.8


def test_page_network_example() -> None:
    # seed 26: one vector fits on 40 points and fools 22 of them, and 116 of 200 new points
    rng = random.Random(26)
    net = m.tiny_relu_net(rng, 4, 8, 3)
    lg = lambda u: m.forward(net, u)
    jac = lambda u: m.logits_jacobian(net, u)
    train = [[rng.uniform(0, 1) for _ in range(4)] for _ in range(40)]
    test = [[rng.uniform(0, 1) for _ in range(4)] for _ in range(200)]
    v, rate = universal_perturbation(lg, jac, train, 0.3, norm="2", target_rate=0.8, max_passes=10)
    assert abs(m.norm2(v) - 0.3) < 1e-9
    assert abs(rate - 0.55) < 1e-12
    assert abs(fooling_rate(lg, test, v) - 0.58) < 1e-12


def test_edges() -> None:
    lg, jac = binary(WE, BE)
    v, rate = universal_perturbation(lg, jac, DATA, 0.0)
    assert v == [0.0, 0.0] and rate == 0.0
    assert fooling_rate(lg, [], [0.0, 0.0]) == 0.0
    assert math.dist(project_ball([3.0, 4.0], 1.0, "2"), [0.6, 0.8]) < 1e-12
    assert project_ball([3.0, -4.0], 1.0, "inf") == [1.0, -1.0]
    # a point already of another label needs no step
    assert minimal_step(lg, jac, [0.1, 0.1], 1) == [0.0, 0.0]


def test_linear_binary_models_reach_the_best_universal_rate() -> None:
    # All points have label 1 and f_i = w.x_i + b > 0. A vector v with ||v||_2 <= epsilon
    # fools x_i exactly when f_i + w.v <= 0, and w.v >= -epsilon ||w||_2, so no v fools more
    # than the points with f_i <= epsilon ||w||_2; the l_infinity bound uses ||w||_1.
    rng = random.Random(7601)
    for _ in range(500):
        d, n = rng.randint(1, 4), rng.randint(1, 12)
        w = [rng.choice([-1, 1]) * rng.uniform(0.2, 2.0) for _ in range(d)]
        data = [[rng.uniform(0.3, 0.7) for _ in range(d)] for _ in range(n)]
        b = -min(m.dot(w, x) for x in data) + rng.uniform(0.01, 0.4)
        eps = rng.uniform(0.0, 0.3)
        f = [m.dot(w, x) + b for x in data]
        lg, jac = binary(w, b)
        for norm, wn in (("2", m.norm2(w)), ("inf", m.norm1(w))):
            if min(abs(fi - eps * wn) for fi in f) < 1e-6:
                continue  # too close to a tie
            best = sum(1 for fi in f if fi <= eps * wn) / n
            v, rate = universal_perturbation(lg, jac, data, eps, norm=norm, target_rate=1.0, max_passes=4)
            assert rate == fooling_rate(lg, data, v)
            assert rate <= best
            size = m.norm2(v) if norm == "2" else m.norminf(v)
            assert size <= eps + 1e-12
            if norm == "2":
                assert rate == best


def test_relu_nets_keep_the_perturbation_in_the_ball() -> None:
    rng = random.Random(7602)
    for _ in range(40):
        d, h, k = rng.randint(1, 4), rng.randint(2, 6), rng.randint(2, 3)
        net = m.tiny_relu_net(rng, d, h, k)
        lg = lambda u: m.forward(net, u)
        jac = lambda u: m.logits_jacobian(net, u)
        data = [[rng.uniform(0, 1) for _ in range(d)] for _ in range(10)]
        eps = rng.uniform(0.05, 0.5)
        norm = rng.choice(["2", "inf"])
        v, rate = universal_perturbation(lg, jac, data, eps, norm=norm, target_rate=0.5, max_passes=3)
        size = m.norm2(v) if norm == "2" else m.norminf(v)
        assert size <= eps + 1e-12
        assert rate == fooling_rate(lg, data, v)

History

Szegedy et al. (2014) found that adversarial examples made for one network often fool another, and Goodfellow, Shlens and Szegedy (2015) related this to directions in which models are close to linear. Moosavi-Dezfooli, Fawzi, Fawzi and Frossard posted universal perturbations in October 2016 and published them at CVPR 2017. They built them with DeepFool steps on a part of the ImageNet training set, reported high fooling rates on validation images for several networks, and showed that the vectors transfer across networks. They related the effect to shared directions of large curvature of the decision boundaries. Later work found data-free and generative methods.

References

  1. Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Omar Fawzi and Pascal Frossard, Universal adversarial perturbations, CVPR 2017, pages 1765 to 1773, the definition of a universal perturbation and of the fooling rate, the algorithm with DeepFool steps and the projection, the ImageNet experiments and the study of transfer across networks
  2. Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi and Pascal Frossard, DeepFool, a simple and accurate method to fool deep neural networks, CVPR 2016, pages 2574 to 2582, the inner step of the algorithm
  3. 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

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