Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 ℓ2\ell_2 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 ρ2(x)\rho_2(x) from xx 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 [0,1]d[0,1]^d of any size; the attack reports the ℓ2\ell_2 size of the change it found, so the radius ϵ\epsilon 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 1+γ1 + \gamma with a small overshoot γ\gamma, so that the point is really on the other side and not on the border.

The problem

Given logits z(v)∈RKz(v) \in \mathbb{R}^K on v∈[0,1]dv \in [0,1]^d and an input xx with label k0=arg⁡max⁡kzk(x)k_0 = \arg\max_k z_k(x), estimate

ρ2(x)=min⁡{∥r∥2:arg⁡max⁡kzk(x+r)≠k0}\rho_2(x) = \min \{\lVert r \rVert_2 : \arg\max_k z_k(x + r) \ne k_0\}

and return a point x+rx + r with another label and ∥r∥2\lVert r \rVert_2 close to ρ2(x)\rho_2(x).

For an affine model z(v)=Wv+bz(v) = Wv + b the answer has a closed form. Write fk(v)=zk(v)−zk0(v)f_k(v) = z_k(v) - z_{k_0}(v) and wk=∇fkw_k = \nabla f_k for k≠k0k \ne k_0. The region of class k0k_0 is the polyhedron {v:fk(v)≤0 for all k}\{v : f_k(v) \le 0 \text{ for all } k\}, and the distance to the face of class kk is ∣fk(x)∣/∥wk∥2|f_k(x)| / \lVert w_k \rVert_2. So

ρ2(x)=min⁡k≠k0∣fk(x)∣∥wk∥2,r⋆=∣fl(x)∣∥wl∥22 wl,\rho_2(x) = \min_{k \ne k_0} \frac{|f_k(x)|}{\lVert w_k \rVert_2}, \qquad r^\star = \frac{|f_l(x)|}{\lVert w_l \rVert_2^2}\, w_l,

with ll the class that attains the minimum (ignoring the box). For two classes this is the distance ∣w⊤x+b∣/∥w∥2|w^\top x + b| / \lVert w \rVert_2 to a hyperplane.

The algorithm

  1. DEEPFOOL(z, x, gamma, T) ▷ gamma ≥ 0 is the overshoot
  2. 1k0 ← argmax_k z_k(x); r ← 0
  3. 2for it ← 0 to T do
  4. 3p ← clip_[0,1](x + (1 + gamma) r)
  5. 4if argmax_k z_k(p) ≠ k0 or it = T then return (p, it)
  6. 5J ← the Jacobian of z at p
  7. 6for 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
  8. 7r ← r + step
  9. 8return (p, T)

Line L6 is the closed form above, applied to the linear model of zz at pp. The code adds 10−1210^{-12} to ∣fl∣|f_l| so that the step crosses the hyperplane, and skips classes with wk=0w_k = 0. Line L3 applies the overshoot to the whole sum of the steps, as in the paper (they use γ=0.02\gamma = 0.02), and clips to the box. Line L4 stops at the first point with another label, or after TT iterations, in which case the label may still be k0k_0.

Example

An affine model, one step. Take the model of the page adversarial example: K=3K = 3, z(v)=Wvz(v) = Wv with rows (1,0)(1, 0), (0,1)(0, 1) and (−1,−1)(-1, -1), and x=(0.6,0.4)x = (0.6, 0.4) with k0=0k_0 = 0 and γ=0.02\gamma = 0.02. The logits are (0.6,0.4,−1)(0.6, 0.4, -1).

class kk wk=Wk−W0w_k = W_k - W_0 fk(x)f_k(x) ∥wk∥2\lVert w_k \rVert_2 distance ∣fk∣/∥wk∥2\lvert f_k \rvert / \lVert w_k \rVert_2
1 (−1,1)(-1, 1) −0.2-0.2 1.414211.41421 0.1414210.141421
2 (−2,−1)(-2, -1) −1.6-1.6 2.236072.23607 0.7155420.715542

