Algorithmadvanced
Randomized smoothing
Also called Gaussian smoothing certificate.
Classifies by the majority label under Gaussian noise and certifies an l2 radius from the gap between the top two class probabilities.
- Time
- O(n (c + d)) worst
- Space
- O(d + k) extra
- Where
- c = the cost of one call of the base classifier; d = the input dimension; k = the number of labels; n = the number of noise samples of both stages
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jeremy Cohen, Elan Rosenfeld, J. Zico Kolter, Mathias Lecuyer, Suman Jana, 2019
Randomized smoothing turns any base classifier into a smoothed classifier that returns the label that gives most often when Gaussian noise is added to the input: with . Cohen, Rosenfeld and Kolter (2019) proved that if the top label has probability at least and every other label at most , then is constant on the ball of radius around , where is the quantile function of the standard normal distribution. The probabilities are not known, so the CERTIFY procedure estimates a lower bound of from samples, and the certificate holds with probability at least over the samples. The certificate is for , not for , and it works for any , of any size, because it needs only calls of .
Threat model. Randomized smoothing is a defense with a certificate. The goal can be untargeted or targeted, since the certificate rules out every other label. The knowledge is unlimited: the attacker may know , and the procedure, but not the noise draws of the defender. The capability is a change at test time with , where is the certified radius of the point.
In plain words
Take any classifier and do not trust its answer on one input. Instead, add random noise to the input many times, ask the classifier each time, and report the answer that comes back most often.
Noise blurs the inputs, so moving the input a little changes the vote only a little. If one answer wins the vote by a clear margin, a small move of the input cannot make another answer win. The bigger the margin and the noise, the bigger the safe distance.
The vote is counted from a finite number of samples, so the method uses a careful lower estimate of the share of the winner. The guarantee is about the voting classifier, not about the original one, and it can fail with a small, known probability, such as one in a thousand.
The problem
Given a base classifier , a noise level and an input , define for . Return a label and a radius such that for every , or abstain. Only calls of are allowed, so the answer must hold with probability at least over the noise draws. The perturbation set is the ball .
The algorithm
CERTIFY(f, sigma, x, n_0, n, alpha)- 1
counts_0 ← SAMPLE-UNDER-NOISE(f, x, n_0, sigma) - 2
c_A ← the label with the most counts in counts_0 ▷ only a guess of the top label - 3
counts ← SAMPLE-UNDER-NOISE(f, x, n, sigma) ▷ fresh, independent samples - 4
p_A ← LOWER-CONF-BOUND(counts[c_A], n, 1 - alpha) ▷ one-sided Clopper-Pearson bound - 5
if p_A > 1/2 then - 6
return (c_A, sigma · Φ^-1(p_A)) - 7
return ABSTAIN SAMPLE-UNDER-NOISE(f, x, n, sigma)- 8
for i ← 1 to n do - 9
eta ← a draw from N(0, sigma^2 I) - 10
counts[f(x + eta)] ← counts[f(x + eta)] + 1 - 11
return counts PREDICT(f, sigma, x, n, alpha)- 12
counts ← SAMPLE-UNDER-NOISE(f, x, n, sigma) - 13
c_A, c_B ← the two labels with the most counts - 14
if BINOMIAL-P-VALUE(counts[c_A], counts[c_A] + counts[c_B], 1/2) <= alpha then return c_A - 15
return ABSTAIN
Lines L1 and L2 pick the label to certify from a small sample. Line L3 draws a new sample, so the count of in it is a binomial variable whose success probability is the true . Line L4 takes the one-sided Clopper-Pearson lower bound: the number with . Line L6 uses the bound , which turns the radius of the theorem into . If , no radius is certified.
PREDICT only returns the label. Line L14 is a two-sided binomial test of whether beats ; if the test is not significant, the procedure abstains, and a returned label differs from with probability at most .
Example
The check value: with , and , the radius is .
The table shows line L4 and line L6 for and , for several counts of the top label among samples.
| (line L4) | radius (line L6) | |||
|---|---|---|---|---|
| 550 | 1000 | 0.55 | 0.50068 | 0.00085 |
| 600 | 1000 | 0.60 | 0.55108 | 0.06419 |
| 900 | 1000 | 0.90 | 0.86746 | 0.55724 |
| 9000 | 10000 | 0.90 | 0.89041 | 0.61436 |
| 1000 | 1000 | 1.00 | 0.99312 | 1.23163 |
| 100000 | 100000 | 1.00 | 0.99993 | 1.90573 |
With the same share of votes, more samples move closer to and the radius closer to the check value . Even with every vote for , the radius is bounded: , so for large the radius grows only like , very slowly.
For a linear base classifier the smoothed classifier is the same as , and the exact is , so is exactly the distance from to the hyperplane. For , , and , and the radius is , the distance to the boundary. So the theorem is tight.
Correctness
Theorem (Cohen, Rosenfeld and Kolter 2019). Let and with . Then for every .
Corollary (CERTIFY). With probability at least over the samples of lines L1 to L3, if CERTIFY returns , then for every .
The theorem follows from the Neyman-Pearson lemma for the two Gaussians and : among all sets with probability under the first, a half-space orthogonal to has the least probability under the second, and that probability is . The top label keeps more than half of the mass, which is more than any other label can have, as long as . For the corollary, the label of line L2 is fixed before line L3 draws its samples, and the Clopper-Pearson bound is below the true probability with probability at least ; a smaller gives a smaller radius. The full proof is in proofs/correctness.md.
Proof: The Gaussian smoothed classifier is constant on the certified l2 ball, and CERTIFY is correct with probability at least 1 - alphafull
Let be any measurable base classifier, let , and let . For a label write , and let . We write for the distribution function of the standard normal distribution and for its inverse. The proof has three parts: the radius for known probabilities (Lemma 1 to the Theorem), the Clopper-Pearson bound (Lemma 3), and the procedure (the Corollary).
Lemma 1 (Neyman-Pearson). Let and be two distributions on with densities and , and let for some . If a measurable function has , then .
Proof. Let . On we have and , so . Outside we have and , so again . Integration gives .
Lemma 2 (the Gaussian half-space). Let and with , and let . The set has and , and it has the form of Lemma 1.
Proof. The density ratio is , an increasing function of , so is a set for a . Under , the variable is normal with mean and standard deviation , so . Under , it is normal with mean and the same standard deviation, so . The set has the form , and the same argument with the opposite inequality gives: if , then .
Theorem (Cohen, Rosenfeld and Kolter 2019). Let be a label, and let with and for every . If , then .
Proof. The case is clear. Otherwise let and , so and . Apply Lemma 1 with and the set of Lemma 2 for : since , we get . For , apply the second statement of Lemma 2 with and : since , we get , by the symmetry . Because is strictly increasing, holds when , that is, when . Then has the strictly largest probability at , so .
With and the radius is , which is the radius of line L6. The choice is allowed, because for every , and gives .
Lemma 3 (Clopper-Pearson coverage). Let and . Define and, for , let be the unique with , where . Then .
Proof. For , is continuous and strictly increasing on with and ; it is increasing because a variable with can be built as a variable plus extra successes, by a coupling of each trial, and strict because the extra mass is positive for . So exists and is unique, and holds if and only if . Also decreases in , so is non-decreasing in . Let ; if it does not exist, the probability is . By monotonicity, holds exactly when , and .
Corollary (CERTIFY). Run CERTIFY with , and . With probability at least over the noise draws, the following holds: if CERTIFY returns , then for every .
Proof. The draws of line L1 and of line L3 are independent. Condition on the result of lines L1 and L2, so the label is fixed. Under this condition the samples of line L3 are still independent draws of , so the count of at line L3 is . Line L4 computes for the level . By Lemma 3, the event has conditional probability at least , for every value of ; so it has probability at least without the condition. On , suppose that CERTIFY returns at line L6. Then , so with and the hypotheses of the Theorem hold: , and for . The Theorem gives for every . If CERTIFY abstains at line L7, there is nothing to prove. So the claim holds on , and .
Complexity
- Time. calls of , plus per noise draw, so for samples in total. Line L4 costs per step of a bisection. For an ImageNet model, Cohen et al. used , so one certificate costs as much as 100000 forward passes.
- Space. for one noisy input and the counts.
- Samples against radius. The largest radius that samples can certify grows like , so a larger radius needs a larger more than more samples.
Properties
- Probabilistic. The certificate holds with probability at least over the defender's noise (a theorem about the procedure). Over test points, the expected number of wrong certificates is at most .
- Model-agnostic. Only calls of are needed, so it scales to networks that no exact or bound-based verifier can handle.
- Tight in . For a linear base classifier the radius equals the true distance to the boundary (Theorem 2 of Cohen et al.), so the bound cannot be improved using and alone.
- A lower bound on robust accuracy of . The fraction of test points with a correct label and a radius above is a lower bound (with high probability) on the robust accuracy of at radius , the certified accuracy. It says nothing about .
- Weak in . An radius gives an radius of only , which is small for images.
- Accuracy costs. The noise lowers the clean accuracy of , more for a larger , so trades accuracy for radius.
Variants and improvements
- Training with noise. The base classifier should be trained on noisy inputs with the same ; otherwise is near random under noise and abstains. Salman et al. (2019) train it with adversarial examples of the smoothed classifier and get larger certified radii.
- PixelDP. Lecuyer et al. (2019) add a noise layer and use the stability bound of differential privacy, in the spirit of the Gaussian mechanism, to certify; the radius is looser than the one of Cohen et al.
- Other noise and other norms. Uniform or Laplace noise gives certificates in , and other distributions give other norms; the tight radius for each comes from a Neyman-Pearson argument for that noise.
- Better confidence bounds. Any valid one-sided lower confidence bound works at line L4; Clopper-Pearson is exact for the binomial and is the usual choice.
- Abstain or answer. PREDICT can abstain when the vote is close; it never needs a radius. In use, PREDICT runs at test time and CERTIFY is used to report certified accuracy.
When to use it
Use randomized smoothing when the model is too large for interval bound propagation or linear bound propagation, when a probabilistic guarantee is acceptable, and when the threat is an change. Do not use it when every prediction must be cheap, since each one costs many forward passes, or when the threat is an change of fixed size in high dimension. For small networks and an exact answer, use Reluplex.
Pitfalls
- The same samples for the guess and the bound. If line L3 reuses the samples of line L1, the label is chosen to look good on the same data, and the bound of line L4 is no longer valid. Keep the two samples independent.
- The point estimate in place of the bound. Using at line L4 gives a radius that is too large about half the time. Line L4 must use a lower confidence bound.
- A certificate for the base classifier. The radius is for . The base classifier can have adversarial examples very close to , and an attack on is no counterexample to the certificate.
- Clipped noise. Clipping to at line L9 changes the noise distribution, and the theorem, which needs Gaussian noise, no longer applies as stated. Clipping inside is fine, because it is then part of the base classifier.
- Too few samples. With small , line L4 gives a bound well below , and many points abstain at line L7. Cohen et al. use and for this reason.
- Reading for the whole test set. The level holds for each point on its own. Over many points some certificates are wrong, about in expectation.
Implementations
The code of this page is an abstract model on synthetic data. The base classifiers are linear models with given weights and two-layer ReLU networks from mlkit.tiny_relu_net, and the inputs are seeded random points. It never reads real data or touches a real system. The tests check the value , the binomial tail against a direct sum, that the Clopper-Pearson bound meets and covers the true probability with level exactly over all outcomes, that the exact radius of a linear model is the distance to its boundary, that the certified radius of CERTIFY is at most that distance on all but a few of 60 points, that the exact smoothed label is constant inside each certified ball, and that points on the boundary abstain.
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
# 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)
randomized_smoothing.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-smoothing/. The authors are listed in prov/HVTX47.jsonl.
"""Randomized smoothing with Gaussian noise: PREDICT and CERTIFY of Cohen, Rosenfeld and Kolter (2019).
The smoothed classifier is g(x) = the label c that maximizes P(f(x + eta) = c), with
eta drawn from N(0, sigma^2 I). CERTIFY estimates the top label from n0 noisy samples,
then counts it in n fresh samples and takes a one-sided Clopper-Pearson lower bound
pA of its probability. If pA > 1/2, then with probability at least 1 - alpha over the
samples, g is constant on the open l2 ball of radius sigma * PhiInv(pA) around x.
The certificate is about g, not about the base classifier f.
The base classifiers in the tests are synthetic models built from a fixed seed.
"""
import math
import random
from statistics import NormalDist
from typing import Callable, Optional, Sequence
Classifier = Callable[[list[float]], int]
ABSTAIN = -1
_STD = NormalDist()
def binomial_upper_tail(k: int, n: int, p: float) -> float:
"""P(K >= k) for K ~ Binomial(n, p). Cost O(n - k)."""
if k <= 0:
return 1.0
if k > n:
return 0.0
if p <= 0.0:
return 0.0
if p >= 1.0:
return 1.0
log_term = math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1) + k * math.log(p) + (n - k) * math.log1p(-p)
term = math.exp(log_term)
total = term
ratio = p / (1.0 - p)
for i in range(k, n):
term *= (n - i) / (i + 1) * ratio
total += term
return min(total, 1.0)
def lower_confidence_bound(k: int, n: int, alpha: float) -> float:
"""The one-sided Clopper-Pearson lower bound of a binomial proportion at level 1 - alpha.
It is the p with P(K >= k) = alpha under Binomial(n, p), and 0 when k = 0. For every
p, P_p(bound > p) <= alpha. Found by bisection, so it is exact to about 1e-12.
Cost O(n) per step of the bisection.
"""
if k <= 0:
return 0.0
lo, hi = 0.0, 1.0
for _ in range(45):
mid = (lo + hi) / 2.0
if binomial_upper_tail(k, n, mid) < alpha:
lo = mid
else:
hi = mid
return lo
def binomial_p_value(k: int, n: int) -> float:
"""Two-sided p-value of the test of p = 1/2 for k successes in n trials. Cost O(n)."""
if n == 0:
return 1.0
m = max(k, n - k)
return min(1.0, 2.0 * binomial_upper_tail(m, n, 0.5))
def sample_under_noise(f: Classifier, x: Sequence[float], n: int, sigma: float, rng: random.Random) -> dict[int, int]:
"""Counts of the labels of f(x + eta) for n independent draws of eta from N(0, sigma^2 I). Cost n calls of f."""
counts: dict[int, int] = {}
for _ in range(n): # @line L8
noisy = [a + rng.gauss(0.0, sigma) for a in x] # @line L9
c = f(noisy) # @line L10
counts[c] = counts.get(c, 0) + 1 # @line L10
return counts # @line L11
def top_two(counts: dict[int, int]) -> tuple[int, int, int, int]:
"""(cA, nA, cB, nB): the two labels with the most counts, ties to the smaller label."""
order = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
ca, na = order[0]
cb, nb = order[1] if len(order) > 1 else (ABSTAIN, 0)
return ca, na, cb, nb
def certify(f: Classifier, sigma: float, x: Sequence[float], n0: int, n: int, alpha: float,
rng: random.Random) -> tuple[int, float]:
"""(cA, R) with an l2 radius R > 0 for the smoothed classifier, or (ABSTAIN, 0.0).
With probability at least 1 - alpha over the noise, if the answer is (cA, R), then
g(x + delta) = cA for every delta with ||delta||_2 < R.
Precondition: sigma > 0, n0 >= 1, n >= 1, 0 < alpha < 1. Cost n0 + n calls of f.
"""
counts0 = sample_under_noise(f, x, n0, sigma, rng) # @line L1
ca = top_two(counts0)[0] # @line L2
counts = sample_under_noise(f, x, n, sigma, rng) # @line L3
pa = lower_confidence_bound(counts.get(ca, 0), n, alpha) # @line L4
if pa > 0.5: # @line L5
return ca, sigma * _STD.inv_cdf(pa) # @line L6
return ABSTAIN, 0.0 # @line L7
def predict(f: Classifier, sigma: float, x: Sequence[float], n: int, alpha: float, rng: random.Random) -> int:
"""The label of the smoothed classifier, or ABSTAIN. A wrong label has probability at most alpha.
Cost n calls of f.
"""
counts = sample_under_noise(f, x, n, sigma, rng) # @line L12
ca, na, _, nb = top_two(counts) # @line L13
if binomial_p_value(na, na + nb) <= alpha: # @line L14
return ca # @line L14
return ABSTAIN # @line L15
def radius_from_probabilities(sigma: float, pa: float, pb: float) -> float:
"""The radius (sigma / 2) (PhiInv(pA) - PhiInv(pB)) of Theorem 1 of Cohen et al., for 0 < pB <= pA < 1."""
return sigma / 2.0 * (_STD.inv_cdf(pa) - _STD.inv_cdf(pb))
def linear_classifier(w: Sequence[float], b: float) -> Classifier:
"""The base classifier x -> 1 if w.x + b > 0 else 0."""
def f(x: list[float]) -> int:
return 1 if math.fsum(wi * xi for wi, xi in zip(w, x, strict=True)) + b > 0 else 0
return f
def exact_top_probability(w: Sequence[float], b: float, x: Sequence[float], sigma: float) -> tuple[int, float]:
"""For the linear classifier, the label of g at x and its exact probability under the noise.
w.(x + eta) + b is normal with mean w.x + b and standard deviation sigma ||w||, so the
probability of the label 1 is Phi((w.x + b) / (sigma ||w||)).
"""
s = math.fsum(wi * xi for wi, xi in zip(w, x, strict=True)) + b
p1 = _STD.cdf(s / (sigma * math.sqrt(math.fsum(wi * wi for wi in w))))
return (1, p1) if p1 > 0.5 else (0, 1.0 - p1)
def distance_to_boundary(w: Sequence[float], b: float, x: Sequence[float]) -> float:
"""The l2 distance from x to the hyperplane w.x + b = 0."""
s = math.fsum(wi * xi for wi, xi in zip(w, x, strict=True)) + b
return abs(s) / math.sqrt(math.fsum(wi * wi for wi in w))
def certified_accuracy(results: Sequence[tuple[int, float]], labels: Sequence[int], radius: float) -> float:
"""Fraction of points with a correct certified label and a certified radius above the given one."""
if not labels:
return 0.0
good = sum(1 for (c, r), y in zip(results, labels, strict=True) if c == y and r > radius)
return good / len(labels)
def smoothed_label_estimate(f: Classifier, sigma: float, x: Sequence[float], n: int,
rng: random.Random) -> Optional[int]:
"""The most frequent label of f(x + eta) over n samples, with no confidence claim. For tests only."""
counts = sample_under_noise(f, x, n, sigma, rng)
return top_two(counts)[0] if counts else None
test_randomized_smoothing.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-smoothing/. The authors are listed in prov/HVTX47.jsonl.
"""Tests of randomized smoothing on seeded synthetic classifiers only."""
import math
import random
from statistics import NormalDist
import mlkit as m
from randomized_smoothing import (
ABSTAIN,
binomial_p_value,
binomial_upper_tail,
certified_accuracy,
certify,
distance_to_boundary,
exact_top_probability,
linear_classifier,
lower_confidence_bound,
predict,
radius_from_probabilities,
)
PHI = NormalDist()
def test_check_value_of_the_radius():
r = radius_from_probabilities(0.5, 0.9, 0.1)
assert abs(r - 0.64078) < 1e-5
assert abs(r - 0.5 * PHI.inv_cdf(0.9)) < 1e-12
def test_binomial_tail_against_direct_sum():
for n in (1, 5, 20, 60):
for k in range(n + 2):
for p in (0.01, 0.3, 0.5, 0.77, 0.99):
direct = sum(math.comb(n, i) * p ** i * (1 - p) ** (n - i) for i in range(k, n + 1))
assert abs(binomial_upper_tail(k, n, p) - direct) < 1e-12
def test_clopper_pearson_bound_meets_alpha():
for n in (1, 10, 100, 1000):
for alpha in (0.001, 0.05):
assert abs(lower_confidence_bound(n, n, alpha) - alpha ** (1.0 / n)) < 1e-9
for k in sorted({1, n // 3, n // 2, n - 1, n} - {0}):
p = lower_confidence_bound(k, n, alpha)
assert abs(binomial_upper_tail(k, n, p) - alpha) < 1e-9
assert p <= k / n
assert lower_confidence_bound(0, 10, 0.05) == 0.0
def test_clopper_pearson_exact_coverage():
# P_p(bound(K) > p) <= alpha for every p, computed exactly over all outcomes K.
for n in (5, 12, 40):
for alpha in (0.05, 0.2):
bounds = [lower_confidence_bound(k, n, alpha) for k in range(n + 1)]
assert all(a <= b for a, b in zip(bounds, bounds[1:]))
for t in range(1, 200):
p = t / 200
miss = sum(math.comb(n, k) * p ** k * (1 - p) ** (n - k) for k in range(n + 1) if bounds[k] > p)
assert miss <= alpha + 1e-12
def test_p_value():
assert binomial_p_value(5, 10) == 1.0
assert abs(binomial_p_value(10, 10) - 2 * 0.5 ** 10) < 1e-15
assert abs(binomial_p_value(0, 10) - 2 * 0.5 ** 10) < 1e-15
def test_linear_certificate_is_sound_and_close_to_the_distance():
rng = random.Random(2019)
w, b = [1.5, -2.0, 0.5], 0.25
f = linear_classifier(w, b)
sigma, alpha = 0.5, 0.01
wrong, ratio = 0, []
for _ in range(60):
x = [rng.uniform(-1, 1) for _ in range(3)]
c, r = certify(f, sigma, x, 20, 400, alpha, rng)
exact_c, _ = exact_top_probability(w, b, x, sigma)
dist = distance_to_boundary(w, b, x)
if c != ABSTAIN:
# For a linear f, g = f, and the exact certified radius is the distance to the boundary.
if c != exact_c or r > dist:
wrong += 1
ratio.append(r / dist)
assert wrong <= 2
assert len(ratio) > 30
assert sum(ratio) / len(ratio) > 0.7
def test_exact_radius_of_a_linear_model_is_the_distance():
rng = random.Random(5)
for _ in range(200):
w = [rng.uniform(-2, 2) for _ in range(4)]
b = rng.uniform(-1, 1)
x = [rng.uniform(-1, 1) for _ in range(4)]
sigma = rng.uniform(0.1, 1.0)
_, pa = exact_top_probability(w, b, x, sigma)
if 0.5 < pa < 1 - 1e-12:
assert abs(sigma * PHI.inv_cdf(pa) - distance_to_boundary(w, b, x)) < 1e-6
def test_certified_ball_keeps_the_smoothed_label():
# Inside the certified ball the exact top probability of g stays above 1/2.
rng = random.Random(7)
w, b = [0.8, 0.6], -0.2
f = linear_classifier(w, b)
for _ in range(40):
x = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
c, r = certify(f, 0.25, x, 20, 300, 0.001, rng)
if c == ABSTAIN:
continue
for _ in range(20):
d = [rng.gauss(0, 1), rng.gauss(0, 1)]
s = rng.random() * r / m.norm2(d)
xd = [a + s * v for a, v in zip(x, d)]
label, p = exact_top_probability(w, b, xd, 0.25)
assert label == c and p > 0.5
def test_abstains_on_the_boundary():
rng = random.Random(8)
f = linear_classifier([1.0, 0.0], 0.0)
abstain = sum(1 for _ in range(50) if certify(f, 0.5, [0.0, 0.3], 10, 200, 0.05, rng)[0] == ABSTAIN)
assert abstain >= 45
assert sum(1 for _ in range(50) if predict(f, 0.5, [0.0, 0.3], 200, 0.05, rng) != ABSTAIN) <= 6
def test_relu_network_base_classifier():
rng = random.Random(11)
net = m.tiny_relu_net(rng, 2, 6, 3)
def f(x):
return m.argmax(m.forward(net, x))
results, labels = [], []
for _ in range(15):
x = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
labels.append(f(x))
results.append(certify(f, 0.25, x, 20, 200, 0.01, rng))
acc0 = certified_accuracy(results, labels, 0.0)
acc1 = certified_accuracy(results, labels, 0.2)
assert 0.0 <= acc1 <= acc0 <= 1.0
assert all(r <= 0.25 * PHI.inv_cdf(0.01 ** (1 / 200)) + 1e-12 for _, r in results)
def test_more_samples_give_a_larger_radius_bound():
for n in (100, 1000, 10000):
pa = lower_confidence_bound(int(0.9 * n), n, 0.001)
assert pa < 0.9
a = lower_confidence_bound(90, 100, 0.001)
b = lower_confidence_bound(900, 1000, 0.001)
c = lower_confidence_bound(9000, 10000, 0.001)
assert a < b < c < 0.9
History
Adding noise to inputs at test time was proposed as a heuristic defense several times, and some such defenses were later broken. Lecuyer et al. posted PixelDP in February 2018 (IEEE S&P 2019): a noise layer with a guarantee from differential privacy, the first certificate of this kind that scaled to ImageNet. Li et al. (2019) gave a tighter bound with Rényi divergence. Cohen, Rosenfeld and Kolter (ICML 2019) proved the tight radius for Gaussian noise with the Neyman-Pearson lemma, separated the smoothed classifier from the base classifier, and gave the sampling procedures with their statistical guarantees. They reported certified accuracy on ImageNet at radii where no other certificate worked (a measurement on their models). Later work trained better base classifiers and extended the method to other norms and to other kinds of data.
References
- Jeremy Cohen, Elan Rosenfeld and J. Zico Kolter, Certified adversarial robustness via randomized smoothing, ICML 2019, PMLR 97, pages 1310 to 1320, Theorem 1 (the robustness radius), Theorem 2 (its tightness), the PREDICT and CERTIFY procedures with their guarantees, and the experiments on ImageNet
- Mathias Lecuyer, Vaggelis Atlidakis, Roxana Geambasu, Daniel Hsu and Suman Jana, Certified robustness to adversarial examples with differential privacy, IEEE S&P 2019, PixelDP, the first certificate for a classifier with a noise layer, from the stability guarantee of differential privacy
- Nicholas Carlini, Anish Athalye, Nicolas Papernot, Wieland Brendel, Jonas Rauber, Dimitris Tsipras, Ian Goodfellow, Aleksander Madry and Alexey Kurakin, On evaluating adversarial robustness, arXiv 2019, certified robust accuracy as a lower bound and attacks as an upper bound
- Battista Biggio and Fabio Roli, Wild patterns: Ten years after the rise of adversarial machine learning, Pattern Recognition 84, pages 317 to 331, 2018, the threat model in three parts used on this page
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 HVTX47 Edit this page History Report an error Markdown