Algorithmcore
DeepFool
Also called DeepFool attack.
Finds a near-minimal l2 perturbation by linearizing the classifier, stepping to the nearest boundary of the linear model, and repeating until the label changes. Exact in one step for affine models.
- Time
- O(T (g + K d)) worst
- Space
- Θ(K d) extra
- Where
- K = the number of classes; T = the number of iterations; d = the input dimension; g = the cost of the logits and their Jacobian
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Seyed Mohsen Moosavi Dezfooli, Alhussein Fawzi, Pascal Frossard, 2015
DeepFool finds a small change that moves an input across the nearest decision boundary of a classifier, in the norm. At the current point it replaces the classifier by its first-order model, a set of hyperplanes, one for each wrong class. It computes the distance to each hyperplane, takes the shortest step to the nearest one, and repeats from the new point until the label changes. For an affine classifier the first step is the exact minimal perturbation. Moosavi-Dezfooli, Fawzi and Frossard (2016) proposed it to measure robustness: the size of the change estimates the distance from to the nearest point with another label. It needs only a few gradients, far fewer than the Carlini-Wagner attack, and it is the inner step of the universal adversarial perturbation.
Threat model. The goal is untargeted. The knowledge is white box: the attacker computes the logits and their Jacobian. The capability is a change at test time in of any size; the attack reports the size of the change it found, so the radius is an output.
In plain words
Picture the regions of the classes as countries with straight borders. If you stand in one country and want to leave it in the fewest steps, you walk straight to the nearest border, at a right angle to it.
A real classifier has curved borders. DeepFool pretends that the borders near you are straight, walks to the nearest straight border, and looks again. If you are still inside, the borders were bent, and it repeats. Usually two or three walks are enough.
At the end it walks a little further, by a factor with a small overshoot , so that the point is really on the other side and not on the border.
The problem
Given logits on and an input with label , estimate
and return a point with another label and close to .
For an affine model the answer has a closed form. Write and for . The region of class is the polyhedron , and the distance to the face of class is . So
with the class that attains the minimum (ignoring the box). For two classes this is the distance to a hyperplane.
The algorithm
DEEPFOOL(z, x, gamma, T) ▷ gamma ≥ 0 is the overshoot- 1
k0 ← argmax_k z_k(x); r ← 0 - 2
for it ← 0 to T do - 3
p ← clip_[0,1](x + (1 + gamma) r) - 4
if argmax_k z_k(p) ≠ k0 or it = T then return (p, it) - 5
J ← the Jacobian of z at p - 6
for k ≠ k0: w_k ← J_k - J_k0; f_k ← z_k(p) - z_k0(p); l ← the k with the least |f_k| / ||w_k||_2; step ← (|f_l| / ||w_l||_2^2) w_l - 7
r ← r + step - 8
return (p, T)
Line L6 is the closed form above, applied to the linear model of at . The code adds to so that the step crosses the hyperplane, and skips classes with . Line L3 applies the overshoot to the whole sum of the steps, as in the paper (they use ), and clips to the box. Line L4 stops at the first point with another label, or after iterations, in which case the label may still be .
Example
An affine model, one step. Take the model of the page adversarial example: , with rows , and , and with and . The logits are .
| class | distance | |||
|---|---|---|---|---|
| 1 | ||||
| 2 |
Class 1 is nearest. The step is , and line L3 gives , with logits and label . DeepFool stops after one iteration. The distance is , the true minimum times . It used one Jacobian and two logit calls.
A small network, two steps. Take the network of mlkit.tiny_relu_net with seed 3, , hidden ReLU units and , at :
| iteration | logits | label | step | |
|---|---|---|---|---|
| 0 | (0.5, 0.5) | (-0.0741, -0.4478, -0.4643) | 0 | (0.0826, -0.3447) |
| 1 | (0.5843, 0.1485) | (-0.1340, -0.1821, -0.4723) | 0 | (0.0047, -0.0570) |
| 2 | (0.5891, 0.0903) | (-0.1490, -0.1481, -0.4679) | 1 | none |
The first step aims at a straight line that the network bends, so the point falls short. The second step, from the new linear model, crosses the border. The distance found is . A search over a grid of step on finds no point of another label closer than (an estimate from the grid, accurate to about ). So DeepFool is within about percent of the minimum here, and accounts for most of it.
Correctness
Theorem 1 (affine models). Let be affine, and let lie in . Then DeepFool returns after one iteration, the label of is not , and , up to the margin.
Theorem 2 (any model). DeepFool returns a point of after at most iterations. If it stops before , the label of the point is not . It calls the logits times and the Jacobian times.
Theorem 1 holds because the region of is the intersection of the half spaces , the distance to a union of half spaces is the least distance to one of them, and the step of line L6 is the shortest vector to the nearest one. For two classes the step reduces to , the orthogonal projection onto the hyperplane. The full proofs are in proofs/correctness.md.
For a nonlinear model, DeepFool is a heuristic. Its distance is an upper bound on , and it can stop at without a label change.
Proof: DeepFool finds the minimum l2 perturbation of an affine classifier in one iterationfull
Let the model have logits and label , and let (line L1). For write and . At the current point the function nearest_boundary_step picks the class with the smallest among the classes with , and returns , where .
Lemma 1 (the step of one iteration). Let the model be affine, , so that each is a constant vector and each is affine. Let have label , so for all . Then:
- The distance from to the closed half space is .
- The distance from to the set is at least .
- for . So for every .
Proof. (1) The half space is . The distance from a point to the half space with and is , attained at . (2) A point has only if for some , that is . So is inside the union of the half spaces of part (1). A class with has constant and . If , its half space is empty. If , then everywhere; a tie goes to the smaller index, and the label at is , so and the class never takes the label. So only the classes with count. The distance to a union is the minimum of the distances. (3) Since is affine, , and .
Theorem 1 (affine models). Let the model be affine and let the point , where is the overshoot, lie in . Then DeepFool returns . The label of is not , and , where is the lower bound of Lemma 1 at . So the distance is the true minimum times , up to the term in .
Proof. At , line L3 gives because , and line L4 does not return because the label of is (assume ). Lines L5 to L7 set . At , line L3 gives , since is in the box. By Lemma 1(3) with , , so and the label of is not . Line L4 returns . The length of is . By Lemma 1(2) no point closer than to has another label, and the point , at distance , is on the boundary, so is the minimum distance to the closure of .
Theorem 2 (any model). For every model, DeepFool returns with and . If , the label of is not . It calls the logits times and the Jacobian times.
Proof. Line L3 clips every point to . The loop of line L2 runs for , and line L4 returns at the latest when ; so line L8 is never reached and . Line L4 returns with only when the label of is not . Each pass calls the logits once in line L3 and, if it does not return, the Jacobian once in line L5; line L1 adds one call of the logits.
What is not claimed. For a nonlinear model, the linearization of line L6 is only a local model. DeepFool can need many iterations, can stop at without a label change, and its distance is an upper bound on the true minimum, not the minimum. If every is , the step is and the loop runs to .
Complexity
- Time. Each iteration costs one logit evaluation and one Jacobian, , which is backward passes in general, plus for line L6. The total is . The paper reports that a few iterations are enough on its image models (a measurement). For many classes, the paper limits line L6 to the classes with the highest logits.
- Space. for the Jacobian, plus for and .
- Model. These counts are in the real-ram model, with one Jacobian as a unit of work.
Properties
- Deterministic. No randomness.
- Minimal on affine models. Theorem 1. On a network it is close to minimal when the borders bend little near .
- An upper bound on the distance. The point found has another label, so . To get robust accuracy at radius , count the points whose DeepFool distance is above ; this gives an upper bound on robust accuracy.
- Not tied to a radius. DeepFool does not take . This makes it good for measuring robustness and poor for testing a given threat model.
Variants and improvements
- Other norms. For with dual exponent , , the distance to the face of class is , and the step is . For it is , an FGSM-like step with the exact size.
- Robustness measure. The paper reports over a test set of points.
- Universal perturbations. The universal adversarial perturbation runs DeepFool on many inputs in turn and adds the steps into one vector.
- Targeted step. Fix in line L6 to move toward a chosen class.
- Training. The paper fine-tunes networks on DeepFool points and reports larger distances afterward. Adversarial training with PGD is the more common method today.
When to use it
Use DeepFool to estimate how far inputs are from the decision boundary, to compare models, or as a fast start for a slower minimal attack. For a precise minimal distance, follow it with the Carlini-Wagner attack. To test robustness at a fixed radius, use the PGD attack. To prove that no closer point exists, use a certificate such as randomized smoothing or linear bound propagation.
Pitfalls
- No overshoot. With the point lands on the border, and rounding can keep the old label. Keep a small , such as .
- The box. The linear step ignores , and the clip of line L3 shortens it. Then the loop can creep toward the border by steps that shrink geometrically. On the network of seed 131 in the same family, at , the second coordinate hits at iteration 2, and DeepFool needs 20 iterations, with a distance of against on the grid.
- Gradients of zero. If for all , as in a flat region of a ReLU network, the step is and the loop runs to . A failure then proves nothing.
- Gradient masking. Like every gradient attack, DeepFool fails on models whose gradients are hidden or noisy. Large DeepFool distances on a defended model are not a proof of robustness.
- Comparing norms. The distance is in . Do not compare it with an radius.
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: affine models with given or seeded weights, or two-layer ReLU networks from mlkit.tiny_relu_net, on seeded random inputs. It never reads real data or touches a real system. The tests check the two examples of the page, edge cases, that the step on 500 random binary affine models equals the closed-form projection onto the hyperplane, that on random multiclass affine models DeepFool stops after one iteration at times the closed-form minimum, and that the outputs on random networks lie in the box and change the label when the loop stops early.
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
# Part of https://algorithm.tamnd.com/deepfool/. The authors are listed in prov/A515G9.jsonl.
"""DeepFool of Moosavi-Dezfooli, Fawzi and Frossard (2016), multi-class l2 version, on synthetic models only.
The model is given as two functions on an input: its logits and the Jacobian of the
logits. The tests build both from a seeded affine model or a seeded two-layer ReLU
network of mlkit. Nothing here reads real data or touches a real system.
"""
import math
from typing import Callable, Sequence
Vector = list[float]
Logits = Callable[[Vector], Vector]
Jacobian = Callable[[Vector], list[Vector]]
def _argmax(z: Sequence[float]) -> int:
return max(range(len(z)), key=lambda i: z[i])
def nearest_boundary_step(z: Sequence[float], jz: Sequence[Sequence[float]], k0: int) -> Vector:
"""The l2 step to the nearest boundary of the linearized classifier at the current point.
For each class k != k0, w_k = grad z_k - grad z_k0 and f_k = z_k - z_k0. The step is
(|f_l| / ||w_l||^2) w_l for the class l that minimizes |f_l| / ||w_l||. Cost O(K d).
"""
best_l, best_ratio = -1, math.inf
for k in range(len(z)):
if k == k0:
continue
wk = [a - b for a, b in zip(jz[k], jz[k0])]
nk = math.sqrt(math.fsum(t * t for t in wk))
if nk == 0.0:
continue
ratio = abs(z[k] - z[k0]) / nk
if ratio < best_ratio:
best_l, best_ratio, best_w, best_n = k, ratio, wk, nk
if best_l < 0:
return [0.0] * len(jz[0])
c = (abs(z[best_l] - z[k0]) + 1e-12) / (best_n * best_n)
return [c * t for t in best_w]
def deepfool(logits: Logits, jac: Jacobian, x: Sequence[float], overshoot: float = 0.02,
max_iter: int = 50) -> tuple[Vector, int]:
"""Run DeepFool from x. Returns (the perturbed input, the number of iterations).
The perturbation is r = (1 + overshoot) * the sum of the steps; the returned input is
clip01(x + r). The loop stops when the label differs from the label of x, or after
max_iter iterations, and then the label may still be the same. Precondition:
overshoot >= 0. Cost: one logits and one Jacobian call per iteration, and O(K d) more.
"""
k0 = _argmax(logits(list(x))) # @line L1
r = [0.0] * len(x)
for it in range(max_iter + 1): # @line L2
p = [min(max(a + (1.0 + overshoot) * t, 0.0), 1.0) for a, t in zip(x, r)] # @line L3
z = logits(p)
if _argmax(z) != k0 or it == max_iter: # @line L4
return p, it
jz = jac(p) # @line L5
step = nearest_boundary_step(z, jz, k0) # @line L6
r = [a + b for a, b in zip(r, step)] # @line L7
return p, max_iter # @line L8
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_deepfool.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deepfool/. The authors are listed in prov/A515G9.jsonl.
"""Tests of DeepFool, on seeded synthetic models only."""
import math
import random
import mlkit as m
from deepfool import deepfool, nearest_boundary_step
WE = [[1.0, 0.0], [0.0, 1.0], [-1.0, -1.0]]
BE = [0.0, 0.0, 0.0]
XE = [0.6, 0.4]
def affine(w, b):
return (lambda u: [m.dot(r, u) + bi for r, bi in zip(w, b)]), (lambda u: w)
def min_distance(w, b, x):
"""Brute force over all classes: l2 distance from x to the complement of its region."""
z = [m.dot(r, x) + bi for r, bi in zip(w, b)]
y = m.argmax(z)
return min((z[y] - z[j]) / m.norm2(m.sub(w[y], w[j])) for j in range(len(w)) if j != y)
def test_page_example() -> None:
lg, jac = affine(WE, BE)
p, it = deepfool(lg, jac, XE)
assert it == 1
assert m.argmax(lg(p)) == 1
step = nearest_boundary_step(lg(XE), jac(XE), 0)
assert all(abs(a - e) < 1e-9 for a, e in zip(step, [-0.1, 0.1]))
assert abs(math.dist(p, XE) - 1.02 * 0.2 / math.sqrt(2)) < 1e-9
def test_page_network_examples() -> None:
# seed 3: two iterations, label 1, distance 0.41925
net = m.tiny_relu_net(random.Random(3), 2, 4, 3)
lg = lambda u: m.forward(net, u)
jac = lambda u: m.logits_jacobian(net, u)
x = [0.5, 0.5]
assert m.argmax(lg(x)) == 0
p, it = deepfool(lg, jac, x)
assert it == 2 and m.argmax(lg(p)) == 1
assert all(abs(a - e) < 1e-4 for a, e in zip(p, [0.5891, 0.0903]))
assert abs(math.dist(p, x) - 0.41925) < 1e-4
# seed 131: the clip at the box makes the loop creep for 20 iterations
net = m.tiny_relu_net(random.Random(131), 2, 4, 3)
p, it = deepfool(lg, jac, x)
assert it == 20 and m.argmax(lg(p)) != m.argmax(lg(x))
assert abs(math.dist(p, x) - 0.551) < 1e-3
def test_edges() -> None:
lg, jac = affine([[1.0, 0.0], [1.0, 0.0]], [1.0, 0.0])
# equal gradients: no boundary can be reached by a linear step, so the input stays
p, it = deepfool(lg, jac, [0.5, 0.5], max_iter=3)
assert p == [0.5, 0.5] and it == 3
lg, jac = affine(WE, BE)
p, it = deepfool(lg, jac, XE, max_iter=0)
assert p == XE and it == 0
def test_binary_affine_step_is_the_closed_form() -> None:
# For f(x) = w.x + b the step is -(f(x) / ||w||^2) w, the projection onto the hyperplane.
rng = random.Random(7401)
for _ in range(500):
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)]
f = m.dot(w, x) + b
z = [0.0, f] # class 1 has logit f, class 0 has logit 0, so z_1 - z_0 = f
jz = [[0.0] * d, w]
k0 = 1 if f > 0 else 0
step = nearest_boundary_step(z, jz, k0)
target = m.scale(-f / m.dot(w, w), w)
assert m.norm2(m.sub(step, target)) < 1e-9 * (1 + m.norm2(target))
assert abs(m.dot(w, m.add(x, step)) + b) < 1e-9
def test_affine_multiclass_one_iteration_and_minimal() -> None:
rng = random.Random(7402)
for _ in range(500):
d, k = rng.randint(1, 4), rng.randint(2, 5)
w = [[rng.uniform(-2, 2) for _ in range(d)] for _ in range(k)]
b = [rng.uniform(-0.3, 0.3) for _ in range(k)]
x = [rng.uniform(0.3, 0.7) for _ in range(d)]
lg, jac = affine(w, b)
dmin = min_distance(w, b, x)
if dmin > 0.25:
continue # keep the boundary point inside the box
p, it = deepfool(lg, jac, x)
assert it == 1
assert m.argmax(lg(p)) != m.argmax(lg(x))
assert abs(math.dist(p, x) - 1.02 * dmin) < 1e-9
def test_relu_nets_label_changes_and_box() -> None:
rng = random.Random(7403)
done = 0
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)
lg = lambda u: m.forward(net, u)
jac = lambda u: m.logits_jacobian(net, u)
x = [rng.uniform(0, 1) for _ in range(d)]
p, it = deepfool(lg, jac, x, max_iter=20)
assert all(0.0 <= a <= 1.0 for a in p)
if it < 20:
done += 1
assert m.argmax(lg(p)) != m.argmax(lg(x))
# Some seeded nets keep one label over the whole box, so the loop cannot always stop early.
assert done > 200
History
Szegedy et al. (2014) measured robustness with a slow box-constrained L-BFGS search, and Goodfellow, Shlens and Szegedy (2015) with the fast but coarse FGSM. Moosavi-Dezfooli, Fawzi and Frossard posted DeepFool in November 2015 (CVPR 2016). It found smaller perturbations than FGSM at a cost close to it on MNIST, CIFAR10 and ImageNet models, and it showed that FGSM overestimates robustness (measurements in their Section 4). The same group later used DeepFool to build universal perturbations (2017) and to study the curvature of decision boundaries. Carlini and Wagner (2017) found that their attack gives somewhat smaller distances than DeepFool, at a much higher cost.
References
- 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, Section 2 (the binary case, exact for an affine classifier, and the iterative algorithm), Section 3 (the multiclass case and the extension to l_p norms), Section 4 (the robustness measure and the comparison with FGSM and the L-BFGS method of Szegedy et al.)
- Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Omar Fawzi and Pascal Frossard, Universal adversarial perturbations, CVPR 2017, the use of DeepFool as the inner step of the universal perturbation
- Nicholas Carlini and David Wagner, Towards evaluating the robustness of neural networks, IEEE Symposium on Security and Privacy 2017, pages 39 to 57, the comparison of the distances found by DeepFool and by the C&W attack
- 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.
| 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 A515G9 Edit this page History Report an error Markdown