Algorithm Search⌘K

Algorithmresearch

Clean-label poisoning

Also called feature collision attack, poison frogs.

Adds correctly labeled training points, crafted so that a model trained on them misclassifies one chosen target input; Poison Frogs makes their features match the target's.

Time
O(p h d) worst
Space
O(d + h) extra
Where
d = the input dimension; h = the feature dimension; p = the number of iterations
Properties
deterministicnot exactofflineiterative
Origin
Ali Shafahi, W. Ronny Huang, Mahyar Najibi, Octavian Suciu, Christoph Studer, Tudor Dumitras, Tom Goldstein, 2018

Clean-label poisoning makes a model misclassify one chosen target input by adding training points that carry their correct labels. The attacker does not control the labels: a human or a pipeline labels the points honestly, and each poison still looks like an ordinary member of its class. In the method of Shafahi et al. (2018), called Poison Frogs, the attacker starts from a base input bb of the class it wants the target tt to fall into, and moves it to a poison xx whose features f(x)f(x) are close to f(t)f(t) while xx stays close to bb. A model trained on the poison with the label of bb learns that this region of feature space belongs to the base class, and the target goes with it. The optimization is a forward-backward splitting, that is, a proximal gradient method; its convergence is a theorem for linear features, and the success of the attack is a measurement.

In plain words

You want a model to get one particular input wrong, but you can only add training examples, and someone else labels them correctly.

Take an example of the class you want the target to be confused with. Change it a little, so that a person still sees the same class, but so that the model "sees" it like the target. Its label is still correct, so nothing looks wrong.

When the model trains on it, it learns that inputs that look like this to the model belong to the base class. The target looks the same to the model, so it is now put in the base class too.

The problem

The threat model, in the three parts of Biggio and Roli:

  • Goal of the attacker. A targeted integrity attack: one chosen test input tt is classified as the base class, while the accuracy on other inputs stays the same, so that the attack is hard to notice.
  • Knowledge. The feature map ff of the model (white box), as in transfer learning where a public feature extractor is frozen and only the last layer is trained; or a substitute of it. The target input.
  • Capability. Add a few training points. Their labels are assigned honestly, and each poison must stay close to a real member of its class.

Input. A feature map f:[0,1]d→Rhf : [0, 1]^d \to \mathbb{R}^h, a target tt, a base b∈[0,1]db \in [0, 1]^d, a weight β>0\beta > 0, a step λ>0\lambda > 0 and a number of iterations.

Output. A poison x∈[0,1]dx \in [0, 1]^d with a small value of

F(x)=∥f(x)−f(t)∥2+β∥x−b∥2.F(x) = \lVert f(x) - f(t) \rVert^2 + \beta \lVert x - b \rVert^2 .

The first term pulls the features to the target; the second keeps the input near the base, so that its correct label is the label of bb.

The algorithm

  1. POISON(f, t, b, beta, lambda, steps)
  2. 1x <- b
  3. 2repeat steps times
  4. 3x_hat <- x - lambda * gradient of ||f(x) - f(t)||^2 at x (forward step)
  5. 4x <- clip to [0, 1]^d of (x_hat + 2 lambda beta b) / (1 + 2 lambda beta) (backward step)
  6. 5return x

Line L3 is a gradient step on the term with the features, which is hard and nonconvex for a network. Line L4 is the exact proximal step of the simple term β∥x−b∥2\beta \lVert x - b \rVert^2 together with the box: it minimizes β∥x−b∥2+12λ∥x−x^∥2\beta \lVert x - b \rVert^2 + \frac{1}{2\lambda}\lVert x - \hat{x} \rVert^2 over [0,1]d[0, 1]^d, which is coordinatewise, and so is the clip of the unconstrained minimizer. Shafahi et al. also take a forward step on the feature term and a backward step on the distance term; the formula of line L4 is the exact backward step for FF as written on this page, and the box is added here so that the poison is a valid input. The code stops early when no coordinate moves by more than a tolerance.

The poison is then given the label of bb and added to the training set; the victim trains as usual.

Example

Take d=2d = 2, the linear feature map f(x)=x1+x2f(x) = x_1 + x_2 (so h=1h = 1), the target t=(1,1)t = (1, 1), the base b=(0,0)b = (0, 0), β=1\beta = 1 and λ=0.25\lambda = 0.25. At the base, F(b)=(0−2)2+0=4F(b) = (0 - 2)^2 + 0 = 4.

