← All tutorials

Companion notebook

Knowledge Distillation

On this page

1 Soft targets from the teacher 2 The distillation loss 3 One training step 4 Distilling a ResNet-18 into a small CNN 5 Distilling features and relations 6 Distillation in practice 7 Pitfalls 8 References

A large model that works well can cost too much to run. Knowledge Distillation (KD) trains a small model, the student, to copy a large trained model, the teacher. The big model you cannot afford to serve teaches the small model you can.

The problem is deployment. An ensemble of averaged models is the most reliable accuracy boost, but too expensive to serve. Bucila et al. showed an ensemble's knowledge could be compressed into one model; distillation is the simplest version of that idea.

The teacher's soft outputs carry information the hard labels never will. A teacher that says 90% cat, 8% dog, 2% car is telling you which mistakes are reasonable. That ranking, the "dark knowledge", is what the student learns, from the teacher's softmax (the step that turns raw scores into probabilities) softened with a temperature, alongside the usual hard-label loss.

Distillation acts on every training step of the student. Each batch goes through the frozen teacher, with no gradients, and through the student, and the loss mixes both outputs; the companion run recomputes the teacher's outputs batch by batch. Nothing carries over between steps except the student's own weights, and the price per step is one extra teacher forward pass.

It works at scale. DistilBERT (Sanh et al. 2019) is BERT-base (a pretrained language model that reads text in both directions) with 40% of the parameters removed, and it keeps 97% of BERT's performance on the GLUE language benchmark; Hinton et al. (2015) showed the effect first on digits and speech.

small net alone 146 errors distilled, T = 20 74 errors big net 67 errors
Figure 1. MNIST test errors (Hinton et al. 2015); distillation closes most of the gap.
baseline model 58.9% distilled model 60.8% 10-model ensemble 61.1% bars from 0%
Figure 2. Speech frame accuracy; distillation keeps 86% of the gain.

1 Soft targets from the teacher

Besides the hard label ("this is a cat"), the student trains on the teacher's soft predictions, its probability over all classes. To make them more useful, the teacher's logits, its raw score per class, are softened with temperature scaling. The logit for class i is zi, and the temperature is T.

Dividing the logits by a temperature before the softmax flattens the probabilities.
si = ziT
The softened score si is the logit zi divided by the temperature T. Dividing every score by the same number keeps their order but shrinks the gaps between them when T is above 1, and the softmax on the next line turns gaps into probability ratios, so smaller gaps mean flatter probabilities.
pi = exp(si)Σj exp(sj)
The softmax turns the scores into probabilities pi: exp makes every score positive and keeps the larger score larger, and dividing by the sum over all classes j makes them add to 1. Applied to the teacher's logits zt this gives pt; applied to the student's zs, ps. At T = 1 this is the standard softmax. Above 1 the distribution softens and shows class similarities (a truck is closer to a car than to a cat). Below 1 it sharpens toward one-hot, all probability on one class; a very large T makes every class equally likely, so the soft targets carry nothing.

With a higher temperature the student picks up the teacher's inductive biases (tendencies its architecture and training baked in) and gets a much better signal, especially when labels are sparse or noisy.

T = 0.599%cat1%dog0%car0%birdT = 264%cat19%dog10%car6%birdT = 2029%cat25%dog24%car23%bird
Figure 3. At 0.5 almost one-hot, at 2 a clear ranking, at 20 nearly uniform.

2 The distillation loss

The student learns from two targets: the true labels, through cross-entropy (the loss that punishes a confident wrong answer hardest), and the teacher's soft predictions, through KL divergence (one number for how far apart two probability distributions sit). A mixing weight α (alpha) blends them into the total loss L; the true label is y.

