Algorithm Search⌘K

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
Properties
randomizednot exactofflineiterative
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 uu returns the probability vector p(u)p(u), and nothing about the weights or gradients. The capability is a change at test time in [0,1]d[0,1]^d. The attack reports the ℓ2\ell_2 distance it found after TT steps, with exactly 3T3T 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 dd coordinates costs 2d2d 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 p(u)=softmax⁡(z(u))p(u) = \operatorname{softmax}(z(u)) on [0,1]d[0,1]^d, an input xx with label yy, a constant c>0c > 0 and a confidence κ≥0\kappa \ge 0, minimize

F(u)=∥u−x∥22+c ℓ(u),ℓ(u)=max⁡(ln⁡py(u)−max⁡i≠yln⁡pi(u), −κ),F(u) = \lVert u - x \rVert_2^2 + c\, \ell(u), \qquad \ell(u) = \max\Big(\ln p_y(u) - \max_{i \ne y} \ln p_i(u),\ -\kappa\Big),

over u∈[0,1]du \in [0,1]^d, using only values of pp. Since ln⁡py−ln⁡pi=zy−zi\ln p_y - \ln p_i = z_y - z_i, the loss ℓ\ell is the C&W margin of the logits. The goal is a point of another label that is close to xx. The best value is the distance ρ2(x)\rho_2(x) to the nearest point of another label.

The algorithm

  1. ZOO(p, x, y, c, kappa, T, lr, h)
  2. 1u ← x; best ← none
  3. 2for t ← 1 to T do
  4. 3i ← a coordinate drawn uniformly from 1..d
  5. 4g ← (F(u + h e_i) - F(u - h e_i)) / (2h) ▷ two queries
  6. 5update the Adam moments of coordinate i with g (beta1 = 0.9, beta2 = 0.999, with bias correction)
  7. 6u_i ← clip_[0,1](u_i - lr · m_i / (sqrt(v_i) + 1e-8))
  8. 7query p(u); if its label is not y and u is closer to x than best then best ← u
  9. 8return (best, 3T)

Line L4 is the symmetric difference along the unit vector eie_i, with h=10−4h = 10^{-4}, 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 cc, 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: K=3K = 3, logits z(u)=Wuz(u) = Wu 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 label 00. The model returns p(x)=(0.4949,0.4052,0.0999)p(x) = (0.4949, 0.4052, 0.0999). The nearest point of another label is (0.5,0.5)(0.5, 0.5), at ρ2=0.2/2=0.14142\rho_2 = 0.2/\sqrt2 = 0.14142. Run ZOO with c=1c = 1, κ=0.05\kappa = 0.05, T=400T = 400, lr=0.005\mathrm{lr} = 0.005, h=10−4h = 10^{-4} and random.Random(1):

step coordinate estimate gg uu z1−z0z_1 - z_0 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 ±1\pm 1 of c(z0−z1)c(z_0 - z_1), plus the small term 2(u−x)2(u - x). Adam then moves each coordinate by about lr\mathrm{lr} per step. At step 41, after 123 queries, the iterate crosses the boundary at distance 0.143260.14326, which is 1.0131.013 times ρ2\rho_2. After that the iterate goes on to the minimizer of FF, where the margin reaches κ\kappa, near distance (0.2+0.05)/2=0.17678(0.2 + 0.05)/\sqrt2 = 0.17678. It never finds a closer adversarial point, so the run returns (0.49176,0.49385)(0.49176, 0.49385) 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, ℓ(u)=max⁡(zy(u)−max⁡i≠yzi(u),−κ)\ell(u) = \max(z_y(u) - \max_{i \ne y} z_i(u), -\kappa). So the attack minimizes the C&W loss, and the label from the scores is the label from the logits.

Lemma 2. If ϕ(s)=F(u+sei)\phi(s) = F(u + s e_i) is three times differentiable on [−h,h][-h, h] with ∣ϕ′′′∣≤M|\phi'''| \le M, the estimate of line L4 is within Mh2/6M h^2 / 6 of ∂iF(u)\partial_i F(u).

Theorem 1. For TT steps the attack makes exactly 3T3T queries, every iterate is in [0,1]d[0,1]^d, and a returned point is in the box, has a label other than yy, and is the closest to xx of all adversarial iterates. So its distance is at least ρ2(x)\rho_2(x) in the box.

Lemma 1 holds because the log of the softmax is ziz_i minus a term common to all classes. Lemma 2 is Taylor's theorem with the remainder. Near a kink of the max in ℓ\ell it does not apply, and rounding adds an error of about εmach∣F∣/h\varepsilon_{\text{mach}} |F| / h. 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 FF, 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 p(u)=softmax⁡(z(u))p(u) = \operatorname{softmax}(z(u)) for an input uu, let x∈[0,1]dx \in [0,1]^d have label yy, and let ℓ(u)=max⁡(ln⁡py(u)−max⁡i≠yln⁡pi(u),−κ)\ell(u) = \max(\ln p_y(u) - \max_{i \ne y} \ln p_i(u), -\kappa) be the loss of log_margin. The objective of line L4 is F(u)=∥u−x∥22+c ℓ(u)F(u) = \lVert u - x \rVert_2^2 + c\, \ell(u).

Lemma 1 (the log margin is the logit margin). If no probability is below the floor 10−30010^{-300}, then ℓ(u)=max⁡(zy(u)−max⁡i≠yzi(u),−κ)\ell(u) = \max(z_y(u) - \max_{i \ne y} z_i(u), -\kappa).

Proof. With s=ln⁡∑kezks = \ln \sum_k e^{z_k}, every ln⁡pi=zi−s\ln p_i = z_i - s. The common term ss cancels in ln⁡py−ln⁡pi\ln p_y - \ln p_i, and the maximum over i≠yi \ne y of zi−sz_i - s is max⁡i≠yzi−s\max_{i\ne y} z_i - s. □\square

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 eie_i be the unit vector of coordinate ii, and let ϕ(s)=F(u+sei)\phi(s) = F(u + s e_i) be three times differentiable on [−h,h][-h, h] with ∣ϕ′′′∣≤M|\phi'''| \le M there. Then the estimate g=(ϕ(h)−ϕ(−h))/(2h)g = (\phi(h) - \phi(-h)) / (2h) of coordinate_estimate satisfies ∣g−∂iF(u)∣≤Mh2/6|g - \partial_i F(u)| \le M h^2 / 6.

