Algorithm Search⌘K

Algorithmadvanced

Poisoning attack on support vector machines

Also called Biggio poisoning attack.

Finds a training point that most increases an SVM's validation error by gradient ascent through the incremental SVM solution.

Time
O(p (n^2 d + k n + d s^3 + v d^2)) worst
Space
O(n^2 + v) extra
Where
d = the dimension; k = the number of SMO iterations per training; n = the number of training points; p = the number of ascent steps; s = the number of margin support vectors; v = the number of validation points
Properties
deterministicnot exactofflineiterative
Origin
Battista Biggio, Blaine Nelson, Pavel Laskov, 2012

The poisoning attack of Biggio, Nelson and Laskov (2012) is the first optimization attack on the training data of a support vector machine. The attacker adds one point (xc,yc)(x_c, y_c) to the training set and chooses xcx_c to maximize the hinge loss of the trained SVM on a validation set, by gradient ascent. The gradient goes through the training: when xcx_c moves a little and no training point changes its role (margin support vector, error vector, or neither), the dual solution changes smoothly, and the KKT conditions give its derivative by a linear solve. On this page the kernel is linear, so the SVM solution is an affine function of xcx_c on each region where the roles stay fixed. The attack is a local search with no guarantee of a global maximum; its effect is a measurement.

In plain words

An SVM learns a line that separates two classes. An attacker who can add one training point wants to put it where it hurts the line the most.

Start with a copy of a point of one class and give it the other label. Train the SVM, check how badly it does on some held out points, and work out which way to move the bad point to make that worse. Move it a step that way and repeat.

The hard part is the "which way". Moving the point changes the training, and the line moves in turn. While the same points stay on the margin, the line moves in a simple, predictable way, so the direction comes from one small system of equations. When the points on the margin change, the attack retrains and starts again from there.

The problem

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

  • Goal of the attacker. Raise the error of the SVM on clean test data. The attack is not targeted at one test point.
  • Knowledge. Full: the training set, the learning algorithm, the parameter CC and the kernel, and a validation set from the same distribution. This is a worst case for the defender.
  • Capability. Add one point with a label of the attacker's choice (in Algorithm 1, the flipped label of a cloned point), inside a box of feasible values; several points are added one at a time.

Input. Training points (xi,yi)(x_i, y_i) with yi∈{+1,−1}y_i \in \{+1, -1\}, a validation set V={(xk,yk)}V = \{(x_k, y_k)\}, the SVM parameter CC, a label ycy_c, a start xc(0)x_c^{(0)}, a step tt, a box [l,h]d[l, h]^d, a step limit and a tolerance ϵ\epsilon.

Output. A point xcx_c in the box with a large value of

L(xc)=∑k∈Vmax⁡(0, 1−ykfxc(xk)),L(x_c) = \sum_{k \in V} \max\big(0,\ 1 - y_k f_{x_c}(x_k)\big),

where fxc(x)=⟨w,x⟩+bf_{x_c}(x) = \langle w, x \rangle + b is the SVM trained on the training set plus (xc,yc)(x_c, y_c).

The SVM. The dual is min⁡α12α⊤Qα−1⊤α\min_\alpha \tfrac{1}{2}\alpha^\top Q \alpha - \mathbf{1}^\top \alpha subject to 0≤αi≤C0 \le \alpha_i \le C and ∑iyiαi=0\sum_i y_i \alpha_i = 0, with Qij=yiyj⟨xi,xj⟩Q_{ij} = y_i y_j \langle x_i, x_j \rangle and w=∑iαiyixiw = \sum_i \alpha_i y_i x_i. The solution splits the points into the margin support vectors SS (0<αi<C0 < \alpha_i < C, yif(xi)=1y_i f(x_i) = 1), the error vectors EE (αi=C\alpha_i = C, yif(xi)≤1y_i f(x_i) \le 1) and the rest RR (αi=0\alpha_i = 0, yif(xi)≥1y_i f(x_i) \ge 1).

The algorithm

  1. SVM-POISON(training set, V, C, y_c, x_c0, t, box, steps, epsilon)
  2. 1x_c <- x_c0
  3. 2for p = 1 to steps do
  4. 3train the SVM on the training set plus (x_c, y_c); this gives alpha, b, S, E, R
  5. 4u <- gradient of L at x_c, from the KKT system on S with S, E, R held fixed
  6. 5x_c <- the projection onto the box of x_c + t u / ||u||
  7. 6stop if L rose by less than epsilon since the last step
  8. 7return x_c

Line L4. Write K=(QSSySyS⊤0)K = \begin{pmatrix} Q_{SS} & y_S \\ y_S^\top & 0 \end{pmatrix}. If the attack point is not in SS, its αc\alpha_c is 00 or CC and does not move, and only the column QScQ_{Sc}, with entries ysyc⟨xs,xc⟩y_s y_c \langle x_s, x_c \rangle, depends on xcx_c. The derivative of the KKT equations gives, for each coordinate jj,

∂(αS,b)∂xc,j=−K−1(αcycyS⊙xS,j0),∂w∂xc=∑s∈Sysxs(∂αs∂xc) ⁣⊤+αcycI,\frac{\partial (\alpha_S, b)}{\partial x_{c,j}} = -K^{-1} \begin{pmatrix} \alpha_c y_c y_S \odot x_{S,j} \\ 0 \end{pmatrix}, \qquad \frac{\partial w}{\partial x_c} = \sum_{s \in S} y_s x_s \Big(\frac{\partial \alpha_s}{\partial x_c}\Big)^{\!\top} + \alpha_c y_c I,