Class 1 is nearest. The step is (0.2/2)(−1,1)=(−0.1,0.1)(0.2/2)(-1, 1) = (-0.1, 0.1), and line L3 gives p=x+1.02⋅(−0.1,0.1)=(0.498,0.502)p = x + 1.02 \cdot (-0.1, 0.1) = (0.498, 0.502), with logits (0.498,0.502,−1)(0.498, 0.502, -1) and label 11. DeepFool stops after one iteration. The distance is 1.02⋅0.141421=0.1442501.02 \cdot 0.141421 = 0.144250, the true minimum times 1+γ1 + \gamma. It used one Jacobian and two logit calls.

A small network, two steps. Take the network of mlkit.tiny_relu_net with seed 3, d=2d = 2, h=4h = 4 hidden ReLU units and K=3K = 3, at x=(0.5,0.5)x = (0.5, 0.5):

iteration pp 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 0.419250.41925. A search over a grid of step 1/4001/400 on [0,1]2[0,1]^2 finds no point of another label closer than 0.414680.41468 (an estimate from the grid, accurate to about 0.0020.002). So DeepFool is within about 1.11.1 percent of the minimum here, and γ\gamma accounts for most of it.

Correctness

Theorem 1 (affine models). Let zz be affine, and let q=x+(1+γ)r⋆q = x + (1 + \gamma) r^\star lie in [0,1]d[0,1]^d. Then DeepFool returns qq after one iteration, the label of qq is not k0k_0, and ∥q−x∥2=(1+γ)ρ2(x)\lVert q - x \rVert_2 = (1 + \gamma)\rho_2(x), up to the 10−1210^{-12} margin.

Theorem 2 (any model). DeepFool returns a point of [0,1]d[0,1]^d after at most TT iterations. If it stops before TT, the label of the point is not k0k_0. It calls the logits it+2it + 2 times and the Jacobian itit times.

Theorem 1 holds because the region of k0k_0 is the intersection of the half spaces fk≤0f_k \le 0, 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 −f(x) w/∥w∥22-f(x)\, w / \lVert w \rVert_2^2, 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 ρ2(x)\rho_2(x), and it can stop at TT without a label change.

Proof: DeepFool finds the minimum l2 perturbation of an affine classifier in one iterationfull

Let the model have logits z(v)∈RKz(v) \in \mathbb{R}^K and label k^(v)=arg⁡max⁡kzk(v)\hat k(v) = \arg\max_k z_k(v), and let k0=k^(x)k_0 = \hat k(x) (line L1). For k≠k0k \ne k_0 write fk(v)=zk(v)−zk0(v)f_k(v) = z_k(v) - z_{k_0}(v) and wk(v)=∇fk(v)w_k(v) = \nabla f_k(v). At the current point pp the function nearest_boundary_step picks the class ll with the smallest ∣fl(p)∣/∥wl(p)∥2|f_l(p)| / \lVert w_l(p) \rVert_2 among the classes with wk≠0w_k \ne 0, and returns rp=∣fl(p)∣+δ∥wl∥22 wlr_p = \frac{|f_l(p)| + \delta}{\lVert w_l \rVert_2^2}\, w_l, where δ=10−12\delta = 10^{-12}.

Lemma 1 (the step of one iteration). Let the model be affine, z(v)=Wv+bz(v) = Wv + b, so that each wkw_k is a constant vector and each fkf_k is affine. Let pp have label k0k_0, so fk(p)≤0f_k(p) \le 0 for all kk. Then:

  1. The ℓ2\ell_2 distance from pp to the closed half space {v:fk(v)≥0}\{v : f_k(v) \ge 0\} is ∣fk(p)∣/∥wk∥2|f_k(p)| / \lVert w_k \rVert_2.
  2. The ℓ2\ell_2 distance from pp to the set A={v∈Rd:k^(v)≠k0}A = \{v \in \mathbb{R}^d : \hat k(v) \ne k_0\} is at least ρ=min⁡k:wk≠0∣fk(p)∣/∥wk∥2\rho = \min_{k: w_k \ne 0} |f_k(p)| / \lVert w_k \rVert_2.
  3. fl(p+t rp)=(t−1)∣fl(p)∣+tδf_l(p + t\, r_p) = (t - 1)|f_l(p)| + t\delta for t≥0t \ge 0. So fl(p+trp)>0f_l(p + t r_p) > 0 for every t≥1t \ge 1.