The gradient of (x1+x2−2)2(x_1 + x_2 - 2)^2 at bb is 2(0−2)(1,1)=(−4,−4)2(0 - 2)(1, 1) = (-4, -4), so line L3 gives x^=(1,1)\hat{x} = (1, 1), and line L4 gives x=(1,1)/1.5=(2/3,2/3)x = (1, 1) / 1.5 = (2/3, 2/3). The next iteration gives x^=(2/3,2/3)−0.5(4/3−2)(1,1)=(1,1)\hat{x} = (2/3, 2/3) - 0.5(4/3 - 2)(1, 1) = (1, 1) again, so (2/3,2/3)(2/3, 2/3) is the fixed point, and it is the minimizer: F=(4/3−2)2+2⋅(2/3)2=4/3F = (4/3 - 2)^2 + 2 \cdot (2/3)^2 = 4/3.

The poison moves only along (1,1)(1, 1), the direction that the feature map sees; along (1,−1)(1, -1), which ff cannot see, it stays at the base. In high dimension most directions are of this kind, which is why a poison can look like its base and still have the features of the target.

Correctness

The attack has no correct output; whether the target flips is a measurement. What is proved is about the optimization.

Theorem (convergence for linear features, proved on this page). If f(x)=Axf(x) = A x and 0<λ≤1/(2∥A∥22)0 < \lambda \le 1 / (2 \lVert A \rVert_2^2), then FF has a unique minimizer x∗x^* over [0,1]d[0, 1]^d, and the iterates of lines L3 and L4 satisfy ∥xp−x∗∥≤(1+2λβ)−p∥b−x∗∥\lVert x_p - x^* \rVert \le (1 + 2\lambda\beta)^{-p} \lVert b - x^* \rVert. The proof shows that one iteration is a contraction whose fixed points are the minimizers.

Theorem (the backward step, proved on this page). Line L4 is the exact minimizer of β∥x−b∥2+12λ∥x−x^∥2\beta \lVert x - b \rVert^2 + \frac{1}{2\lambda} \lVert x - \hat{x} \rVert^2 over the box.

Heuristic (ReLU features). For a network, ∥f(x)−f(t)∥2\lVert f(x) - f(t) \rVert^2 is not convex, so the method finds a point with a lower objective, not a global minimum. On each region where the ReLU pattern is fixed the term is a convex quadratic; the tests check that the poison lowers FF and stays in the box.

Heuristic (why the target flips). A model that fits the poison with the label of bb must give the base class to a region of feature space that contains f(t)f(t). Shafahi et al. report that one poison was enough in most of their transfer learning trials with a frozen feature extractor, and that end-to-end training needed many poisons and a faint blend of the target into each base. Both are measurements, not theorems.

Proof: The backward step, the fixed points and the linear convergence of forward-backward splitting for the poison objective with linear featuresfull

Setting. F(x)=h(x)+g(x)F(x) = h(x) + g(x) over Rd\mathbb{R}^d, with the feature term h(x)=∥f(x)−f(t)∥2h(x) = \lVert f(x) - f(t) \rVert^2 and g(x)=β∥x−b∥2+ι(x)g(x) = \beta \lVert x - b \rVert^2 + \iota(x), where ι\iota is 00 on the box B=[0,1]dB = [0, 1]^d and +∞+\infty outside, β>0\beta > 0 and b∈Bb \in B. One iteration of lines L3 and L4 is T(x)=P(x−λ∇h(x))T(x) = P(x - \lambda \nabla h(x)) with P(u)=clip⁡B((u+c b)/(1+c))P(u) = \operatorname{clip}_B\big((u + c\, b)/(1 + c)\big) and c=2λβc = 2\lambda\beta.

Claim 1 (the backward step). For every uu, P(u)P(u) is the unique minimizer over BB of qu(x)=β∥x−b∥2+12λ∥x−u∥2q_u(x) = \beta \lVert x - b \rVert^2 + \frac{1}{2\lambda}\lVert x - u \rVert^2.

