Algorithmadvanced
Defensive distillation
Also called distillation defense.
An empirical defense that retrains a network on its own soft labels at a high temperature. It makes softmax gradients tiny but leaves the boundaries in place, and Carlini and Wagner broke it.
- Time
- O(S n K d) worst
- Space
- Θ(n K + K d) extra
- Where
- K = the number of classes; S = the number of training steps; d = the input dimension; n = the number of training points
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nicolas Papernot, Patrick McDaniel, Xi Wu, Somesh Jha, Ananthram Swami, 2015
Defensive distillation is an empirical defense against adversarial examples, and it is broken. It trains a teacher network with the softmax at a high temperature , labels the training data with the soft outputs of the teacher at that temperature, trains a student on those soft labels at the same , and then uses the student at temperature . Papernot, McDaniel, Wu, Jha and Swami (2016) proposed it. Their abstract reports that it cut the success rate of their attack on an MNIST network from 95 percent to below 0.5 percent. Carlini and Wagner (2016, 2017) then showed that the defense does not make the model more robust. Distillation makes the logits about times larger, so the softmax saturates and its gradient becomes tiny. Attacks that work on the logits, or that divide the logits by , succeed on the distilled model at the same distances as on an undefended one. The defense is the classic example of gradient masking.
In plain words
A softmax with temperature divides the logits by before the exponentials. A large gives soft outputs, close to uniform, that show how much the network hesitates between classes.
The defense trains the network twice at a large . The second network learns from the soft outputs of the first. Then it is used at , without the division. Its logits are now large, so its output probabilities are almost exactly or .
An attacker who follows the gradient of the loss on those probabilities sees an almost flat surface and gets no useful direction. But the borders between the classes have not moved. An attacker who looks at the logits, or divides them by again, finds adversarial examples as easily as before.
The problem
Given training data , , with classes, the defense wants a classifier with the same accuracy and fewer adversarial examples. The method works through the softmax with temperature,
It does not change the threat model or the norm of the attack. It changes only how the model is trained. Since no certificate comes with it, it can only be judged by attacks, which is why it is called empirical.
The algorithm
DEFENSIVE-DISTILLATION(data, K, T, S, lr)- 1
X ← the inputs; Y ← the one-hot labels - 2
teacher ← train with loss H(Y, softmax_T(z(X))) for S steps - 3
Q ← softmax_T(z_teacher(X)) ▷ the soft labels - 4
student ← train with loss H(Q, softmax_T(z(X))) for S steps - 5
return (teacher, student) ▷ deploy the student with softmax_1
is the cross-entropy. The paper uses the same architecture for the teacher and the student, and temperatures up to . The code of this page uses softmax regression, , trained from zero by full-batch gradient descent, so that the effect of has a closed form.
Example
Take three seeded Gaussian blobs in the plane with centers , and , , 10 points each, from mlkit.make_blobs with seed 3. Run the procedure twice for 100 steps: at with step size (the baseline), and at with step size . Both students classify all 30 points correctly.
| baseline, | distilled, | |
|---|---|---|
| logits at the first point | ||
| probabilities there | ||
| median input gradient of the loss | ||
| median distance to the nearest boundary | ||
| FGSM at in , labels changed | 7 of 30 | 7 of 30 |
The distilled logits are exactly times the baseline logits, at every input. So the labels and the boundaries are the same, and every point has the same distance to the nearest boundary. Only the softmax changes: the median gradient of the cross-entropy at temperature drops by a factor of about . An attack that uses the size of that gradient, or that computes in low precision where the gradient rounds to , stalls. FGSM uses only the sign, and in float64 the sign survives, so it changes the same 7 labels on both models. On the soft labels of line L3, the first point gets from the teacher at .
Correctness
The claims here are about what the defense does, and they show why it fails. For softmax regression trained from zero by full-batch gradient descent:
Theorem 1 (temperature only scales). Training at temperature with step size gives weights exactly times those of training at temperature with step size , at every step.
Corollary 1. The distilled student has logits times those of the student trained at , at every input. So it has the same labels, the same decision boundaries and the same distance from every input to the nearest boundary.
Corollary 2 (the gradient vanishes). If has label with logit margin in the student trained at , the input gradient of the cross-entropy of the distilled student at temperature has norm at most .
Theorem 1 is an induction: if the weights are times larger, is the same, and the gradient in the logits is times larger, so a step of size keeps the factor . Corollary 2 bounds . The proofs are in proofs/correctness.md. Together they show that the defense changes the gradient, not the boundary. A minimal-distance attack, such as DeepFool or the Carlini-Wagner attack, has the same optimum on both models. For deep networks this is an explanation that Carlini and Wagner give, not a theorem.
Proof: Distillation of a linear model only scales its logits, so boundaries stay and gradients vanishfull
The models are softmax regressions, with , trained from zero by full-batch gradient descent on the mean tempered loss , where (the function train_softmax). We compare a run at temperature with step size to a run at temperature with step size , on the same data and the same targets.
Lemma 1 (the gradient in the logits). .
Proof. With , the loss is because . Its gradient in is , and .
Theorem 1 (temperature scaling). Let be the weights after steps at temperature with step size , and the weights after steps at temperature with step size , both on targets . Then and for every .
Proof. By induction on . Both runs start at zero. Suppose the claim holds at . Then , so , and by Lemma 1 the logit gradient of each sample in the run at is times the one in the run at . The weight gradients are these logit gradients times (or times for ), averaged, so they are also times the gradients of the run at . The step gives , where is the gradient of the run at , and the same for .
Corollary 1 (the whole procedure). Run defensive_distillation at temperature with step size , and again at temperature with step size . Then the student of the first run has logits times the logits of the student of the second run, at every input.
Proof. The teachers (line L2) are trained on the same hard labels, so by Theorem 1 the teacher at is times the teacher at . The soft labels of line L3 are in the first run and the same in the second run. So the students (line L4) are trained on the same targets, and Theorem 1 applies again.
Corollary 2 (no change in the boundaries). The distilled student and the student trained at give the same label to every input, have the same decision boundaries , and give every input the same distance to the nearest boundary.
Proof. Multiplying all logits by keeps their order and their sets of ties. The distance from to the boundary between and is , and the factor cancels.
So a minimum-distance attack on the distilled model has the same optimum as on the model trained at . The defense does not move the boundary.
Corollary 3 (the softmax gradient vanishes). Let the student be used at temperature , with logits where are the logits of the student trained at . Let have label with margin . Then the input gradient of the cross-entropy at the student satisfies , where are the rows of the student trained at .
Proof. With , the gradient is . The coefficients satisfy . And , because and .
The bound goes to fast as grows. In floating point, rounds to exactly when is large, and the gradient that FGSM and PGD use is then exactly . This is gradient masking: the attack loses its signal, but the model is not more robust. An attack on the logits (as in the C&W attack) or on sees the gradient , which does not vanish.
What is not claimed. The exact scaling needs the step size , linear models and full-batch gradient descent. For deep networks and other step sizes, Carlini and Wagner explain the effect of distillation in the same way, as logits that grow with ; that is an observation on those networks, not a theorem here.
Complexity
- Time. Two trainings of steps, each for softmax regression, plus for the soft labels. The total is . For a network, the cost is twice the cost of normal training.
- Space. for the soft labels and for the weights.
- At test time. No extra cost. The student has the same size as the original model.
Properties
- Empirical, and broken. No certificate. Attacks on the logits defeat it.
- No change to the boundaries. In the linear case, exactly (Corollary 1). For networks, Carlini and Wagner find the same distances with their attacks.
- Gradient masking. It makes the gradient of the softmax output small, which defeats attacks that rely on that gradient.
- Keeps accuracy. The paper reports a small change in accuracy on MNIST and CIFAR10.
- Cheap. It costs one extra training run.
Variants and improvements
- Changed attacks. Carlini and Wagner (2016) divide the logits by before the softmax, or attack the logits directly, and both succeed on distilled networks. Their 2017 attacks use the logits by design.
- Extended distillation. Papernot and McDaniel (2017) proposed a version that also uses the uncertainty of the teacher. It is also an empirical defense, with no certificate.
- Better defenses. Adversarial training with PGD gives real empirical robustness against strong attacks. Randomized smoothing and bound propagation give certificates.
- Knowledge distillation itself. Knowledge distillation for model compression is a sound method. The problem is only the claim of robustness.
When to use it
Do not use defensive distillation as a defense. Use it as a study case: to see gradient masking on a small model, to test whether an evaluation would catch a weak defense, or to teach why a defense must be tested with adaptive attacks. For a real defense, use adversarial training and test it with strong attacks, or use a certified method.
Pitfalls
- Judging a defense by one attack. The paper evaluated the defense mainly with JSMA on the softmax outputs, the kind of attack that the defense defeats. An adaptive attack must be part of every evaluation.
- Small gradients are not robustness. A tiny gradient of the loss says nothing about the distance to the boundary, as the example shows: the gradient falls by and the distance is the same.
- Precision. In float32, the probabilities round to exactly and and the gradient becomes exactly . In float64 the sign often survives. An evaluation that works in one precision can fail in another.
- Transfer attacks. Adversarial examples made on an undefended model transfer to the distilled model, since the boundaries are close. See adversarial transferability.
- Using the student at temperature . Then the gradients are normal again, and the defense does nothing even against simple attacks.
Implementations
The code of this page is an abstract model on synthetic data. It trains softmax regression models only on Gaussian blobs that the tests build from a fixed seed with mlkit.make_blobs, and it never reads real data or touches a real system. The FGSM step in the tests runs on the same seeded models and data. The tests check the example of the page, edge cases, the gradient of the tempered loss against finite differences on 500 random logit vectors, that training at with step size gives times the weights of training at on seeded data, and that the student agrees with the teacher.
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/defensive-distillation/. The authors are listed in prov/RHC19E.jsonl.
"""Defensive distillation of Papernot et al. (2016), with softmax regression models, on synthetic data only.
A teacher is trained at a temperature T on the hard labels, a student is trained at
the same T on the soft labels of the teacher, and the student is used at temperature 1.
The models here are linear (softmax regression), so that the tests can compare them
with closed forms. The data come from seeded Gaussian blobs of mlkit. Nothing here
reads real data or touches a real system.
"""
import math
from typing import Sequence
import mlkit as m
Vector = list[float]
Model = tuple[list[Vector], Vector]
def logits(model: Model, x: Sequence[float]) -> Vector:
"""The logits W x + b of a softmax regression model. Cost O(k d)."""
w, b = model
return [m.dot(r, x) + bi for r, bi in zip(w, b)]
def soft_labels(model: Model, x: Sequence[float], temperature: float) -> Vector:
"""softmax(z(x) / T), the soft label of x at temperature T. Cost O(k d)."""
return m.softmax([a / temperature for a in logits(model, x)])
def tempered_loss(z: Sequence[float], q: Sequence[float], temperature: float) -> float:
"""Cross-entropy of the target distribution q against softmax(z / T). Cost O(k)."""
s = [a / temperature for a in z]
top = max(s)
lse = top + math.log(math.fsum(math.exp(a - top) for a in s))
return math.fsum(qi * (lse - si) for qi, si in zip(q, s))
def tempered_loss_gradient(z: Sequence[float], q: Sequence[float], temperature: float) -> Vector:
"""Gradient of tempered_loss in the logits: (softmax(z / T) - q) / T. Cost O(k)."""
p = m.softmax([a / temperature for a in z])
return [(pi - qi) / temperature for pi, qi in zip(p, q)]
def train_softmax(xs: Sequence[Sequence[float]], targets: Sequence[Sequence[float]], temperature: float,
steps: int, lr: float) -> Model:
"""Full-batch gradient descent on the mean tempered_loss, from zero weights.
targets[i] is a probability vector over the k classes for xs[i]. Returns (W, b).
Cost O(steps n k d).
"""
n, d, k = len(xs), len(xs[0]), len(targets[0])
w = [[0.0] * d for _ in range(k)]
b = [0.0] * k
for _ in range(steps):
gw = [[0.0] * d for _ in range(k)]
gb = [0.0] * k
for x, q in zip(xs, targets):
g = tempered_loss_gradient(logits((w, b), x), q, temperature)
for c in range(k):
gb[c] += g[c]
for j in range(d):
gw[c][j] += g[c] * x[j]
w = [[w[c][j] - lr * gw[c][j] / n for j in range(d)] for c in range(k)]
b = [b[c] - lr * gb[c] / n for c in range(k)]
return w, b
def defensive_distillation(data: m.Data, k: int, temperature: float, steps: int, lr: float) -> tuple[Model, Model]:
"""Train a teacher and a student at temperature T. Returns (teacher, student).
The student is meant to be used at temperature 1, that is, with softmax(z(x)).
Preconditions: labels in range(k), temperature > 0. Cost O(steps n k d).
"""
xs = [x for x, _ in data] # @line L1
hard = [[1.0 if c == y else 0.0 for c in range(k)] for _, y in data]
teacher = train_softmax(xs, hard, temperature, steps, lr) # @line L2
soft = [soft_labels(teacher, x, temperature) for x in xs] # @line L3
student = train_softmax(xs, soft, temperature, steps, lr) # @line L4
return teacher, student # @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_defensive_distillation.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/defensive-distillation/. The authors are listed in prov/RHC19E.jsonl.
"""Tests of defensive distillation, on seeded synthetic data only."""
import math
import random
import mlkit as m
from defensive_distillation import (defensive_distillation, logits, soft_labels, tempered_loss,
tempered_loss_gradient, train_softmax)
CENTERS = [[0.3, 0.3], [0.7, 0.3], [0.5, 0.7]]
def page_data():
return m.make_blobs(random.Random(3), 30, 2, CENTERS, 0.08)
def input_gradient_norm(model, x, y):
"""||grad_x cross_entropy(softmax(z(x)), y)||, the gradient that FGSM and PGD use at temperature 1."""
p = m.softmax(logits(model, x))
p[y] -= 1.0
w = model[0]
g = [math.fsum(p[c] * w[c][j] for c in range(len(w))) for j in range(len(x))]
return m.norm2(g)
def boundary_distance(model, x):
"""Closed form: the l2 distance from x to the nearest decision boundary of a linear model."""
w = model[0]
z = logits(model, x)
y = m.argmax(z)
return min((z[y] - z[j]) / m.norm2(m.sub(w[y], w[j])) for j in range(len(w)) if j != y)
def test_page_example() -> None:
data = page_data()
_, base = defensive_distillation(data, 3, 1.0, 100, 2.0)
_, dist = defensive_distillation(data, 3, 20.0, 100, 2.0 * 20 * 20)
acc = lambda mod: m.accuracy(lambda u: m.argmax(logits(mod, u)), data)
assert acc(base) == acc(dist) == 1.0
gb = sorted(input_gradient_norm(base, x, y) for x, y in data)
gd = sorted(input_gradient_norm(dist, x, y) for x, y in data)
assert gb[15] > 1.0 and gd[15] < 1e-9 # the median gradient nearly vanishes
for x, _ in data:
assert abs(boundary_distance(base, x) - boundary_distance(dist, x)) < 1e-9
# FGSM uses only the sign of the gradient, so in float64 it still flips 7 of 30 at eps 0.1
for mod in (base, dist):
flips = 0
for x, y in data:
p = m.softmax(logits(mod, x))
p[y] -= 1.0
g = [math.fsum(p[c] * mod[0][c][j] for c in range(3)) for j in range(2)]
xa = m.clip01([a + 0.1 * ((t > 0) - (t < 0)) for a, t in zip(x, g)])
flips += m.argmax(logits(mod, xa)) != y
assert flips == 7
def test_edges() -> None:
assert tempered_loss([0.0, 0.0], [0.5, 0.5], 3.0) == math.log(2)
assert tempered_loss_gradient([0.0, 0.0], [0.5, 0.5], 3.0) == [0.0, 0.0]
model = ([[0.0, 0.0], [0.0, 0.0]], [0.0, 0.0])
assert soft_labels(model, [0.3, 0.9], 10.0) == [0.5, 0.5]
assert train_softmax([[0.1, 0.2]], [[1.0, 0.0]], 1.0, 0, 1.0) == model
def test_tempered_loss_gradient_matches_finite_differences() -> None:
rng = random.Random(7901)
for _ in range(500):
k = rng.randint(2, 6)
z = [rng.uniform(-10, 10) for _ in range(k)]
q = m.softmax([rng.uniform(-3, 3) for _ in range(k)])
t = rng.choice([0.5, 1.0, 5.0, 20.0])
g = tempered_loss_gradient(z, q, t)
for i in range(k):
up, dn = list(z), list(z)
up[i] += 1e-5
dn[i] -= 1e-5
fd = (tempered_loss(up, q, t) - tempered_loss(dn, q, t)) / 2e-5
assert abs(fd - g[i]) < 1e-6
assert abs(math.fsum(g)) < 1e-12 # the gradient sums to 0, so b only shifts all logits
def test_temperature_only_scales_the_logits() -> None:
# With the step size scaled by T^2, gradient descent at temperature T keeps W / T and
# b / T equal to the weights of the run at temperature 1, so the student logits are T
# times the logits of the student trained at T = 1. The labels and the boundaries agree.
rng = random.Random(7902)
for _ in range(6):
k = rng.randint(2, 3)
centers = [[rng.uniform(0.2, 0.8) for _ in range(2)] for _ in range(k)]
data = m.make_blobs(rng, 12, 2, centers, 0.1)
_, s1 = defensive_distillation(data, k, 1.0, 40, 1.0)
for t in (4.0, 30.0):
_, st = defensive_distillation(data, k, t, 40, t * t)
for r1, rt in zip(s1[0], st[0]):
assert all(abs(b / t - a) <= 1e-9 * (1 + abs(a)) for a, b in zip(r1, rt))
for x, _ in data:
assert m.argmax(logits(st, x)) == m.argmax(logits(s1, x))
assert abs(boundary_distance(st, x) - boundary_distance(s1, x)) < 1e-9
def test_student_matches_teacher() -> None:
data = page_data()
teacher, student = defensive_distillation(data, 3, 20.0, 100, 2.0 * 20 * 20)
agree = sum(1 for x, _ in data if m.argmax(logits(teacher, x)) == m.argmax(logits(student, x)))
assert agree == len(data)
History
Hinton, Vinyals and Dean (2015) introduced distillation with a temperature to compress large networks. Papernot, McDaniel, Wu, Jha and Swami posted defensive distillation in November 2015 and published it at IEEE S&P 2016, with an evaluation based on JSMA. Carlini and Wagner showed in July 2016 that changed attacks succeed against it, and in their 2017 paper their attacks on the logits found adversarial examples on distilled networks as close as on undefended ones. Athalye, Carlini and Wagner (2018) later named the general problem obfuscated gradients and showed that many other defenses fail in the same way.
References
- Nicolas Papernot, Patrick McDaniel, Xi Wu, Somesh Jha and Ananthram Swami, Distillation as a defense to adversarial perturbations against deep neural networks, IEEE Symposium on Security and Privacy 2016, pages 582 to 597, the procedure with a teacher and a student at temperature T, the analysis of the gradients, and the evaluation with JSMA on MNIST and CIFAR10
- Nicholas Carlini and David Wagner, Defensive distillation is not robust to adversarial examples, arXiv 1607.04311, 2016, the explanation by logits that grow with T, and the changed attacks that succeed on distilled networks
- Nicholas Carlini and David Wagner, Towards evaluating the robustness of neural networks, IEEE Symposium on Security and Privacy 2017, pages 39 to 57, the attacks on the logits that succeed on distilled networks at the same distances as on undefended ones
- Geoffrey Hinton, Oriol Vinyals and Jeff Dean, Distilling the knowledge in a neural network, NIPS 2014 Deep Learning Workshop, distillation with a temperature in the softmax, which the defense reuses
- Anish Athalye, Nicholas Carlini and David Wagner, Obfuscated gradients give a false sense of security, ICML 2018, gradient masking and obfuscated gradients as a general cause of broken defenses
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 RHC19E Edit this page History Report an error Markdown