Proof. (1) The half space is {v:wk⊤(v−p)≥−fk(p)}\{v : w_k^\top (v - p) \ge -f_k(p)\}. The distance from a point to the half space {v:a⊤(v−p)≥β}\{v : a^\top (v - p) \ge \beta\} with β≥0\beta \ge 0 and a≠0a \ne 0 is β/∥a∥2\beta / \lVert a \rVert_2, attained at p+βa/∥a∥22p + \beta a / \lVert a \rVert_2^2. (2) A point vv has k^(v)≠k0\hat k(v) \ne k_0 only if zk(v)≥zk0(v)z_k(v) \ge z_{k_0}(v) for some kk, that is fk(v)≥0f_k(v) \ge 0. So AA is inside the union of the half spaces of part (1). A class with wk=0w_k = 0 has fkf_k constant and fk(p)≤0f_k(p) \le 0. If fk(p)<0f_k(p) < 0, its half space is empty. If fk(p)=0f_k(p) = 0, then zk=zk0z_k = z_{k_0} everywhere; a tie goes to the smaller index, and the label at pp is k0k_0, so k0<kk_0 < k and the class kk never takes the label. So only the classes with wk≠0w_k \ne 0 count. The distance to a union is the minimum of the distances. (3) Since flf_l is affine, fl(p+trp)=fl(p)+t wl⊤rp=fl(p)+t(∣fl(p)∣+δ)f_l(p + t r_p) = f_l(p) + t\, w_l^\top r_p = f_l(p) + t(|f_l(p)| + \delta), and fl(p)=−∣fl(p)∣f_l(p) = -|f_l(p)|. □\square

Theorem 1 (affine models). Let the model be affine and let the point q=x+(1+γ)rxq = x + (1 + \gamma) r_x, where γ≥0\gamma \ge 0 is the overshoot, lie in [0,1]d[0,1]^d. Then DeepFool returns (q,1)(q, 1). The label of qq is not k0k_0, and ∥q−x∥2=(1+γ)(ρ+δ/∥wl∥2)\lVert q - x \rVert_2 = (1 + \gamma)(\rho + \delta / \lVert w_l \rVert_2), where ρ\rho is the lower bound of Lemma 1 at p=xp = x. So the distance is the true minimum times 1+γ1 + \gamma, up to the term in δ\delta.

Proof. At it=0it = 0, line L3 gives p=xp = x because r=0r = 0, and line L4 does not return because the label of xx is k0k_0 (assume max_iter≥1\text{max\_iter} \ge 1). Lines L5 to L7 set r=rxr = r_x. At it=1it = 1, line L3 gives p=clip⁡(x+(1+γ)rx)=qp = \operatorname{clip}(x + (1+\gamma) r_x) = q, since qq is in the box. By Lemma 1(3) with t=1+γ≥1t = 1 + \gamma \ge 1, fl(q)>0f_l(q) > 0, so zl(q)>zk0(q)z_l(q) > z_{k_0}(q) and the label of qq is not k0k_0. Line L4 returns (q,1)(q, 1). The length of rxr_x is (∣fl(x)∣+δ)/∥wl∥2=ρ+δ/∥wl∥2(|f_l(x)| + \delta) / \lVert w_l \rVert_2 = \rho + \delta / \lVert w_l \rVert_2. By Lemma 1(2) no point closer than ρ\rho to xx has another label, and the point x+rx−δwl/∥wl∥22x + r_x - \delta w_l / \lVert w_l\rVert_2^2, at distance ρ\rho, is on the boundary, so ρ\rho is the minimum distance to the closure of AA. □\square