Proof. quq_u is a sum over coordinates of β(xj−bj)2+12λ(xj−uj)2\beta (x_j - b_j)^2 + \frac{1}{2\lambda}(x_j - u_j)^2, and BB is a product of intervals, so the problem splits into dd problems in one variable. Each is a strictly convex quadratic with derivative 2β(xj−bj)+(xj−uj)/λ2\beta(x_j - b_j) + (x_j - u_j)/\lambda, which is zero at mj=(uj+2λβ bj)/(1+2λβ)m_j = (u_j + 2\lambda\beta\, b_j)/(1 + 2\lambda\beta). A strictly convex function of one variable decreases up to mjm_j and increases after it, so its minimizer on [0,1][0, 1] is mjm_j clipped to [0,1][0, 1]. □\square

Claim 2 (fixed points are minimizers). Let hh be convex and differentiable. Then x=T(x)x = T(x) if and only if xx minimizes FF over BB.

Proof. By Claim 1, x=T(x)x = T(x) means that xx minimizes the convex function g(z)+12λ∥z−(x−λ∇h(x))∥2g(z) + \frac{1}{2\lambda}\lVert z - (x - \lambda \nabla h(x)) \rVert^2, that is, 0∈∂g(x)+1λ(x−x+λ∇h(x))=∂g(x)+∇h(x)0 \in \partial g(x) + \frac{1}{\lambda}\big(x - x + \lambda \nabla h(x)\big) = \partial g(x) + \nabla h(x). Since hh is differentiable, ∂F(x)=∇h(x)+∂g(x)\partial F(x) = \nabla h(x) + \partial g(x), so this says 0∈∂F(x)0 \in \partial F(x), which for the convex FF means that xx is a minimizer. □\square

Claim 3 (linear convergence for linear features). Let f(x)=Axf(x) = A x and 0<λ≤1/(2∥A∥22)0 < \lambda \le 1/(2\lVert A \rVert_2^2). Then FF has a unique minimizer x∗x^* over BB, and the iterates x0=bx_0 = b, xp+1=T(xp)x_{p+1} = T(x_p) satisfy

∥xp−x∗∥≤(1+2λβ)−p ∥b−x∗∥.\lVert x_p - x^* \rVert \le (1 + 2\lambda\beta)^{-p}\, \lVert b - x^* \rVert .

Proof. Here h(x)=∥A(x−t)∥2h(x) = \lVert A(x - t) \rVert^2 is convex with ∇h(x)=2A⊤A(x−t)\nabla h(x) = 2A^\top A (x - t). The forward map G(x)=x−λ∇h(x)G(x) = x - \lambda\nabla h(x) has G(x)−G(y)=(I−2λA⊤A)(x−y)G(x) - G(y) = (I - 2\lambda A^\top A)(x - y). The symmetric matrix I−2λA⊤AI - 2\lambda A^\top A has the eigenvalues 1−2λσi21 - 2\lambda\sigma_i^2, where the σi2≤∥A∥22\sigma_i^2 \le \lVert A \rVert_2^2 are the eigenvalues of A⊤AA^\top A, so they lie in [0,1][0, 1] and ∥G(x)−G(y)∥≤∥x−y∥\lVert G(x) - G(y) \rVert \le \lVert x - y \rVert. The map clip⁡B\operatorname{clip}_B is the Euclidean projection onto a convex set and is 11-Lipschitz, so ∥P(u)−P(v)∥≤∥u−v∥/(1+c)\lVert P(u) - P(v) \rVert \le \lVert u - v \rVert / (1 + c). Hence T=P∘GT = P \circ G is a contraction with factor r=1/(1+2λβ)<1r = 1/(1 + 2\lambda\beta) < 1 on the closed set BB, which TT maps into itself. By the Banach fixed point theorem it has exactly one fixed point x∗x^*, which by Claim 2 is a minimizer, and every minimizer is a fixed point, so the minimizer is unique. Finally ∥xp+1−x∗∥=∥T(xp)−T(x∗)∥≤r∥xp−x∗∥\lVert x_{p+1} - x^* \rVert = \lVert T(x_p) - T(x^*) \rVert \le r \lVert x_p - x^* \rVert, and induction gives the bound. □\square

