TExcelTAD

Knowledge Distillation

Quantization stores the same network in fewer bits; pruning deletes parts of it. Knowledge distillation trains a different, smaller network, the student, to imitate a large, accurate one, the teacher. The student can have any architecture, so it can be exactly as small and as fast as the deployment target requires (a few dense layers instead of a deep ensemble, a 6-layer transformer instead of 24 layers). What makes distillation work is that the teacher gives the student more than the right answer: its full probability distribution says which wrong answers are almost right, information that one-hot labels throw away.

Soft targets and temperature

A teacher looking at a handwritten 3 might give logits that rank "3" first, "5" second and "8" third. With the usual softmax, almost all probability goes to "3" and the ranking of the rest is invisible. Hinton, Vinyals and Dean (2015) soften the distribution with a temperature TT:

pi(T)=exp⁡(vi/T)∑jexp⁡(vj/T),qi(T)=exp⁡(zi/T)∑jexp⁡(zj/T)p_i^{(T)} = \frac{\exp(v_i / T)}{\sum_j \exp(v_j / T)}, \qquad q_i^{(T)} = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}

where vv are the teacher's logits and zz the student's. T=1T = 1 is the ordinary softmax; larger TT flattens it and reveals the relative similarities ("this 3 looks more like a 5 than a 1"), Hinton's "dark knowledge".

The student is trained on a weighted sum of two losses: matching the teacher's softened distribution, and the ordinary cross-entropy with the true labels yy (when they exist):

L=α T2 KL(p(T) ∥ q(T))+(1−α) CE(y,q(1))\mathcal{L} = \alpha \, T^2 \, \mathrm{KL}\big(p^{(T)} \,\|\, q^{(T)}\big) + (1 - \alpha) \, \mathrm{CE}\big(y, q^{(1)}\big)

The KL divergence equals the cross-entropy with the soft targets minus the teacher's entropy, which does not depend on the student, so both give the same gradients. Why the factor T2T^2? The gradient of the soft term with respect to the student's logits is

∂ KL(p(T)∥q(T))∂zi=1T(qi(T)−pi(T))≈1NT2(zi−vi)for large T\frac{\partial\, \mathrm{KL}(p^{(T)} \| q^{(T)})}{\partial z_i} = \frac{1}{T}\big(q_i^{(T)} - p_i^{(T)}\big) \approx \frac{1}{N T^2} (z_i - v_i) \quad \text{for large } T

(with NN classes and zero-mean logits, expanding exp⁡(x/T)≈1+x/T\exp(x/T) \approx 1 + x/T). The soft gradients shrink like 1/T21/T^2, so multiplying by T2T^2 keeps their weight against the hard loss roughly the same when you change TT. The large-TT limit also shows what distillation becomes at high temperature: matching the teacher's logits with a squared error.

python · try it yourself
import numpy as np

def softmax(z, T=1.0):
    z = np.asarray(z, dtype=float) / T
    e = np.exp(z - z.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)

classes = ["3", "5", "8", "9", "1"]
teacher_logits = np.array([9.0, 6.5, 5.0, 2.0, -1.0])        # a teacher looking at a handwritten 3
for T in (1, 2, 4, 8):
    p = softmax(teacher_logits, T)
    print(f"T = {T}: " + "  ".join(f"{c}:{v:.3f}" for c, v in zip(classes, p)))

# Gradient of the soft loss KL(p_T || q_T) with respect to the student's logits z is (q_T - p_T) / T.
rng = np.random.default_rng(0)
v = rng.normal(0, 3, (1000, 10))                            # teacher logits
z = rng.normal(0, 3, (1000, 10))                            # student logits
def kl(z, T):
    p, q = softmax(v, T), softmax(z, T)
    return np.sum(p * (np.log(p) - np.log(q)), axis=1)
T, eps = 4.0, 1e-6
numeric = (kl(z + eps * np.eye(10)[0], T) - kl(z - eps * np.eye(10)[0], T)) / (2 * eps)
analytic = (softmax(z, T) - softmax(v, T))[:, 0] / T
print(f"\ngradient check at T = 4: max |numeric - analytic| = {np.abs(numeric - analytic).max():.1e}")
for T in (1, 2, 4, 8, 16):
    g = (softmax(z, T) - softmax(v, T)) / T
    print(f"T = {T:2d}: mean gradient norm {np.linalg.norm(g, axis=1).mean():.4f}, "
          f"times T^2: {T**2 * np.linalg.norm(g, axis=1).mean():.4f}")
