Algorithm Search⌘K

Algorithmadvanced

Jacobian-based saliency map attack

Also called JSMA.

A targeted l0 attack that uses a saliency map of the Jacobian to pick pairs of features, and sets them high until the model gives the target class or a budget of changed features runs out.

Time
O(G (g + K d + d^2)) worst
Space
Θ(K d) extra
Where
G = the budget of changed features; K = the number of classes; d = the input dimension; g = the cost of the Jacobian of the logits
Properties
deterministicnot exactofflineiterative
Origin
Nicolas Papernot, Patrick McDaniel, Somesh Jha, Matt Fredrikson, Z. Berkay Celik, Ananthram Swami, 2015

The Jacobian-based saliency map attack (JSMA) is a targeted attack that changes few input features, so it is small in the ℓ0\ell_0 norm and not in ℓ∞\ell_\infty. At each step it computes the Jacobian of the logits, scores every pair of features by how much raising them helps the target class and hurts all the others, and sets the best pair to the top of the range. It stops when the model gives the target class, or when a budget of changed features runs out. Papernot, McDaniel, Jha, Fredrikson, Celik and Swami (2016) introduced it; on their MNIST network it reached the target in 97 percent of the cases with about 4 percent of the pixels changed, as their abstract reports.

Threat model. The goal is targeted: the class tt is given. The knowledge is white box: the attacker computes the Jacobian of the logits. The capability is a change at test time that raises at most G=⌊γd⌋G = \lfloor \gamma d \rfloor features of x∈[0,1]dx \in [0,1]^d by θ\theta each, clipped at 11; γ\gamma is the fraction of features that may change.

In plain words

Each feature of the input can push the model toward some classes and away from others. The Jacobian tells you, for each feature, how much each logit grows when the feature grows.

JSMA looks for features that help the target class and at the same time hurt the other classes. One feature alone often does only one of the two, so JSMA scores pairs: a pair is allowed only if together the two features raise the target logit and lower the sum of the other logits. It takes the pair with the best score and sets both features to the maximum.

Then it computes the Jacobian again at the new point and repeats. Each feature changes at most once. The result changes few features, but each by a large amount.

The problem

Given logits z:[0,1]d→RKz : [0,1]^d \to \mathbb{R}^K, an input xx, a target class tt, a step θ>0\theta > 0 and a fraction γ∈[0,1]\gamma \in [0, 1], find x′x' with

arg⁡max⁡kzk(x′)=t,x′∈[0,1]d,∥x′−x∥0≤⌊γd⌋.\arg\max_k z_k(x') = t, \qquad x' \in [0,1]^d, \qquad \lVert x' - x \rVert_0 \le \lfloor \gamma d \rfloor.

The smallest such change is a combinatorial search over sets of features. JSMA is a greedy method for it.

For a pair of features (p,q)(p, q) at the current point, write

αpq=∂zt∂xp+∂zt∂xq,βpq=∑j≠t(∂zj∂xp+∂zj∂xq).\alpha_{pq} = \frac{\partial z_t}{\partial x_p} + \frac{\partial z_t}{\partial x_q}, \qquad \beta_{pq} = \sum_{j \ne t}\left(\frac{\partial z_j}{\partial x_p} + \frac{\partial z_j}{\partial x_q}\right).

The saliency of the pair is −αpqβpq-\alpha_{pq}\beta_{pq} when αpq>0\alpha_{pq} > 0 and βpq<0\beta_{pq} < 0, and 00 otherwise.

The algorithm

  1. JSMA(z, x, t, theta, gamma)
  2. 1x' ← x; D ← {i : x_i < 1}; C ← empty list ▷ D is the search domain
  3. 2G ← floor(gamma · d)
  4. 3while argmax_k z_k(x') ≠ t and |C| + 2 ≤ G and |D| ≥ 2 do
  5. 4J ← the Jacobian of z at x'
  6. 5(p, q) ← the pair of D with alpha > 0, beta < 0 and the largest -alpha · beta
  7. 6if there is no such pair then stop the loop
  8. 7for i in (p, q): x'_i ← min(x'_i + theta, 1); remove i from D; append i to C
  9. 8return (x', argmax_k z_k(x') = t, C)

