Algorithm Search⌘K

Algorithmadvanced

Boundary attack

Also called decision-based attack.

A black-box attack that sees only labels. It starts from an input of another class and takes random steps along the decision boundary, keeping those that stay wrong and get closer.

Time
O(T (d + q)) worst
Space
Θ(d) extra
Where
T = the number of steps; d = the input dimension; q = the cost of one label query
Properties
randomizednot exactofflineiterative
Origin
Wieland Brendel, Jonas Rauber, Matthias Bethge, 2017

The boundary attack finds an adversarial example while it sees only the label that a model returns for a query, with no gradients and no scores. It starts from a point that already has another label, for example random noise, and walks toward the original input xx. Each step tries a random move along a sphere around xx and then a small move toward xx, and keeps the new point only if its label is still wrong. So the point always stays adversarial and never moves away from xx, and it slides along the decision boundary toward the nearest part of it. Brendel, Rauber and Bethge (2018) introduced it and showed that, with enough queries, it finds distances close to those of white-box gradient attacks. Because it needs no gradients, it is not fooled by defenses that only hide or break the gradient.

Threat model. The goal is untargeted. The knowledge is black box with labels only: a query returns k(u)=arg⁡max⁡jzj(u)k(u) = \arg\max_j z_j(u) and nothing else. The attacker needs a starting point a0a^0 with k(a0)≠yk(a^0) \ne y. The capability is a change at test time in [0,1]d[0,1]^d; the attack reports the ℓ2\ell_2 distance it reaches after TT steps, with at most 2T2T queries.

In plain words

Think of a room with a wall that splits it into two parts, and you are on the wrong side. You want to stand on the wrong side as close as you can to a point xx on the right side, but you are blind: you can only ask whether you are on the wrong side.

Start anywhere on the wrong side. Take a random step around xx at the same distance, and ask. If you are still on the wrong side, step a little toward xx and ask again. If you are still on the wrong side, stay there. If either answer is no, go back.

Over time you end up at the wall, at the place closest to xx. If most tries fail, make the steps smaller. If most succeed, make them larger.

The problem

Given a label oracle kk on [0,1]d[0,1]^d, an input xx with label y=k(x)y = k(x), and a start a0a^0 with k(a0)≠yk(a^0) \ne y, find aa with k(a)≠yk(a) \ne y and ∥a−x∥2\lVert a - x \rVert_2 as small as possible, with a budget of queries. The best value is ρ2(x)\rho_2(x), the distance from xx to the nearest input of another label. Any output gives an upper bound on it.

The algorithm

  1. BOUNDARY(k, x, y, a0, T, alpha, beta)
  2. 1a ← a0
  3. 2for t ← 1 to T do ▷ stop early if a = x
  4. 3eta ← a vector of d draws from N(0, 1)
  5. 4D ← ||a - x||_2; m ← a + alpha D eta / ||eta||_2; o ← clip(x + D (m - x) / ||m - x||_2); c ← clip(o + beta (x - o))
  6. 5if k(o) ≠ y then ▷ the move on the sphere is still adversarial
  7. 6if k(c) ≠ y then a ← c ▷ the move toward x too
  8. 7every 10 steps: alpha ← alpha · 1.5 if more than 5 of 10 o were adversarial, else alpha / 1.5; beta ← min(beta · 1.5, 0.9) if more than 2 of 10 c were accepted, else beta / 1.5
  9. 8return (a, the number of queries)

Line L4 builds two candidates. The orthogonal candidate oo is a random move of relative size α\alpha projected back onto the sphere of radius DD around xx. The full candidate cc then moves a fraction β\beta of the way to xx. Line L7 is a simple form of the rule of the paper, which tunes α\alpha so that about half of the moves on the sphere stay adversarial, and shrinks β\beta when moves toward xx fail. The paper also clips and rescales the proposal so that it stays in the box and has the required size.

Example

A straight boundary. Take two classes in the plane with k(u)=1k(u) = 1 when u1+u2>0.8u_1 + u_2 > 0.8 and k(u)=0k(u) = 0 otherwise. Let x=(0.5,0.5)x = (0.5, 0.5), with label 11. The nearest point of label 00 is on the line at (0.4,0.4)(0.4, 0.4), so ρ2=0.2/2=0.14142\rho_2 = 0.2 / \sqrt2 = 0.14142. Start at a0=(0.1,0.1)a^0 = (0.1, 0.1), at distance 0.565690.56569, with α=β=0.1\alpha = \beta = 0.1 and the generator random.Random(1):

