Algorithm Search⌘K

Algorithmcore

Carlini-Wagner attack

Also called CW attack, C&W attack.

Finds a small l2 perturbation by minimizing the squared distance plus c times a margin loss on the logits, with a tanh change of variables for the box and a binary search on c.

Time
O(s T (g + d)) worst
Space
Θ(d) extra
Where
T = the number of optimizer steps in one round; d = the input dimension; g = the cost of the logits and two rows of their Jacobian; s = the number of rounds of the binary search
Properties
deterministicnot exactofflineiterative
Origin
Nicholas Carlini, David Wagner, 2016

The Carlini-Wagner attack (C&W attack) looks for the smallest change η\eta in ℓ2\ell_2 that gives an input a wrong label. It replaces the hard constraint "the label is wrong" by a penalty: it minimizes ∥η∥22+c⋅ℓ(x+η)\lVert \eta \rVert_2^2 + c \cdot \ell(x + \eta), where ℓ\ell is a margin loss on the logits that becomes negative once another class wins. It removes the box constraint x+η∈[0,1]dx + \eta \in [0,1]^d with the change of variables x′=12(tanh⁡w+1)x' = \tfrac12(\tanh w + 1), runs the Adam optimizer on ww, and sets the weight cc by binary search. Carlini and Wagner (2017) built it to measure how robust a network really is, and with it they broke defensive distillation, which had stopped the earlier attacks. With DeepFool it is the standard minimal-distance attack, and it is slower and more precise.

Threat model. The goal is untargeted on this page (the paper uses mostly targeted attacks; the change is one line). The knowledge is white box: the attacker computes the logits and their gradients. The capability is a change at test time anywhere in [0,1]d[0,1]^d; the attack reports the ℓ2\ell_2 size of the smallest change it found, so the radius ϵ\epsilon is an output, not an input.

In plain words

A fixed-radius attack asks "is there a wrong label within distance ϵ\epsilon?". The C&W attack asks "how close is the nearest wrong label?".

It sets up a trade. One term wants the change to be small. The other term wants the logit of some wrong class to beat the logit of the true class. A weight cc says how much the second term counts. With a small cc the change stays tiny but the label may not flip. With a large cc the label flips but the change may be bigger than needed. So the attack tries a value of cc, checks the label, and halves the range of cc, as in a binary search.

The pixels must stay between 00 and 11. The attack writes each pixel as a smooth function of a free number, so that every value of that number gives a valid pixel.

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 f(x)=yf(x) = y, the attack approximates