and then ∇L=−∑k:ykf(xk)<1yk((∂w/∂xc)⊤xk+∇b)\nabla L = -\sum_{k : y_k f(x_k) < 1} y_k \big( (\partial w / \partial x_c)^\top x_k + \nabla b \big). This is the linear kernel case of equation (10) of Biggio et al. In the code, line L3 runs SMO and then solves the KKT equations exactly on the sets it found, by Gaussian elimination.

Example

Two classes in the plane, C=0.1C = 0.1: training points (−2,0),(−2,1)(-2, 0), (-2, 1) with label −1-1 and (2,0),(2,1)(2, 0), (2, 1) with label +1+1, and validation points (±1,0),(±1,1)(\pm 1, 0), (\pm 1, 1) with the sign of the first coordinate as label. The clean SVM is w=(0.5,0)w = (0.5, 0), b=0b = 0: every validation point has margin 0.50.5, so L=4⋅0.5=2L = 4 \cdot 0.5 = 2 and the error is 00.

The attacker adds xc=(a,0.5)x_c = (a, 0.5) with label +1+1, starting at a=−2a = -2. The solution has αc=C\alpha_c = C, the two points with label +1+1 in SS and the other three in EE. The constraint ∑yiαi=0\sum y_i \alpha_i = 0 and the two margin equations give

w=(0.6+0.1a, 0),b=−0.2−0.2a,L(a)=2.4−0.4(a+2),w = (0.6 + 0.1 a,\ 0), \qquad b = -0.2 - 0.2 a, \qquad L(a) = 2.4 - 0.4 (a + 2),

so the gradient is (−0.4,0)(-0.4, 0): move left. With t=0.5t = 0.5 in the box [−5,5]2[-5, 5]^2 the losses are 2.4,2.6,…,3.62.4, 2.6, \ldots, 3.6, and the attack stops at xc=(−5,0.5)x_c = (-5, 0.5), where LL no longer rises. The clean points with label −1-1 at first coordinate −1-1 have margin 0.8+0.3a0.8 + 0.3 a, which is negative for a<−8/3a < -8/3, so from the third step on, half of the validation set is misclassified.

Correctness

Theorem (the gradient, proved on this page). Fix a solution with sets S,E,RS, E, R, the attack point not in SS, S≠∅S \neq \emptyset, and KK nonsingular. On the region of xcx_c where these sets give a solution of the KKT conditions, (αS,b)(\alpha_S, b) and ww are affine functions of xcx_c; where also no validation point has ykf(xk)=1y_k f(x_k) = 1, LL is differentiable and its gradient is the formula of line L4. The proof differentiates the KKT equations; the KKT conditions are sufficient for the convex dual, so the solution of the equations is the SVM.

Theorem (flat regions, proved on this page). With a linear kernel, if ∣S∣=d+1\lvert S \rvert = d + 1 and the points of SS are affinely independent, the d+1d + 1 equations ys(⟨w,xs⟩+b)=1y_s(\langle w, x_s \rangle + b) = 1 fix ww and bb, so the gradient of LL is 00 on the region. Algorithm 1 then stops.

What is not proved. LL is not concave in xcx_c, so gradient ascent finds a local maximum at best, and a fixed step may overshoot. Biggio et al. report that the attack finds good local maxima in their experiments; this is a measurement.

Proof: The gradient of the validation hinge loss of a linear SVM in one training point, with the active sets held fixedfull

Setting. Training points x1,…,xmx_1, \ldots, x_m with labels yi∈{+1,−1}y_i \in \{+1, -1\}, of which the last, c=mc = m, is the attack point. Qij=yiyj⟨xi,xj⟩Q_{ij} = y_i y_j \langle x_i, x_j \rangle. The dual is min⁡12α⊤Qα−1⊤α\min \tfrac{1}{2}\alpha^\top Q \alpha - \mathbf{1}^\top \alpha over 0≤αi≤C0 \le \alpha_i \le C, ∑iyiαi=0\sum_i y_i \alpha_i = 0; it is a convex quadratic program, so the KKT conditions are necessary and sufficient. With gi=yi(⟨w,xi⟩+b)g_i = y_i(\langle w, x_i \rangle + b) and w=∑iαiyixiw = \sum_i \alpha_i y_i x_i they read: ∑iyiαi=0\sum_i y_i \alpha_i = 0, and for each ii, either 0<αi<C0 < \alpha_i < C and gi=1g_i = 1 (set SS), or αi=C\alpha_i = C and gi≤1g_i \le 1 (set EE), or αi=0\alpha_i = 0 and gi≥1g_i \ge 1 (set RR). The primal ww is unique, and bb is unique when S≠∅S \ne \emptyset.

Claim 1 (an affine solution on a region). Fix a partition of the points into SS, EE, RR and {c}\{c\}, with S≠∅S \neq \emptyset, and fix αc∈{0,C}\alpha_c \in \{0, C\}; so cc is an error vector or a rest point, but it is listed apart from EE and RR. Let K=(QSSySyS⊤0)K = \begin{pmatrix} Q_{SS} & y_S \\ y_S^\top & 0 \end{pmatrix} and assume KK is nonsingular. For xc∈Rdx_c \in \mathbb{R}^d define (αS(xc),b(xc))(\alpha_S(x_c), b(x_c)) as the solution of