steps queries α\alpha for the next 10 β\beta for the next 10 distance ratio to ρ2\rho_2
0 0 0.1 0.1 0.56569 4.0
10 20 0.15 0.15 0.19724 1.395
20 39 0.225 0.1 0.14251 1.008
50 82 0.15 0.0296 0.14251 1.008
100 157 0.225 0.0039 0.14167 1.002
200 295 0.0198 0.0001 0.14144 1.0001

In the first 10 steps all 10 full candidates are accepted, since the point is far from the boundary, and the distance drops fast. At step 20 the point (0.4106,0.3891)(0.4106, 0.3891) is close to the line, and most moves toward xx cross it, so β\beta shrinks. From step 20 to step 90 no full candidate is accepted. The point only gets closer when the move on the sphere slides it along the line toward (0.4,0.4)(0.4, 0.4). At step 200 the point is (0.4009,0.3991)(0.4009, 0.3991).

Three classes. On the linear model of the page adversarial example, with rows (1,0)(1, 0), (0,1)(0, 1) and (−1,−1)(-1, -1), x=(0.6,0.4)x = (0.6, 0.4), label 00, start (0,1)(0, 1) and random.Random(1), 200 steps use 297 queries and reach the distance 0.141460.14146, which is 1.00021.0002 times ρ2=0.14142\rho_2 = 0.14142. This is the row of the boundary attack in the table of the page evasion attack.

Correctness

Theorem 1 (the invariant). With α>0\alpha > 0 and 0<β<10 < \beta < 1 at the start, after every step the point aa is in [0,1]d[0,1]^d, its label is not yy, and its distance to xx does not grow. When a full candidate is accepted, the distance shrinks by a factor of at least 1−β1 - \beta. The attack uses at most 2T2T queries.

Corollary (a bound from below on linear models). If k(u)=1k(u) = 1 exactly when w⊤u+b>0w^\top u + b > 0, the distance of every iterate is at least ∣w⊤x+b∣/∥w∥2=ρ2(x)|w^\top x + b| / \lVert w \rVert_2 = \rho_2(x).

The proof rests on two facts. Before the clip, oo is at distance DD from xx and c−x=(1−β)(o−x)c - x = (1 - \beta)(o - x). The clip to the box can only move a point toward xx, because xx is in the box. A point is accepted only after a query shows its label is not yy. The full proofs are in proofs/correctness.md.

The theorem does not say that the distance reaches ρ2(x)\rho_2(x), or how fast. That depends on the step sizes, the dimension and the shape of the boundary. On the 500 seeded random linear models of the tests, in one to four dimensions, 120 steps gave at most 1.0661.066 times the minimum (a measurement).

Proof: The boundary attack stays adversarial and never moves away from the inputfull

Let x∈[0,1]dx \in [0,1]^d have label yy, and let the start a0∈[0,1]da^0 \in [0,1]^d have a label other than yy. The attack sees only labels. We write D(a)=∥a−x∥2D(a) = \lVert a - x \rVert_2 and Π\Pi for the clip to [0,1]d[0,1]^d.

Lemma 1 (the clip does not move points away from xx). For every u∈Rdu \in \mathbb{R}^d, ∥Π(u)−x∥2≤∥u−x∥2\lVert \Pi(u) - x \rVert_2 \le \lVert u - x \rVert_2.

Proof. Since xi∈[0,1]x_i \in [0,1], clipping uiu_i to [0,1][0,1] moves it toward xix_i or leaves it in place, so ∣Π(u)i−xi∣≤∣ui−xi∣|\Pi(u)_i - x_i| \le |u_i - x_i| for each ii. □\square