Proof. By Taylor's theorem with the Lagrange remainder, ϕ(±h)=ϕ(0)±hϕ′(0)+12h2ϕ′′(0)±16h3ϕ′′′(ξ±)\phi(\pm h) = \phi(0) \pm h \phi'(0) + \tfrac12 h^2 \phi''(0) \pm \tfrac16 h^3 \phi'''(\xi_\pm) for some ξ±\xi_\pm in [−h,h][-h, h]. Subtracting, ϕ(h)−ϕ(−h)=2hϕ′(0)+16h3(ϕ′′′(ξ+)+ϕ′′′(ξ−))\phi(h) - \phi(-h) = 2h\phi'(0) + \tfrac16 h^3 (\phi'''(\xi_+) + \phi'''(\xi_-)). Divide by 2h2h; the error is at most 112h2⋅2M\tfrac1{12} h^2 \cdot 2M. □\square

The function FF has kinks where the maximum of ℓ\ell changes its active term, so Lemma 2 does not hold at points within hh of a kink. There the estimate is a mean of two one-sided slopes. Floating point adds an error of about εmach∣F∣/h\varepsilon_{\text{mach}} |F| / h, which is why hh is not taken much smaller than 10−410^{-4}.

Theorem 1 (the output). For TT steps, the attack makes exactly 3T3T queries. Every iterate lies in [0,1]d[0,1]^d. If it returns a point u⋆u^\star (not None), then u⋆∈[0,1]du^\star \in [0,1]^d, the label of u⋆u^\star is not yy, and u⋆u^\star is the closest to xx of all the iterates whose label is not yy. Hence ∥u⋆−x∥2≥d⋆(x)=inf⁡{∥v−x∥2:v∈[0,1]d with a label other than y}\lVert u^\star - x \rVert_2 \ge d^\star(x) = \inf\{\lVert v - x \rVert_2 : v \in [0,1]^d \text{ with a label other than } y\}, the true minimum adversarial distance in the box.

Proof. Each step makes two queries in line L4 and one in line L7, and adds 33 to the count. Line L1 starts at x∈[0,1]dx \in [0,1]^d, and line L6 changes one coordinate and clips it to [0,1][0,1], 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 yy 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 d⋆(x)d^\star(x) is the infimum. ■\blacksquare

What is not claimed. The attack uses a fixed cc and one random coordinate a step. It has no proof of convergence to a minimum of FF, 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 1.621.62 times the closed-form minimum (a measurement, not a theorem).

Complexity

  • Time. Each step makes three queries of cost qq and computes a distance in O(d)O(d) and a margin in O(K)O(K). The total is O(T(q+d+K))O(T (q + d + K)). The distance can be kept up to date in O(1)O(1), since only one coordinate changes.
  • Queries. Exactly 3T3T. A full gradient by differences would cost 2d2d queries, so ZOO with TT steps touches each coordinate about T/dT/d times. For large dd the number of queries is the main cost, which is why the paper reduces the attack space and samples important coordinates.
  • Space. Θ(d)\Theta(d) 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 ρ2(x)\rho_2(x), and a failure proves nothing.

Variants and improvements

  • ZOO-Newton. Estimate also the second derivative along the coordinate, (F(u+hei)−2F(u)+F(u−hei))/h2(F(u + h e_i) - 2F(u) + F(u - h e_i))/h^2, and take a Newton step. The paper gives both versions.
  • Search over cc. Run the attack for several values of cc 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: ℓ(u)=max⁡(max⁡i≠tln⁡pi−ln⁡pt,−κ)\ell(u) = \max(\max_{i \ne t} \ln p_i - \ln p_t, -\kappa).

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 hh. A large hh biases the estimate, and a tiny hh 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 FF, as in the example. The last iterate is often farther than the best one.
  • A fixed cc. Too small a cc never crosses the boundary, too large a cc gives large distances. Search over cc or report it.
  • Query cost grows with dd. 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.

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

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

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