Line L5 checks all pairs of DD, in order; the first pair with the best score wins a tie. Line L7 removes a chosen feature from DD, so each feature changes at most once and ∣C∣|C| counts the changed features. This is the version that raises features and uses the logits. The paper also describes a version that lowers features, and computes the map on the softmax outputs.

Example

Take K=3K = 3 classes, d=6d = 6 features, the affine model z(v)=Wv+bz(v) = Wv + b with

W=(−0.50.510001−1−0.500.50100.5−1−1−1),b=(1,0,0),W = \begin{pmatrix} -0.5 & 0.5 & 1 & 0 & 0 & 0 \\ 1 & -1 & -0.5 & 0 & 0.5 & 0 \\ 1 & 0 & 0.5 & -1 & -1 & -1 \end{pmatrix}, \qquad b = (1, 0, 0),

the input x=(0.2,0,0,0.5,0.2,0.4)x = (0.2, 0, 0, 0.5, 0.2, 0.4), the target t=1t = 1, θ=1\theta = 1 and γ=1\gamma = 1. The logits are (0.9,0.3,−0.9)(0.9, 0.3, -0.9), so the label is 00. The Jacobian is WW at every point. Per feature, ∂z1/∂xi=(1,−1,−0.5,0,0.5,0)\partial z_1 / \partial x_i = (1, -1, -0.5, 0, 0.5, 0), and the sum of the other two rows is (0.5,0.5,1.5,−1,−1,−1)(0.5, 0.5, 1.5, -1, -1, -1).

In the first iteration all six features are in DD. Five pairs are allowed:

pair α\alpha β\beta saliency −αβ-\alpha\beta
(0, 3) 1.0 -0.5 0.5
(0, 4) 1.5 -0.5 0.75
(0, 5) 1.0 -0.5 0.5
(3, 4) 0.5 -2.0 1.0
(4, 5) 0.5 -2.0 1.0

Pairs (3,4)(3, 4) and (4,5)(4, 5) tie, and (3,4)(3, 4) comes first. Line L7 sets x3=x4=1x_3 = x_4 = 1, and the logits become (0.9,0.7,−2.2)(0.9, 0.7, -2.2): the label is still 00. In the second iteration D={0,1,2,5}D = \{0, 1, 2, 5\}, and only (0,5)(0, 5) is allowed, with saliency 0.50.5. After it, x′=(1,0,0,1,1,1)x' = (1, 0, 0, 1, 1, 1) with logits (0.5,1.5,−2)(0.5, 1.5, -2), and the label is 11.

JSMA changed four features, C=(3,4,0,5)C = (3, 4, 0, 5), so ∥x′−x∥0=4\lVert x' - x \rVert_0 = 4 and ∥x′−x∥∞=0.8\lVert x' - x \rVert_\infty = 0.8, from feature 00. With γ=0.5\gamma = 0.5 the budget is 33, only one pair fits, and the attack fails after the first pair.

The greedy choice is not minimal here. Setting only x0=1x_0 = 1 gives logits (0.5,1.1,−0.1)(0.5, 1.1, -0.1), already class 11. The pair (0,4)(0, 4) has the largest α\alpha, but its β\beta is weak, and the product prefers (3,4)(3, 4).

Correctness

Theorem 1. JSMA stops after at most ⌊G/2⌋\lfloor G / 2 \rfloor full passes of the loop. It returns x′∈[0,1]dx' \in [0,1]^d with x′≥xx' \ge x in every coordinate, ∥x′−x∥0=∣C∣≤G\lVert x' - x \rVert_0 = |C| \le G, and a success flag that is true exactly when the label of x′x' is tt.