Lemma 2 (the two candidates). Let a≠xa \ne x, α>0\alpha > 0, 0<β<10 < \beta < 1, and let the noise η≠0\eta \ne 0 be such that the moved point m=a+αD(a) η/∥η∥2m = a + \alpha D(a)\, \eta / \lVert \eta \rVert_2 is not xx. Then, before the clip, the orthogonal candidate oo has D(o)=D(a)D(o) = D(a), and the full candidate cc has c−x=(1−β)(o−x)c - x = (1 - \beta)(o - x), so D(c)=(1−β)D(a)D(c) = (1 - \beta) D(a). After the clip, D(Π(c))≤(1−β)D(a)D(\Pi(c)) \le (1 - \beta) D(a).

Proof. In candidate, o=x+(m−x)⋅D(a)/∥m−x∥2o = x + (m - x) \cdot D(a) / \lVert m - x \rVert_2, so D(o)=D(a)D(o) = D(a). Then c=o+β(x−o)c = o + \beta(x - o), so c−x=(1−β)(o−x)c - x = (1 - \beta)(o - x). The last claim follows from Lemma 1. □\square

The case m=xm = x has probability 00 for Gaussian noise, and the code does not guard against it.

Theorem 1 (the invariant). Assume α>0\alpha > 0 and 0<β<10 < \beta < 1 at the start. After every step tt, the iterate ata^t lies in [0,1]d[0,1]^d, its label is not yy, and D(at)≤D(at−1)D(a^t) \le D(a^{t-1}). When a full candidate is accepted, D(at)≤(1−βt)D(at−1)D(a^t) \le (1 - \beta_t) D(a^{t-1}). The attack uses at most 2T2T queries for TT steps.

Proof. Line L1 sets a0a^0 to the start, which satisfies the first two claims. The iterate changes only in line L6, and only to the clipped full candidate after a query has shown that its label is not yy. That point lies in [0,1]d[0,1]^d, and Lemma 2 gives the bound on its distance. The rule of line L7 multiplies α\alpha and β\beta by 1.51.5 or 1/1.51/1.5 and caps β\beta at 0.90.9, so α\alpha stays positive and β\beta stays in (0,max⁡(β0,0.9)](0, \max(\beta_0, 0.9)], which is inside (0,1)(0, 1). Each step makes one query in line L5 and at most one more in line L6. If the iterate reaches xx itself, line L2 stops, because then xx would have a label other than yy, which does not happen. □\square

Corollary (a bound from below on linear models). If the label is 11 exactly when w⊤u+b>0w^\top u + b > 0, then for every tt, D(at)≥∣w⊤x+b∣/∥w∥2D(a^t) \ge |w^\top x + b| / \lVert w \rVert_2. So the distance of the output is between the true minimum distance and D(a0)D(a^0).

Proof. The iterate is on the other side of the hyperplane w⊤u+b=0w^\top u + b = 0 (or on it), and the distance from xx to that closed half space is ∣w⊤x+b∣/∥w∥2|w^\top x + b| / \lVert w \rVert_2. ■\blacksquare

What is not claimed. The proof shows that the distance never grows; it does not show that it reaches the minimum. The rate depends on the step sizes, the dimension and the shape of the boundary. In the seeded tests on random linear models in one to four dimensions, 120 steps gave a distance at most 1.0661.066 times the minimum (a measurement, not a theorem). The adaptation rule of line L7 is a simple version of the one in the paper by Brendel, Rauber and Bethge.

Complexity

  • Time. Each step draws dd numbers, builds two candidates in O(d)O(d), and makes at most two queries of cost qq. The total is O(T(d+q))O(T (d + q)).
  • Queries. At most 2T2T. This is the real cost in practice. In high dimensions the walk needs many steps, since a random direction is almost orthogonal to the useful one. The paper reports many thousands of queries per input on image models (a measurement).
  • Space. Θ(d)\Theta(d) for the point, the noise and the two candidates.

Properties

  • Label only. No gradients or scores.
  • Always adversarial. The current point never loses the wrong label (Theorem 1). So it can stop at any time and return a valid result.
  • Monotone. The distance never grows.
  • Randomized. The result depends on the seed.
  • Robust to gradient masking. It does not use gradients, so it is a useful check on defenses that make gradients useless.