K(αSb)=(1−QSE C1−QSc(xc) αc− yE⊤C1−ycαc),(1)K \begin{pmatrix} \alpha_S \\ b \end{pmatrix} = \begin{pmatrix} \mathbf{1} - Q_{SE}\, C\mathbf{1} - Q_{Sc}(x_c)\, \alpha_c \\ -\, y_E^\top C\mathbf{1} - y_c \alpha_c \end{pmatrix}, \tag{1}

with αE=C\alpha_E = C, αR=0\alpha_R = 0, and w(xc)=∑iαiyixiw(x_c) = \sum_{i} \alpha_i y_i x_i. Let UU be the set of xcx_c where these values satisfy the KKT inequalities (0<αs<C0 < \alpha_s < C on SS, gi≤1g_i \le 1 on EE, gi≥1g_i \ge 1 on RR, including i=ci = c). Then on UU the SVM solution is (w(xc),b(xc))(w(x_c), b(x_c)), and αS\alpha_S, bb and ww are affine in xcx_c.

Proof. The rows of (1) for s∈Ss \in S say ∑jQsjαj+ysb=1\sum_j Q_{sj}\alpha_j + y_s b = 1, which is gs=1g_s = 1; the last row is ∑iyiαi=0\sum_i y_i \alpha_i = 0. So on UU all KKT conditions hold, and by sufficiency the point is optimal; since ww is unique and bb is unique when S≠∅S \ne \emptyset, it is the SVM solution. The matrix KK uses only QSSQ_{SS} and ySy_S, which do not involve xcx_c because c∉Sc \notin S. On the right side, only QSc(xc)Q_{Sc}(x_c) depends on xcx_c, and its entries ysyc⟨xs,xc⟩y_s y_c \langle x_s, x_c \rangle are linear in xcx_c. So (αS,b)=K−1(right side)(\alpha_S, b) = K^{-1}(\text{right side}) is affine in xcx_c. Finally w=∑s∈Sαsysxs+C∑e∈Eyexe+αcycxcw = \sum_{s \in S} \alpha_s y_s x_s + C\sum_{e \in E} y_e x_e + \alpha_c y_c x_c, a sum of affine functions. □\square

Claim 2 (the derivative). On UU, for each coordinate jj,

∂∂xc,j(αSb)=−K−1((αcycysxs,j)s∈S0),∂w∂xc=∑s∈Sysxs(∂αs∂xc) ⁣⊤+αcycI.\frac{\partial}{\partial x_{c,j}} \begin{pmatrix} \alpha_S \\ b \end{pmatrix} = -K^{-1}\begin{pmatrix} \big(\alpha_c y_c y_s x_{s,j}\big)_{s \in S} \\ 0 \end{pmatrix}, \qquad \frac{\partial w}{\partial x_c} = \sum_{s \in S} y_s x_s \Big(\frac{\partial \alpha_s}{\partial x_c}\Big)^{\!\top} + \alpha_c y_c I .

Proof. Differentiate (1) in xc,jx_{c,j}. KK is constant, and the derivative of the row ss of the right side is −αc ∂Qsc/∂xc,j=−αcysycxs,j-\alpha_c\, \partial Q_{sc}/\partial x_{c,j} = -\alpha_c y_s y_c x_{s,j}; the last row is constant. Multiply by K−1K^{-1}. For ww, the terms of EE are constant, the term αsysxs\alpha_s y_s x_s has derivative ysxs(∂αs/∂xc)⊤y_s x_s (\partial \alpha_s / \partial x_c)^\top, and αcycxc\alpha_c y_c x_c has derivative αcycI\alpha_c y_c I because αc\alpha_c is constant. □\square

Claim 3 (the gradient of LL). Let V+={k:ykf(xk)<1}V^+ = \{k : y_k f(x_k) < 1\} and assume no validation point has ykf(xk)=1y_k f(x_k) = 1. Then near such an xcx_c in the interior of UU, L(xc)=∑k∈V+(1−yk(⟨w(xc),xk⟩+b(xc)))L(x_c) = \sum_{k \in V^+} \big(1 - y_k(\langle w(x_c), x_k \rangle + b(x_c))\big) with V+V^+ fixed, and

∇L=−∑k∈V+yk((∂w∂xc) ⁣⊤xk+∇b),\nabla L = -\sum_{k \in V^+} y_k \Big( \Big(\frac{\partial w}{\partial x_c}\Big)^{\!\top} x_k + \nabla b \Big),

which is what poison_gradient computes.

Proof. Each ykf(xk)y_k f(x_k) is a continuous (affine) function of xcx_c by Claim 1, so a strict inequality ykf(xk)≠1y_k f(x_k) \ne 1 holds near xcx_c, and the set V+V^+ does not change there. On that neighborhood LL is a finite sum of affine functions, and the chain rule with Claim 2 gives the formula. Since LL is affine on the neighborhood, central finite differences inside it equal the gradient up to rounding, which the tests use. □\square

Claim 4 (flat regions). If moreover ∣S∣=d+1\lvert S \rvert = d + 1 and the vectors (xs,1)∈Rd+1(x_s, 1) \in \mathbb{R}^{d+1}, s∈Ss \in S, are linearly independent, then ww and bb are constant on UU, and ∇L=0\nabla L = 0.