Theorem 2 (any model). For every model, DeepFool returns (p,it)(p, it) with p∈[0,1]dp \in [0,1]^d and 0≤it≤max_iter0 \le it \le \text{max\_iter}. If it<max_iterit < \text{max\_iter}, the label of pp is not k0k_0. It calls the logits it+2it + 2 times and the Jacobian itit times.

Proof. Line L3 clips every point to [0,1]d[0,1]^d. The loop of line L2 runs for it=0,1,…,max_iterit = 0, 1, \dots, \text{max\_iter}, and line L4 returns at the latest when it=max_iterit = \text{max\_iter}; so line L8 is never reached and it≤max_iterit \le \text{max\_iter}. Line L4 returns with it<max_iterit < \text{max\_iter} only when the label of pp is not k0k_0. 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. ■\blacksquare

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 max_iter\text{max\_iter} without a label change, and its distance is an upper bound on the true minimum, not the minimum. If every wk(p)w_k(p) is 00, the step is 00 and the loop runs to max_iter\text{max\_iter}.

Complexity

  • Time. Each iteration costs one logit evaluation and one Jacobian, gg, which is KK backward passes in general, plus O(Kd)O(K d) for line L6. The total is O(T(g+Kd))O(T (g + K d)). 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. Θ(Kd)\Theta(K d) for the Jacobian, plus Θ(d)\Theta(d) for rr and pp.
  • 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 xx.
  • An upper bound on the distance. The point found has another label, so ρ2(x)≤∥p−x∥2\rho_2(x) \le \lVert p - x \rVert_2. To get robust accuracy at radius ϵ\epsilon, count the points whose DeepFool distance is above ϵ\epsilon; this gives an upper bound on robust accuracy.
  • Not tied to a radius. DeepFool does not take ϵ\epsilon. This makes it good for measuring robustness and poor for testing a given threat model.

Variants and improvements

  • Other norms. For ℓp\ell_p with dual exponent qq, 1/p+1/q=11/p + 1/q = 1, the distance to the face of class kk is ∣fk∣/∥wk∥q|f_k| / \lVert w_k \rVert_q, and the step is ∣fl∣∥wl∥qq∣wl∣q−1⊙sign⁡(wl)\frac{|f_l|}{\lVert w_l \rVert_q^q} |w_l|^{q - 1} \odot \operatorname{sign}(w_l). For ℓ∞\ell_\infty it is ∣fl∣∥wl∥1sign⁡(wl)\frac{|f_l|}{\lVert w_l \rVert_1}\operatorname{sign}(w_l), an FGSM-like step with the exact size.
  • Robustness measure. The paper reports ρ^adv=1n∑x∥r(x)∥2/∥x∥2\hat\rho_{\mathrm{adv}} = \frac{1}{n}\sum_x \lVert r(x) \rVert_2 / \lVert x \rVert_2 over a test set of nn points.
  • Universal perturbations. The universal adversarial perturbation runs DeepFool on many inputs in turn and adds the steps into one vector.
  • Targeted step. Fix l=tl = t 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 ℓ2\ell_2 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 γ=0\gamma = 0 the point lands on the border, and rounding can keep the old label. Keep a small γ\gamma, such as 0.020.02.
  • The box. The linear step ignores [0,1]d[0,1]^d, 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 x=(0.5,0.5)x = (0.5, 0.5), the second coordinate hits 00 at iteration 2, and DeepFool needs 20 iterations, with a distance of 0.5510.551 against 0.5180.518 on the grid.
  • Gradients of zero. If wk(p)=0w_k(p) = 0 for all kk, as in a flat region of a ReLU network, the step is 00 and the loop runs to TT. 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 ℓ2\ell_2. Do not compare it with an ℓ∞\ell_\infty 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 (1+γ)(1 + \gamma) 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.

deepfool.pyI0RawGitHub
# 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

  1. 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.)
  2. 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
  3. 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
  4. Battista Biggio and Fabio Roli, Wild patterns: Ten years after the rise of adversarial machine learning, Pattern Recognition 84, pages 317 to 331, 2018, the threat model in three parts used on this page

Where this leads

About this page

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

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