Search

Search papers and lessons

Knowledge Distillation

Level 3 · 14 min read

Knowledge distillation trains a small student model to match the softened output probabilities of a large teacher, so the student learns how the teacher ranks wrong answers, not just which answer is right.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Losses & regularization
  • Neural network basics
  • Efficiency
  • Sign in to see your progress

TL;DR

Knowledge distillation trains a small student network to imitate a large teacher network. Instead of training the student only on the correct labels, you also train it to match the teacher's output probabilities, softened by a temperature so that the small probabilities on wrong classes are visible. Those probabilities carry information the hard label throws away: which wrong answers are close to right and which are absurd.

The student ends up smaller and faster than the teacher while keeping much of its accuracy. It is one of the main tools in model compression.

Where you'll see it: shrinking language models for phones and browsers, turning a bank of ensemble members into one network that serves a single request, and producing the small models that ship alongside large ones in many open-weight releases.

Intuition

A label is a lossy summary

Suppose an image of a dog is labelled "dog". The label says one thing. A trained teacher, shown the same image, might say dog with 0.90, wolf with 0.07, cat with 0.02, and car with almost nothing. The teacher's full output says that a dog looks like a wolf and a little like a cat, but not like a car. That ranking is knowledge about the problem, learned from many examples, and the hard label discards it.

Hinton has called this information "dark knowledge". The wrong-class probabilities are small, easy to ignore, and very informative about how the classes relate to one another.

Why train a small model at all

Big models are accurate but expensive. They need more memory, more compute per request, and often more energy than a deployment can afford. A small model is cheap to run but usually less accurate when trained from labels alone, partly because the labels give it less to learn from. Distillation fixes that imbalance by giving the small model the teacher's richer targets. The student can often reach accuracy that would be hard to get from the same data with the hard labels alone.

24681000.20.40.60.81temperature Tprobability
  • cat
  • dog
Teacher probabilities for a cat with scores (cat 8, dog 4, car 0). At T = 1 the answer is nearly one-hot. Raising T spreads mass onto dog and car, so the ranking becomes visible.

The plot shows the mechanism. At T=1T = 1 the teacher is almost certain, and the useful ranking is hidden in the tiny numbers. As TT rises, the probabilities spread and the student sees how the classes relate.

The recipe in one picture

flowchart LR
  X["Input example"] --> T["Teacher network"]
  X --> S["Student network"]
  T --> TS["Soft targets at temperature T"]
  S --> SS["Student softened outputs"]
  S --> SH["Student outputs at T equal 1"]
  Y["True label"] --> HL["Hard label loss"]
  TS --> KL["Soft target loss"]
  SS --> KL
  SH --> HL
  KL --> L["Total loss"]
  HL --> L

The math

Softened outputs

Let zitz^t_i be the teacher's logits (scores before softmax) and zisz^s_i the student's, for i=1,…,Ki = 1, \dots, K classes. With temperature T>0T \gt 0, define

qi=exp⁡(zit/T)∑jexp⁡(zjt/T),pi=exp⁡(zis/T)∑jexp⁡(zjs/T).q_i = \frac{\exp(z^t_i / T)}{\sum_{j} \exp(z^t_j / T)}, \qquad p_i = \frac{\exp(z^s_i / T)}{\sum_{j} \exp(z^s_j / T)}.

These are the temperature softmax from Softmax Temperature. The vector q\mathbf{q} is the soft target, and p\mathbf{p} is the student's softened prediction. The true label is yi∈{0,1}y_i \in \{0, 1\}, a one-hot vector.

The loss

The student minimises a weighted sum of two terms:

L=(1−α) Lhard+α T2 Lsoft,L = (1 - \alpha)\, \mathcal{L}_{\text{hard}} + \alpha\, T^2\, \mathcal{L}_{\text{soft}},

where

Lhard=−∑iyiln⁡σ(zs)i,Lsoft=−∑iqiln⁡pi.\mathcal{L}_{\text{hard}} = -\sum_{i} y_i \ln \sigma(\mathbf{z}^s)_i, \qquad \mathcal{L}_{\text{soft}} = -\sum_{i} q_i \ln p_i.

The hard term is ordinary Cross-Entropy Loss at temperature 1. The soft term is cross-entropy against the teacher's distribution, evaluated at temperature TT. The weight α∈[0,1]\alpha \in [0, 1] balances the two, and TT is a hyperparameter often chosen in the range 2 to 10.

Why the soft term equals a KL divergence