Claim 4 (the conditions that the tests check). With f(x)=Axf(x) = A x, ∇F(x)=2A⊤A(x−t)+2β(x−b)\nabla F(x) = 2A^\top A(x - t) + 2\beta(x - b) on BB. A point x∈Bx \in B is the minimizer if and only if, for each jj, ∂jF(x)≥0\partial_j F(x) \ge 0 when xj=0x_j = 0, ∂jF(x)≤0\partial_j F(x) \le 0 when xj=1x_j = 1, and ∂jF(x)=0\partial_j F(x) = 0 when 0<xj<10 < x_j < 1. If the solution x∘x^\circ of (A⊤A+βI)x=A⊤At+βb(A^\top A + \beta I)x = A^\top A t + \beta b lies in BB, then x∗=x∘x^* = x^\circ.

Proof. FF is convex and differentiable on a neighborhood of BB (where ι=0\iota = 0), so xx minimizes it over BB if and only if ⟨∇F(x),y−x⟩≥0\langle \nabla F(x), y - x \rangle \ge 0 for every y∈By \in B. Taking yy equal to xx except in coordinate jj shows that the condition implies the three cases; conversely the three cases make every term ∂jF(x)(yj−xj)\partial_j F(x)(y_j - x_j) of the inner product nonnegative. The matrix A⊤A+βIA^\top A + \beta I is positive definite, so x∘x^\circ is the unique zero of ∇F\nabla F, and it minimizes FF over Rd\mathbb{R}^d; if it is in BB it minimizes FF over BB, and by uniqueness it is x∗x^*. □\square

Claim 5 (the gradient of the ReLU features). Let f(x)=relu⁡(Wx+c1)f(x) = \operatorname{relu}(W x + c_1) and let xx have no pre-activation equal to 00. Then near xx, f(x)=D(Wx+c1)f(x) = D(Wx + c_1) with the fixed diagonal 0/10/1 matrix DD of the active units, hh is a convex quadratic there, and ∇h(x)=2W⊤D(f(x)−f(t))\nabla h(x) = 2W^\top D (f(x) - f(t)), which is what relu_collision_grad returns.

Proof. Each pre-activation is continuous, so its sign is constant near xx, and so is DD. Then ff is affine near xx, h(x)=∥D(Wx+c1)−f(t)∥2h(x) = \lVert D(Wx + c_1) - f(t) \rVert^2 is a convex quadratic, and the chain rule gives ∇h(x)=2W⊤D⊤(D(Wx+c1)−f(t))=2W⊤D(f(x)−f(t))\nabla h(x) = 2 W^\top D^\top (D(Wx + c_1) - f(t)) = 2W^\top D(f(x) - f(t)), since D⊤=DD^\top = D and D(Wx+c1)=f(x)D(Wx + c_1) = f(x) near xx. The code sums 2(prei−fi(t))Wi2(\text{pre}_i - f_i(t)) W_i over the active units ii, which is the same vector, because prei=fi(x)\text{pre}_i = f_i(x) for an active unit. □\square

The algorithm. Line L1 starts at b∈Bb \in B; lines L3 and L4 are TT; by Claim 3 the iterates converge linearly to the unique minimizer for linear features and a step in the allowed range, and the tests check Claim 4 on the result. For ReLU features hh is not convex, Claim 2 does not apply, and nothing is claimed beyond Claim 5 and Claim 1; that the target flips after training is a measurement. ■\blacksquare

Complexity

  • One iteration. One gradient of the feature term, O(hd)O(h d) for a linear map or for one ReLU layer, plus O(d)O(d) for line L4.
  • Total. O(phd)O(p h d) for pp iterations; for a deep network replace hdh d by the cost of one backward pass.
  • Space. O(d+h)O(d + h).

Properties

  • Clean labels. Every poison has the label a human would give it, so label checks do not find it.
  • Targeted and quiet. Only the target is meant to change; the accuracy on other inputs barely moves, so a drop in test accuracy does not reveal the attack.
  • Needs the features. The method uses ff; against an unknown model it must use a substitute, and the poison may not transfer.
  • Depends on dimension. The poison stays near its base only when many input directions are invisible to ff, as in images. In the 8-dimensional model of the tests it does not stay near (see Pitfalls).