Proof. On UU, the d+1d + 1 equations ys(⟨w,xs⟩+b)=1y_s(\langle w, x_s \rangle + b) = 1 for s∈Ss \in S hold, and they form a linear system in (w,b)∈Rd+1(w, b) \in \mathbb{R}^{d+1} whose matrix has the rows ys(xs,1)y_s (x_s, 1), which is nonsingular by the hypothesis. Its right side is 1\mathbf{1}, which does not depend on xcx_c, and no point of SS is the attack point, so the unique solution (w,b)(w, b) does not depend on xcx_c. Then LL is constant near xcx_c. □\square

The algorithm. Line L5 moves xcx_c along ∇L/∥∇L∥\nabla L / \lVert \nabla L \rVert, which is the direction of fastest increase of the affine function LL on the current region, and projects onto the box. Nothing more is claimed: when the step leaves the region the sets change, LL may fall, and line L6 stops; LL is not concave, so the result is not a global maximum. ■\blacksquare

Complexity

  • Time per step. Training costs O(n2d)O(n^2 d) for QQ and O(kn)O(k n) for kk SMO iterations; the exact solve on SS costs O(s3)O(s^3). The gradient solves KK for dd right sides, O(ds3)O(d s^3) (or O(s3+ds2)O(s^3 + d s^2) with one factorization), and the validation sum costs O(vd2)O(v d^2). The incremental SVM of Cauwenberghs and Poggio updates the solution in place of a full retraining.
  • Total. pp steps, so O(p(n2d+kn+ds3+vd2))O(p (n^2 d + k n + d s^3 + v d^2)).
  • Space. O(n2)O(n^2) for QQ and O(v)O(v) for the validation set.

Properties

  • One point at a time. Several attack points are found one after another, each with the previous ones in the training set.
  • Needs full knowledge. The gradient needs the training set and the validation set. An attacker with less knowledge must estimate them, for example from a substitute data set.
  • Kernels. Equation (10) of Biggio et al. holds for any differentiable kernel, so the attack works in input space with a nonlinear kernel. The code covers the linear kernel only.

Variants and improvements

  • Bilevel poisoning. Mei and Zhu (2015) wrote optimal training set attacks as a bilevel program, with the learner as the inner problem, and solved it through its KKT conditions for several convex learners.
  • Back-gradient poisoning. Munoz-Gonzalez et al. (2017) replaced the KKT solve by differentiation through the steps of gradient descent, which reaches neural networks.
  • Certified bounds. Steinhardt, Koh and Liang (2017) bound the loss that any poisoning of a fixed fraction can cause against an outlier removal defense, for linear models.
  • Targeted poisoning. Clean-label poisoning aims at one test point, and a backdoor at inputs with a trigger.

When to use it

Use it to measure the worst case robustness of an SVM, or of another convex learner, to a few added points, in a setting where the attacker could know the training data. It is a tool for evaluation on synthetic or owned data, not a defense. For deep networks use back-gradient methods; for a guarantee in place of a measurement use certified bounds. Defenses that remove outliers, such as spectral signatures for a group of poisoned points, do not target this attack.

Pitfalls

  • Flat regions with a linear kernel. In low dimension the margin set often has d+1d + 1 points, the gradient is 00, and the attack does not move. The example of the tests in d=2d = 2 shows this; in d=8d = 8 with 15 points per class the attack moves.
  • The attack point on the margin. If xcx_c is a margin support vector, αc\alpha_c moves too, and the formula of line L4 does not apply. Start from a point deep in the other class, where αc=C\alpha_c = C.
  • Sets that change. The gradient holds only while SS, EE and RR stay fixed. A large step crosses into another region, and LL may fall; line L6 stops there.
  • An inexact solver. SMO stops at a tolerance, so α\alpha is close but not exact, and K−1K^{-1} amplifies the error. The code solves the KKT equations exactly on the sets that SMO finds and checks them.

Implementations

The code runs only on a linear SVM and on data that the tests build from a fixed seed, two Gaussian blobs in at most 8 dimensions; it never reads a real data set or a deployed model. The tests check the SVM on 500 random problems by a duality certificate (a feasible α\alpha whose dual value equals the primal value of (w,b)(w, b) is optimal, by weak duality), check the gradient against central finite differences where the sets do not change, check the example and the flat region, and measure the attack: on four seeds with the means and covariance of Biggio et al. but d=8d = 8 and 15 points per class, one point raises the validation error from 5.0, 5.75, 4.5 and 7.0 percent to 21.0, 12.0, 11.5 and 7.75 percent.

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.

svm_poisoning_attack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svm-poisoning-attack/. The authors are listed in prov/VZRNHS.jsonl.

"""The poisoning attack of Biggio, Nelson and Laskov (2012) on a linear soft-margin SVM, as an abstract model.

The tests build every training set and validation set from a fixed seed (two Gaussian
blobs in a few dimensions). Nothing here reads a real data set or a deployed model.
Labels are +1 and -1. The SVM is the dual problem

    min_a  1/2 a^T Q a - 1^T a   subject to  0 <= a_i <= C  and  sum_i y_i a_i = 0,

with Q_ij = y_i y_j <x_i, x_j>, solved by SMO and then made exact on its active set.
"""

import math
from dataclasses import dataclass
from typing import Sequence

Vector = list[float]
Matrix = list[list[float]]


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