Cross-entropy splits into entropy plus a KL divergence:

−∑iqiln⁡pi=H(q)+DKL(q ∥ p).-\sum_i q_i \ln p_i = H(\mathbf{q}) + D_{\mathrm{KL}}(\mathbf{q} \,\|\, \mathbf{p}).

The entropy H(q)H(\mathbf{q}) does not depend on the student, so it has no effect on the gradient. Minimising Lsoft\mathcal{L}_{\text{soft}} is the same as minimising the KL divergence from the teacher's softened distribution to the student's.

The T2T^2 factor

Differentiating pip_i with respect to the student logits brings in a factor of 1/T1/T from the chain rule, and at high temperature the soft term's gradient shrinks by about 1/T21/T^2. Multiplying the soft term by T2T^2 keeps its gradient magnitude roughly the same across temperatures, so α\alpha keeps the same meaning when you change TT. This is a scaling choice, not a change to what is being learned.

Worked examples

Example
One image, temperature 4

A teacher produces logits zt=(8,4,0)z^t = (8, 4, 0) for the classes (cat, dog, car). A student produces logits zs=(3,1.5,0)z^s = (3, 1.5, 0). The true label is cat.

  1. Teacher at T=1T = 1: exp⁡(8)=2980.96\exp(8) = 2980.96, exp⁡(4)=54.60\exp(4) = 54.60, exp⁡(0)=1\exp(0) = 1. Sum =3036.56= 3036.56. So q(1)≈(0.9817,0.0180,0.0003)\mathbf{q}^{(1)} \approx (0.9817, 0.0180, 0.0003). The answer is almost one-hot.
  2. Teacher at T=4T = 4: divide logits by 4 to get (2,1,0)(2, 1, 0). Exponentials: 7.3897.389, 2.7182.718, 11. Sum =11.107= 11.107. So q≈(0.6652,0.2447,0.0900)\mathbf{q} \approx (0.6652, 0.2447, 0.0900).
  3. Student at T=4T = 4: divide logits by 4 to get (0.75,0.375,0)(0.75, 0.375, 0). Exponentials: 2.1172.117, 1.4551.455, 11. Sum =4.572= 4.572. So p≈(0.4631,0.3183,0.2187)\mathbf{p} \approx (0.4631, 0.3183, 0.2187).
  4. Soft cross-entropy: −(0.6652ln⁡0.4631+0.2447ln⁡0.3183+0.0900ln⁡0.2187)≈0.929-(0.6652 \ln 0.4631 + 0.2447 \ln 0.3183 + 0.0900 \ln 0.2187) \approx 0.929.
  5. Teacher entropy: H(q)≈0.832H(\mathbf{q}) \approx 0.832. So DKL(q∥p)≈0.929−0.832=0.097D_{\mathrm{KL}}(\mathbf{q} \| \mathbf{p}) \approx 0.929 - 0.832 = 0.097.
  6. Hard term at T=1T = 1: the student's probability for cat is 20.09/25.57≈0.785520.09 / 25.57 \approx 0.7855, so Lhard=−ln⁡0.7856≈0.241\mathcal{L}_{\text{hard}} = -\ln 0.7856 \approx 0.241.
  7. Total with α=0.5\alpha = 0.5: L=0.5⋅0.241+0.5⋅16⋅0.097≈0.121+0.776=0.897L = 0.5 \cdot 0.241 + 0.5 \cdot 16 \cdot 0.097 \approx 0.121 + 0.776 = 0.897.

Interpretation: the soft term is the larger contributor, and it measures disagreement about the whole ranking, including how the student rates dog and car. At T=4T = 4 the student gives cat 0.463 against the teacher's 0.665, and gives dog and car more mass (0.318 and 0.219) than the teacher does (0.245 and 0.090), so the soft term pushes the student to raise cat and lower dog and car.

Example
Serving cost of a distilled model

Illustrative numbers. A teacher takes 350 ms per request on one accelerator. A distilled student, of similar architecture but a quarter of the width, takes 35 ms. The service handles 1,000,000 requests per day.

  1. Teacher busy time: 1,000,000×0.350 s=350,0001{,}000{,}000 \times 0.350 \text{ s} = 350{,}000 s per day.
  2. Student busy time: 1,000,000×0.035 s=35,0001{,}000{,}000 \times 0.035 \text{ s} = 35{,}000 s per day.
  3. Ratio: 350,000/35,000=10350{,}000 / 35{,}000 = 10. The student needs one tenth of the accelerator time.
  4. If the student loses 1 point of accuracy against the teacher, the saving has to be weighed against that loss. The distillation literature usually reports a small gap, not zero, and the size of the gap depends on the task.