The proof is a loop invariant: CC has no repeated feature, its size is even and at most GG, the domain is the first domain minus CC, and xi′=min⁡(xi+θ,1)x'_i = \min(x_i + \theta, 1) for i∈Ci \in C while xi′=xix'_i = x_i otherwise. Each full pass adds two new features and keeps all of this. A lemma shows that line L5 returns the allowed pair with the largest saliency. The full proof is in proofs/correctness.md.

So every reported success is a valid targeted adversarial example for the model, inside the budget. The theorem says nothing about the smallest set: JSMA is greedy, and a failure does not prove that no set of GG features works. On the 500 seeded random affine models of the tests, JSMA succeeds in 94 cases, and an exhaustive search finds a smaller set in 82 of them (a measurement).

Proof: JSMA changes only the chosen features, stays in the box and in the budget, and stopsfull

Let x∈[0,1]dx \in [0,1]^d, θ>0\theta > 0, target class tt and Γ=⌊γd⌋\Gamma = \lfloor \gamma d \rfloor the budget of line L2, where γ\gamma is max_distortion. Let D0={i:xi<1}D_0 = \{i : x_i < 1\} be the first search domain (line L1). The list CC is changed.

Lemma 1 (the pair rule). saliency_pair returns a pair (p,q)(p, q) of distinct indices of the domain with αpq>0\alpha_{pq} > 0, βpq<0\beta_{pq} < 0 and the largest value of −αpqβpq-\alpha_{pq}\beta_{pq}, where αpq=∂pzt+∂qzt\alpha_{pq} = \partial_p z_t + \partial_q z_t and βpq=∑j≠t(∂pzj+∂qzj)\beta_{pq} = \sum_{j \ne t} (\partial_p z_j + \partial_q z_j). Ties go to the first such pair in the order of the domain. If no pair has α>0\alpha > 0 and β<0\beta < 0, it returns None.

Proof. The double loop visits each unordered pair of distinct positions u<vu < v of the domain once, in order. It replaces the best pair only when the pair is allowed and its value is strictly larger than the best so far, which starts at 00. An allowed pair has −αβ>0-\alpha\beta > 0, so the first allowed pair is always taken, and a later pair replaces it only with a strictly larger value. □\square

Lemma 2 (the loop invariant). Each time line L3 is checked, these hold:

  1. CC has no repeated index, ∣C∣|C| is even and ∣C∣≤Γ|C| \le \Gamma.
  2. The domain is D0∖CD_0 \setminus C, in the order of the indices.
  3. xia=xix^a_i = x_i for i∉Ci \notin C, and xia=min⁡(xi+θ,1)x^a_i = \min(x_i + \theta, 1) for i∈Ci \in C.
  4. xa∈[0,1]dx^a \in [0,1]^d, and xia≠xix^a_i \ne x_i exactly when i∈Ci \in C.

Proof. At the first check, CC is empty, the domain is D0D_0 and xa=xx^a = x, so the claims hold. Suppose they hold at one check and the loop body runs to line L7. Then line L3 gave ∣C∣+2≤Γ|C| + 2 \le \Gamma. Line L5 returned two distinct indices p,qp, q of the domain, so by part 2 they are in D0D_0 and not in CC. Line L7 sets xpa=min⁡(xp+θ,1)x^a_p = \min(x_p + \theta, 1) and the same for qq (part 3 says these two coordinates still had their start values), removes both from the domain and appends both to CC. So CC gets two new distinct indices and its size stays even and at most Γ\Gamma, and parts 2 and 3 hold again. For part 4, xi<1x_i < 1 for i∈D0i \in D_0 and θ>0\theta > 0, so xi<min⁡(xi+θ,1)≤1x_i < \min(x_i + \theta, 1) \le 1, and xi≥0x_i \ge 0. If the body leaves at line L6, nothing changes. □\square

Theorem 1 (the output). The attack stops after at most ⌊Γ/2⌋\lfloor \Gamma / 2 \rfloor passes of the loop. It returns (xa,s,C)(x^a, s, C) with xa∈[0,1]dx^a \in [0,1]^d, ∥xa−x∥0=∣C∣≤Γ\lVert x^a - x \rVert_0 = |C| \le \Gamma, xa≥xx^a \ge x in every coordinate, and ss true exactly when arg⁡max⁡kzk(xa)=t\arg\max_k z_k(x^a) = t.