def solve(a: Matrix, rhs: Vector) -> Vector:
    """Solve a x = rhs by Gaussian elimination with partial pivoting. Raises ValueError if a is singular. Cost O(m^3)."""
    m = len(a)
    aug = [list(a[i]) + [rhs[i]] for i in range(m)]
    scale = max((abs(x) for row in a for x in row), default=0.0)
    for col in range(m):
        piv = max(range(col, m), key=lambda r: abs(aug[r][col]))
        if abs(aug[piv][col]) <= 1e-12 * max(scale, 1.0):
            raise ValueError("singular system")
        aug[col], aug[piv] = aug[piv], aug[col]
        for r in range(m):
            if r != col and aug[r][col] != 0.0:
                f = aug[r][col] / aug[col][col]
                for c in range(col, m + 1):
                    aug[r][c] -= f * aug[col][c]
    return [aug[i][m] / aug[i][i] for i in range(m)]


@dataclass
class Svm:
    """A trained linear SVM: dual variables, weights w, bias b, and the index sets of the solution."""

    alpha: Vector
    w: Vector
    b: float
    margin: list[int]  # S: 0 < alpha < C, so y f(x) = 1
    error: list[int]  # E: alpha = C, so y f(x) <= 1
    rest: list[int]  # R: alpha = 0, so y f(x) >= 1


def _sets(alpha: Sequence[float], c: float, eps: float) -> tuple[list[int], list[int], list[int]]:
    s, e, r = [], [], []
    for i, a in enumerate(alpha):
        (r if a <= eps else e if a >= c - eps else s).append(i)
    return s, e, r


def _finish(xs: Sequence[Sequence[float]], ys: Sequence[int], alpha: Vector, b: float, c: float) -> Svm:
    d = len(xs[0])
    w = [math.fsum(alpha[i] * ys[i] * xs[i][j] for i in range(len(xs))) for j in range(d)]
    s, e, r = _sets(alpha, c, 1e-9 * c)
    return Svm(alpha, w, b, s, e, r)


def kkt_violation(xs: Sequence[Sequence[float]], ys: Sequence[int], m: Svm, c: float) -> float:
    """The largest violation of the KKT conditions of m, in units of the margin. Cost O(n d)."""
    worst = abs(math.fsum(a * y for a, y in zip(m.alpha, ys)))
    for i, (x, y) in enumerate(zip(xs, ys)):
        g = y * (dot(m.w, x) + m.b)
        a = m.alpha[i]
        worst = max(worst, -a, a - c)
        if i in m.margin:
            worst = max(worst, abs(g - 1.0))
        elif i in m.error:
            worst = max(worst, g - 1.0)
        else:
            worst = max(worst, 1.0 - g)
    return worst


def _polish(xs: Sequence[Sequence[float]], ys: Sequence[int], alpha: Vector, c: float) -> tuple[Vector, float] | None:
    """Solve the KKT equations exactly on the active sets that alpha suggests; None if they do not hold."""
    n = len(xs)
    s, e, _ = _sets(alpha, c, 1e-6 * c)
    if not s:
        return None
    fixed = [c if i in e else 0.0 for i in range(n)]
    k = len(s)
    a = [[ys[p] * ys[q] * dot(xs[p], xs[q]) for q in s] + [float(ys[p])] for p in s]
    a.append([float(ys[q]) for q in s] + [0.0])
    rhs = [1.0 - math.fsum(ys[p] * ys[j] * dot(xs[p], xs[j]) * fixed[j] for j in e) for p in s]
    rhs.append(-math.fsum(ys[j] * fixed[j] for j in e))
    try:
        sol = solve(a, rhs)
    except ValueError:
        return None
    new = fixed[:]
    for t, p in enumerate(s):
        new[p] = sol[t]
    b = sol[k]
    m = _finish(xs, ys, new, b, c)
    m.margin, m.error = s, e
    m.rest = [i for i in range(n) if i not in s and i not in e]
    if kkt_violation(xs, ys, m, c) > 1e-9:
        return None
    return new, b


def train_svm(xs: Sequence[Sequence[float]], ys: Sequence[int], c: float, tol: float = 1e-10, max_iter: int = 200000) -> Svm:
    """Train a linear soft-margin SVM by SMO with the maximal violating pair, then solve its active set exactly.

    Precondition: both labels occur and c > 0. Cost O(max_iter n + n^2 d) for SMO, and O(n^3) for the exact solve.
    """
    n = len(xs)
    q = [[ys[i] * ys[j] * dot(xs[i], xs[j]) for j in range(n)] for i in range(n)]
    alpha = [0.0] * n
    grad = [-1.0] * n  # Q alpha - 1
    for _ in range(max_iter):
        up = [t for t in range(n) if (ys[t] > 0 and alpha[t] < c) or (ys[t] < 0 and alpha[t] > 0)]
        low = [t for t in range(n) if (ys[t] > 0 and alpha[t] > 0) or (ys[t] < 0 and alpha[t] < c)]
        i = max(up, key=lambda t: -ys[t] * grad[t])
        j = min(low, key=lambda t: -ys[t] * grad[t])
        if -ys[i] * grad[i] + ys[j] * grad[j] < tol:
            break
        ai, aj = alpha[i], alpha[j]
        if ys[i] != ys[j]:
            quad = max(q[i][i] + q[j][j] + 2 * q[i][j], 1e-12)
            delta = (-grad[i] - grad[j]) / quad
            diff = ai - aj
            ni, nj = ai + delta, aj + delta
            if diff > 0:
                if nj < 0:
                    nj, ni = 0.0, diff
            elif ni < 0:
                ni, nj = 0.0, -diff
            if diff > 0:
                if ni > c:
                    ni, nj = c, c - diff
            elif nj > c:
                nj, ni = c, c + diff
        else:
            quad = max(q[i][i] + q[j][j] - 2 * q[i][j], 1e-12)
            delta = (grad[i] - grad[j]) / quad
            total = ai + aj
            ni, nj = ai - delta, aj + delta
            if total > c:
                if ni > c:
                    ni, nj = c, total - c
            elif nj < 0:
                nj, ni = 0.0, total
            if total > c:
                if nj > c:
                    nj, ni = c, total - c
            elif ni < 0:
                ni, nj = 0.0, total
        di, dj = ni - ai, nj - aj
        alpha[i], alpha[j] = ni, nj
        for t in range(n):
            grad[t] += q[t][i] * di + q[t][j] * dj
    polished = _polish(xs, ys, alpha, c)
    if polished is not None:
        new, b = polished
        m = _finish(xs, ys, new, b, c)
        s, e, _ = _sets(alpha, c, 1e-6 * c)
        m.margin, m.error = s, e
        m.rest = [i for i in range(n) if i not in s and i not in e]
        return m
    free = [t for t in range(n) if 0 < alpha[t] < c]
    if free:
        b = -math.fsum(ys[t] * grad[t] for t in free) / len(free)
    else:
        up = [t for t in range(n) if (ys[t] > 0 and alpha[t] < c) or (ys[t] < 0 and alpha[t] > 0)]
        low = [t for t in range(n) if (ys[t] > 0 and alpha[t] > 0) or (ys[t] < 0 and alpha[t] < c)]
        b = (max(-ys[t] * grad[t] for t in up) + min(-ys[t] * grad[t] for t in low)) / 2
    return _finish(xs, ys, alpha, b, c)