Interpretation: distillation changes the cost of the service, not just its model file. The question to answer before shipping is whether the accuracy gap is acceptable on your own evaluation data.

Tradeoffs and failure modes

SituationProblemBetter choice
Teacher is badly calibrated or wrong on many inputsStudent copies the teacher's mistakesImprove the teacher, or mix in the hard-label term with a larger 1−α1 - \alpha
Temperature too low (near 1)Soft targets are almost one-hot and carry little ranking informationRaise TT to about 2 to 10 and tune it
Temperature too highTargets are nearly uniform and the signal is weakLower TT
Little or no unlabelled data availableThe student only sees the training set the teacher was trained onGenerate extra inputs, or use a transfer set
Student architecture too small for the taskThe gap stays large regardless of trainingChoose a larger student, or lower the compression target
Ensemble teacher with many membersInference cost of the teacher is still high at training timeAverage the members' soft targets, then distil once

A common pitfall is evaluating the student only on the teacher's outputs. Agreement with the teacher is not accuracy against the truth. Always report both.

History

Model compression by mimicking a large model is older than the name. Bucila, Caruana and Niculescu-Mizil reported in 2006 that a large ensemble could be used to label a huge synthetic dataset, and a small neural network trained on those labels could match the ensemble much more cheaply. Their work was about compressing ensembles, and they used the teacher's predictions as targets.

Hinton, Vinyals and Dean gave the method its name and a general form in 2015, in the paper "Distilling the Knowledge in a Neural Network". They introduced the temperature-softened soft targets and the weighted loss described above, and they argued that the soft targets carry information that hard labels lack. Ba and Caruana had shown in 2014 that a shallow student trained to mimic a deep teacher could perform well, which helped make the idea attractive.

The approach caught on because it is simple to implement and works with any architecture that outputs a distribution. Later work applied it to language models, to object detectors, and to self-supervised models, and it became one of the standard ways to produce small deployable models.

Check yourself

QuestionIn one sentence, what information do soft targets provide that a one-hot label does not?Show answer

They give the relative probabilities the teacher assigns to wrong classes, which encode how the classes are related. For example, a dog may be close to a wolf and far from a car. A one-hot label only says which class is correct.

QuestionA teacher's logits are (6,2,0)(6, 2, 0). Compute the softened distribution at T=2T = 2. Give the probabilities to three decimals.Show answer

Divide the logits by 2 to get (3,1,0)(3, 1, 0). Exponentials: e3=20.086e^3 = 20.086, e1=2.718e^1 = 2.718, e0=1e^0 = 1. Sum =23.804= 23.804. Probabilities: 20.086/23.804≈0.84420.086 / 23.804 \approx 0.844, 2.718/23.804≈0.1142.718 / 23.804 \approx 0.114, 1/23.804≈0.0421 / 23.804 \approx 0.042. These sum to 1.000, as they should.

QuestionWhy does the soft loss term get multiplied by T2T^2?Show answer

Differentiating the temperature softmax brings a factor of 1/T1/T from the chain rule, and the soft term's gradient therefore shrinks by about 1/T21/T^2 as TT grows. Multiplying by T2T^2 restores the gradient scale so that the weight α\alpha has a consistent meaning across different temperatures. It does not change the optimum the student is trained toward.

QuestionYour distilled student matches the teacher's predictions on the training set almost perfectly, but it is no better than a model trained on hard labels on the held-out test set. What might be going on?Show answer

The student may be copying the teacher's behaviour on the training inputs without generalising, for example because the transfer data is too close to the training set, or because the teacher itself is overfitted and its soft targets are unreliable. Check the teacher's held-out accuracy, use a separate and varied set of inputs for distillation, and tune α\alpha and TT on a validation split.

QuestionA distilled model costs 10 times less to serve but loses 2 accuracy points. Give a decision rule for whether to ship it.Show answer

Ship it only if the accuracy loss is within the product's tolerance, measured on data that resembles real traffic, and if the cost saving is needed. Compare the expected cost of the 2-point loss (for example, errors that users notice, or downstream failures) with the saving in compute. If the errors are rare and cheap, the trade is usually worth it. If errors are costly, such as in medical or financial decisions, the answer may be no, or the student may need more work before shipping.

Sources