Variants and improvements

  • Targeted version. Start from an input of the target class and keep only points of that class.
  • Better starts. Start from a point of another label found by a transfer attack, or from the result of a line search between noise and xx.
  • HopSkipJumpAttack. Chen, Jordan and Wainwright (2020) estimate the direction of the gradient at the boundary from the labels of random points near it, then take a step and do a binary search back to the boundary. It needs far fewer queries.
  • Other norms. The same walk works in ℓ∞\ell_\infty with a different proposal.
  • Scores. If the model returns scores, use a score-based method such as the ZOO attack, which needs fewer queries.

When to use it

Use the boundary attack on small models to study the threat model in which only labels are visible, or to check a defense that might hide gradients. If a defended model is robust against gradient attacks and the boundary attack finds much smaller distances, the gradients were not useful, and the defense needs a stronger evaluation. For white-box evaluation, use the Carlini-Wagner attack or the PGD attack, which are faster and more precise.

Pitfalls

  • Few queries, large distances. Early in the walk the distance can be far above ρ2\rho_2. A result with a small query budget is a weak upper bound.
  • Stalls. Near the boundary, β\beta shrinks fast, and the distance can stop moving for many steps, as in the example from step 20 to step 90. Restart with larger steps if this lasts.
  • The start matters. A start far from the boundary or in a bad region costs queries. On a model with several regions of other labels, the walk can stay near a boundary that is not the nearest one.
  • Randomness. Report the seed and run several seeds, since the result changes with the noise.
  • Rounding. On a real system, inputs are rounded before the model sees them. The abstract model of this page has no such step.

Implementations

The code of this page is an abstract model on synthetic data. The attack runs only on label functions that the tests build from a fixed seed: linear rules with given or seeded weights, and two-layer ReLU networks from mlkit.tiny_relu_net, on seeded random inputs, with the noise from random.Random seeded in the test. It never reads real data or touches a real system. The tests check the two examples of the page, edge cases, that on 500 random inputs the two candidates never move away from xx, that on 500 random linear models the result stays adversarial, within the query budget, and between ρ2\rho_2 and the start distance, and that on seeded networks the result stays 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.

boundary_attack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-attack/. The authors are listed in prov/0K6SWG.jsonl.

"""The boundary attack of Brendel, Rauber and Bethge (2018), untargeted l2 version, on synthetic models only.

The attack sees only the label that the model returns for a query. The model is a
Python function from an input to a label; 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, Sequence

Vector = list[float]
Label = Callable[[Vector], int]


def _dist(u: Sequence[float], v: Sequence[float]) -> float:
    return math.sqrt(math.fsum((a - b) ** 2 for a, b in zip(u, v)))


def _clip(v: Sequence[float]) -> Vector:
    return [min(max(a, 0.0), 1.0) for a in v]


def candidate(x: Sequence[float], adv: Sequence[float], noise: Sequence[float], alpha: float,
              beta: float) -> tuple[Vector, Vector]:
    """The orthogonal candidate and the full candidate of one step.

    The noise is scaled to length alpha * D, where D = ||adv - x||, and added to adv. The
    sum is moved back to the sphere of radius D around x: this is the orthogonal
    candidate. The full candidate then moves a fraction beta of the way to x. Both are
    clipped to [0, 1]^d. Precondition: adv != x and noise != 0. Cost O(d).
    """
    dist = _dist(adv, x)
    nn = math.sqrt(math.fsum(t * t for t in noise))
    moved = [a + alpha * dist * t / nn for a, t in zip(adv, noise)]
    back = dist / _dist(moved, x)
    ortho = [c + (a - c) * back for a, c in zip(moved, x)]
    full = [a + beta * (c - a) for a, c in zip(ortho, x)]
    return _clip(ortho), _clip(full)


def boundary_attack(label: Label, x: Sequence[float], y: int, start: Sequence[float], steps: int,
                    rng: random.Random, alpha: float = 0.1, beta: float = 0.1) -> tuple[Vector, int]:
    """Walk along the boundary from the adversarial input start toward x.

    Every step costs at most two label queries. Every 10 steps the step sizes adapt: alpha
    grows by 1.5 when more than half of the orthogonal candidates were adversarial and
    shrinks otherwise; beta grows by 1.5 when more than a fifth of the full candidates
    were accepted and shrinks otherwise, and stays below 0.9. Returns (the adversarial
    input, the number of label queries). Preconditions: label(start) != y and start in
    [0, 1]^d. Cost O(steps d) plus the queries.
    """
    adv = list(start)  # @line L1
    queries = 0
    ortho_ok = full_ok = 0
    for t in range(1, steps + 1):  # @line L2
        if adv == list(x):
            break
        noise = [rng.gauss(0.0, 1.0) for _ in x]  # @line L3
        ortho, full = candidate(x, adv, noise, alpha, beta)  # @line L4
        queries += 1
        if label(ortho) != y:  # @line L5
            ortho_ok += 1
            queries += 1
            if label(full) != y:  # @line L6
                adv = full
                full_ok += 1
        if t % 10 == 0:  # @line L7
            alpha = alpha * 1.5 if ortho_ok > 5 else alpha / 1.5
            beta = min(beta * 1.5, 0.9) if full_ok > 2 else beta / 1.5
            ortho_ok = full_ok = 0
    return adv, queries  # @line L8
mlkit.py 252 lines
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small vector tools, synthetic data and two tiny models for the adversarial machine learning pages.

Vectors are lists of floats. Every model here is synthetic: it is built from a seeded
random.Random and never from real data. The helper holds no attack loop, no
certification and no defense; those live in the slug files of the pages.
"""