Proof. Each full pass adds two indices to CC, and line L3 needs ∣C∣+2≤Γ|C| + 2 \le \Gamma before a pass. So there are at most ⌊Γ/2⌋\lfloor \Gamma / 2 \rfloor full passes, and at most one more pass that leaves at line L6. The properties of xax^a and CC are Lemma 2 at the last check, together with min⁡(xi+θ,1)≥xi\min(x_i + \theta, 1) \ge x_i. Line L8 computes ss from the label of xax^a. ■\blacksquare

Corollary (success means a valid targeted adversarial input). If ss is true, then xax^a is in the box, has the label tt, and differs from xx in at most Γ\Gamma features. So every reported success is a real one for the given model.

What is not claimed. JSMA is greedy. It does not find the smallest set of features. On the 500 random affine models of the seeded test, JSMA succeeds in 94 cases, and in 82 of them an exhaustive search over feature sets set to 1 finds a smaller successful set. In 64 of the cases where JSMA fails, such a set exists (a measurement, partly because JSMA changes features in pairs). A failure of JSMA (ss false) does not prove that no change of Γ\Gamma features reaches tt.

Complexity

  • Time. Each pass costs one Jacobian, gg, which is KK backward passes in general, O(Kd)O(K d) to sum the rows, and O(d2)O(d^2) to score the pairs. There are at most G/2G/2 passes, so the total is O(G(g+Kd+d2))O(G (g + K d + d^2)).
  • Space. Θ(Kd)\Theta(K d) for the Jacobian, plus Θ(d)\Theta(d) for x′x', DD and CC.
  • Model. These counts are in the real-ram model, with one Jacobian as a unit of work. On large inputs the d2d^2 pair search is the main cost, which is one reason later ℓ0\ell_0 attacks score features in other ways.

Properties

  • Deterministic. No randomness. Ties go to the first pair.
  • Targeted and ℓ0\ell_0. It controls the number of changed features, not their size.
  • Monotone. This version only raises features. A second version only lowers them.
  • Not minimal. Greedy, as the example shows.
  • Valid output. Every success is in the box and in the budget (Theorem 1).

Variants and improvements

  • Single features. The paper first defines the map for one feature: the score is ∂zt∂xi ∣∑j≠t∂zj∂xi∣\frac{\partial z_t}{\partial x_i}\,\lvert \sum_{j \ne t} \frac{\partial z_j}{\partial x_i} \rvert when the first factor is positive and the sum is negative. The condition is rarely met for one feature alone, which is why the attack uses pairs.
  • Softmax or logits. The map can use the Jacobian of the softmax outputs or of the logits. Carlini and Wagner (2017) call the two versions JSMA-F and JSMA-Z.
  • Lowering features. Swap the signs of the conditions and lower features toward 00.
  • Untargeted. Pick the target as the class that is easiest to reach, or score the pairs against the true class only.
  • The C&W ℓ0\ell_0 attack. Carlini and Wagner run their ℓ2\ell_2 attack many times and fix the features that matter least, which gives smaller ℓ0\ell_0 changes than JSMA on their models.

When to use it

Use JSMA on small models to study ℓ0\ell_0 threat models, in which an attacker can change a few features by any amount, such as a few pixels or a few fields of a record. For ℓ∞\ell_\infty or ℓ2\ell_2 threat models, use the PGD attack, DeepFool or the Carlini-Wagner attack. For a strong ℓ0\ell_0 evaluation, run more than one attack, because a greedy failure is weak evidence.