ρ2(x)=min⁡{∥x′−x∥2:x′∈[0,1]d, f(x′)≠y}.\rho_2(x) = \min \{\lVert x' - x \rVert_2 : x' \in [0,1]^d,\ f(x') \ne y\}.

It solves, for a weight c>0c > 0 and a confidence κ≥0\kappa \ge 0,

min⁡w∈Rd∥x′(w)−x∥22+c ℓ(x′(w)),x′(w)=12(tanh⁡w+1),ℓ(v)=max⁡(zy(v)−max⁡i≠yzi(v), −κ).\min_{w \in \mathbb{R}^d} \lVert x'(w) - x \rVert_2^2 + c\, \ell(x'(w)), \qquad x'(w) = \tfrac12(\tanh w + 1), \qquad \ell(v) = \max\big(z_y(v) - \max_{i \ne y} z_i(v),\ -\kappa\big).

The loss ℓ\ell is positive while class yy wins, and it stops at −κ-\kappa once another class wins by κ\kappa, so the attack does not push further than it needs. For a target class tt, use max⁡(max⁡i≠tzi−zt,−κ)\max(\max_{i \ne t} z_i - z_t, -\kappa) instead; this is the function the paper calls f6f_6, the best of the seven it tried.

The algorithm

  1. CW-L2(z, x, y, c, kappa, T, s) ▷ x in [0, 1]^d with f(x) = y
  2. 1lo ← 0; hi ← ∞; best ← none
  3. 2repeat s times ▷ rounds of the binary search on c
  4. 3w ← artanh(2x - 1) ▷ start at x itself
  5. 4for t ← 1 to T do
  6. 5x' ← (tanh(w) + 1) / 2 ▷ always in (0, 1)^d
  7. 6if max_{i≠y} z_i(x') - z_y(x') ≥ kappa and f(x') ≠ y and x' is closer to x than best then best ← x'
  8. 7w ← Adam step on ∇_w (||x' - x||_2^2 + c · ℓ(x'))
  9. 8if this round recorded an adversarial x' then hi ← c else lo ← c
  10. 9c ← (lo + hi) / 2 if hi < ∞ else 10 c
  11. 10return best

Line L3 starts each round at ww with x′(w)=xx'(w) = x; the code keeps 2xi−12x_i - 1 inside (−1,1)(-1, 1) by a margin of 10−910^{-9}, so that artanh⁡\operatorname{artanh} stays finite. Line L6 records every adversarial iterate that is closer than the best so far, in every round. Line L7 uses the gradient

∂∂wi=(2(xi′−xi)+c (∂izy(x′)−∂izj(x′)))⋅12(1−tanh⁡2wi),\frac{\partial}{\partial w_i} = \Big(2(x'_i - x_i) + c\,\big(\partial_i z_y(x') - \partial_i z_j(x')\big)\Big)\cdot \tfrac12\big(1 - \tanh^2 w_i\big),

where jj is the best other class, and the term in cc drops out where ℓ=−κ\ell = -\kappa. Lines L8 and L9 are the binary search: a success means cc was large enough, so cc goes down; a failure means cc goes up, by a factor of 1010 until the first success.

Example

Take the linear 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 y=0y = 0. The nearest wrong label is class 11, across the line v1=v2v_1 = v_2, at ρ2(x)=0.2/2=0.141421\rho_2(x) = 0.2/\sqrt2 = 0.141421. Run the attack with c=0.1c = 0.1, κ=0\kappa = 0, T=100T = 100 Adam steps of rate 0.010.01 and s=8s = 8 rounds.

Along the direction (−1,1)/2(-1, 1)/\sqrt2 the objective is τ2+c max⁡(0.2−2 τ,0)\tau^2 + c\,\max(0.2 - \sqrt2\,\tau, 0), with its minimum at τ=c/2\tau = c/\sqrt2. This crosses the boundary only when c/2≥0.141421c/\sqrt2 \ge 0.141421, that is c≥0.2c \ge 0.2. The rounds show it:

round cc adversarial point found? closest distance in the round
1 0.1 no none
2 1 yes 0.14151
3 0.55 yes 0.14168
4 0.325 yes 0.14143
5 0.2125 yes 0.14156
6 0.15625 no none
7 0.184375 yes 0.14159
8 0.1703125 no none

The first round fails, so line L9 multiplies cc by 1010. Then the search halves the interval each round. Round 7 has c<0.2c < 0.2 and still records an adversarial point: the momentum of Adam carries one iterate just across the line before it comes back, and line L6 records it. This is allowed, because line L6 checks the label of the actual point.

The output is x⋆=(0.499997,0.500003)x^\star = (0.499997, 0.500003) from round 4, at distance 0.1414260.141426, which is 1.000031.00003 times ρ2(x)\rho_2(x). The run cost 8⋅100=8008 \cdot 100 = 800 gradients. With κ=0.1\kappa = 0.1, the attack must reach z1−z0≥0.1z_1 - z_0 \ge 0.1, which is at least 0.3/2=0.2121320.3/\sqrt2 = 0.212132 away, and it returns (0.44998,0.55002)(0.44998, 0.55002) at distance 0.2121610.212161.

Correctness

Theorem 1 (a valid output). If the attack returns a point x⋆x^\star, then x⋆∈[0,1]dx^\star \in [0,1]^d, f(x⋆)≠yf(x^\star) \ne y, the best other logit is at least κ\kappa above zy(x⋆)z_y(x^\star), and ∥x⋆−x∥2≥ρ2(x)\lVert x^\star - x \rVert_2 \ge \rho_2(x).

Theorem 2. The output is the closest point to xx among all adversarial iterates of all rounds.

Lemma (the search). Before the first success, cc grows by a factor of 1010 in each round. After it, lo<c<hilo < c < hi, and each round halves hi−lohi - lo.

The change of variables maps Rd\mathbb{R}^d onto (0,1)d(0,1)^d one to one, so every iterate is a valid input (Lemma 1 of the proof page). Line L6 records only points that pass the test, so the output is a real adversarial example, and its distance is an upper bound on ρ2(x)\rho_2(x). The full proofs are in proofs/correctness.md.

For two classes and an affine model, the objective is convex in x′x', and the attack gets close to ρ2(x)\rho_2(x), as in the example. For a network the objective is not convex, Adam can stop at a local minimum, and success need not be monotone in cc. So the distance found is an upper bound on ρ2(x)\rho_2(x), never a lower bound.

Proof: The C&W attack returns a valid adversarial input, never closer than the true minimumfull

We write f(v)=arg⁡max⁡kzk(v)f(v) = \arg\max_k z_k(v) for the label, y=f(x)y = f(x) for the label of the input x∈[0,1]dx \in [0,1]^d, and d⋆(x)=inf⁡{∥v−x∥2:v∈[0,1]d, f(v)≠y}d^\star(x) = \inf\{\lVert v - x \rVert_2 : v \in [0,1]^d,\ f(v) \ne y\} for the true minimum adversarial distance. The attack works on a variable w∈Rdw \in \mathbb{R}^d and the point x′=12(tanh⁡w+1)x' = \tfrac12(\tanh w + 1), taken coordinate by coordinate (line L5).

Lemma 1 (the box constraint disappears). For every w∈Rdw \in \mathbb{R}^d, x′∈(0,1)dx' \in (0,1)^d. Every point of (0,1)d(0,1)^d is x′x' for exactly one ww.

Proof. The function tanh⁡\tanh is a strictly increasing bijection from R\mathbb{R} onto (−1,1)(-1, 1), so t↦12(tanh⁡t+1)t \mapsto \tfrac12(\tanh t + 1) is a strictly increasing bijection from R\mathbb{R} onto (0,1)(0,1). Apply it to each coordinate. □\square

In floating point, tanh⁡\tanh can round to ±1\pm 1, so a coordinate can be exactly 00 or 11. It is still in [0,1][0,1]. The function from_box keeps 2xi−12x_i - 1 inside [−1+10−9,1−10−9][-1 + 10^{-9}, 1 - 10^{-9}], so the start of line L3 is finite even when xix_i is 00 or 11.

Lemma 2 (the gradient of line L7). Let F(w)=∥x′−x∥22+c ℓ(x′)F(w) = \lVert x' - x \rVert_2^2 + c\, \ell(x') with ℓ(v)=max⁡(zy(v)−max⁡i≠yzi(v),−κ)\ell(v) = \max(z_y(v) - \max_{i \ne y} z_i(v), -\kappa). At a point where the best other class jj is unique and ℓ(x′)>−κ\ell(x') > -\kappa, ∂F/∂wi=(2(xi′−xi)+c (∂izy−∂izj)(x′))⋅12(1−tanh⁡2wi)\partial F / \partial w_i = \big(2(x'_i - x_i) + c\,(\partial_i z_y - \partial_i z_j)(x')\big) \cdot \tfrac12 (1 - \tanh^2 w_i). Where ℓ(x′)<−κ\ell(x') < -\kappa, the same formula holds without the term in cc.

Proof. Near such a point, ℓ(v)=zy(v)−zj(v)\ell(v) = z_y(v) - z_j(v) in the first case and ℓ(v)=−κ\ell(v) = -\kappa in the second, so ∇vℓ\nabla_v \ell is ∇zy−∇zj\nabla z_y - \nabla z_j or 00. The gradient of ∥v−x∥22\lVert v - x \rVert_2^2 is 2(v−x)2(v - x). Since xi′x'_i depends only on wiw_i, with dxi′/dwi=12(1−tanh⁡2wi)dx'_i / dw_i = \tfrac12 (1 - \tanh^2 w_i), the chain rule gives the formula. This is what objective_gradient computes. □\square

Theorem 1 (a valid output). If the attack returns a point x⋆x^\star (not None), then x⋆∈[0,1]dx^\star \in [0,1]^d, f(x⋆)≠yf(x^\star) \ne y, max⁡i≠yzi(x⋆)−zy(x⋆)≥κ\max_{i \ne y} z_i(x^\star) - z_y(x^\star) \ge \kappa, and ∥x⋆−x∥2≥d⋆(x)\lVert x^\star - x \rVert_2 \ge d^\star(x).

Proof. The variable best is set only in line L6, and only to a point x′x' of line L5 whose label differs from yy and whose best other logit is at least κ\kappa above zy(x′)z_y(x'). By Lemma 1 and the remark after it, x′∈[0,1]dx' \in [0,1]^d. So x⋆x^\star is in the set over which d⋆(x)d^\star(x) is the infimum, and its distance is at least the infimum. □\square

So the attack gives an upper bound ∥x⋆−x∥2\lVert x^\star - x \rVert_2 on the distance from xx to the nearest adversarial input, and never a value below the truth. If it returns None, it proves nothing: the point xx may still have adversarial inputs close by.

Theorem 2 (the best point is the closest one seen). The returned point is, among all points x′x' of line L5 in all rounds that have a label other than yy, one with the smallest distance to xx.

Proof. Line L6 replaces best only by a point with a strictly smaller distance, and every adversarial x′x' of every round passes through line L6. □\square

Lemma 3 (the search on cc). Let c0>0c_0 > 0. Before the first round that succeeds, line L9 multiplies cc by 1010 and hi=∞hi = \infty. After it, 0≤lo<c<hi<∞0 \le lo < c < hi < \infty holds after each line L9, and hi−lohi - lo is halved by each round.

Proof. While every round fails, line L8 sets lo=clo = c and line L9 sets cc to 10c10c, so lo<clo < c. At the first success, hi=c>lohi = c > lo, and line L9 sets c=(lo+hi)/2c = (lo + hi)/2, strictly between lolo and hihi. In each later round, line L8 replaces either hihi or lolo by the current cc, which lies strictly between them, and so it halves the gap and keeps lo<hilo < hi. Line L9 then puts cc at the midpoint again. ■\blacksquare

What is not claimed. The function FF is not convex for a nonlinear model, and success of a round need not be monotone in cc. So Lemma 3 is a statement about the search, not a proof that it finds the best cc, and Adam is not proved to reach a global minimum of FF. Theorems 1 and 2 hold for every model, and they are the properties an attack must have.

Complexity

  • Time. Each step costs one evaluation of the logits and of the gradient of zy−zjz_y - z_j, which is gg (one forward and one backward pass), plus O(d)O(d) for the distance term, the change of variables and the Adam update. The total is O(s T (g+d))O(s\, T\, (g + d)). With the large step counts used on image models, the attack costs thousands of gradients, against one for FGSM and a few for DeepFool.
  • Space. Θ(d)\Theta(d) for ww, the two Adam moment vectors and the best point.
  • Model. These counts are in the real-ram model, with one gradient as a unit of work.

Properties

  • Deterministic. The start is xx, and Adam has no randomness.
  • Minimal, not fixed-radius. The output distance estimates ρ2(x)\rho_2(x) from above. To get robust accuracy at a radius ϵ\epsilon, count the points whose distance is above ϵ\epsilon; this is an upper bound on robust accuracy.
  • Uses logits, not probabilities. The margin on logits does not saturate. A loss on softmax outputs has gradients near 00 when one class has probability near 11, which is what made distillation look robust.
  • Confidence. A larger κ\kappa gives larger changes that the model labels wrong by a wide margin. Such points transfer better to other models.

Variants and improvements

  • Targeted attack. Use ℓ(v)=max⁡(max⁡i≠tzi(v)−zt(v),−κ)\ell(v) = \max(\max_{i \ne t} z_i(v) - z_t(v), -\kappa).
  • The ℓ0\ell_0 attack. Run the ℓ2\ell_2 attack, find the coordinate that contributes least, fix it to its value in xx, and repeat while the attack still succeeds. The coordinates that stay free form a small set, as in the Jacobian saliency map attack.
  • The ℓ∞\ell_\infty attack. Replace ∥η∥22\lVert \eta \rVert_2^2 by ∑imax⁡(∣ηi∣−τ,0)\sum_i \max(|\eta_i| - \tau, 0) and lower τ\tau after each success.
  • Elastic net (EAD). Chen et al. (2018) add an ℓ1\ell_1 term to the objective.
  • Black box. The ZOO attack runs the same objective with gradients estimated from score queries.
  • Detectors. Carlini and Wagner (2017, AISec) treat a detector and a classifier as one model with one more class, and run the attack on it. They bypassed ten detection methods in this way.

When to use it

Use the C&W attack to estimate the minimal ℓ2\ell_2 distance to the decision boundary, to evaluate a defense with an attack on the logits, and as a check after FGSM and PGD. It is slow, so it is not used inside training. For a quick estimate use DeepFool; for a fixed radius use the PGD attack, which can run on the C&W margin loss too. To prove that no smaller change exists, use a verifier or a certificate such as randomized smoothing.

Pitfalls

  • Clipping instead of the change of variables. Projected or clipped gradient steps work, but Carlini and Wagner found them worse with Adam: clipped coordinates get stuck at 00 or 11.
  • A loss on probabilities. On a network with a saturated softmax, such as a distilled network at temperature 11, the gradient of the loss on probabilities is almost 00, and the attack fails. Use the logits.
  • One value of cc. A fixed cc is either too small (no success) or too large (a bigger change than needed). The binary search matters.
  • Only the last iterate. The last iterate can be on the wrong side of the boundary. Record the closest adversarial iterate, as line L6 does.
  • Calling a failure robustness. If all rounds fail, nothing is proved. Increase TT, ss and the start value of cc before drawing a conclusion.
  • Ties. With κ=0\kappa = 0, a point exactly on the boundary may count as class yy. A small κ\kappa avoids points that rounding can flip back.

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: linear 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 example of the page with κ=0\kappa = 0 and κ=0.1\kappa = 0.1, the change of variables and the margin, the gradient of line L7 against central finite differences, the distance against the closed form on 300 random two-class linear models, the lower bound ρ2(x)\rho_2(x) on 500 random multiclass linear models, and that every output on random networks is adversarial and inside the box.

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.

carlini_wagner_attack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/carlini-wagner-attack/. The authors are listed in prov/2XQ46N.jsonl.

"""The l2 attack of Carlini and Wagner (2017), on synthetic models only.

The model is given as two functions on an input in [0, 1]^d: its logits and the
Jacobian of the logits. The tests build both from a seeded linear 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 margin(z: Sequence[float], y: int, kappa: float) -> tuple[float, int]:
    """The untargeted loss f = max(z_y - max_{i != y} z_i, -kappa), and the best other class."""
    j = max((i for i in range(len(z)) if i != y), key=lambda i: z[i])
    return max(z[y] - z[j], -kappa), j


def to_box(w: Sequence[float]) -> Vector:
    """The change of variables x' = (tanh(w) + 1) / 2, which maps R^d onto (0, 1)^d."""
    return [(math.tanh(a) + 1.0) / 2.0 for a in w]


def from_box(x: Sequence[float]) -> Vector:
    """The inverse map w = artanh(2 x - 1), with 2 x - 1 kept inside (-1, 1)."""
    lim = 1.0 - 1e-9
    return [math.atanh(min(max(2.0 * a - 1.0, -lim), lim)) for a in x]


def objective_gradient(logits: Logits, jac: Jacobian, x: Sequence[float], w: Sequence[float], y: int,
                       c: float, kappa: float) -> tuple[float, Vector]:
    """Value and w-gradient of ||x' - x||_2^2 + c f(x') with x' = to_box(w)."""
    xp = to_box(w)
    z = logits(xp)
    f, j = margin(z, y, kappa)
    dist2 = math.fsum((a - b) ** 2 for a, b in zip(xp, x))
    gx = [2.0 * (a - b) for a, b in zip(xp, x)]
    if f > -kappa:  # the max is not clamped, so f = z_y - z_j locally
        jz = jac(xp)
        gx = [g + c * (jz[y][i] - jz[j][i]) for i, g in enumerate(gx)]
    gw = [g * (1.0 - math.tanh(a) ** 2) / 2.0 for g, a in zip(gx, w)]
    return dist2 + c * f, gw


def carlini_wagner_attack(logits: Logits, jac: Jacobian, x: Sequence[float], y: int, c: float = 0.1,
                          kappa: float = 0.0, steps: int = 100, lr: float = 0.05,
                          search_steps: int = 6) -> Vector | None:
    """Smallest l2 adversarial input found by the C&W l2 attack, or None.

    An input x' counts as adversarial when argmax logits(x') != y and the best other
    logit is at least kappa above the logit of y (for kappa = 0 a wrong label is enough,
    with ties going to the first index). The weight c of the
    loss is set by binary search: up when a round fails, down when it succeeds.
    Each round runs Adam on w from the start w = artanh(2 x - 1).
    Precondition: x in [0, 1]^d and argmax logits(x) == y. Cost: search_steps * steps
    evaluations of logits and jac, and O(search_steps * steps * d) more.
    """
    lo, hi = 0.0, math.inf  # @line L1
    best: Vector | None = None
    best_d = math.inf
    for _ in range(search_steps):  # @line L2
        w = from_box(x)  # @line L3
        mom, vel = [0.0] * len(x), [0.0] * len(x)
        success = False
        for t in range(1, steps + 1):  # @line L4
            xp = to_box(w)  # @line L5
            z = logits(xp)
            gap = max(z[i] for i in range(len(z)) if i != y) - z[y]
            if max(range(len(z)), key=lambda i: z[i]) != y and gap >= kappa:  # @line L6
                success = True
                dist = math.dist(xp, x)
                if dist < best_d:
                    best, best_d = xp, dist
            _, g = objective_gradient(logits, jac, x, w, y, c, kappa)  # @line L7
            mom = [0.9 * a + 0.1 * b for a, b in zip(mom, g)]
            vel = [0.999 * a + 0.001 * b * b for a, b in zip(vel, g)]
            mh, vh = 1.0 - 0.9 ** t, 1.0 - 0.999 ** t
            w = [a - lr * (mi / mh) / (math.sqrt(vi / vh) + 1e-12) for a, mi, vi in zip(w, mom, vel)]
        if success:  # @line L8
            hi = c
        else:
            lo = c
        c = (lo + hi) / 2.0 if hi < math.inf else 10.0 * c  # @line L9
    return best  # @line L10
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_carlini_wagner_attack.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/carlini-wagner-attack/. The authors are listed in prov/2XQ46N.jsonl.

"""Tests of the C&W l2 attack, on seeded synthetic models only."""

import math
import random

import mlkit as m
from carlini_wagner_attack import carlini_wagner_attack, from_box, margin, objective_gradient, to_box

# The worked example of the page: three classes in the plane.
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 linear(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, y):
    """Closed form: the l2 distance from x to the complement of the region of class y of an affine classifier."""
    z = [m.dot(r, x) + bi for r, bi in zip(w, b)]
    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 = linear(WE, BE)
    assert m.argmax(lg(XE)) == 0
    dmin = min_distance(WE, BE, XE, 0)
    assert abs(dmin - 0.2 / math.sqrt(2)) < 1e-12
    out = carlini_wagner_attack(lg, jac, XE, 0, steps=100, lr=0.01, search_steps=8)
    assert out is not None and m.argmax(lg(out)) == 1
    assert dmin <= math.dist(out, XE) <= dmin + 0.005
    # with confidence kappa = 0.1 the output has z_1 - z_0 >= 0.1, so it is at least 0.3 / sqrt(2) away
    out = carlini_wagner_attack(lg, jac, XE, 0, kappa=0.1, steps=100, lr=0.01, search_steps=8)
    assert out is not None and lg(out)[1] - lg(out)[0] >= 0.1
    assert 0.3 / math.sqrt(2) <= math.dist(out, XE) <= 0.3 / math.sqrt(2) + 0.005


def test_change_of_variables_and_margin() -> None:
    for x in ([0.0, 1.0, 0.5], [0.25, 0.75, 0.999]):
        back = to_box(from_box(x))
        assert all(abs(a - b) < 1e-8 for a, b in zip(back, x))
    assert margin([3.0, 1.0, 2.0], 0, 0.0) == (1.0, 2)
    assert margin([1.0, 3.0, 2.0], 0, 0.5) == (-0.5, 1)


def test_objective_gradient_matches_finite_differences() -> None:
    rng = random.Random(7301)
    checked = 0
    for _ in range(500):
        d, h, k = rng.randint(1, 4), rng.randint(2, 6), 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, 0.9) for _ in range(d)]
        y = m.argmax(lg(x))
        w = [a + rng.uniform(-0.3, 0.3) for a in from_box(x)]
        c = rng.uniform(0.1, 5.0)
        kappa = rng.choice([0.0, 0.5])
        xp = to_box(w)
        pre = [m.dot(r, xp) + bi for r, bi in zip(net["W1"], net["b1"])]
        z = lg(xp)
        gaps = sorted(z, reverse=True)
        f, _ = margin(z, y, kappa)
        if min(abs(a) for a in pre) < 1e-3 or gaps[0] - gaps[1] < 1e-3 or abs(f + kappa) < 1e-3:
            continue  # too close to a kink for a finite difference
        _, g = objective_gradient(lg, jac, x, w, y, c, kappa)
        for i in range(d):
            up, dn = list(w), list(w)
            up[i] += 1e-6
            dn[i] -= 1e-6
            fd = (objective_gradient(lg, jac, x, up, y, c, kappa)[0] - objective_gradient(lg, jac, x, dn, y, c, kappa)[0]) / 2e-6
            assert abs(fd - g[i]) < 1e-5
        checked += 1
    assert checked > 300


