Algorithmadvanced
Zeroth order optimization attack
Also called ZOO attack.
A black-box attack that sees only the output probabilities. It minimizes the Carlini-Wagner loss by coordinate descent, with each partial derivative estimated by a symmetric difference of two queries.
- Time
- O(T (q + d + K)) worst
- Space
- Θ(d) extra
- Where
- K = the number of classes; T = the number of steps; d = the input dimension; q = the cost of one query
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Pin Yu Chen, Huan Zhang, Yash Sharma, Jinfeng Yi, Cho Jui Hsieh, 2017
The zeroth order optimization attack (ZOO) runs the Carlini-Wagner attack without gradients. It sees only the probabilities that the model returns for a query. It picks one input coordinate at a time, estimates the partial derivative of the attack loss from two queries, at the point moved a little up and a little down along that coordinate, and takes an Adam step on that coordinate. Chen, Zhang, Sharma, Yi and Hsieh (2017) introduced it. On their MNIST and CIFAR10 models it reached success rates and distances close to the white-box C&W attack, with no substitute model, at the cost of many queries. For large inputs they reduce the number of coordinates and sample the important ones first.
Threat model. The goal is untargeted here; the paper also gives the targeted form. The knowledge is black box with scores: a query of returns the probability vector , and nothing about the weights or gradients. The capability is a change at test time in . The attack reports the distance it found after steps, with exactly queries.
In plain words
The C&W attack needs the slope of its loss, which comes from the gradient of the model. Without the model, you can still measure the slope along one direction: query the input moved a little up and a little down, and divide the difference of the two losses by the distance between them.
Doing this for all coordinates costs queries for one gradient. ZOO does not wait for a full gradient. It picks one coordinate at random, measures its slope, and moves only that coordinate. This is coordinate descent, and each step is cheap.
The loss uses the logarithm of the probabilities. The differences of these logarithms are the differences of the logits, so the loss is the same as the C&W loss.
The problem
Given probabilities on , an input with label , a constant and a confidence , minimize
over , using only values of . Since , the loss is the C&W margin of the logits. The goal is a point of another label that is close to . The best value is the distance to the nearest point of another label.
The algorithm
ZOO(p, x, y, c, kappa, T, lr, h)- 1
u ← x; best ← none - 2
for t ← 1 to T do - 3
i ← a coordinate drawn uniformly from 1..d - 4
g ← (F(u + h e_i) - F(u - h e_i)) / (2h) ▷ two queries - 5
update the Adam moments of coordinate i with g (beta1 = 0.9, beta2 = 0.999, with bias correction) - 6
u_i ← clip_[0,1](u_i - lr · m_i / (sqrt(v_i) + 1e-8)) - 7
query p(u); if its label is not y and u is closer to x than best then best ← u - 8
return (best, 3T)
Line L4 is the symmetric difference along the unit vector , with , the value of the paper. Line L5 keeps separate Adam moments and step counts for each coordinate, as in ZOO-ADAM. Line L7 keeps the closest adversarial iterate seen so far, not the last iterate. This code uses one fixed , and one coordinate per step. On a GPU the paper estimates a batch of coordinates at once.
Example
Take the linear model of the page adversarial example: , logits with rows , and , and with label . The model returns . The nearest point of another label is , at . Run ZOO with , , , , and random.Random(1):
| step | coordinate | estimate | distance | ||
|---|---|---|---|---|---|
| 1 | 0 | 1.0 | (0.595, 0.4) | -0.195 | 0.005 |
| 3 | 1 | -1.0 | (0.59, 0.405) | -0.185 | 0.01118 |
| 20 | 1 | -0.9003 | (0.55513, 0.45477) | -0.10036 | 0.0708 |
| 40 | 0 | 0.8027 | (0.49654, 0.49385) | -0.00269 | 0.13969 |
| 41 | 0 | 0.7931 | (0.49176, 0.49385) | 0.00209 | 0.14326 |
| 400 | 1 | -0.6954 | (0.50283, 0.55339) | 0.05056 | 0.18158 |
At the start the margin term is active, and the estimates are close to the true partial derivatives of , plus the small term . Adam then moves each coordinate by about per step. At step 41, after 123 queries, the iterate crosses the boundary at distance , which is times . After that the iterate goes on to the minimizer of , where the margin reaches , near distance . It never finds a closer adversarial point, so the run returns after 1200 queries. This is the ZOO row in the table of the page evasion attack.
Correctness
Lemma 1. If no probability is below the floor of the code, . So the attack minimizes the C&W loss, and the label from the scores is the label from the logits.
Lemma 2. If is three times differentiable on with , the estimate of line L4 is within of .
Theorem 1. For steps the attack makes exactly queries, every iterate is in , and a returned point is in the box, has a label other than , and is the closest to of all adversarial iterates. So its distance is at least in the box.
Lemma 1 holds because the log of the softmax is minus a term common to all classes. Lemma 2 is Taylor's theorem with the remainder. Near a kink of the max in it does not apply, and rounding adds an error of about . Theorem 1 follows from the count of queries per step, the clip of line L6, and the rule of line L7. The full proofs are in proofs/correctness.md. There is no claim of convergence to a minimum of , and a run can return none.
Proof: The ZOO attack estimates the right derivatives, counts its queries and returns only valid adversarial inputsfull
Let the model return probabilities for an input , let have label , and let be the loss of log_margin. The objective of line L4 is .
Lemma 1 (the log margin is the logit margin). If no probability is below the floor , then .
Proof. With , every . The common term cancels in , and the maximum over of is .
So the attack minimizes the same loss as the C&W attack, but it sees only the scores, never the logits or the gradients. The label from the scores is the label from the logits, because softmax keeps the order of the entries.
Lemma 2 (the symmetric difference). Let be the unit vector of coordinate , and let be three times differentiable on with there. Then the estimate of coordinate_estimate satisfies .
Proof. By Taylor's theorem with the Lagrange remainder, for some in . Subtracting, . Divide by ; the error is at most .
The function has kinks where the maximum of changes its active term, so Lemma 2 does not hold at points within of a kink. There the estimate is a mean of two one-sided slopes. Floating point adds an error of about , which is why is not taken much smaller than .
Theorem 1 (the output). For steps, the attack makes exactly queries. Every iterate lies in . If it returns a point (not None), then , the label of is not , and is the closest to of all the iterates whose label is not . Hence , the true minimum adversarial distance in the box.
Proof. Each step makes two queries in line L4 and one in line L7, and adds to the count. Line L1 starts at , and line L6 changes one coordinate and clips it to , so every iterate stays in the box. After line L6, line L7 queries the new iterate and records it only when its label is not and its distance is strictly smaller than the best so far. Only such points are ever stored and returned in line L8. A stored point is in the set over which is the infimum.
What is not claimed. The attack uses a fixed and one random coordinate a step. It has no proof of convergence to a minimum of , and a run can end with None even when an adversarial input is near. In the seeded tests on binary linear models, 300 steps gave a distance at most about times the closed-form minimum (a measurement, not a theorem).
Complexity
- Time. Each step makes three queries of cost and computes a distance in and a margin in . The total is . The distance can be kept up to date in , since only one coordinate changes.
- Queries. Exactly . A full gradient by differences would cost queries, so ZOO with steps touches each coordinate about times. For large the number of queries is the main cost, which is why the paper reduces the attack space and samples important coordinates.
- Space. for the iterate, the best point and the Adam moments.
Properties
- Scores only. It needs the probabilities, not the gradients. With labels only, use the boundary attack.
- The same loss as C&W. By Lemma 1.
- Valid output. A returned point is in the box and has another label (Theorem 1).
- Randomized. The coordinate order depends on the seed.
- Upper bound. Like every attack, a success gives an upper bound on , and a failure proves nothing.
Variants and improvements
- ZOO-Newton. Estimate also the second derivative along the coordinate, , and take a Newton step. The paper gives both versions.
- Search over . Run the attack for several values of and keep the smallest success, as in C&W.
- Attack-space reduction. Optimize over a smaller grid of coordinates and resize, then refine.
- Random directions. Estimate the derivative along random vectors instead of coordinates. Methods of this kind, for example with natural evolution strategies, need fewer queries on image models.
- Targeted version. Swap the roles: .
When to use it
Use ZOO on small models to study the threat model in which only scores are visible, or to compare an evaluation with and without gradients. If a model resists gradient attacks but not ZOO, its gradients were masked. For a white-box evaluation, the Carlini-Wagner attack gives the same loss with exact gradients and far less work.
Pitfalls
- The step . A large biases the estimate, and a tiny is lost in rounding. Also, scores rounded by the model make small differences zero.
- Kinks. Near a change of the active class in the max, or of a ReLU, the estimate mixes two slopes.
- Keep the best iterate. The iterate moves past the boundary toward the minimizer of , as in the example. The last iterate is often farther than the best one.
- A fixed . Too small a never crosses the boundary, too large a gives large distances. Search over or report it.
- Query cost grows with . Results on small models do not carry over to high dimensions without the reductions of the paper.
Implementations
The code of this page is an abstract model on synthetic data. The attack runs only on score functions that the tests build from a fixed seed: softmax outputs of affine models with given or seeded weights, and of two-layer ReLU networks from mlkit.tiny_relu_net, on seeded random inputs, with the coordinates drawn from random.Random seeded in the test. It never reads real data or touches a real system. The tests check the example of the page, edge cases, Lemma 1 on 500 random logit vectors, the estimate of line L4 against the exact derivative on 500 random affine models, the query count, the box and the lower bound on seeded binary linear models, and that results on seeded networks are adversarial.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vector tools, synthetic data and two tiny models for the adversarial machine learning pages.
Vectors are lists of floats. Every model here is synthetic: it is built from a seeded
random.Random and never from real data. The helper holds no attack loop, no
certification and no defense; those live in the slug files of the pages.
"""
import math
import random
from typing import Callable, Sequence
Vector = list[float]
Matrix = list[list[float]]
Net = dict[str, list]
Data = list[tuple[Vector, int]]
def dot(u: Sequence[float], v: Sequence[float]) -> float:
"""Inner product of two vectors of the same length. Cost O(d)."""
return math.fsum(a * b for a, b in zip(u, v, strict=True))
def add(u: Sequence[float], v: Sequence[float]) -> Vector:
"""Coordinatewise sum u + v. Cost O(d)."""
return [a + b for a, b in zip(u, v, strict=True)]
def sub(u: Sequence[float], v: Sequence[float]) -> Vector:
"""Coordinatewise difference u - v. Cost O(d)."""
return [a - b for a, b in zip(u, v, strict=True)]
def scale(c: float, v: Sequence[float]) -> Vector:
"""The vector c v. Cost O(d)."""
return [c * a for a in v]
def norm1(v: Sequence[float]) -> float:
"""The l1 norm, the sum of |v_i|. Cost O(d)."""
return math.fsum(abs(a) for a in v)
def norm2(v: Sequence[float]) -> float:
"""The Euclidean norm. Cost O(d)."""
return math.sqrt(math.fsum(a * a for a in v))
def norminf(v: Sequence[float]) -> float:
"""The l_infinity norm, max |v_i|, and 0 for the empty vector. Cost O(d)."""
return max((abs(a) for a in v), default=0.0)
def project_l2(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
"""Euclidean projection of v onto the l2 ball of the given center and radius >= 0.
A point inside the ball is returned unchanged; a point outside is moved along the
segment to the center until it is on the sphere. Cost O(d).
"""
diff = sub(v, center)
r = norm2(diff)
if r <= radius:
return list(v)
return add(center, scale(radius / r, diff))
def project_linf(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
"""Euclidean projection of v onto the l_infinity ball: clip each coordinate to [c_i - r, c_i + r]. Cost O(d)."""
return [min(max(a, c - radius), c + radius) for a, c in zip(v, center, strict=True)]
def clip01(v: Sequence[float]) -> Vector:
"""Euclidean projection onto the box [0, 1]^d. Cost O(d)."""
return [min(max(a, 0.0), 1.0) for a in v]
def make_blobs(rng: random.Random, n: int, d: int, centers: Sequence[Sequence[float]], sigma: float) -> Data:
"""n synthetic points in R^d from Gaussian blobs N(center, sigma^2 I).
Point i gets the label i mod len(centers) and is drawn around that center, so the
classes are balanced. The points are not clipped. Cost O(n d) and n d draws of rng.
"""
for c in centers:
if len(c) != d:
raise ValueError("each center must have d coordinates")
data: Data = []
for i in range(n):
label = i % len(centers)
x = [c + rng.gauss(0.0, sigma) for c in centers[label]]
data.append((x, label))
return data
def sigmoid(t: float) -> float:
"""The logistic function 1 / (1 + e^(-t)), computed without overflow. Cost O(1)."""
if t >= 0:
return 1.0 / (1.0 + math.exp(-t))
e = math.exp(t)
return e / (1.0 + e)
def _softplus(t: float) -> float:
"""ln(1 + e^t) without overflow."""
return max(t, 0.0) + math.log1p(math.exp(-abs(t)))
def logistic_loss(w: Sequence[float], b: float, x: Sequence[float], y: int) -> float:
"""Logistic loss of the linear model z = w.x + b on a label y in {0, 1}.
The loss is ln(1 + e^(-s z)) with s = 2 y - 1. Cost O(d).
"""
s = 2 * y - 1
return _softplus(-s * (dot(w, x) + b))
def grad_x_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> Vector:
"""Gradient of logistic_loss in the input x: (sigmoid(z) - y) w. Cost O(d)."""
g = sigmoid(dot(w, x) + b) - y
return scale(g, w)
def grad_w_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> tuple[Vector, float]:
"""Gradient of logistic_loss in the parameters: ((sigmoid(z) - y) x, sigmoid(z) - y). Cost O(d)."""
g = sigmoid(dot(w, x) + b) - y
return scale(g, x), g
def train_logistic(data: Data, steps: int, lr: float, l2: float) -> tuple[Vector, float]:
"""Full-batch gradient descent on the mean logistic loss plus (l2 / 2) ||w||^2.
Labels are in {0, 1}. The weights start at zero, so the result is deterministic.
The bias has no penalty. Returns (w, b). Cost O(steps n d).
"""
d = len(data[0][0])
n = len(data)
w = [0.0] * d
b = 0.0
for _ in range(steps):
gw = [0.0] * d
gb = 0.0
for x, y in data:
g = sigmoid(dot(w, x) + b) - y
for j in range(d):
gw[j] += g * x[j]
gb += g
w = [w[j] - lr * (gw[j] / n + l2 * w[j]) for j in range(d)]
b -= lr * gb / n
return w, b
def tiny_relu_net(rng: random.Random, d: int, h: int, k: int) -> Net:
"""A fixed-seed two-layer ReLU network with d inputs, h hidden units and k logits.
The weights are drawn from N(0, 1/d) in the first layer and N(0, 1/h) in the second,
and the biases from N(0, 0.01). The dict has the keys W1 (h rows of d), b1 (h),
W2 (k rows of h) and b2 (k). Cost O(h d + k h).
"""
s1, s2 = 1.0 / math.sqrt(d), 1.0 / math.sqrt(h)
return {
"W1": [[rng.gauss(0.0, s1) for _ in range(d)] for _ in range(h)],
"b1": [rng.gauss(0.0, 0.1) for _ in range(h)],
"W2": [[rng.gauss(0.0, s2) for _ in range(h)] for _ in range(k)],
"b2": [rng.gauss(0.0, 0.1) for _ in range(k)],
}
def _hidden(net: Net, x: Sequence[float]) -> tuple[Vector, Vector]:
"""Pre-activations and activations of the hidden layer."""
pre = [dot(row, x) + bi for row, bi in zip(net["W1"], net["b1"], strict=True)]
return pre, [max(a, 0.0) for a in pre]
def forward(net: Net, x: Sequence[float]) -> Vector:
"""Logits z(x) = W2 relu(W1 x + b1) + b2 of a tiny_relu_net. Cost O(h d + k h)."""
_, act = _hidden(net, x)
return [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
def argmax(z: Sequence[float]) -> int:
"""The first index of a largest entry. Cost O(k)."""
best = 0
for i in range(1, len(z)):
if z[i] > z[best]:
best = i
return best
def softmax(z: Sequence[float]) -> Vector:
"""The softmax of a logit vector, shifted by the maximum to avoid overflow. Cost O(k)."""
m = max(z)
e = [math.exp(a - m) for a in z]
s = math.fsum(e)
return [a / s for a in e]
def cross_entropy(z: Sequence[float], label: int) -> float:
"""Cross-entropy loss -ln softmax(z)[label], computed as logsumexp(z) - z[label]. Cost O(k)."""
m = max(z)
return m + math.log(math.fsum(math.exp(a - m) for a in z)) - z[label]
def logits_jacobian(net: Net, x: Sequence[float]) -> Matrix:
"""The k by d Jacobian of the logits in the input, W2 diag(relu'(pre)) W1.
The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
Cost O(k h d).
"""
pre, _ = _hidden(net, x)
d = len(x)
rows = []
for w2 in net["W2"]:
row = [0.0] * d
for i, a in enumerate(pre):
if a > 0 and w2[i] != 0.0:
c = w2[i]
w1 = net["W1"][i]
for j in range(d):
row[j] += c * w1[j]
rows.append(row)
return rows
def input_gradient(net: Net, x: Sequence[float], label: int) -> Vector:
"""Gradient in x of cross_entropy(forward(net, x), label), by backpropagation.
The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
Cost O(h d + k h).
"""
pre, act = _hidden(net, x)
z = [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
p = softmax(z)
p[label] -= 1.0
back = [0.0] * len(pre)
for c, row in zip(p, net["W2"], strict=True):
for i in range(len(pre)):
back[i] += c * row[i]
g = [0.0] * len(x)
for i, a in enumerate(pre):
if a > 0:
w1 = net["W1"][i]
for j in range(len(x)):
g[j] += back[i] * w1[j]
return g
def accuracy(predict: Callable[[Vector], int], data: Data) -> float:
"""Fraction of the pairs (x, y) of data with predict(x) == y. Cost: n calls of predict."""
if not data:
return 0.0
return sum(1 for x, y in data if predict(x) == y) / len(data)
zeroth_order_optimization_attack.py 71 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zeroth-order-optimization-attack/. The authors are listed in prov/7Y1PKM.jsonl.
"""The ZOO attack of Chen et al. (2017), untargeted, with coordinate-wise Adam, on synthetic models only.
The attack sees only the probability vector that the model returns for a query. It
estimates one partial derivative at a time with a symmetric difference. The model is a
Python function from an input to probabilities; the tests build it from seeded affine
models and seeded ReLU networks of mlkit. Nothing here reads real data or touches a
real system.
"""
import math
import random
from typing import Callable, Optional, Sequence
Vector = list[float]
Scores = Callable[[Vector], Vector]
def log_margin(p: Sequence[float], y: int, kappa: float) -> float:
"""max(ln p_y - max over i != y of ln p_i, -kappa). Probabilities are floored at 1e-300."""
ly = math.log(max(p[y], 1e-300))
lo = max(math.log(max(p[i], 1e-300)) for i in range(len(p)) if i != y)
return max(ly - lo, -kappa)
def objective(scores: Scores, x: Sequence[float], u: Sequence[float], y: int, c: float, kappa: float) -> float:
"""The loss ||u - x||^2 + c * log_margin(scores(u), y, kappa). One query."""
d2 = math.fsum((a - b) ** 2 for a, b in zip(u, x))
return d2 + c * log_margin(scores(list(u)), y, kappa)
def coordinate_estimate(scores: Scores, x: Sequence[float], u: Sequence[float], y: int, c: float, kappa: float,
i: int, h: float) -> float:
"""Symmetric difference estimate of the i-th partial derivative of the objective. Two queries."""
up, dn = list(u), list(u)
up[i] += h
dn[i] -= h
return (objective(scores, x, up, y, c, kappa) - objective(scores, x, dn, y, c, kappa)) / (2.0 * h)
def zoo_attack(scores: Scores, x: Sequence[float], y: int, rng: random.Random, c: float = 1.0,
kappa: float = 0.0, steps: int = 1000, lr: float = 0.01, h: float = 1e-4) -> tuple[Optional[Vector], int]:
"""Run ZOO-ADAM from x with a fixed constant c.
Every step picks one coordinate at random, estimates its partial derivative with two
queries, takes one Adam step on it (beta1 0.9, beta2 0.999) and clips it to [0, 1];
a third query checks the label. Returns (the closest input found whose label is not
y, or None, and the number of queries). Precondition: x in [0, 1]^d.
Cost: 3 queries and O(d) work per step.
"""
d = len(x)
u = list(x) # @line L1
mom, vel, cnt = [0.0] * d, [0.0] * d, [0] * d
best, best_d, queries = None, math.inf, 0
for _ in range(steps): # @line L2
i = rng.randrange(d) # @line L3
g = coordinate_estimate(scores, x, u, y, c, kappa, i, h) # @line L4
cnt[i] += 1 # @line L5
mom[i] = 0.9 * mom[i] + 0.1 * g
vel[i] = 0.999 * vel[i] + 0.001 * g * g
mh = mom[i] / (1 - 0.9 ** cnt[i])
vh = vel[i] / (1 - 0.999 ** cnt[i])
u[i] = min(max(u[i] - lr * mh / (math.sqrt(vh) + 1e-8), 0.0), 1.0) # @line L6
p = scores(list(u)) # @line L7
queries += 3
dist = math.sqrt(math.fsum((a - b) ** 2 for a, b in zip(u, x)))
if max(range(len(p)), key=lambda k: p[k]) != y and dist < best_d:
best, best_d = list(u), dist
return best, queries # @line L8
test_zeroth_order_optimization_attack.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zeroth-order-optimization-attack/. The authors are listed in prov/7Y1PKM.jsonl.
"""Tests of ZOO, on seeded synthetic models only."""
import math
import random
import mlkit as m
from zeroth_order_optimization_attack import coordinate_estimate, log_margin, objective, zoo_attack
# The worked example of the page: three classes in the plane, as on the C&W page.
WE = [[1.0, 0.0], [0.0, 1.0], [-1.0, -1.0]]
XE = [0.6, 0.4]
def affine_scores(w, b):
return lambda u: m.softmax([m.dot(r, u) + bi for r, bi in zip(w, b)])
def test_page_example() -> None:
sc = affine_scores(WE, [0.0, 0.0, 0.0])
dmin = 0.2 / math.sqrt(2)
out, queries = zoo_attack(sc, XE, 0, random.Random(1), c=1.0, kappa=0.05, steps=400, lr=0.005)
assert queries == 1200
assert out is not None and m.argmax(sc(out)) != 0
assert dmin <= math.dist(out, XE) <= dmin + 0.01
# the numbers of the page: the best point is found at step 41 and never improved
assert all(abs(a - e) < 1e-5 for a, e in zip(out, [0.49176, 0.49385]))
assert abs(math.dist(out, XE) - 0.14326) < 1e-5
assert zoo_attack(sc, XE, 0, random.Random(1), c=1.0, kappa=0.05, steps=40, lr=0.005)[0] is None
assert zoo_attack(sc, XE, 0, random.Random(1), c=1.0, kappa=0.05, steps=41, lr=0.005) == (out, 123)
def test_edges() -> None:
sc = affine_scores(WE, [0.0, 0.0, 0.0])
assert zoo_attack(sc, XE, 0, random.Random(1), steps=0) == (None, 0)
assert log_margin([0.5, 0.25, 0.25], 0, 0.0) == math.log(2)
assert log_margin([0.25, 0.5, 0.25], 0, 0.1) == -0.1
assert objective(sc, XE, XE, 0, 1.0, 0.0) == log_margin(sc(XE), 0, 0.0)
def test_log_margin_of_softmax_is_the_logit_margin() -> None:
# ln softmax(z)_y - ln softmax(z)_i = z_y - z_i, so scores give the C&W margin of the logits.
rng = random.Random(7801)
for _ in range(500):
k = rng.randint(2, 6)
z = [rng.uniform(-8, 8) for _ in range(k)]
y = rng.randrange(k)
kappa = rng.choice([0.0, 0.5, 2.0])
want = max(z[y] - max(z[i] for i in range(k) if i != y), -kappa)
assert abs(log_margin(m.softmax(z), y, kappa) - want) < 1e-9
def test_coordinate_estimate_matches_the_analytic_derivative() -> None:
rng = random.Random(7802)
checked = 0
for _ in range(500):
d, k = rng.randint(1, 5), rng.randint(2, 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)]
sc = affine_scores(w, b)
x = [rng.uniform(0, 1) for _ in range(d)]
u = [rng.uniform(0, 1) for _ in range(d)]
y = rng.randrange(k)
c, kappa = rng.uniform(0.1, 3.0), rng.choice([0.0, 1.0])
z = [m.dot(r, u) + bi for r, bi in zip(w, b)]
j = max((i for i in range(k) if i != y), key=lambda i: z[i])
rest = sorted((z[i] for i in range(k) if i != y), reverse=True)
if (len(rest) > 1 and rest[0] - rest[1] < 1e-2) or abs(z[y] - z[j] + kappa) < 1e-2:
continue # too close to a kink of the max
i = rng.randrange(d)
active = z[y] - z[j] > -kappa
want = 2 * (u[i] - x[i]) + (c * (w[y][i] - w[j][i]) if active else 0.0)
got = coordinate_estimate(sc, x, u, y, c, kappa, i, 1e-4)
assert abs(got - want) < 1e-5
checked += 1
assert checked > 400
def test_binary_linear_models_respect_the_lower_bound() -> None:
rng = random.Random(7803)
for trial in range(150):
d = rng.randint(1, 3)
w = [[rng.uniform(-2, 2) for _ in range(d)] for _ in range(2)]
diff = m.sub(w[0], w[1])
if m.norm2(diff) < 0.5:
continue
x = [rng.uniform(0.4, 0.6) for _ in range(d)]
dmin = rng.uniform(0.02, 0.15)
b = [dmin * m.norm2(diff) - m.dot(diff, x), 0.0]
sc = affine_scores(w, b)
out, queries = zoo_attack(sc, x, 0, random.Random(trial), c=2.0, kappa=0.05, steps=300, lr=0.01)
assert queries == 900
assert out is not None and m.argmax(sc(out)) == 1
assert all(0.0 <= a <= 1.0 for a in out)
assert math.dist(out, x) >= dmin - 1e-12
# a measured bound for these seeds, not a theorem: the worst ratio was about 1.62
assert math.dist(out, x) <= 2.0 * dmin
def test_relu_nets_outputs_are_adversarial() -> None:
rng = random.Random(7804)
for trial in range(40):
d, h, k = rng.randint(1, 4), rng.randint(2, 6), rng.randint(2, 3)
net = m.tiny_relu_net(rng, d, h, k)
sc = lambda u: m.softmax(m.forward(net, u))
x = [rng.uniform(0, 1) for _ in range(d)]
y = m.argmax(sc(x))
out, queries = zoo_attack(sc, x, y, random.Random(trial), c=5.0, steps=150, lr=0.02)
assert queries == 450
if out is not None:
assert m.argmax(sc(out)) != y
assert all(0.0 <= a <= 1.0 for a in out)
History
Black-box attacks before ZOO trained a substitute model and relied on transferability, as in Papernot et al. (2017). Chen, Zhang, Sharma, Yi and Hsieh posted ZOO in August 2017 and published it at AISec 2017. They used the C&W loss on log probabilities, coordinate Adam and Newton steps with symmetric differences, and reductions of the attack space for ImageNet models. Later score-based attacks estimated gradients along random directions or searched with fewer queries, and the boundary attack (2018) removed the need for scores.
References
- Pin-Yu Chen, Huan Zhang, Yash Sharma, Jinfeng Yi and Cho-Jui Hsieh, ZOO, zeroth order optimization based black-box attacks to deep neural networks without training substitute models, Proceedings of the 10th ACM Workshop on Artificial Intelligence and Security (AISec 2017), pages 15 to 26, the loss on log probabilities, the symmetric difference estimate, the coordinate Adam and Newton methods, and the reduction of the attack space for large inputs
- Nicholas Carlini and David Wagner, Towards evaluating the robustness of neural networks, IEEE Symposium on Security and Privacy 2017, pages 39 to 57, the margin loss with confidence kappa that ZOO adapts
- Wieland Brendel, Jonas Rauber and Matthias Bethge, Decision-based adversarial attacks, reliable attacks against black-box machine learning models, ICLR 2018, the attack with labels only, for comparison
- Battista Biggio and Fabio Roli, Wild patterns: Ten years after the rise of adversarial machine learning, Pattern Recognition 84, pages 317 to 331, 2018, the threat model in three parts used on this page
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7Y1PKM Edit this page History Report an error Markdown