Skip to content
LearnAI
PART 3 · TRAINING LLMS/ Reasoning & distillation

3.10Distillation

How a small student model learns from a big teacher. Soft targets, temperature and "dark knowledge", sequence-level distillation, and how DeepSeek-R1's reasoning was passed down to 1.5B–70B models.

⏱ 15 minIntermediate

Big models are expensive; their knowledge doesn’t have to be

The best models are huge, slow and costly to run. Yet once a big model has learned something, a much smaller one can often learn to do most of the same job, if it is taught by the big model rather than from raw data. That transfer is distillationDistillationTraining a smaller 'student' model to imitate a larger 'teacher' model's outputs..

Why would learning from a model be easier than learning from data? Because a trained model’s outputs are a far richer signal than the labels in a dataset. A labeled image says “cat”, full stop. A trained classifier looking at the same image says something like “cat 90%, tiger 7%, dog 2%, truck 0.0001%”. That tells you the image is a cat, and that it looks a bit like a tiger, and that it looks nothing like a truck. A label carries a single fact. The teacher’s distribution carries a little map of similarity.

ANALOGY· Learning from a master versus an answer key

Picture two students preparing for a wine-tasting exam. One has only an answer key: “Glass 1: Merlot.” The other tastes alongside a master sommelier who says, “Merlot, almost certainly. A hint of Cabernet about it. Definitely not a white.” The second student learns why glass 1 is a Merlot and how the wines relate, from the same number of glasses.

The answer key is a hard label. The sommelier’s hedged commentary is the teacher’s soft targets. The “hint of Cabernet” is dark knowledge: information about the wrong answers that a label throws away. And asking the sommelier to “say more about the runners-up” is raising the temperature.

Soft targets and temperature

Hinton, Vinyals and Dean’s 2015 paper “Distilling the Knowledge in a Neural Network” gave this idea its standard form (building on earlier “model compression” work by Buciluǎ, Caruana and Niculescu-Mizil in 2006). The recipe:

  1. Run the teacher on an input and take its logitsLogitsRaw, unnormalized scores a model outputs, one per class or token. Softmax turns them into probabilities..
  2. Turn them into probabilities with a softmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total. at a raised temperatureTemperatureA sampling knob that divides logits before softmax. Low values make output more deterministic; high values make it more random. T>1T > 1. This is the same temperature you met in sampling: dividing logits by TT flattens the distribution, so the small probabilities become visible.
  3. Train the student so its own softmax at the same TT matches the teacher’s. These matched distributions are the soft targetsSoft targetsA teacher model's full probability distribution over outputs, often softened with a temperature above 1, used as the training target for a student instead of a one-hot label..
  4. Usually, also add an ordinary loss on the true hard labels, and combine the two.

Why the temperature? At T=1T = 1 a confident teacher puts 99.9% on the right class, and the remaining 0.1% is split among the others in amounts so tiny they barely affect the loss. Hinton and colleagues called the information hidden in those tiny numbers dark knowledgeDark knowledgeThe information hidden in a teacher's small probabilities for wrong answers, such as a cat image being judged more tiger-like than truck-like. Soft targets transfer it to a student.. Raising TT brings it into the light: “tiger 0.0007 vs truck 0.0000001” becomes “tiger 12% vs truck 2%”, big enough to learn from.

INTERACTIVESoft targets, temperature and two students
Input
step 0
All three distributions shown at temperature T = 4.0
cat ★
35.8
11.0
11.0
tiger
18.7
11.2
11.2
dog
13.8
14.7
14.7
fox
11.9
13.5
13.5
wolf
9.3
12.8
12.8
car
4.0
12.4
12.4
truck
3.4
12.6
12.6
plane
3.1
11.8
11.8
teacher student (hard labels) student (soft targets)★ = true label · numbers are %
Hard-label student
KL to teacher (at T)
0.334
P(true), T = 1
7.1%
rank match (wrong classes)
67%
Soft-target student
KL to teacher (at T)
0.334
P(true), T = 1
7.1%
rank match (wrong classes)
67%

Both students learn the right top class. Only the soft-target student learns that a cat looks more like a tiger than a truck: hard labels say nothing about the wrong classes, so their order stays wherever initialization left it. Raise T to see more of the teacher's “dark knowledge”; at T ≈ 1 the soft targets are almost one-hot.

A teacher's predictions for one image, softened by temperature. Two students with free logits train side by side: one on the hard label only, one on the teacher's soft targets. Change T, then train.