T = 1: 3:0.908  5:0.075  8:0.017  9:0.001  1:0.000
T = 2: 3:0.686  5:0.196  8:0.093  9:0.021  1:0.005
T = 4: 3:0.463  5:0.248  8:0.170  9:0.080  1:0.038
T = 8: 3:0.329  5:0.241  8:0.199  9:0.137  1:0.094

gradient check at T = 4: max |numeric - analytic| = 4.1e-10
T =  1: mean gradient norm 0.9056, times T^2: 0.9056
T =  2: mean gradient norm 0.2962, times T^2: 1.1850
T =  4: mean gradient norm 0.0784, times T^2: 1.2543
T =  8: mean gradient norm 0.0195, times T^2: 1.2470
T = 16: mean gradient norm 0.0048, times T^2: 1.2411

At T=1T = 1 the teacher gives 0.908 to "3" and only 0.001 to "9"; at T=4T = 4 the same logits give 0.463, 0.248, 0.170, 0.080 and 0.038, a distribution with real information in every entry. The finite-difference check confirms the gradient formula to 4×10−104 \times 10^{-10}. The gradient norms fall from 0.9056 at T=1T = 1 to 0.0048 at T=16T = 16, while the T2T^2-scaled norms stay between 1.185 and 1.254 for T≥2T \ge 2, as the approximation predicts.

Distillation from scratch