def hinge_total(m: Svm, val: Sequence[tuple[Sequence[float], int]]) -> float:
    """The attacker objective L = sum over the validation set of max(0, 1 - y f(x)). Cost O(v d)."""
    return math.fsum(max(0.0, 1.0 - y * (dot(m.w, x) + m.b)) for x, y in val)


def error_rate(m: Svm, val: Sequence[tuple[Sequence[float], int]]) -> float:
    """Fraction of validation points with y f(x) <= 0. Cost O(v d)."""
    return sum(1 for x, y in val if y * (dot(m.w, x) + m.b) <= 0) / len(val)


def poison_gradient(xs: Sequence[Sequence[float]], ys: Sequence[int], m: Svm, c: float, val: Sequence[tuple[Sequence[float], int]]) -> Vector:
    """Gradient of hinge_total in the last training point x_c, with the sets S, E, R of m held fixed.

    The last point (xs[-1], ys[-1]) is the attack point. Precondition: it is not in S
    (its alpha is 0 or C), S is not empty, and the KKT matrix on S is nonsingular; the
    gradient then exists wherever no point changes set and no validation point sits on
    its margin. Cost O(s^3 + s d^2 + v d) for s = |S| and v validation points.
    """
    cidx = len(xs) - 1
    d = len(xs[0])
    if cidx in m.margin:
        raise ValueError("the attack point is a margin support vector")
    s = m.margin
    if not s:
        raise ValueError("no margin support vector")
    yc, ac = ys[cidx], m.alpha[cidx]
    k = len(s)
    a = [[ys[p] * ys[q] * dot(xs[p], xs[q]) for q in s] + [float(ys[p])] for p in s]
    a.append([float(ys[q]) for q in s] + [0.0])
    # Columns j = 1..d: d(alpha_S, b) / d(x_c)_j = -K^{-1} [a_c y_c y_s (x_s)_j ; 0]
    dalpha = [[0.0] * d for _ in range(k)]
    db = [0.0] * d
    for j in range(d):
        rhs = [-ac * yc * ys[p] * xs[p][j] for p in s] + [0.0]
        sol = solve(a, rhs)
        for t in range(k):
            dalpha[t][j] = sol[t]
        db[j] = sol[k]
    # dw / d(x_c) = sum_s y_s x_s (d alpha_s)^T + a_c y_c I
    dw = [[math.fsum(ys[p] * xs[p][r] * dalpha[t][j] for t, p in enumerate(s)) + (ac * yc if r == j else 0.0) for j in range(d)] for r in range(d)]
    g = [0.0] * d
    for x, y in val:
        if 1.0 - y * (dot(m.w, x) + m.b) > 0.0:
            for j in range(d):
                g[j] -= y * (math.fsum(x[r] * dw[r][j] for r in range(d)) + db[j])
    return g


def poison(
    xs: Sequence[Sequence[float]],
    ys: Sequence[int],
    val: Sequence[tuple[Sequence[float], int]],
    c: float,
    x0: Sequence[float],
    yc: int,
    step: float,
    lo: float,
    hi: float,
    iters: int,
    eps: float,
) -> tuple[Vector, list[float]]:
    """Gradient ascent on the validation hinge loss over one attack point (x_c, yc) in the box [lo, hi]^d.

    Stops when the loss rises by less than eps, after iters steps, or where the gradient
    does not exist or is zero. Returns the final x_c and the loss after each training.
    Precondition: the conditions of poison_gradient at each step. Cost O(iters) SVM trainings.
    """
    xc = list(x0)  # @line L1
    losses: list[float] = []
    for _ in range(iters):  # @line L2
        m = train_svm(list(xs) + [xc], list(ys) + [yc], c)  # @line L3
        losses.append(hinge_total(m, val))
        if len(losses) >= 2 and losses[-1] - losses[-2] < eps:  # @line L6
            break
        try:
            u = poison_gradient(list(xs) + [xc], list(ys) + [yc], m, c, val)  # @line L4
        except ValueError:
            break
        norm = math.sqrt(math.fsum(a * a for a in u))
        if norm <= 1e-9 * max(len(val), 1):  # a flat region, for example |S| = d + 1
            break
        xc = [min(max(a + step * g / norm, lo), hi) for a, g in zip(xc, u)]  # @line L5
    return xc, losses  # @line L7