Things to try:

  1. Slide T from 1 up to 10 before training. At T = 1 the teacher’s distribution is almost one-hot. As T rises, the family resemblance appears: for the cat, tiger and dog stand out well above car, truck and plane.
  2. Train both students. Both learn that the answer is “cat”; the hard-label student even becomes more confident. But look at “wrong-class order matches”. The hard-label student’s ranking of the other classes is whatever its random initialization left. The soft-target student recovers the teacher’s similarity structure.
  3. Switch to the fox. The teacher thinks a fox looks like a wolf and a dog. That knowledge is in no label anywhere, yet the soft-target student picks it up from a single example.
  4. Train at T = 1, then reset and train at T = 4. At low temperature the tiny probabilities produce tiny gradients, so the soft-target student learns the fine structure much more slowly. That’s the practical reason for raising T.

Hinton and colleagues showed some striking effects. In an MNIST experiment, a student trained on a transfer set from which every example of the digit 3 had been removed could still recognize most 3s, after adjusting one bias term, purely from the probability mass the teacher gave to “3” when looking at other digits. In speech recognition, they distilled an ensemble of 10 models into a single model that captured most of the ensemble’s improvement.

Distilling language models

For an LLM, every next-token prediction is a classification over a vocabularyVocabularyThe fixed set of tokens a model knows, typically 32k–260k entries for modern LLMs. of perhaps 100,000+ tokens, so the classic recipe applies directly. Two families of methods are common.

Logit (token-level) distillation. At every position of the training text, match the student’s next-token distribution to the teacher’s with a KL divergence, exactly as in the demo but over the vocabulary. This needs the teacher’s logits, so you must run the teacher yourself, and teacher and student should share a tokenizer. It’s used to train small members of model families from larger siblings: DistilBERT (2019) was trained this way, keeping about 97% of BERT’s language-understanding performance at 40% smaller size, and Google’s Gemma 2 technical report describes training its smaller models with knowledge distillation from a larger teacher during pretraining.

Sequence-level distillation. Generate complete outputs with the teacher and fine-tune the student on them with ordinary SFT. Kim and Rush (2016) introduced this for translation, where training on the teacher’s beam-search outputs worked better than token-level matching. It needs no access to the teacher’s internals, just its text. Most “synthetic data” pipelines in modern post-training are, in effect, sequence-level distillation: Alpaca’s 52,000 instructions were generated by an OpenAI model, and many open models are fine-tuned largely on outputs of stronger ones.

Case study: DeepSeek-R1’s distilled models

The DeepSeek-R1 paper (2025) is the most visible distillation story of the reasoning era. After training R1 with large-scale RL (see Reasoning models), DeepSeek used it to generate roughly 800,000 training samples, mostly long chains of thought on math, code and other reasoning problems, plus general-purpose data. They then fine-tuned six existing open models on this data with SFT only, no RL:

Distilled modelBase model
DeepSeek-R1-Distill-Qwen-1.5BQwen2.5-Math-1.5B
DeepSeek-R1-Distill-Qwen-7BQwen2.5-Math-7B
DeepSeek-R1-Distill-Llama-8BLlama-3.1-8B
DeepSeek-R1-Distill-Qwen-14BQwen2.5-14B
DeepSeek-R1-Distill-Qwen-32BQwen2.5-32B
DeepSeek-R1-Distill-Llama-70BLlama-3.3-70B-Instruct

The results were striking: the paper reports DeepSeek-R1-Distill-Qwen-7B reaching 55.5% on AIME 2024 and the 32B model 72.6%. Even more interesting is a controlled comparison. DeepSeek also ran large-scale RL directly on Qwen2.5-32B; it ended up far behind the 32B model distilled from R1. Their conclusion: reasoning patterns discovered by a bigger model through RL can be transferred to a smaller one more cheaply than the smaller model can discover them itself, though pushing beyond the teacher still requires stronger base models and more RL.

On-policy distillation

Sequence-level distillation has a subtle flaw. The student only ever practices on the teacher’s text. At inference time, though, it generates its own text, makes its own early mistakes, and finds itself in situations the teacher’s outputs never showed. Errors compound, a mismatch known as exposure bias.

On-policy distillation fixes this by letting the student generate, then asking the teacher to grade the student’s tokens. Agarwal et al. (2023) formalized it as Generalized Knowledge Distillation (GKD): sample sequences from the student, and train the student to match the teacher’s next-token distribution on those sequences. It combines the dense, per-token feedback of distillation with the “learn from your own mistakes” property of RL. A widely read 2025 post from Thinking Machines Lab described a version that uses the per-token reverse KL to the teacher as a reward, and reported reaching RL-level reasoning results at a fraction of RL’s compute. The Qwen3 technical report also describes an on-policy distillation stage for its smaller models. Exact recipes differ and are still evolving, so treat specific gains as setup-dependent.

MATH CORNER · optionalThe distillation loss, and why there's a T² in it

Let teacher logits be ztz^{t} and student logits zsz^{s}. Softened distributions at temperature TT:

pi(T)=ezit/T∑jezjt/T,qi(T)=ezis/T∑jezjs/T.p_i^{(T)} = \frac{e^{z^t_i / T}}{\sum_j e^{z^t_j / T}}, \qquad q_i^{(T)} = \frac{e^{z^s_i / T}}{\sum_j e^{z^s_j / T}}.

The classic combined loss, with weight α\alpha and hard label yy:

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

The gradient of the KL term with respect to a student logit is 1T(qi(T)−pi(T))\frac{1}{T}\left(q_i^{(T)} - p_i^{(T)}\right). Gradients therefore shrink like 1/T1/T, and like 1/T21/T^2 in the high-temperature limit, so the T2T^2 factor keeps the soft loss’s contribution roughly constant as you change TT. (The demo uses exactly this scaled gradient.)

Worked example with three classes (cat, tiger, truck). Teacher logits (4,2,0)(4, 2, 0); the student currently has logits (3,1,1)(3, 1, 1), so it can’t yet tell a tiger from a truck:

T=1T = 1T=2T = 2T=4T = 4
teacher pp(0.867,0.117,0.016)(0.867, 0.117, 0.016)(0.665,0.245,0.090)(0.665, 0.245, 0.090)(0.506,0.307,0.186)(0.506, 0.307, 0.186)
student qq(0.787,0.107,0.107)(0.787, 0.107, 0.107)(0.576,0.212,0.212)(0.576, 0.212, 0.212)(0.452,0.274,0.274)(0.452, 0.274, 0.274)

At T=2T = 2: KL(p∥q)=0.665ln⁡0.6650.576+0.245ln⁡0.2450.212+0.090ln⁡0.0900.212≈0.096+0.035−0.077=0.054\mathrm{KL}(p \| q) = 0.665 \ln\frac{0.665}{0.576} + 0.245 \ln\frac{0.245}{0.212} + 0.090 \ln\frac{0.090}{0.212} \approx 0.096 + 0.035 - 0.077 = 0.054.

The scaled soft-target gradient is T(q−p)=(−0.178,−0.066,+0.244)T(q - p) = (-0.178, -0.066, +0.244). Gradient descent moves logits against the gradient, so it raises cat, raises tiger a little, and lowers truck: the student learns that tigers are more cat-like than trucks. The hard-label gradient is q(1)−y=(−0.213,+0.107,+0.107)q^{(1)} - y = (-0.213, +0.107, +0.107): it pushes tiger and truck down by exactly the same amount. A one-hot label has no opinion about which wrong answer is less wrong.

In code

Token-level distillation for a causal LM, with the teacher frozen:

import torch, torch.nn.functional as F

T, alpha = 2.0, 0.5
with torch.no_grad():
    t_logits = teacher(input_ids).logits             # (B, L, V)
s_logits = student(input_ids).logits                 # same tokenizer required

soft = F.kl_div(
    F.log_softmax(s_logits / T, dim=-1),             # student log-probs at T
    F.log_softmax(t_logits / T, dim=-1),             # teacher log-probs at T
    log_target=True, reduction="batchmean",
) * T * T                                            # the T² correction

hard = F.cross_entropy(s_logits[:, :-1].flatten(0, 1), input_ids[:, 1:].flatten())
loss = alpha * soft + (1 - alpha) * hard
loss.backward(); optimizer.step()

Sequence-level distillation needs no special code at all: generate with the teacher, filter the outputs (for reasoning data, typically keep only chains that reach a correct answer), and run ordinary SFT on them.

COMMON MISCONCEPTIONS
  • “Distillation just copies the teacher’s answers.” Classic distillation copies the teacher’s whole distribution, including how it ranks wrong answers. That extra information is why it can beat training on labels alone.
  • “A distilled student can’t beat its teacher.” Usually it doesn’t overall, but students can exceed their teachers on some benchmarks, especially when the teacher’s outputs are filtered for correctness. And the student often beats an identically sized model trained without a teacher.
  • “Higher temperature is always better.” Very high TT flattens everything toward uniform and washes out even the right answer. In practice moderate values (often in the low single digits) work well; it’s a tuned hyperparameter.
  • “Distillation needs the teacher’s weights.” Logit distillation needs the teacher’s output probabilities. Sequence-level distillation needs only its generated text, which is why it’s so widespread, and why providers’ terms of service often address it.

Check your understanding

0/5 answered
  1. Q1.Why does raising the temperature help in classic (Hinton-style) distillation?

  2. Q2.A teacher gives an image of a cat: cat 90%, tiger 7%, truck 0.001%. What does this tell a student that the hard label 'cat' does not?

  3. Q3.How were the DeepSeek-R1-Distill models (1.5B to 70B) trained?

  4. Q4.What problem does on-policy distillation address?

  5. Q5.Why is the soft-target KL loss multiplied by T²?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.