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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Seyed Mohsen Moosavi Dezfooli, Alhussein Fawzi, Omar Fawzi, Pascal Frossard, 2016
A universal adversarial perturbation is one vector , 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 still has the label of , add the DeepFool step that pushes across the nearest boundary, then project back onto the ball of radius . 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 with , , added at test time to every input and clipped to . 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 and looks at the training inputs one at a time. If already changes the label of an input, it moves on. If not, it computes the smallest extra push that changes the label of , adds that push to , and shrinks 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 on with label , data , a radius and a norm , find with that makes the fooling rate
large. The paper asks for on the data distribution for a given . Maximizing is a hard combinatorial problem in general. The algorithm is a heuristic for it.
The algorithm
UNIVERSAL(z, x^1..x^n, epsilon, p, target, P)- 1
v ← 0 - 2
for pass ← 1 to P do - 3
for i ← 1 to n do - 4
if k(clip(x^i + v)) = k(x^i) then - 5
r ← DEEPFOOL step at clip(x^i + v), away from the class k(x^i) - 6
v ← the projection of v + r onto the ball ||v||_p ≤ epsilon - 7
rate ← R(v) - 8
if rate ≥ target then stop the loop - 9
return (v, rate)
Line L5 runs the iterations of DeepFool from the point , with an overshoot of and at most 10 iterations in the code. It returns the total step. Line L6 projects onto the ball: for it scales down to length , and for it clips each coordinate to . 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 , , so . Take five points, all of label 1:
| point | |||||
|---|---|---|---|---|---|
| 0.2 | 0.3 | 0.5 | 0.7 | 0.5 |
Let and . The first pass goes as follows. At , , the step is , and . At , , the step is , and . At , , the step makes of length , and line L6 scales it to , of length . At the last two points is at the edge of the ball in the direction of , so the steps add to it and the projection gives the same again. The fooling rate is , and the second pass changes nothing.
This is the best rate for the ball: any moves by at least , so only the two points with can change label. For the bound uses , so the best moves by . The algorithm ends the first pass at and fools four of the five points, a rate of . Only , with , keeps its label.
A small network. Take the network of mlkit.tiny_relu_net with seed 26, , and . Draw 40 training points and 200 new points, uniform in , from the same seeded generator. With in , the algorithm stops changing after the first pass. The vector has length and fools 22 of the 40 training points (rate ) and 116 of the 200 new points (rate ). For comparison, 100 random directions of length fool on average percent of the new points, and a separate DeepFool run on each new point changes the label within 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 satisfies , and the returned rate is on the data.
Theorem 2 (an upper bound). For a binary affine model , with all points of label 1 and no clip active, every in the ball has , with for and for .
Theorem 3 (optimal in on binary affine models). Under the conditions of Theorem 2 with , and with no equal to , one pass gives .
Theorem 1 holds because starts at and changes only by a projection onto the ball. Theorem 2 is Hölder's inequality: . For Theorem 3, every DeepFool step is a positive multiple of , so stays on the ray of and its length only grows, up to ; 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 the result can be below 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 , let , and let with . The map of line L6 is project_ball. The fooling rate of is the fraction of the whose label at differs from the label at .
Lemma 1. is the Euclidean projection onto , so for every .
Proof. For , project_l2 keeps a point of the ball and moves any other point to , the nearest point of the sphere. For , is the box , and clipping each coordinate gives the nearest point of a box.
Theorem 1 (a valid output). The returned satisfies , and the returned rate is the fooling rate of on the data.
Proof. Line L1 sets . The only other assignment to is line L6, whose result is in by Lemma 1. Line L7 computes the rate of the current after each pass, and 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, and the rate is , the rate of .
Theorem 2 (an upper bound for binary linear models). Let the logits be with and , so the label is when and otherwise. Let every have label , and assume that no clip acts on the points that the algorithm visits. Then every has fooling rate at most , where for and for .
Proof. A point is fooled by when . By Hölder's inequality, . So a fooled point has .
Theorem 3 (the rate is the best one). Under the assumptions of Theorem 2 with , after one pass the fooling rate is , provided that no is equal to .
Proof. For the logits and label , the only other class is , and its difference vector is . So each DeepFool step of line L5 is a positive multiple of , and the projection of line L6 multiplies by a positive number. By induction, with at all times, and never decreases: a step adds a positive amount to and the projection caps at . The point is fooled by such a exactly when , so a point once fooled stays fooled. Take a point with 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 fools . If the projection does not act, fools after line L6. If it acts, after line L6, and means is fooled. So at the end of the pass every point with is fooled, and no other point can be fooled by Theorem 2.
What is not claimed. For the iterates stay on the line of only until a projection clips some coordinates, so the result can be below ; 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 labels and runs DeepFool on at most points, each at most iterations of cost , and line L7 costs more pairs of label calls. The total for passes is .
- Space. for one Jacobian, for 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 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 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 . The fooling rate uses , 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 , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NQDGS5 Edit this page History Report an error Markdown