The total loss blends the true labels with the teacher's soft targets.
L = (1−α)·CE(zs, y)
The first term is the hard-label loss, CE, the cross-entropy of the student's logits zs against the true label y, weighted by the labels' share 1 − α. It corrects the student where the teacher is wrong. The two weights add to 1, so α moves the weight between the two targets without changing the overall size of the loss. Raising α leans the student on the teacher: α = 1 is pure imitation and α = 0 drops the teacher entirely.
+ α·T2·KL(pt ‖ ps)
The second term is the soft-target loss, the KL divergence between the teacher's soft targets pt and the student's softened guess ps, both at the same temperature T from the temperature card, weighted by α. The factor T2 is there because dividing the logits by T shrinks this term's gradients by roughly T2; multiplying it back keeps the two terms on a comparable scale as T changes.
imagefrozen teacherstudentmixed losssoft 0.7hard 0.3soft targets, T = 2trains the studenttrue label

Figure 4. Soft targets and the true label mix at 0.7 and 0.3; only the student trains.

The KL divergence measures how far the student's bars sit from the teacher's.
KL(pt ‖ ps) = Σi pt,i log pt,ips,i
The divergence adds one term per class: the teacher's probability pt,i times the log of its ratio to the student's ps,i. Where the bars match the ratio is 1 and the log is 0, so the total is zero when every bar matches and grows as they move apart. Weighting by the teacher's probability makes a miss on a class the teacher believes in cost more than a miss on a class it rules out.

Figure 5. The student after ten steps; the slider sets T.

The listing is the loss card line for line, with the card's names; the defaults are the run's T = 2.0 and α = 0.7.

import torch.nn.functional as F