def test_binary_linear_models_against_closed_form() -> None:
    # With two classes the objective is convex in x', and the true minimum is the
    # distance |z_0 - z_1| / ||w_0 - w_1|| to the hyperplane (inside the box here).
    rng = random.Random(7302)
    for _ in range(300):
        d = rng.randint(1, 4)
        w = [[rng.uniform(-2, 2) for _ in range(d)] for _ in range(2)]
        x = [rng.uniform(0.4, 0.6) for _ in range(d)]
        target = rng.uniform(0.02, 0.3)
        diff = m.sub(w[0], w[1])
        if m.norm2(diff) < 0.2:
            continue
        b = [target * m.norm2(diff) - m.dot(diff, x), 0.0]  # z_0 - z_1 = target ||w_0 - w_1||
        lg, jac = linear(w, b)
        dmin = min_distance(w, b, x, 0)
        assert abs(dmin - target) < 1e-9
        out = carlini_wagner_attack(lg, jac, x, 0, steps=40, lr=0.04, search_steps=5)
        assert out is not None
        assert m.argmax(lg(out)) == 1
        assert all(0.0 < a < 1.0 for a in out)
        assert dmin - 1e-12 <= math.dist(out, x) <= dmin + 0.01


def test_multiclass_linear_models_respect_the_lower_bound() -> None:
    # With more classes the margin loss is not convex, and the attack may stop at a
    # boundary that is not the nearest one. Any output is still at least the minimum away.
    rng = random.Random(7303)
    found = 0
    for _ in range(500):
        d, k = rng.randint(1, 3), rng.randint(3, 4)
        w = [[rng.uniform(-2, 2) for _ in range(d)] for _ in range(k)]
        b = [rng.uniform(-0.5, 0.5) for _ in range(k)]
        x = [rng.uniform(0.3, 0.7) for _ in range(d)]
        lg, jac = linear(w, b)
        y = m.argmax(lg(x))
        out = carlini_wagner_attack(lg, jac, x, y, steps=25, lr=0.05, search_steps=3)
        if out is not None:
            found += 1
            assert m.argmax(lg(out)) != y
            assert math.dist(out, x) >= min_distance(w, b, x, y) - 1e-12
            assert all(0.0 < a < 1.0 for a in out)
    assert found > 300