The teacher is a neural network with 256 hidden units (18,944 weights) trained on all 1,257 training images of the 8 x 8 digits. The student is a softmax regression (640 weights, 30 times fewer), trained by gradient descent in NumPy on the loss above. The realistic situation for distillation: the student's training set has only 100 labelled images, but the teacher can label them softly. Five student variants are trained on the same five random subsets of 100 images and evaluated on the same 540 test images; the table gives mean and standard deviation over the subsets, and the student's agreement with the teacher's test predictions (its fidelity). Two controls make the comparison honest: the teacher's hard argmax labels (does the teacher's answer help, or its distribution?) and label smoothing (0.91 on the true class, 0.01 on each other class: do any soft targets help?).

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
teacher = MLPClassifier(hidden_layer_sizes=(256,), max_iter=600, random_state=0).fit(X_tr, y_tr)
t_logits = lambda X: np.log(np.clip(teacher.predict_proba(X), 1e-12, 1))   # logits up to a constant
t_test = teacher.predict(X_te)

def softmax(z, T=1.0):
    e = np.exp(z / T - (z / T).max(axis=1, keepdims=True))
    return e / e.sum(axis=1, keepdims=True)

def train_student(X, y=None, soft=None, T=4.0, alpha=1.0, epochs=1500, lr=0.5, l2=1e-3):
    """Softmax regression by full-batch gradient descent on alpha*T^2*KL(soft_T || q_T) + (1-alpha)*CE(y, q)."""
    n, d = X.shape
    W, b = np.zeros((d, 10)), np.zeros(10)
    Y = np.eye(10)[y] if y is not None else None
    for _ in range(epochs):
        z = X @ W + b
        g = np.zeros_like(z)
        if alpha > 0:
            g += alpha * T * (softmax(z, T) - soft)          # T^2 * (q_T - p_T) / T
        if alpha < 1:
            g += (1 - alpha) * (softmax(z) - Y)
        W -= lr * (X.T @ g / n + l2 * W)
        b -= lr * g.mean(axis=0)
    pred = (X_te @ W + b).argmax(1)
    return (pred == y_te).mean(), (pred == t_test).mean()

T = 4.0
print(f"teacher MLP (64-256-10, {sum(W.size for W in teacher.coefs_)} weights): test accuracy {(t_test == y_te).mean():.3f}")
print(f"student: softmax regression (64-10, 640 weights); test n = {len(y_te)}; mean +- sd over 5 subsets\n")
rows = {"hard true labels": [], "smoothed true labels": [], "teacher's argmax labels": [],
        "soft labels, T = 4": [], "soft + true (alpha 0.5)": []}
for seed in range(5):
    idx = np.random.default_rng(seed).choice(len(X_tr), 100, replace=False)
    Xs, ys = X_tr[idx], y_tr[idx]
    soft = softmax(t_logits(Xs), T)
    rows["hard true labels"].append(train_student(Xs, ys, alpha=0.0))
    smooth = 0.9 * np.eye(10)[ys] + 0.01                  # label smoothing: knowledge-free soft targets
    rows["smoothed true labels"].append(train_student(Xs, soft=smooth, T=1.0))
    rows["teacher's argmax labels"].append(train_student(Xs, teacher.predict(Xs), alpha=0.0))
    rows["soft labels, T = 4"].append(train_student(Xs, soft=soft, T=T))
    rows["soft + true (alpha 0.5)"].append(train_student(Xs, ys, soft=soft, T=T, alpha=0.5))
print("100 labelled images        | accuracy        | agreement with teacher")
for name, r in rows.items():
    a = np.array(r)
    print(f"{name:26s} | {a[:, 0].mean():.3f} +- {a[:, 0].std():.3f} | {a[:, 1].mean():.3f}")

print("\nall 1257 training images   | accuracy | agreement")
for name, kw in [("hard true labels", dict(y=y_tr, alpha=0.0)),
                 ("soft labels, T = 4", dict(soft=softmax(t_logits(X_tr), T), T=T))]:
    acc, agr = train_student(X_tr, **kw)
    print(f"{name:26s} |  {acc:.3f}   |  {agr:.3f}")
teacher MLP (64-256-10, 18944 weights): test accuracy 0.981
student: softmax regression (64-10, 640 weights); test n = 540; mean +- sd over 5 subsets

100 labelled images        | accuracy        | agreement with teacher
hard true labels           | 0.894 +- 0.013 | 0.898
smoothed true labels       | 0.890 +- 0.021 | 0.891
teacher's argmax labels    | 0.894 +- 0.013 | 0.898
soft labels, T = 4         | 0.950 +- 0.010 | 0.956
soft + true (alpha 0.5)    | 0.943 +- 0.009 | 0.948

all 1257 training images   | accuracy | agreement
hard true labels           |  0.963   |  0.969
soft labels, T = 4         |  0.967   |  0.978

On 100 images, hard labels give the student 0.894 test accuracy. Soft labels at T=4T = 4 give 0.950, a gain of 5.6 points, much larger than the variation between subsets (0.010 to 0.013). The controls show where the gain comes from: the teacher's argmax labels give exactly the hard-label result (evidently the teacher classifies all its training images correctly, so the labels are identical), and label smoothing does not help either (0.890). The gain comes from the shape of the teacher's distributions, which encodes what the teacher learned from the 1,157 images the student never saw. Mixing in the true labels with α=0.5\alpha = 0.5 was slightly worse here (0.943).

With all 1,257 images, the difference almost disappears: 0.963 with hard labels and 0.967 with soft ones, 2 test images of 540, within noise; the fidelity rises from 0.969 to 0.978. Distillation transfers knowledge; it does not create it. Its biggest gains come when the teacher knows more than the student's own data can teach: a teacher trained on more or better-labelled data, an ensemble, or a large pretrained model, distilled through a large unlabelled transfer set that the teacher labels.

Choosing the temperature

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
teacher = MLPClassifier(hidden_layer_sizes=(256,), max_iter=600, random_state=0).fit(X_tr, y_tr)
logp = np.log(np.clip(teacher.predict_proba(X_tr), 1e-12, 1))

def softmax(z, T=1.0):
    e = np.exp(z / T - (z / T).max(axis=1, keepdims=True))
    return e / e.sum(axis=1, keepdims=True)

def distil(idx, T, epochs=1500, lr=0.5, l2=1e-3):
    Xs, soft = X_tr[idx], softmax(logp[idx], T)
    W, b = np.zeros((64, 10)), np.zeros(10)
    for _ in range(epochs):
        g = T * (softmax(Xs @ W + b, T) - soft)
        W -= lr * (Xs.T @ g / len(idx) + l2 * W)
        b -= lr * g.mean(axis=0)
    return ((X_te @ W + b).argmax(1) == y_te).mean()

for T in (1, 2, 4, 8, 16):
    accs = [distil(np.random.default_rng(s).choice(len(X_tr), 100, replace=False), T) for s in range(5)]
    top = softmax(logp, T).max(axis=1).mean()
    print(f"T = {T:2d}: teacher's mean top probability {top:.3f} | student accuracy {np.mean(accs):.3f} +- {np.std(accs):.3f}")
T =  1: teacher's mean top probability 0.996 | student accuracy 0.895 +- 0.012
T =  2: teacher's mean top probability 0.954 | student accuracy 0.920 +- 0.011
T =  4: teacher's mean top probability 0.751 | student accuracy 0.950 +- 0.010
T =  8: teacher's mean top probability 0.421 | student accuracy 0.956 +- 0.010
T = 16: teacher's mean top probability 0.230 | student accuracy 0.960 +- 0.006

At T=1T = 1 the teacher's average top probability is 0.996, practically one-hot, and the student learns no more than from hard labels (0.895). Raising the temperature exposes more of the distribution and the student improves steadily: 0.920 at T=2T = 2, 0.950 at 4, 0.960 at 16. For this linear student, which cannot reproduce the teacher's exact probabilities anyway, high temperatures (close to matching logits) work best. Typical values in the literature are TT between 2 and 20, and TT and α\alpha are tuned on a validation set like any hyperparameter. Small students sometimes do better with lower temperatures, because they lack the capacity to match every detail of a very flat distribution.

Distillation in practice

  • Transformers. DistilBERT (Sanh et al., 2019) halves BERT's layers and trains with a soft-target loss plus losses that match hidden states; it reports keeping about 97 % of BERT's language-understanding score while being 40 % smaller and 60 % faster. TinyBERT and MiniLM distil attention maps as well.
  • Language models. Large models are often distilled by having the teacher generate training text or answers (sequence-level distillation), or by matching the teacher's next-token distributions on a large corpus.
  • Ensembles into one model. A gradient-boosted ensemble or a bag of networks can be distilled into one small network for cheap serving.
  • Combined with the others. Distil first, then quantize the student. Distillation also helps quantization-aware training: the full-precision model acts as the teacher of its quantized copy.

Pitfalls

  • Evaluating fidelity instead of accuracy. A student that agrees with the teacher 95 % of the time inherits the teacher's errors; report both, on a held-out test set the teacher was not trained on.
  • Unfair baselines. Compare with a student trained as well as possible on hard labels (same architecture, same tuning, same data), and with label smoothing; otherwise you measure regularisation, not distillation.
  • A transfer set from the wrong distribution. Soft labels on inputs unlike the production data teach the student about the wrong region of input space.
  • Calibration. A student trained at high temperature may be over- or under-confident at T=1T = 1; check calibration and recalibrate if probabilities are used.

Practice

  1. Compute the softmax of the logits (2,1,0)(2, 1, 0) at T=1T = 1 and T=2T = 2.
Answer

T=1T = 1: e2,e1,e0=7.389,2.718,1e^2, e^1, e^0 = 7.389, 2.718, 1, sum 11.107: (0.665,0.245,0.090)(0.665, 0.245, 0.090). T=2T = 2: e1,e0.5,e0=2.718,1.649,1e^1, e^{0.5}, e^0 = 2.718, 1.649, 1, sum 5.367: (0.506,0.307,0.186)(0.506, 0.307, 0.186).

  1. In the second example, the teacher's argmax labels gave exactly the same student as the true labels. When would they differ, and could that ever help?
Answer

When the teacher misclassifies some transfer images (on images it did not train on, or with noisy true labels). If the true labels are noisy, the teacher's labels can even be better; if the teacher is wrong, the student learns its mistakes. Distilling on an unlabelled set means relying on the teacher's labels entirely.

  1. Why does the soft loss carry a factor T2T^2 and not TT?
Answer

Its gradient with respect to the logits is (q(T)−p(T))/T(q^{(T)} - p^{(T)})/T, and the difference q(T)−p(T)q^{(T)} - p^{(T)} itself shrinks like 1/T1/T for large TT, so the gradient shrinks like 1/T21/T^2. The first example measured it: the scaled norms stayed near 1.2 from T=2T = 2 to 16.

Test yourself

What does raising the temperature T do to the teacher's softmax?

  1. It flattens the distribution and reveals the relative probabilities of the wrong classes
  2. It makes the distribution more peaked
  3. It changes which class is ranked first
  4. It removes the need for a student

In the experiment with 100 labelled images, which control showed that the gain does not come from soft targets as such?

  1. Label smoothing of the true labels (0.890, no better than hard labels)
  2. The teacher's argmax labels
  3. Training on all 1,257 images
  4. The T = 1 run

Why is the soft loss multiplied by T squared?

  1. Its gradients shrink like 1/T^2, so the factor keeps their weight against the hard loss when T changes
  2. To make the loss positive
  3. Because the KL divergence is quadratic
  4. To slow down training

With all 1,257 training images available to the student, soft labels gave 0.967 and hard labels 0.963 test accuracy (n = 540). What is the honest conclusion?

  1. The difference is about 2 test images and within noise; the big gain appeared when the student had little labelled data
  2. Distillation always adds 0.4 points
  3. Hard labels are better
  4. The teacher is useless