import math
import random
from typing import Callable, Sequence

Vector = list[float]
Matrix = list[list[float]]
Net = dict[str, list]
Data = list[tuple[Vector, int]]


def dot(u: Sequence[float], v: Sequence[float]) -> float:
    """Inner product of two vectors of the same length. Cost O(d)."""
    return math.fsum(a * b for a, b in zip(u, v, strict=True))


def add(u: Sequence[float], v: Sequence[float]) -> Vector:
    """Coordinatewise sum u + v. Cost O(d)."""
    return [a + b for a, b in zip(u, v, strict=True)]


def sub(u: Sequence[float], v: Sequence[float]) -> Vector:
    """Coordinatewise difference u - v. Cost O(d)."""
    return [a - b for a, b in zip(u, v, strict=True)]


def scale(c: float, v: Sequence[float]) -> Vector:
    """The vector c v. Cost O(d)."""
    return [c * a for a in v]


def norm1(v: Sequence[float]) -> float:
    """The l1 norm, the sum of |v_i|. Cost O(d)."""
    return math.fsum(abs(a) for a in v)


def norm2(v: Sequence[float]) -> float:
    """The Euclidean norm. Cost O(d)."""
    return math.sqrt(math.fsum(a * a for a in v))


def norminf(v: Sequence[float]) -> float:
    """The l_infinity norm, max |v_i|, and 0 for the empty vector. Cost O(d)."""
    return max((abs(a) for a in v), default=0.0)