Pitfalls

  • Read failures with care. A failure of a greedy search is not a proof of robustness. Report JSMA results as an upper bound on robust accuracy for the ℓ0\ell_0 budget.
  • Softmax saturation. On the softmax version, outputs near 00 or 11 have tiny gradients, and the map can be empty. This is how defensive distillation seemed to stop JSMA. Attacks that work on the logits are not stopped in this way.
  • Features at the top. A feature already at 11 is not in the domain. Inputs that are mostly at 11 leave few choices.
  • Cost on large inputs. The d2d^2 pair search is slow for large dd. Restrict it to the top features, or use another method.
  • Even counts. The attack changes features in pairs, so it cannot report a set of odd size, even when one feature is enough, as in the example.

Implementations

The code of this page is an abstract model on synthetic data. The attack runs only on models that the tests build from a fixed seed: affine models with given or seeded weights, or two-layer ReLU networks from mlkit.tiny_relu_net, on seeded random inputs. It never reads real data or touches a real system. The tests check the example of the page, edge cases, the pair choice against a brute-force search on 500 random Jacobians, the output on 500 random affine models against an exhaustive search over feature sets, and the box, the budget and the success flag on seeded networks.

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.

jacobian_saliency_map_attack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jacobian-saliency-map-attack/. The authors are listed in prov/NXJN7D.jsonl.

"""The Jacobian saliency map attack (JSMA) of Papernot et al. (2016), on synthetic models only.

This is the targeted version that increases features, picks pairs of features and uses
the Jacobian of the logits (the variant that Carlini and Wagner call JSMA-Z). The model
is given as two functions on an input: its logits and the Jacobian of the logits. The
tests build both from seeded affine models or seeded ReLU networks of mlkit. Nothing
here reads real data or touches a real system.
"""

import math
from typing import Callable, Optional, Sequence

Vector = list[float]
Logits = Callable[[Vector], Vector]
Jacobian = Callable[[Vector], list[Vector]]


def _argmax(z: Sequence[float]) -> int:
    return max(range(len(z)), key=lambda i: z[i])


def saliency_pair(jz: Sequence[Sequence[float]], target: int, domain: Sequence[int]) -> Optional[tuple[int, int]]:
    """The pair (p, q) of the search domain with the largest saliency, or None.

    For a pair, alpha is the sum over p and q of d z_target / d x_i, and beta is the sum
    over p and q of the derivatives of all other logits. A pair is allowed only when
    alpha > 0 and beta < 0, and its saliency is -alpha * beta. Ties go to the first pair
    in the order of the domain. Cost O(K d + |domain|^2).
    """
    a = [jz[target][i] for i in range(len(jz[0]))]
    b = [math.fsum(jz[j][i] for j in range(len(jz)) if j != target) for i in range(len(jz[0]))]
    best, best_s = None, 0.0
    for u in range(len(domain)):
        for v in range(u + 1, len(domain)):
            p, q = domain[u], domain[v]
            alpha, beta = a[p] + a[q], b[p] + b[q]
            if alpha > 0 and beta < 0 and -alpha * beta > best_s:
                best, best_s = (p, q), -alpha * beta
    return best


def jsma(logits: Logits, jac: Jacobian, x: Sequence[float], target: int, theta: float = 1.0,
         max_distortion: float = 1.0) -> tuple[Vector, bool, list[int]]:
    """Run the attack from x toward the class target.

    Each iteration adds theta to the two chosen features and clips them at 1; a chosen
    feature leaves the search domain. The number of changed features stays at most
    floor(max_distortion * d). Returns (the perturbed input, success, the changed
    features in the order of change). Preconditions: x in [0, 1]^d, theta > 0.
    Cost: one logits and one Jacobian call per iteration, and O(d^2) for the pair search.
    """
    xa = list(x)  # @line L1
    domain = [i for i in range(len(xa)) if xa[i] < 1.0]
    budget = math.floor(max_distortion * len(xa))  # @line L2
    changed: list[int] = []
    while _argmax(logits(xa)) != target and len(changed) + 2 <= budget and len(domain) >= 2:  # @line L3
        jz = jac(xa)  # @line L4
        pair = saliency_pair(jz, target, domain)  # @line L5
        if pair is None:  # @line L6
            break
        for i in pair:  # @line L7
            xa[i] = min(xa[i] + theta, 1.0)
            domain.remove(i)
            changed.append(i)
    return xa, _argmax(logits(xa)) == target, changed  # @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_jacobian_saliency_map_attack.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jacobian-saliency-map-attack/. The authors are listed in prov/NXJN7D.jsonl.