test_svm_poisoning_attack.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svm-poisoning-attack/. The authors are listed in prov/VZRNHS.jsonl.

"""Tests of the SVM poisoning attack on seeded synthetic blobs: a duality certificate, finite differences, a measurement."""

import math
import random

from svm_poisoning_attack import dot, error_rate, hinge_total, kkt_violation, poison, poison_gradient, train_svm


def blobs(rng: random.Random, per_class: int, d: int, shift: float, sigma: float) -> tuple[list[list[float]], list[int]]:
    xs, ys = [], []
    for i in range(2 * per_class):
        y = 1 if i % 2 == 0 else -1
        xs.append([(y * shift if j == 0 else 0.0) + rng.gauss(0.0, sigma) for j in range(d)])
        ys.append(y)
    return xs, ys


def primal(xs, ys, w, b, c) -> float:
    return 0.5 * dot(w, w) + c * math.fsum(max(0.0, 1.0 - y * (dot(w, x) + b)) for x, y in zip(xs, ys))


def dual(alpha, w) -> float:
    return math.fsum(alpha) - 0.5 * dot(w, w)


def test_svm_solution_has_zero_duality_gap() -> None:
    """Weak duality: D(alpha) <= P* <= P(w, b) for feasible alpha, so a zero gap certifies the optimum."""
    rng = random.Random(6201)
    for _ in range(500):
        n, d = rng.randint(2, 10), rng.randint(1, 3)
        xs = [[rng.uniform(-2.0, 2.0) for _ in range(d)] for _ in range(n)]
        ys = [1, -1] + [rng.choice([1, -1]) for _ in range(n - 2)]
        c = rng.choice([0.1, 1.0, 10.0])
        m = train_svm(xs, ys, c)
        assert all(-1e-12 <= a <= c + 1e-12 for a in m.alpha)
        assert abs(math.fsum(a * y for a, y in zip(m.alpha, ys))) < 1e-9
        w = [math.fsum(m.alpha[i] * ys[i] * xs[i][j] for i in range(n)) for j in range(d)]
        assert all(abs(a - b) < 1e-12 for a, b in zip(w, m.w))
        p, q = primal(xs, ys, m.w, m.b, c), dual(m.alpha, m.w)
        assert p - q <= 1e-7 * (1.0 + abs(p)), (p, q)
        assert kkt_violation(xs, ys, m, c) < 1e-6