def kd_loss(z_s, z_t, y, T=2.0, alpha=0.7):
    p_t = F.softmax(z_t / T, dim=1)
    log_p_s = F.log_softmax(z_s / T, dim=1)
    kl = F.kl_div(log_p_s, p_t, reduction="batchmean")
    ce = F.cross_entropy(z_s, y)
    soft = alpha * T**2 * kl
    return (1 - alpha) * ce + soft
  1. 1Computes the soft-target loss from pt and log_p_s, both batch by classes, softened at temperature T and compared by kl (the loss card's second line). F.kl_div takes the student's log-probabilities first and the teacher's probabilities second, which gives KL(pt ‖ ps); reduction="batchmean" sums over classes and averages over the batch.
  2. 2Computes the hard-label loss, cross-entropy against the true label (first line).
  3. 3The return line is the blend, with α and the T2 factor.

3 One training step

Every training step the teacher sets soft targets, the student guesses, the loss mixes both targets, and the student updates.

Figure 6. One step; the label and the frozen teacher both teach.

Each step blends the soft targets with the true labels, and the temperature sets how soft the targets are.
L = (1−α)·CE
+ α·T2·KL
The loss is a weighted sum of two terms, the labels' share 1 − α of the hard-label loss plus α of the soft-target loss. The soft-target loss is scaled by T2 because softening shrinks its gradients by about that much; without the factor the soft signal would barely move the weights.
p = softmax(zT)
Both networks' probabilities come from the same softened softmax: the raw scores z are divided by T first. The teacher's zt give the soft targets pt, the student's zs give its guess ps. Using one temperature for both makes the two distributions comparable bar for bar.
T temperature, higher is softerKL the soft-target loss, the gap between the softened student and teacher distributionsCE the hard-label loss, cross-entropy against the true labelsα the blend weight; L the total lossp softened probabilities; z a network's raw scores (teacher or student)

The student learns the teacher's ranking, not just its answer; a hard label would teach only "cat".

4 Distilling a ResNet-18 into a small CNN

The companion notebook runs the whole recipe (Figure 7). The teacher is a ResNet-18 pretrained on ImageNet (a large labeled image dataset) with its classifier fine-tuned on STL-10 (96×96 color images in 10 classes). The student is DeeperStudentCNN, a plain CNN (convolutional neural network) with no residual connections, far shallower than the teacher but not smaller: almost all of its parameters sit in one wide fully connected layer, so this run shrinks depth, not size. Training uses Adam (an optimizer that adapts each weight's step size) for 10 epochs (full passes over the data).

The listing is that loop, with teacher, student and the STL-10 train_loader already built. The teacher stays in eval mode and runs under torch.no_grad(), so it is frozen and builds no gradient graph; only the student's weights reach the optimizer.

import torch
teacher.eval()
student.train()
params = student.parameters()
opt = torch.optim.Adam(params, lr=1e-3)
for epoch in range(10):
    for x, y in train_loader:
        with torch.no_grad():
            z_t = teacher(x)
        z_s = student(x)
        loss = kd_loss(z_s, z_t, y)
        opt.zero_grad()
        loss.backward()
        opt.step()
  1. 1Teacher in eval mode, student in train mode, optimizer over the student only.
  2. 2Teacher logits with gradients off: the teacher never trains.
  3. 3Student logits and the mixed loss.
  4. 4A normal update of the student.

The repo also trains a different, shallower student, StudentCNNWithFeatures, to mimic the teacher's intermediate features: an MSE (mean squared error) term between the two networks' feature maps joins the CE and KL terms, with weights CE 0.5, KL 0.3, MSE 0.2, temperature 2.0, 10 epochs (Figure 7).

Teacher: ResNet-1818 layers, 11.2M paramsImageNet-pretrained, classifier tuned92.58%Student: DeeperStudentCNN7 convs, 13.4M paramsresponse-based: final outputs only53.46%Student: StudentCNNWithFeatures3 convsfeature-based: also matches features42.48%STL-10 test accuracy, bars from 0%
Figure 7. The companion run; the two students differ in architecture.

53% is a long way from 93%, but this student is shallow and has no residual connections. Its training loss levelled off near 0.24 from epoch 8 of its 10, so the run had stopped improving before it ended. The repo trains no student without a teacher, so the run shows where the distilled student landed, not how much distillation added.

The two students differ in architecture, so 42.48% against 53.46% says nothing about feature matching against logit matching. What carries over is the practical point: matching raw activations (each layer's outputs) across very different architectures needs care, because feature scales differ.

5 Distilling features and relations

The distillation loss matches outputs. Other kinds of distillation match other things the teacher computes.

KindMatchesLossHelps when
Response (the original method)The softened outputsKL between the soft targets and the student's guessThe default; works across architectures
Feature (FitNets, Romero et al. 2015)A middle layerSquared distance from a projected student featureDeep, thin students
Relation (RKD, Park et al. 2019)Distances and angles between examplesGap between the two networks' distances and anglesEmbedding tasks, where the layout of examples matters
Self (Born-Again, Furlanello et al. 2018)A trained model of its own architectureThe same KL loss, one generation to the nextSame-size retraining; soft targets regularize
Responsefinal outputsteacherstudentFeaturemiddle layersteacherstudentRelationwhich examples are aliketeacherstudentSelfsame-size studentteacherstudentoutputoutputoutputoutputoutputoutput
Figure 8. Dashed boxes mark what the student copies in each kind of distillation.

6 Distillation in practice

Distillation changes two lines of an ordinary training loop: one extra teacher forward pass per batch, and kd_loss in place of cross-entropy. The ResNet-18 loop with the kd_loss function from The distillation loss is a complete implementation.

7 Pitfalls

A distilled student can then be shrunk further: Pruning removes the weights it barely uses, and quantization stores the rest in fewer bits (Post-Training Quantization and Quantization-Aware Training). The non-contrastive self-supervised methods use a form of self-distillation without labels, and the KL and cross-entropy terms are the ones in Cross-Entropy Loss.

8 References

  1. Hinton, G., et al. (2015). Distilling the Knowledge in a Neural Network. NIPS Deep Learning Workshop. arXiv:1503.02531.
  2. Bucila, C., et al. (2006). Model compression. KDD.
  3. Romero, A., et al. (2015). FitNets: Hints for Thin Deep Nets. ICLR. arXiv:1412.6550.
  4. Park, W., Kim, D., Lu, Y., Cho, M. (2019). Relational Knowledge Distillation. CVPR. arXiv:1904.05068.
  5. Furlanello, T., et al. (2018). Born-Again Neural Networks. ICML. arXiv:1805.04770.
  6. Mirzadeh, S. I., et al. (2020). Improved Knowledge Distillation via Teacher Assistant. AAAI. arXiv:1902.03393.
  7. Sanh, V., et al. (2019). DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter. arXiv:1910.01108.