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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nicholas Carlini, David Wagner, 2016
The Carlini-Wagner attack (C&W attack) looks for the smallest change in that gives an input a wrong label. It replaces the hard constraint "the label is wrong" by a penalty: it minimizes , where is a margin loss on the logits that becomes negative once another class wins. It removes the box constraint with the change of variables , runs the Adam optimizer on , and sets the weight 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 ; the attack reports the size of the smallest change it found, so the radius is an output, not an input.
In plain words
A fixed-radius attack asks "is there a wrong label within distance ?". 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 says how much the second term counts. With a small the change stays tiny but the label may not flip. With a large the label flips but the change may be bigger than needed. So the attack tries a value of , checks the label, and halves the range of , as in a binary search.
The pixels must stay between and . 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 on and an input with , the attack approximates
It solves, for a weight and a confidence ,
The loss is positive while class wins, and it stops at once another class wins by , so the attack does not push further than it needs. For a target class , use instead; this is the function the paper calls , the best of the seven it tried.
The algorithm
CW-L2(z, x, y, c, kappa, T, s) ▷ x in [0, 1]^d with f(x) = y- 1
lo ← 0; hi ← ∞; best ← none - 2
repeat s times ▷ rounds of the binary search on c - 3
w ← artanh(2x - 1) ▷ start at x itself - 4
for t ← 1 to T do - 5
x' ← (tanh(w) + 1) / 2 ▷ always in (0, 1)^d - 6
if 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' - 7
w ← Adam step on ∇_w (||x' - x||_2^2 + c · ℓ(x')) - 8
if this round recorded an adversarial x' then hi ← c else lo ← c - 9
c ← (lo + hi) / 2 if hi < ∞ else 10 c - 10
return best
Line L3 starts each round at with ; the code keeps inside by a margin of , so that stays finite. Line L6 records every adversarial iterate that is closer than the best so far, in every round. Line L7 uses the gradient
where is the best other class, and the term in drops out where . Lines L8 and L9 are the binary search: a success means was large enough, so goes down; a failure means goes up, by a factor of until the first success.
Example
Take the linear model of the page adversarial example: , with rows , and , and with . The nearest wrong label is class , across the line , at . Run the attack with , , Adam steps of rate and rounds.
Along the direction the objective is , with its minimum at . This crosses the boundary only when , that is . The rounds show it:
| round | 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 by . Then the search halves the interval each round. Round 7 has 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 from round 4, at distance , which is times . The run cost gradients. With , the attack must reach , which is at least away, and it returns at distance .
Correctness
Theorem 1 (a valid output). If the attack returns a point , then , , the best other logit is at least above , and .
Theorem 2. The output is the closest point to among all adversarial iterates of all rounds.
Lemma (the search). Before the first success, grows by a factor of in each round. After it, , and each round halves .
The change of variables maps onto 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 . The full proofs are in proofs/correctness.md.
For two classes and an affine model, the objective is convex in , and the attack gets close to , 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 . So the distance found is an upper bound on , never a lower bound.
Proof: The C&W attack returns a valid adversarial input, never closer than the true minimumfull
We write for the label, for the label of the input , and for the true minimum adversarial distance. The attack works on a variable and the point , taken coordinate by coordinate (line L5).
Lemma 1 (the box constraint disappears). For every , . Every point of is for exactly one .
Proof. The function is a strictly increasing bijection from onto , so is a strictly increasing bijection from onto . Apply it to each coordinate.
In floating point, can round to , so a coordinate can be exactly or . It is still in . The function from_box keeps inside , so the start of line L3 is finite even when is or .
Lemma 2 (the gradient of line L7). Let with . At a point where the best other class is unique and , . Where , the same formula holds without the term in .
Proof. Near such a point, in the first case and in the second, so is or . The gradient of is . Since depends only on , with , the chain rule gives the formula. This is what objective_gradient computes.
Theorem 1 (a valid output). If the attack returns a point (not None), then , , , and .
Proof. The variable best is set only in line L6, and only to a point of line L5 whose label differs from and whose best other logit is at least above . By Lemma 1 and the remark after it, . So is in the set over which is the infimum, and its distance is at least the infimum.
So the attack gives an upper bound on the distance from to the nearest adversarial input, and never a value below the truth. If it returns None, it proves nothing: the point may still have adversarial inputs close by.
Theorem 2 (the best point is the closest one seen). The returned point is, among all points of line L5 in all rounds that have a label other than , one with the smallest distance to .
Proof. Line L6 replaces best only by a point with a strictly smaller distance, and every adversarial of every round passes through line L6.
Lemma 3 (the search on ). Let . Before the first round that succeeds, line L9 multiplies by and . After it, holds after each line L9, and is halved by each round.
Proof. While every round fails, line L8 sets and line L9 sets to , so . At the first success, , and line L9 sets , strictly between and . In each later round, line L8 replaces either or by the current , which lies strictly between them, and so it halves the gap and keeps . Line L9 then puts at the midpoint again.
What is not claimed. The function is not convex for a nonlinear model, and success of a round need not be monotone in . So Lemma 3 is a statement about the search, not a proof that it finds the best , and Adam is not proved to reach a global minimum of . 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 , which is (one forward and one backward pass), plus for the distance term, the change of variables and the Adam update. The total is . 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. for , 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 , and Adam has no randomness.
- Minimal, not fixed-radius. The output distance estimates from above. To get robust accuracy at a radius , count the points whose distance is above ; 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 when one class has probability near , which is what made distillation look robust.
- Confidence. A larger 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 .
- The attack. Run the attack, find the coordinate that contributes least, fix it to its value in , and repeat while the attack still succeeds. The coordinates that stay free form a small set, as in the Jacobian saliency map attack.
- The attack. Replace by and lower after each success.
- Elastic net (EAD). Chen et al. (2018) add an 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 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 or .
- A loss on probabilities. On a network with a saturated softmax, such as a distilled network at temperature , the gradient of the loss on probabilities is almost , and the attack fails. Use the logits.
- One value of . A fixed 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 , and the start value of before drawing a conclusion.
- Ties. With , a point exactly on the boundary may count as class . A small 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 and , 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 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.
# 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 , with a line search on . 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 , and . 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
- 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
- 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
- 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)
- 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
- 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
- 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 2XQ46N Edit this page History Report an error Markdown