Variants and improvements

  • Several poisons and blending. For end-to-end training, Shafahi et al. use many poisons and blend a faint copy of the target into each base, so that the features cannot separate them again during training.
  • Convex polytope. Zhu et al. (2019) craft poisons whose features surround the target, which transfers better to feature extractors the attacker does not know.
  • Gradient matching. Geiping et al. (2021) choose poisons whose training gradient matches the gradient that would flip the target, for models trained from scratch.
  • Backdoors with clean labels. Poisons with correct labels can also plant a trigger; see backdoor-attack.
  • Defenses. Deep k-NN (Peri et al. 2020) removes training points whose label disagrees with their neighbors in feature space, where a poison sits among target-class points. Filtering by spectral signatures looks for a group of poisons that share a direction. Training with DP-SGD limits the effect of any few points on the model. Checking the provenance of training data removes the capability itself.

When to use it

Use it to measure how much one or a few correctly labeled points can change a model that you own, on synthetic data or on data you control, and to test a defense that filters training data. It shows that label checks are not enough. For untargeted damage to accuracy use SVM poisoning or its relatives; for test-time attacks see evasion attacks.

Pitfalls

  • Low dimension. In the tests, with 8 inputs and 4 features, the poison moves about 65 percent of the way from its base to the target: there are too few invisible directions to hide the change. The method needs high-dimensional inputs, and a small model shows only the mechanism.
  • One poison may not flip a linear head. In the tests one poison lowers the score of the target but flips none of the 10 targets, because a linear head on 4 features cannot give one point its own region. The paper reports flips with the much wider features of an image network.
  • The weight beta. A large β\beta keeps the poison at the base and does nothing; a small one lets it become the target, which a human would then label as the target's class. The useful value depends on the scales of the input and of the features.
  • The step. A step λ\lambda above 1/L1/L, where LL bounds the curvature of the feature term, can make the iterates oscillate.
  • Retraining the features. If the victim also trains the feature extractor, the features move and the collision of one poison is lost.

Implementations

The code runs only on feature maps and data that the tests build from a fixed seed: a random linear map, and the hidden layer of a seeded tiny_relu_net from the shared helper mlkit, on inputs in [0,1]d[0, 1]^d with d≤8d \le 8; it never reads a real data set or touches a real model. The tests check the example, check on 500 random linear problems that the poison satisfies the optimality conditions of the box-constrained problem and equals the closed-form solution of (A⊤A+βI)x=A⊤At+βb(A^\top A + \beta I) x = A^\top A t + \beta b (by Gaussian elimination) whenever that solution is in the box, check the gradient of the ReLU features against finite differences on 500 points, and check that the poison lowers FF on 100 random networks. They then measure a tiny transfer learning model with seed 7501: frozen ReLU features of width 4 on 8 inputs, a logistic head retrained on 40 points plus one poison, and 10 correctly classified targets with mean score 2.02.0. One poison lowers the score of its target by 0.440.44 on average, and the unmodified base by 0.030.03; no target flips.

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.

clean_label_poisoning.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/clean-label-poisoning/. The authors are listed in prov/9VQR2S.jsonl.

"""Clean-label poisoning by forward-backward splitting (Shafahi et al. 2018), as an abstract model on synthetic data.

The poison x minimizes F(x) = ||f(x) - f(t)||^2 + beta ||x - b||^2 over the box [0, 1]^d,
where f is a feature map, t the target input and b the base input. The feature maps
here are a fixed linear map and the hidden layer of a seeded tiny_relu_net from mlkit;
the tests build every input from a fixed seed. Nothing here reads a real data set or
touches a real model.
"""

import math
from typing import Callable, Sequence

from mlkit import Net, Vector, dot

GradFn = Callable[[Sequence[float]], Vector]