def project_l2(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
    """Euclidean projection of v onto the l2 ball of the given center and radius >= 0.

    A point inside the ball is returned unchanged; a point outside is moved along the
    segment to the center until it is on the sphere. Cost O(d).
    """
    diff = sub(v, center)
    r = norm2(diff)
    if r <= radius:
        return list(v)
    return add(center, scale(radius / r, diff))


def project_linf(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
    """Euclidean projection of v onto the l_infinity ball: clip each coordinate to [c_i - r, c_i + r]. Cost O(d)."""
    return [min(max(a, c - radius), c + radius) for a, c in zip(v, center, strict=True)]


def clip01(v: Sequence[float]) -> Vector:
    """Euclidean projection onto the box [0, 1]^d. Cost O(d)."""
    return [min(max(a, 0.0), 1.0) for a in v]


def make_blobs(rng: random.Random, n: int, d: int, centers: Sequence[Sequence[float]], sigma: float) -> Data:
    """n synthetic points in R^d from Gaussian blobs N(center, sigma^2 I).

    Point i gets the label i mod len(centers) and is drawn around that center, so the
    classes are balanced. The points are not clipped. Cost O(n d) and n d draws of rng.
    """
    for c in centers:
        if len(c) != d:
            raise ValueError("each center must have d coordinates")
    data: Data = []
    for i in range(n):
        label = i % len(centers)
        x = [c + rng.gauss(0.0, sigma) for c in centers[label]]
        data.append((x, label))
    return data


def sigmoid(t: float) -> float:
    """The logistic function 1 / (1 + e^(-t)), computed without overflow. Cost O(1)."""
    if t >= 0:
        return 1.0 / (1.0 + math.exp(-t))
    e = math.exp(t)
    return e / (1.0 + e)


def _softplus(t: float) -> float:
    """ln(1 + e^t) without overflow."""
    return max(t, 0.0) + math.log1p(math.exp(-abs(t)))


def logistic_loss(w: Sequence[float], b: float, x: Sequence[float], y: int) -> float:
    """Logistic loss of the linear model z = w.x + b on a label y in {0, 1}.

    The loss is ln(1 + e^(-s z)) with s = 2 y - 1. Cost O(d).
    """
    s = 2 * y - 1
    return _softplus(-s * (dot(w, x) + b))


def grad_x_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> Vector:
    """Gradient of logistic_loss in the input x: (sigmoid(z) - y) w. Cost O(d)."""
    g = sigmoid(dot(w, x) + b) - y
    return scale(g, w)


def grad_w_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> tuple[Vector, float]:
    """Gradient of logistic_loss in the parameters: ((sigmoid(z) - y) x, sigmoid(z) - y). Cost O(d)."""
    g = sigmoid(dot(w, x) + b) - y
    return scale(g, x), g


def train_logistic(data: Data, steps: int, lr: float, l2: float) -> tuple[Vector, float]:
    """Full-batch gradient descent on the mean logistic loss plus (l2 / 2) ||w||^2.

    Labels are in {0, 1}. The weights start at zero, so the result is deterministic.
    The bias has no penalty. Returns (w, b). Cost O(steps n d).
    """
    d = len(data[0][0])
    n = len(data)
    w = [0.0] * d
    b = 0.0
    for _ in range(steps):
        gw = [0.0] * d
        gb = 0.0
        for x, y in data:
            g = sigmoid(dot(w, x) + b) - y
            for j in range(d):
                gw[j] += g * x[j]
            gb += g
        w = [w[j] - lr * (gw[j] / n + l2 * w[j]) for j in range(d)]
        b -= lr * gb / n
    return w, b


def tiny_relu_net(rng: random.Random, d: int, h: int, k: int) -> Net:
    """A fixed-seed two-layer ReLU network with d inputs, h hidden units and k logits.

    The weights are drawn from N(0, 1/d) in the first layer and N(0, 1/h) in the second,
    and the biases from N(0, 0.01). The dict has the keys W1 (h rows of d), b1 (h),
    W2 (k rows of h) and b2 (k). Cost O(h d + k h).
    """
    s1, s2 = 1.0 / math.sqrt(d), 1.0 / math.sqrt(h)
    return {
        "W1": [[rng.gauss(0.0, s1) for _ in range(d)] for _ in range(h)],
        "b1": [rng.gauss(0.0, 0.1) for _ in range(h)],
        "W2": [[rng.gauss(0.0, s2) for _ in range(h)] for _ in range(k)],
        "b2": [rng.gauss(0.0, 0.1) for _ in range(k)],
    }


def _hidden(net: Net, x: Sequence[float]) -> tuple[Vector, Vector]:
    """Pre-activations and activations of the hidden layer."""
    pre = [dot(row, x) + bi for row, bi in zip(net["W1"], net["b1"], strict=True)]
    return pre, [max(a, 0.0) for a in pre]


def forward(net: Net, x: Sequence[float]) -> Vector:
    """Logits z(x) = W2 relu(W1 x + b1) + b2 of a tiny_relu_net. Cost O(h d + k h)."""
    _, act = _hidden(net, x)
    return [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]


def argmax(z: Sequence[float]) -> int:
    """The first index of a largest entry. Cost O(k)."""
    best = 0
    for i in range(1, len(z)):
        if z[i] > z[best]:
            best = i
    return best


def softmax(z: Sequence[float]) -> Vector:
    """The softmax of a logit vector, shifted by the maximum to avoid overflow. Cost O(k)."""
    m = max(z)
    e = [math.exp(a - m) for a in z]
    s = math.fsum(e)
    return [a / s for a in e]


def cross_entropy(z: Sequence[float], label: int) -> float:
    """Cross-entropy loss -ln softmax(z)[label], computed as logsumexp(z) - z[label]. Cost O(k)."""
    m = max(z)
    return m + math.log(math.fsum(math.exp(a - m) for a in z)) - z[label]


def logits_jacobian(net: Net, x: Sequence[float]) -> Matrix:
    """The k by d Jacobian of the logits in the input, W2 diag(relu'(pre)) W1.

    The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
    Cost O(k h d).
    """
    pre, _ = _hidden(net, x)
    d = len(x)
    rows = []
    for w2 in net["W2"]:
        row = [0.0] * d
        for i, a in enumerate(pre):
            if a > 0 and w2[i] != 0.0:
                c = w2[i]
                w1 = net["W1"][i]
                for j in range(d):
                    row[j] += c * w1[j]
        rows.append(row)
    return rows


def input_gradient(net: Net, x: Sequence[float], label: int) -> Vector:
    """Gradient in x of cross_entropy(forward(net, x), label), by backpropagation.

    The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
    Cost O(h d + k h).
    """
    pre, act = _hidden(net, x)
    z = [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
    p = softmax(z)
    p[label] -= 1.0
    back = [0.0] * len(pre)
    for c, row in zip(p, net["W2"], strict=True):
        for i in range(len(pre)):
            back[i] += c * row[i]
    g = [0.0] * len(x)
    for i, a in enumerate(pre):
        if a > 0:
            w1 = net["W1"][i]
            for j in range(len(x)):
                g[j] += back[i] * w1[j]
    return g


def accuracy(predict: Callable[[Vector], int], data: Data) -> float:
    """Fraction of the pairs (x, y) of data with predict(x) == y. Cost: n calls of predict."""
    if not data:
        return 0.0
    return sum(1 for x, y in data if predict(x) == y) / len(data)
test_boundary_attack.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-attack/. The authors are listed in prov/0K6SWG.jsonl.

"""Tests of the boundary attack, on seeded synthetic models only."""

import math
import random

import mlkit as m
from boundary_attack import boundary_attack, candidate

# The worked example of the page: label 1 when x_1 + x_2 > 0.8, else 0.
XE = [0.5, 0.5]
START = [0.1, 0.1]


def label_e(u):
    return 1 if u[0] + u[1] > 0.8 else 0


def linear_label(w, b):
    return lambda u: 1 if m.dot(w, u) + b > 0 else 0


def test_page_example() -> None:
    dmin = 0.2 / math.sqrt(2)
    adv, queries = boundary_attack(label_e, XE, 1, START, 200, random.Random(1))
    assert label_e(adv) == 0
    assert dmin <= math.dist(adv, XE) <= 1.001 * dmin
    assert queries <= 400
    # the table of the page
    for steps, q, dist in ((10, 20, 0.19724), (20, 39, 0.14251), (50, 82, 0.14251), (100, 157, 0.14167), (200, 295, 0.14144)):
        adv, queries = boundary_attack(label_e, XE, 1, START, steps, random.Random(1))
        assert queries == q and abs(math.dist(adv, XE) - dist) < 1e-5


def test_three_class_example() -> None:
    # the row of the boundary attack in the table of the page evasion-attack
    w = [[1.0, 0.0], [0.0, 1.0], [-1.0, -1.0]]
    lab = lambda u: m.argmax([m.dot(r, u) for r in w])
    x = [0.6, 0.4]
    adv, queries = boundary_attack(lab, x, 0, [0.0, 1.0], 200, random.Random(1))
    assert lab(adv) != 0 and queries == 297
    assert abs(math.dist(adv, x) - 0.14146) < 1e-5


def test_edges() -> None:
    adv, queries = boundary_attack(label_e, XE, 1, START, 0, random.Random(1))
    assert adv == START and queries == 0
    ortho, full = candidate([0.5, 0.5], [0.5, 0.3], [1.0, 0.0], 0.1, 0.5)
    assert abs(math.dist(ortho, [0.5, 0.5]) - 0.2) < 1e-12
    assert abs(math.dist(full, [0.5, 0.5]) - 0.1) < 1e-12


def test_candidates_never_move_away() -> None:
    # The orthogonal candidate keeps the distance D (before the clip) and the full
    # candidate is at (1 - beta) D. The clip is the projection onto a convex set that
    # contains x, so it can only shorten both distances.
    rng = random.Random(7701)
    for _ in range(500):
        d = rng.randint(1, 6)
        x = [rng.uniform(0, 1) for _ in range(d)]
        adv = [rng.uniform(0, 1) for _ in range(d)]
        noise = [rng.gauss(0, 1) for _ in range(d)]
        alpha, beta = rng.uniform(0.01, 1.0), rng.uniform(0.0, 0.9)
        dist = math.dist(adv, x)
        ortho, full = candidate(x, adv, noise, alpha, beta)
        assert math.dist(ortho, x) <= dist + 1e-12
        assert math.dist(full, x) <= (1 - beta) * dist + 1e-12
        assert all(0.0 <= a <= 1.0 for a in ortho + full)


def test_linear_models_approach_the_closed_form_distance() -> None:
    # For label 1 iff w.x + b > 0, no input of label 0 is closer to x than f(x) / ||w||.
    rng = random.Random(7702)
    for trial in range(500):
        d = rng.randint(1, 4)
        w = [rng.choice([-1, 1]) * rng.uniform(0.3, 2.0) for _ in range(d)]
        x = [rng.uniform(0.3, 0.7) for _ in range(d)]
        dmin = rng.uniform(0.05, 0.3)
        b = dmin * m.norm2(w) - m.dot(w, x)
        lab = linear_label(w, b)
        start = [0.0 if wi > 0 else 1.0 for wi in w]
        if lab(start) == 1:
            continue
        adv, queries = boundary_attack(lab, x, 1, start, 120, random.Random(trial))
        assert lab(adv) == 0
        assert all(0.0 <= a <= 1.0 for a in adv)
        assert queries <= 240
        assert dmin - 1e-12 <= math.dist(adv, x) <= math.dist(start, x)
        # a measured bound for these seeds, not a theorem: after 120 steps the worst ratio was below 1.07
        assert math.dist(adv, x) <= 1.1 * dmin


def test_relu_nets_stay_adversarial() -> None:
    rng = random.Random(7703)
    for trial in range(100):
        d, h, k = rng.randint(1, 4), rng.randint(2, 8), rng.randint(2, 4)
        net = m.tiny_relu_net(rng, d, h, k)
        lab = lambda u: m.argmax(m.forward(net, u))
        x = [rng.uniform(0, 1) for _ in range(d)]
        y = lab(x)
        start = None
        for _ in range(50):
            u = [rng.uniform(0, 1) for _ in range(d)]
            if lab(u) != y:
                start = u
                break
        if start is None:
            continue
        adv, queries = boundary_attack(lab, x, y, start, 60, random.Random(trial))
        assert lab(adv) != y
        assert math.dist(adv, x) <= math.dist(start, x) + 1e-12
        assert queries <= 120

History

Earlier black-box attacks used scores, as in ZOO (2017), or trained a substitute model for a transfer attack, as in Papernot et al. (2017). Brendel, Rauber and Bethge posted the boundary attack in December 2017 and published it at ICLR 2018. They showed that a walk with only labels reaches distances close to those of the Carlini-Wagner attack on MNIST, CIFAR10 and ImageNet models, with many more queries, and that it works on models whose gradients are masked, such as distilled networks. Later methods, such as HopSkipJumpAttack (2020), reduced the number of queries by estimating the direction of the gradient at the boundary.

References

  1. Wieland Brendel, Jonas Rauber and Matthias Bethge, Decision-based adversarial attacks, reliable attacks against black-box machine learning models, ICLR 2018, the description of the attack, with the proposal on the sphere, the step toward the original input and the adaptation of the two step sizes, and the comparison with gradient attacks on MNIST, CIFAR10 and ImageNet models
  2. Jianbo Chen, Michael I. Jordan and Martin J. Wainwright, HopSkipJumpAttack, a query-efficient decision-based attack, IEEE Symposium on Security and Privacy 2020, the estimate of the gradient direction at the boundary from labels, as a faster successor
  3. Nicholas Carlini and David Wagner, Towards evaluating the robustness of neural networks, IEEE Symposium on Security and Privacy 2017, pages 39 to 57, the white-box l2 attack used as the reference in the 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