"""Tests of JSMA, on seeded synthetic models only."""

import itertools
import random

import mlkit as m
from jacobian_saliency_map_attack import jsma, saliency_pair

# The worked example of the page: three classes, six features, target class 1.
WE = [
    [-0.5, 0.5, 1.0, 0.0, 0.0, 0.0],
    [1.0, -1.0, -0.5, 0.0, 0.5, 0.0],
    [1.0, 0.0, 0.5, -1.0, -1.0, -1.0],
]
BE = [1.0, 0.0, 0.0]
XE = [0.2, 0.0, 0.0, 0.5, 0.2, 0.4]


def affine(w, b):
    return (lambda u: [m.dot(r, u) + bi for r, bi in zip(w, b)]), (lambda u: w)


def brute_pair(jz, target, domain):
    """Independent oracle: score every pair from scratch and keep the first best one."""
    best, best_s = None, 0.0
    for p, q in itertools.combinations(domain, 2):
        alpha = jz[target][p] + jz[target][q]
        beta = sum(jz[j][p] + jz[j][q] for j in range(len(jz)) if j != target)
        if alpha > 0 and beta < 0 and -alpha * beta > best_s + 1e-12:
            best, best_s = (p, q), -alpha * beta
    return best, best_s


def smallest_set(lg, x, target):
    """Independent oracle: the size of the smallest set of features that, set to 1, gives the target, or None."""
    d = len(x)
    free = [i for i in range(d) if x[i] < 1.0]
    for size in range(len(free) + 1):
        for s in itertools.combinations(free, size):
            u = list(x)
            for i in s:
                u[i] = 1.0
            if m.argmax(lg(u)) == target:
                return size
    return None


def test_page_example() -> None:
    lg, jac = affine(WE, BE)
    assert m.argmax(lg(XE)) == 0
    assert saliency_pair(WE, 1, [0, 1, 2, 3, 4, 5]) == (3, 4)
    xa, ok, changed = jsma(lg, jac, XE, 1)
    assert ok and changed == [3, 4, 0, 5]
    assert xa == [1.0, 0.0, 0.0, 1.0, 1.0, 1.0]
    assert [round(t, 9) for t in lg(xa)] == [0.5, 1.5, -2.0]
    # with a budget of 3 of the 6 features only one pair fits, and the attack fails
    xa, ok, changed = jsma(lg, jac, XE, 1, max_distortion=0.5)
    assert not ok and changed == [3, 4]


def test_edges() -> None:
    lg, jac = affine(WE, BE)
    assert jsma(lg, jac, XE, 0) == (XE, True, [])  # already the target
    assert jsma(lg, jac, [1.0] * 6, 1)[2] == []  # nothing below 1, empty domain
    assert jsma(lg, jac, XE, 1, max_distortion=0.2)[2] == []  # a budget of one feature fits no pair
    assert saliency_pair(WE, 1, [0]) is None


def test_pair_choice_against_brute_force() -> None:
    rng = random.Random(7501)
    for _ in range(500):
        d, k = rng.randint(2, 7), rng.randint(2, 5)
        jz = [[rng.choice([-1.0, -0.5, 0.0, 0.5, 1.0, rng.uniform(-1, 1)]) for _ in range(d)] for _ in range(k)]
        target = rng.randrange(k)
        domain = sorted(rng.sample(range(d), rng.randint(0, d)))
        got = saliency_pair(jz, target, domain)
        want, score = brute_pair(jz, target, domain)
        if want is None:
            assert got is None
        else:
            p, q = got
            alpha = jz[target][p] + jz[target][q]
            beta = sum(jz[j][p] + jz[j][q] for j in range(k) if j != target)
            assert alpha > 0 and beta < 0
            assert abs(-alpha * beta - score) < 1e-9


