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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of the class it wants the target to fall into, and moves it to a poison whose features are close to while stays close to . A model trained on the poison with the label of 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 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 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 , a target , a base , a weight , a step and a number of iterations.
Output. A poison with a small value of
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 .
The algorithm
POISON(f, t, b, beta, lambda, steps)- 1
x <- b - 2
repeat steps times - 3
x_hat <- x - lambda * gradient of ||f(x) - f(t)||^2 at x (forward step) - 4
x <- clip to [0, 1]^d of (x_hat + 2 lambda beta b) / (1 + 2 lambda beta) (backward step) - 5
return 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 together with the box: it minimizes over , 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 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 and added to the training set; the victim trains as usual.
Example
Take , the linear feature map (so ), the target , the base , and . At the base, .
The gradient of at is , so line L3 gives , and line L4 gives . The next iteration gives again, so is the fixed point, and it is the minimizer: .
The poison moves only along , the direction that the feature map sees; along , which 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 and , then has a unique minimizer over , and the iterates of lines L3 and L4 satisfy . 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 over the box.
Heuristic (ReLU features). For a network, 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 and stays in the box.
Heuristic (why the target flips). A model that fits the poison with the label of must give the base class to a region of feature space that contains . 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. over , with the feature term and , where is on the box and outside, and . One iteration of lines L3 and L4 is with and .
Claim 1 (the backward step). For every , is the unique minimizer over of .
Proof. is a sum over coordinates of , and is a product of intervals, so the problem splits into problems in one variable. Each is a strictly convex quadratic with derivative , which is zero at . A strictly convex function of one variable decreases up to and increases after it, so its minimizer on is clipped to .
Claim 2 (fixed points are minimizers). Let be convex and differentiable. Then if and only if minimizes over .
Proof. By Claim 1, means that minimizes the convex function , that is, . Since is differentiable, , so this says , which for the convex means that is a minimizer.
Claim 3 (linear convergence for linear features). Let and . Then has a unique minimizer over , and the iterates , satisfy
Proof. Here is convex with . The forward map has . The symmetric matrix has the eigenvalues , where the are the eigenvalues of , so they lie in and . The map is the Euclidean projection onto a convex set and is -Lipschitz, so . Hence is a contraction with factor on the closed set , which maps into itself. By the Banach fixed point theorem it has exactly one fixed point , which by Claim 2 is a minimizer, and every minimizer is a fixed point, so the minimizer is unique. Finally , and induction gives the bound.
Claim 4 (the conditions that the tests check). With , on . A point is the minimizer if and only if, for each , when , when , and when . If the solution of lies in , then .
Proof. is convex and differentiable on a neighborhood of (where ), so minimizes it over if and only if for every . Taking equal to except in coordinate shows that the condition implies the three cases; conversely the three cases make every term of the inner product nonnegative. The matrix is positive definite, so is the unique zero of , and it minimizes over ; if it is in it minimizes over , and by uniqueness it is .
Claim 5 (the gradient of the ReLU features). Let and let have no pre-activation equal to . Then near , with the fixed diagonal matrix of the active units, is a convex quadratic there, and , which is what relu_collision_grad returns.
Proof. Each pre-activation is continuous, so its sign is constant near , and so is . Then is affine near , is a convex quadratic, and the chain rule gives , since and near . The code sums over the active units , which is the same vector, because for an active unit.
The algorithm. Line L1 starts at ; lines L3 and L4 are ; 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 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.
Complexity
- One iteration. One gradient of the feature term, for a linear map or for one ReLU layer, plus for line L4.
- Total. for iterations; for a deep network replace by the cost of one backward pass.
- Space. .
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 ; 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 , 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 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 above , where 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 with ; 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 (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 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 . One poison lowers the score of its target by on average, and the unmodified base by ; 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.
# 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
- 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 9VQR2S Edit this page History Report an error Markdown