def test_gradient_matches_finite_differences() -> None:
    rng = random.Random(6202)
    checked = nonzero = 0
    for _ in range(60):
        d = rng.randint(2, 5)
        xs, ys = blobs(rng, 6, d, 1.5, math.sqrt(0.6))
        val = list(zip(*blobs(rng, 10, d, 1.5, math.sqrt(0.6))))
        k = rng.randrange(len(xs) // 2) * 2 + 1  # a point of class -1
        xc = [a + rng.gauss(0.0, 0.3) for a in xs[k]]
        allx, ally = xs + [xc], ys + [1]
        m = train_svm(allx, ally, 1.0)
        if len(allx) - 1 in m.margin or not m.margin:
            continue
        try:
            g = poison_gradient(allx, ally, m, 1.0, val)
        except ValueError:
            continue
        h = 1e-5
        ok = True
        fd = []
        for j in range(d):
            vals = []
            for sgn in (1.0, -1.0):
                moved = list(xc)
                moved[j] += sgn * h
                mm = train_svm(xs + [moved], ally, 1.0)
                same_sets = mm.margin == m.margin and mm.error == m.error
                same_val = all((1 - y * (dot(mm.w, x) + mm.b) > 0) == (1 - y * (dot(m.w, x) + m.b) > 0) for x, y in val)
                ok = ok and same_sets and same_val
                vals.append(hinge_total(mm, val))
            fd.append((vals[0] - vals[1]) / (2 * h))
        if not ok:
            continue
        checked += 1
        nonzero += max(abs(a) for a in g) > 1e-6
        assert all(abs(a - b) <= 1e-5 * (1.0 + abs(b)) for a, b in zip(g, fd)), (g, fd)
    assert checked >= 30 and nonzero >= 15, (checked, nonzero)


EX_X = [[-2.0, 0.0], [2.0, 0.0], [-2.0, 1.0], [2.0, 1.0]]
EX_Y = [-1, 1, -1, 1]
EX_VAL = [([-1.0, 0.0], -1), ([1.0, 0.0], 1), ([-1.0, 1.0], -1), ([1.0, 1.0], 1)]


def test_example_of_the_page() -> None:
    clean = train_svm(EX_X, EX_Y, 0.1)
    assert abs(clean.w[0] - 0.5) < 1e-12 and abs(clean.w[1]) < 1e-12 and abs(clean.b) < 1e-12
    assert abs(hinge_total(clean, EX_VAL) - 2.0) < 1e-12 and error_rate(clean, EX_VAL) == 0.0
    for a in (-2.0, -2.5, -3.0, -5.0):
        m = train_svm(EX_X + [[a, 0.5]], EX_Y + [1], 0.1)
        assert m.margin == [1, 3] and m.error == [0, 2, 4]
        assert abs(m.w[0] - (0.6 + 0.1 * a)) < 1e-12 and abs(m.w[1]) < 1e-12 and abs(m.b - (-0.2 - 0.2 * a)) < 1e-12
        assert abs(hinge_total(m, EX_VAL) - (2.4 - 0.4 * (a + 2.0))) < 1e-12
        g = poison_gradient(EX_X + [[a, 0.5]], EX_Y + [1], m, 0.1, EX_VAL)
        assert abs(g[0] + 0.4) < 1e-12 and abs(g[1]) < 1e-12
        assert error_rate(m, EX_VAL) == (0.5 if a < -8.0 / 3.0 else 0.0)
    xc, losses = poison(EX_X, EX_Y, EX_VAL, 0.1, [-2.0, 0.5], 1, 0.5, -5.0, 5.0, 20, 1e-9)
    assert xc == [-5.0, 0.5] and [round(t, 9) for t in losses] == [2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.6]


def test_flat_region_when_the_margin_set_has_d_plus_one_points() -> None:
    """With a linear kernel and |S| = d + 1, the margin equations fix w and b, so the gradient is zero."""
    rng = random.Random(6203)
    xs, ys = blobs(rng, 25, 2, 1.5, math.sqrt(0.6))
    val = list(zip(*blobs(rng, 250, 2, 1.5, math.sqrt(0.6))))
    m = train_svm(xs + [xs[1]], ys + [1], 1.0)
    assert len(m.margin) == 3
    g = poison_gradient(xs + [xs[1]], ys + [1], m, 1.0, val)
    assert max(abs(a) for a in g) < 1e-10


def test_one_point_raises_the_validation_error() -> None:
    """A measurement: the means (+-1.5, 0, ...) and covariance 0.6 I of Biggio et al., but d = 8 and 15 points per class, C = 1."""
    gains = []
    for seed in (6204, 6205, 6206, 6207):
        rng = random.Random(seed)
        xs, ys = blobs(rng, 15, 8, 1.5, math.sqrt(0.6))
        val = list(zip(*blobs(rng, 200, 8, 1.5, math.sqrt(0.6))))
        clean = train_svm(xs, ys, 1.0)
        # Clone a point of class -1 and flip its label.
        xc, losses = poison(xs, ys, val, 1.0, xs[1], 1, 0.5, -5.0, 5.0, 60, 1e-6)
        attacked = train_svm(xs + [xc], ys + [1], 1.0)
        assert losses[-1] > losses[0]
        assert all(-5.0 <= a <= 5.0 for a in xc)
        gains.append(error_rate(attacked, val) - error_rate(clean, val))
    assert min(gains) > 0.0 and sum(gains) / len(gains) >= 0.05

History

Barreno et al. (2006, 2010) named causative attacks on the training data. Biggio, Nelson and Laskov (2012) gave the first gradient attack on SVM training, using the incremental SVM of Cauwenberghs and Poggio (2000) and experiments on artificial data and MNIST. Mei and Zhu (2015) generalized it to bilevel optimization, Steinhardt, Koh and Liang (2017) gave certified bounds, and Munoz-Gonzalez et al. (2017) extended gradient poisoning to deep networks.

References

  1. Battista Biggio, Blaine Nelson and Pavel Laskov, Poisoning attacks against support vector machines, Proceedings of the 29th International Conference on Machine Learning (ICML) 2012, arXiv:1206.6389, the attack objective (the hinge loss on a validation set), Algorithm 1 (gradient ascent with a fixed step), equation (10) (the gradient through the KKT conditions of the incremental SVM), and the experiments on artificial data (means (+-1.5, 0), covariance 0.6 I, 25 points per class, 500 validation points) and on MNIST
  2. Shike Mei and Xiaojin Zhu, Using machine teaching to identify optimal training-set attacks on machine learners, Proceedings of the 29th AAAI Conference on Artificial Intelligence (AAAI) 2015, optimal training set attacks as a bilevel program, solved through the KKT conditions of the learner
  3. Luis Munoz-Gonzalez, Battista Biggio, Ambra Demontis, Andrea Paudice, Vasin Wongrassamee, Emil C. Lupu and Fabio Roli, Towards poisoning of deep learning algorithms with back-gradient optimization, Proceedings of the 10th ACM Workshop on Artificial Intelligence and Security (AISec) 2017, the poisoning gradient by differentiation through the steps of the learning algorithm
  4. Gert Cauwenberghs and Tomaso Poggio, Incremental and decremental support vector machine learning, Advances in Neural Information Processing Systems 13 (NIPS) 2000, the update of the dual solution that keeps the KKT conditions while one point is added or changed, with the sets S, E and R
  5. Marco Barreno, Blaine Nelson, Anthony D. Joseph and J. D. Tygar, The security of machine learning, Machine Learning 81, 2010, the taxonomy of attacks, with causative attacks that change the training data
  6. Battista Biggio and Fabio Roli, Wild patterns, ten years after the rise of adversarial machine learning, Pattern Recognition 84, 2018, the threat model in three parts, goal, knowledge and capability
  7. Jacob Steinhardt, Pang Wei Koh and Percy Liang, Certified defenses for data poisoning attacks, Advances in Neural Information Processing Systems 30 (NeurIPS) 2017, upper bounds on the loss that a poisoning attacker can cause against defenses that remove outliers, for linear models such as the SVM

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