def linear_features(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """f(x) = A x for a k by d matrix A. Cost O(k d)."""
    return [dot(row, x) for row in a]


def linear_collision_grad(a: Sequence[Sequence[float]], target: Sequence[float]) -> GradFn:
    """The gradient map x -> 2 A^T (A x - A t) of ||A x - A t||^2. Cost O(k d) per call."""
    ft = linear_features(a, target)

    def grad(x: Sequence[float]) -> Vector:
        r = [u - v for u, v in zip(linear_features(a, x), ft, strict=True)]
        return [2.0 * math.fsum(r[i] * a[i][j] for i in range(len(a))) for j in range(len(x))]

    return grad


def relu_features(net: Net, x: Sequence[float]) -> Vector:
    """f(x) = relu(W1 x + b1), the hidden layer of a tiny_relu_net. Cost O(h d)."""
    return [max(dot(row, x) + bi, 0.0) for row, bi in zip(net["W1"], net["b1"], strict=True)]


def relu_collision_grad(net: Net, target: Sequence[float]) -> GradFn:
    """The gradient map of ||f(x) - f(t)||^2 for the ReLU features, 2 W1^T (relu'(pre) * (f(x) - f(t))).

    The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0. Cost O(h d) per call.
    """
    ft = relu_features(net, target)

    def grad(x: Sequence[float]) -> Vector:
        g = [0.0] * len(x)
        for row, bi, fi in zip(net["W1"], net["b1"], ft, strict=True):
            pre = dot(row, x) + bi
            if pre > 0:
                c = 2.0 * (pre - fi)
                for j in range(len(x)):
                    g[j] += c * row[j]
        return g

    return grad


def objective(features: Callable[[Sequence[float]], Vector], x: Sequence[float], target: Sequence[float], base: Sequence[float], beta: float) -> float:
    """F(x) = ||f(x) - f(t)||^2 + beta ||x - b||^2. Cost: two calls of f and O(d)."""
    fx, ft = features(x), features(target)
    return math.fsum((u - v) ** 2 for u, v in zip(fx, ft, strict=True)) + beta * math.fsum(
        (u - v) ** 2 for u, v in zip(x, base, strict=True)
    )


def craft_poison(grad: GradFn, base: Sequence[float], beta: float, lam: float, steps: int, tol: float = 0.0) -> Vector:
    """Forward-backward splitting for min F over [0, 1]^d, started at the base.

    The forward step is a gradient step of size lam on the collision term; the backward
    step is the exact proximal step of beta ||x - b||^2 plus the box, which is the clip
    of (x_hat + 2 lam beta b) / (1 + 2 lam beta). Stops after steps iterations or when
    no coordinate moves by more than tol. Precondition: base in [0, 1]^d, beta > 0,
    lam > 0 (at most 1/L for a collision term whose gradient is L-Lipschitz).
    Cost O(steps (g + d)), where g is the cost of one call of grad.
    """
    x = list(base)  # @line L1
    c = 2.0 * lam * beta
    for _ in range(steps):  # @line L2
        g = grad(x)
        x_hat = [xj - lam * gj for xj, gj in zip(x, g, strict=True)]  # @line L3
        new = [min(max((h + c * bj) / (1.0 + c), 0.0), 1.0) for h, bj in zip(x_hat, base, strict=True)]  # @line L4
        moved = max(abs(u - v) for u, v in zip(new, x))
        x = new
        if moved <= tol:
            break
    return x  # @line L5
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_clean_label_poisoning.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/clean-label-poisoning/. The authors are listed in prov/9VQR2S.jsonl.

"""Tests of the forward-backward poison on a linear feature map and on the ReLU features of a seeded tiny network."""

import math
import random

from mlkit import clip01, dot, make_blobs, norm2, sub, tiny_relu_net, train_logistic
from clean_label_poisoning import (
    craft_poison,
    linear_collision_grad,
    linear_features,
    objective,
    relu_collision_grad,
    relu_features,
)


def solve(m: list[list[float]], r: list[float]) -> list[float]:
    """Gaussian elimination with partial pivoting, the independent oracle for the linear case."""
    n = len(r)
    a = [row[:] + [r[i]] for i, row in enumerate(m)]
    for col in range(n):
        piv = max(range(col, n), key=lambda i: abs(a[i][col]))
        a[col], a[piv] = a[piv], a[col]
        for i in range(col + 1, n):
            f = a[i][col] / a[col][col]
            for j in range(col, n + 1):
                a[i][j] -= f * a[col][j]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (a[i][n] - sum(a[i][j] * x[j] for j in range(i + 1, n))) / a[i][i]
    return x


def test_example_of_the_page() -> None:
    a = [[1.0, 1.0]]
    t, b = [1.0, 1.0], [0.0, 0.0]
    p1 = craft_poison(linear_collision_grad(a, t), b, 1.0, 0.25, 1)
    assert all(abs(v - 2 / 3) < 1e-12 for v in p1)
    p = craft_poison(linear_collision_grad(a, t), b, 1.0, 0.25, 50)
    assert all(abs(v - 2 / 3) < 1e-12 for v in p)
    f = lambda x: linear_features(a, x)  # noqa: E731
    assert abs(objective(f, b, t, b, 1.0) - 4.0) < 1e-12
    assert abs(objective(f, p, t, b, 1.0) - 4 / 3) < 1e-12


def test_linear_features_match_the_closed_form_and_the_box_conditions() -> None:
    rng = random.Random(7502)
    inside = 0
    for _ in range(500):
        k, d = rng.randint(1, 4), rng.randint(1, 8)
        a = [[rng.gauss(0, 1 / math.sqrt(d)) for _ in range(d)] for _ in range(k)]
        t = [rng.random() for _ in range(d)]
        b = [rng.uniform(0.2, 0.8) for _ in range(d)]
        beta = rng.uniform(0.5, 2.0)
        fro = sum(v * v for row in a for v in row)
        lam = 1 / (2 * fro)  # 2 ||A||_F^2 bounds the Lipschitz constant 2 ||A||_2^2 of the gradient
        x = craft_poison(linear_collision_grad(a, t), b, beta, lam, 400)
        assert all(0.0 <= v <= 1.0 for v in x)
        ata = [[sum(a[i][p] * a[i][q] for i in range(k)) for q in range(d)] for p in range(d)]
        g = [2 * sum(ata[p][q] * (x[q] - t[q]) for q in range(d)) + 2 * beta * (x[p] - b[p]) for p in range(d)]
        for v, gv in zip(x, g):  # the optimality conditions of a box-constrained convex problem
            if v <= 0.0:
                assert gv >= -1e-8
            elif v >= 1.0:
                assert gv <= 1e-8
            else:
                assert abs(gv) < 1e-8
        m = [[ata[p][q] + (beta if p == q else 0.0) for q in range(d)] for p in range(d)]
        r = [sum(ata[p][q] * t[q] for q in range(d)) + beta * b[p] for p in range(d)]
        free = solve(m, r)
        if all(0.0 <= v <= 1.0 for v in free):
            inside += 1
            assert max(abs(u - v) for u, v in zip(x, free)) < 1e-9
    assert inside >= 250


def test_relu_gradient_matches_finite_differences() -> None:
    rng = random.Random(7503)
    checked = 0
    while checked < 500:
        d, h = rng.randint(1, 8), rng.randint(1, 16)
        net = tiny_relu_net(rng, d, h, 2)
        x = [rng.random() for _ in range(d)]
        t = [rng.random() for _ in range(d)]
        if any(abs(dot(row, x) + bi) < 1e-3 for row, bi in zip(net["W1"], net["b1"])):
            continue  # too close to a kink for a finite difference
        checked += 1
        g = relu_collision_grad(net, t)(x)
        ft = relu_features(net, t)
        coll = lambda z: sum((u - v) ** 2 for u, v in zip(relu_features(net, z), ft))  # noqa: E731
        e = 1e-6
        for j in range(d):
            up, dn = x[:], x[:]
            up[j] += e
            dn[j] -= e
            assert abs((coll(up) - coll(dn)) / (2 * e) - g[j]) < 1e-5


def test_relu_poison_lowers_the_objective_and_stays_in_the_box() -> None:
    rng = random.Random(7504)
    for _ in range(100):
        d, h = rng.randint(2, 8), rng.randint(1, 16)
        net = tiny_relu_net(rng, d, h, 2)
        t = [rng.random() for _ in range(d)]
        b = [rng.random() for _ in range(d)]
        beta = rng.uniform(0.01, 1.0)
        lam = 1 / (2 * sum(v * v for row in net["W1"] for v in row))
        f = lambda z: relu_features(net, z)  # noqa: E731
        p = craft_poison(relu_collision_grad(net, t), b, beta, lam, 100)
        assert all(0.0 <= v <= 1.0 for v in p)
        assert objective(f, p, t, b, beta) <= objective(f, b, t, b, beta) + 1e-12


def test_one_poison_lowers_the_score_of_the_target() -> None:
    """A measurement in a tiny transfer learning model: frozen ReLU features (8 inputs, 4 features), a retrained logistic head."""
    rng = random.Random(7501)
    d, h = 8, 4
    net = tiny_relu_net(rng, d, h, 2)
    centers = [[0.35] * d, [0.65] * d]
    train = [(clip01(x), y) for x, y in make_blobs(rng, 40, d, centers, 0.15)]
    test = [(clip01(x), y) for x, y in make_blobs(rng, 40, d, centers, 0.15)]

    def head(data: list) -> tuple[list[float], float]:
        return train_logistic([(relu_features(net, x), y) for x, y in data], 200, 1.0, 0.0)

    def score(model: tuple[list[float], float], x: list[float]) -> float:
        return dot(model[0], relu_features(net, x)) + model[1]

    clean = head(train)
    targets = [x for x, y in test if y == 1 and score(clean, x) > 0][:10]
    bases = [x for x, y in train if y == 0]
    drop_poison, drop_base = [], []
    for t in targets:
        b = rng.choice(bases)
        p = craft_poison(relu_collision_grad(net, t), b, 0.05, 0.1, 200)
        assert norm2(sub(relu_features(net, p), relu_features(net, t))) < norm2(sub(relu_features(net, b), relu_features(net, t)))
        drop_poison.append(score(clean, t) - score(head(train + [(p, 0)]), t))
        drop_base.append(score(clean, t) - score(head(train + [(b, 0)]), t))
    assert len(targets) == 10
    mean_p, mean_b = sum(drop_poison) / 10, sum(drop_base) / 10
    assert mean_p >= 0.2 and mean_p >= 5 * mean_b

History

Barreno et al. (2006, 2010) named causative attacks, and Biggio, Nelson and Laskov (2012) gave the first optimized poisoning of an SVM. Koh and Liang (2017) used influence functions to change a few training inputs and flip a test prediction. Shafahi et al. (2018) gave clean-label poisoning by forward-backward splitting, Zhu et al. (2019) made it transfer with convex polytopes, and Geiping et al. (2021) scaled it to training from scratch by gradient matching. Peri et al. (2020) gave the Deep k-NN defense.

References

  1. Ali Shafahi, W. Ronny Huang, Mahyar Najibi, Octavian Suciu, Christoph Studer, Tudor Dumitras and Tom Goldstein, Poison frogs! Targeted clean-label poisoning attacks on neural networks, Advances in Neural Information Processing Systems 31 (NeurIPS) 2018, the objective (feature distance to the target plus beta times the input distance to the base), the forward-backward splitting procedure, the transfer learning experiments with a frozen feature extractor, and the end-to-end experiments with several poisons and a faint blend of the target into the base
  2. Pang Wei Koh and Percy Liang, Understanding black-box predictions via influence functions, Proceedings of the 34th International Conference on Machine Learning (ICML) 2017, training set attacks that change a few training inputs to flip the prediction on a test input
  3. Chen Zhu, W. Ronny Huang, Ali Shafahi, Hengduo Li, Gavin Taylor, Christoph Studer and Tom Goldstein, Transferable clean-label poisoning attacks on deep neural nets, Proceedings of the 36th International Conference on Machine Learning (ICML) 2019, the convex polytope attack, with poisons whose features surround the target, for transfer to unknown feature extractors
  4. Jonas Geiping, Liam Fowl, W. Ronny Huang, Wojciech Czaja, Gavin Taylor, Michael Moeller and Tom Goldstein, Witches' brew: industrial scale data poisoning via gradient matching, International Conference on Learning Representations (ICLR) 2021, clean-label poisons whose training gradient matches the gradient of the adversarial loss on the target, for training from scratch
  5. Neehar Peri, Neal Gupta, W. Ronny Huang, Liam Fowl, Chen Zhu, Soheil Feizi, Tom Goldstein and John P. Dickerson, Deep k-NN defense against clean-label data poisoning attacks, ECCV 2020 Workshops, removal of training points whose label differs from most of their nearest neighbors in feature space
  6. Battista Biggio and Fabio Roli, Wild patterns, ten years after the rise of adversarial machine learning, Pattern Recognition 84, pages 317-331, 2018, the threat model in three parts, goal, knowledge and capability

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