def test_relu_nets_outputs_are_adversarial_and_in_the_box() -> None:
    rng = random.Random(7304)
    found = 0
    for _ in range(60):
        d, h, k = rng.randint(1, 4), rng.randint(2, 8), 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)
        x = [rng.uniform(0, 1) for _ in range(d)]
        y = m.argmax(lg(x))
        out = carlini_wagner_attack(lg, jac, x, y, steps=40, lr=0.05, search_steps=4)
        if out is not None:
            found += 1
            assert m.argmax(lg(out)) != y
            assert all(0.0 < a < 1.0 for a in out)
    assert found > 0

History

Szegedy et al. (2014) found the first adversarial examples of deep networks by a box-constrained L-BFGS search on c∥η∥+lossc \lVert \eta \rVert + \text{loss}, with a line search on cc. Papernot et al. (2016) proposed defensive distillation and reported that it stopped the known attacks. Carlini and Wagner posted a short note in July 2016 that distillation is not robust, and in August 2016 the full paper (IEEE S&P 2017). They compared seven loss functions and three ways to keep the box, chose the margin on logits and the tanh change of variables, and gave attacks for ℓ0\ell_0, ℓ2\ell_2 and ℓ∞\ell_\infty. Their attacks succeeded on all the test points of both distilled and undistilled networks on MNIST and CIFAR10 (a measurement in the paper). The attack became the reference for evaluating defenses, and its margin loss is now common in PGD too.