def test_linear_models_against_exhaustive_search() -> None:
    # On an affine model with theta = 1 the output sets the changed features to 1, so any
    # success is a set that the exhaustive search also finds, and it can only be larger.
    rng = random.Random(7502)
    wins = 0
    for _ in range(500):
        d, k = rng.randint(2, 7), rng.randint(2, 4)
        w = [[rng.uniform(-1, 1) for _ in range(d)] for _ in range(k)]
        b = [rng.uniform(-0.5, 0.5) for _ in range(k)]
        x = [rng.choice([0.0, rng.uniform(0, 1), 1.0]) for _ in range(d)]
        lg, jac = affine(w, b)
        y = m.argmax(lg(x))
        target = rng.choice([j for j in range(k) if j != y])
        xa, ok, changed = jsma(lg, jac, x, target)
        assert ok == (m.argmax(lg(xa)) == target)
        assert len(changed) == len(set(changed)) and len(changed) % 2 == 0
        assert all(xa[i] == 1.0 for i in changed)
        assert all(xa[i] == x[i] for i in range(d) if i not in changed)
        best = smallest_set(lg, x, target)
        if ok:
            wins += 1
            assert best is not None and best <= len(changed)
        if best is None:
            assert not ok
    assert wins > 50


def test_relu_nets_respect_box_and_budget() -> None:
    rng = random.Random(7503)
    for _ in range(300):
        d, h, k = rng.randint(2, 6), rng.randint(2, 6), rng.randint(2, 4)
        net = m.tiny_relu_net(rng, d, h, k)
        lg = lambda u: m.forward(net, u)
        jac = lambda u: m.logits_jacobian(net, u)
        x = [rng.uniform(0, 1) for _ in range(d)]
        target = rng.randrange(k)
        theta = rng.choice([0.3, 1.0])
        gamma = rng.choice([0.5, 1.0])
        xa, ok, changed = jsma(lg, jac, x, target, theta=theta, max_distortion=gamma)
        assert all(0.0 <= a <= 1.0 for a in xa)
        assert len(changed) <= int(gamma * d)
        assert sum(1 for a, b in zip(xa, x) if a != b) <= len(changed)
        assert all(xa[i] >= x[i] for i in range(d))
        assert ok == (m.argmax(lg(xa)) == target)

History

Before JSMA, Szegedy et al. (2014) and Goodfellow, Shlens and Szegedy (2015) studied small changes in ℓ2\ell_2 and ℓ∞\ell_\infty. Papernot, McDaniel, Jha, Fredrikson, Celik and Swami posted JSMA in November 2015 and published it at IEEE EuroS&P 2016. They named the Jacobian of the model the forward derivative, in contrast to the gradient of the loss used by FGSM, and they also gave a taxonomy of goals and knowledge of the adversary. The same group used JSMA to evaluate defensive distillation (2016) and to study transferability. Carlini and Wagner (2016, 2017) showed that attacks that work on the logits break distilled models, and gave an ℓ0\ell_0 attack with smaller changes.

References

  1. Nicolas Papernot, Patrick McDaniel, Somesh Jha, Matt Fredrikson, Z. Berkay Celik and Ananthram Swami, The limitations of deep learning in adversarial settings, IEEE European Symposium on Security and Privacy 2016, pages 372 to 387, the forward derivative, the saliency map with pairs of features, and the MNIST evaluation
  2. Nicolas Carlini and David Wagner, Towards evaluating the robustness of neural networks, IEEE Symposium on Security and Privacy 2017, pages 39 to 57, the description of JSMA on logits and on softmax outputs, and the l0 attack that they compare with it
  3. Nicolas Papernot, Patrick McDaniel, Xi Wu, Somesh Jha and Ananthram Swami, Distillation as a defense to adversarial perturbations against deep neural networks, IEEE Symposium on Security and Privacy 2016, pages 582 to 597, the use of JSMA to evaluate defensive distillation
  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