References

  1. Nicholas Carlini and David Wagner, Towards evaluating the robustness of neural networks, IEEE Symposium on Security and Privacy 2017, pages 39 to 57, the seven objective functions and the choice of the margin loss on the logits, the three ways to handle the box (projected gradient, clipped gradient, change of variables), the binary search on c, the l2, l0 and l_infinity attacks, and the evaluation on defensively distilled networks
  2. Nicholas Carlini and David Wagner, Defensive distillation is not robust to adversarial examples, arXiv 2016, the first report that distilled networks fall to attacks on the logits
  3. Christian Szegedy, Wojciech Zaremba, Ilya Sutskever, Joan Bruna, Dumitru Erhan, Ian Goodfellow and Rob Fergus, Intriguing properties of neural networks, ICLR 2014, Section 4.1 (the box-constrained L-BFGS search for the minimal perturbation, the form that the C&W attack refines)
  4. Nicholas Carlini and David Wagner, Adversarial examples are not easily detected, bypassing ten detection methods, ACM AISec 2017, the C&W loss adapted to a classifier joined with a detector
  5. Pin-Yu Chen, Yash Sharma, Huan Zhang, Jinfeng Yi and Cho-Jui Hsieh, EAD, elastic-net attacks to deep neural networks via adversarial examples, AAAI 2018, the C&W objective with an added l1 term
  6. 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