◆ AI All-in-One

Level 3 In-Depth AI · Transformers and Language Models

Knowledge Distillation and Small Models

Train a small "student" model to imitate a large "teacher", not just the right answers but the teacher's full probability judgements. It is one of the main reasons small language models keep getting better.

Level
●●●●● Intermediate
Reading
10 min
To learn it well
45 minutes to read, an afternoon to practise
↗ Plan a path here

Read first

Pretraining Large Language Models

This leads to

—
The full path from zero — 33 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Language Modeling and Next-Token Prediction
  15. Supervised Learning
  16. Linear Regression
  17. The Perceptron
  18. Logistic Regression
  19. Neural Networks
  20. Recurrent Neural Networks
  21. Backpropagation
  22. Activation Functions
  23. Vanishing and Exploding Gradients
  24. Normalization Layers: BatchNorm and LayerNorm
  25. LSTMs and GRUs
  26. Residual Connections
  27. Sequence-to-Sequence Models
  28. Attention
  29. Self-Attention and Multi-Head Attention
  30. Positional Encodings
  31. The Transformer
  32. GPT and Decoder-Only Models
  33. Pretraining Large Language Models
  34. Knowledge Distillation and Small Models

Read them roughly in this order. See it on the concept map →

Why it matters

The best language models are huge, slow and expensive. Most real uses don't need all that: a support-ticket classifier, an autocomplete on a phone, or a model that runs on a laptop needs to be small, fast and cheap. But training a small model from scratch gives a small model's quality.

Knowledge distillation gets more out of a small model by letting a large teacher model teach a small student model. Instead of learning only from the correct answers in the data, the student learns to match the teacher's outputs, which carry far more information per example.

Distillation is everywhere in modern AI:

  • DistilBERT (2019) kept about 97% of BERT's language-understanding score at 40% fewer parameters and 60% faster.
  • Google's Gemma 2 (2024) trained its 2B and 9B models to match the full next-token probability distributions of a larger teacher.
  • Meta said its small Llama 3.2 1B and 3B models (2024) were trained using the output probabilities of the larger Llama 3.1 models as targets.
  • DeepSeek-R1 (2025) was distilled into small open models by fine-tuning them on 800,000 of R1's reasoning traces (Reasoning Models and Test-Time Compute).
  • Much of the open chat-model ecosystem, from Alpaca in 2023 onwards, was trained on answers generated by stronger models (Instruction Tuning and Chat Models, Synthetic Data).

Distillation, along with training small models on far more data than older rules of thumb suggested (Scaling Laws), is a big reason a 2025 model with a few billion parameters can beat much larger models from a couple of years earlier on many benchmarks.

The intuition

A student learning from a textbook's answer key sees only "the answer is B". A student learning from an expert tutor hears "it's B; C is a reasonable guess but wrong because of X; A and D are absurd". The second student learns much more from the same question: which mistakes are close, which are silly, how the options relate.

A trained classifier or language model produces exactly that richer signal: a probability for every possible answer. Shown a picture of a cat, a good image model might say cat 84%, dog 11%, car 4%. The "11% dog" isn't noise. It says that this cat looks somewhat like a dog and nothing like a car. Geoffrey Hinton called this information hidden in the small probabilities dark knowledge. A label that just says "cat" throws it away.

inputimage of a cat teacherlarge, already trained,frozen studentsmall, trained teacher soft targets (T = 4) cat 0.48 dog 0.29 car 0.23 student (T = 4) cat 0.40 dog 0.33 car 0.27 lossKL(teacher ‖ student)+ CE(true label) gradients update only the student student bars are an illustrative mid-training state
Fig. 1 The teacher–student setup. The same input goes to a large frozen teacher and a small student. The student is trained to match the teacher's softened probabilities (the distillation loss) and, usually, the true label as well.

Key idea In distillation, the student learns from the teacher's soft targets, its full probability distribution over answers, instead of only one-hot labels. Each example then carries information about how all the wrong answers relate to the right one.

How it works

Soft targets and temperature

A model's final layer produces logits z1,…,zKz_1, \dots, z_K, one per class (or, for a language model, one per vocabulary token). The softmax turns them into probabilities. Distillation adds a distillation temperature TT:

pi=ezi/T∑jezj/Tp_i = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}}

With T=1T = 1 this is the ordinary softmax. A higher TT flattens the distribution, lifting the small probabilities so the student can see the dark knowledge. These softened probabilities are the soft targets.

Worked example. Teacher logits for (cat, dog, car) are (4,2,1)(4, 2, 1).

  • At T=1T = 1: e4=54.6e^4 = 54.6, e2=7.39e^2 = 7.39, e1=2.72e^1 = 2.72, total 64.7. Probabilities (0.844,0.114,0.042)(0.844, 0.114, 0.042).
  • At T=4T = 4: divide the logits by 4 to get (1,0.5,0.25)(1, 0.5, 0.25). Then e1=2.718e^1 = 2.718, e0.5=1.649e^{0.5} = 1.649, e0.25=1.284e^{0.25} = 1.284, total 5.651. Probabilities (0.481,0.292,0.227)(0.481, 0.292, 0.227).
temperature T = 1 0.0 0.5 1.0 0.844 cat 0.114 dog 0.042 car temperature T = 4 0.0 0.5 1.0 0.481 cat 0.292 dog 0.227 car teacher logits (4, 2, 1): same ranking, but a higher T reveals how the wrong answers compare
Fig. 2 The same teacher logits turned into probabilities at temperature 1 and temperature 4. At T = 1 the distribution is dominated by "cat"; at T = 4 the relative similarity of "dog" and "car" to the right answer is much easier to see.

The ordering never changes, but at T=4T = 4 the student gets a strong signal that "dog" is the more plausible mistake.

The distillation loss

The student is trained to make its own temperature-TT distribution q(T)\mathbf{q}^{(T)} match the teacher's p(T)\mathbf{p}^{(T)}. The usual measure of mismatch is the KL divergence (Entropy, Cross-Entropy and KL Divergence), and it is usually mixed with the ordinary cross-entropy on the true label yy:

L=α T2 KL ⁣(p(T) ∥ q(T))+(1−α) CE ⁣(y, q(1))L = \alpha \, T^2 \, \mathrm{KL}\!\left(\mathbf{p}^{(T)} \,\Vert\, \mathbf{q}^{(T)}\right) + (1 - \alpha)\, \mathrm{CE}\!\left(y,\ \mathbf{q}^{(1)}\right)
  • α\alpha (between 0 and 1) balances imitating the teacher against fitting the labels.
  • The factor T2T^2 keeps the soft term's gradients at a sensible size: dividing logits by TT shrinks gradients by about 1/T21/T^2, so we multiply back (as recommended in Hinton, Vinyals and Dean, 2015).
  • At inference the student uses T=1T = 1 like any model.

The teacher is frozen. Only the student learns.

Distilling language models

For a language model, every position in the text is a classification over the whole vocabulary, so there are two main flavours:

  • Logit (token-level) distillation: run the teacher over the training text and, at every position, train the student to match the teacher's full next-token distribution (or its top few hundred entries, to save storage). This is what Gemma 2 did. It requires access to the teacher's probabilities, which in practice means an open-weight teacher or one you trained yourself.
  • Sequence-level distillation: have the teacher generate text (answers, explanations, reasoning traces) and fine-tune the student on it with the normal next-token loss. This needs only the teacher's outputs, so it works through an API. Alpaca-style instruction data and the DeepSeek-R1 distilled models are examples. It is really Fine-Tuning on Synthetic Data.

Sequence-level distillation is cheap and popular, but the student only sees the one sample the teacher produced, not its full distribution, and it can inherit the teacher's mistakes and stylistic habits.

Why small models keep improving

A small language model (loosely, under about 10 billion parameters, small enough for a laptop or phone) benefits from several trends that reinforce each other:

  1. Training far past "compute-optimal". The Chinchilla analysis (Scaling Laws) asked how to get the best model for a fixed training budget. But a model that will serve billions of requests should be small and over-trained: Meta trained Llama 3 8B on about 15 trillion tokens, far beyond the roughly 160 billion a Chinchilla-style ratio of 20 tokens per parameter would suggest.
  2. Better data, much of it filtered or rewritten by larger models.
  3. Distillation from strong teachers, by logits or by generated data.
  4. Pruning plus distillation: remove layers, heads or neurons from a trained model and then distil the original into the pruned one to recover quality (NVIDIA's Minitron work, 2024).

Limits

A student is limited by its own size: a tiny model cannot hold all of a huge model's knowledge, and studies have found that when the gap between teacher and student is too large, a medium-sized "teaching assistant" model in between can help. Students also inherit their teachers' biases and errors. And the terms of service of many commercial models restrict using their outputs to train competing models, so check the licence before distilling.

In code

A toy experiment on scikit-learn's handwritten digits (8×8 images, no download needed). A large teacher network is trained first; then a tiny 6-unit student is trained twice, once on the labels alone and once with distillation, from the same random start.

import torch, torch.nn as nn, torch.nn.functional as F
from sklearn.datasets import load_digits
torch.manual_seed(0)

X, y = load_digits(return_X_y=True)                    # 1,797 8x8 images of digits
X = torch.tensor(X / 16, dtype=torch.float32); y = torch.tensor(y)
perm = torch.randperm(len(X)); X, y = X[perm], y[perm]
Xtr, ytr, Xte, yte = X[:1200], y[:1200], X[1200:], y[1200:]

def mlp(h): return nn.Sequential(nn.Linear(64, h), nn.ReLU(), nn.Linear(h, 10))
def acc(m): return (m(Xte).argmax(1) == yte).float().mean().item()
def train(model, loss_fn, steps=1000):
    opt = torch.optim.Adam(model.parameters(), lr=1e-2)
    for _ in range(steps):
        loss = loss_fn(model(Xtr)); opt.zero_grad(); loss.backward(); opt.step()
    return model

teacher = train(mlp(512), lambda out: F.cross_entropy(out, ytr))
with torch.no_grad():
    t_logits = teacher(Xtr)

def distill_loss(out, T=4.0, alpha=0.7):
    soft = F.kl_div(F.log_softmax(out / T, 1), F.softmax(t_logits / T, 1),
                    reduction="batchmean") * T * T          # match the teacher's soft targets
    hard = F.cross_entropy(out, ytr)                         # still respect the true labels
    return alpha * soft + (1 - alpha) * hard

print(f"teacher, 512 hidden units: {acc(teacher):.3f}")
for seed in range(3):
    torch.manual_seed(seed); a = acc(train(mlp(6), lambda out: F.cross_entropy(out, ytr)))
    torch.manual_seed(seed); b = acc(train(mlp(6), distill_loss))
    print(f"student, 6 hidden units, seed {seed}: labels only {a:.3f}   distilled {b:.3f}")

# teacher, 512 hidden units: 0.978
# student, 6 hidden units, seed 0: labels only 0.931   distilled 0.951
# student, 6 hidden units, seed 1: labels only 0.930   distilled 0.951
# student, 6 hidden units, seed 2: labels only 0.905   distilled 0.923

The same tiny network, the same data and the same number of steps: distillation adds about two points of test accuracy in every run. Note that F.kl_div expects the student's log-probabilities as its first argument and the teacher's probabilities as its second.

For language models, logit distillation looks the same with the vocabulary in place of the 10 digits and one loss term per token position. Hugging Face's TRL library includes a DistillationTrainer for on-policy distillation of language models (Fine-Tuning).

Common pitfalls

  • Wrong KL direction or inputs. Mixing up log-probabilities and probabilities, or teacher and student, in the KL call is the classic bug. The loss may still go down while learning the wrong thing.
  • Forgetting T2T^2. Without it, raising the temperature silently shrinks the soft-target term and the student mostly ignores the teacher.
  • Teacher and student tokenizers differ. Logit distillation needs the same vocabulary, or a mapping between them. Sequence-level distillation does not.
  • Distilling the teacher's errors. A student trained on generated text copies its teacher's hallucinations and quirks. Filter generated data, ideally with an automatic check of correctness.
  • Evaluating only on the teacher's strengths. Students can match the teacher on benchmarks that resemble the distillation data and fall behind elsewhere. Evaluate broadly (Evaluating LLMs and Benchmarks).

Watch out Many commercial AI providers' terms prohibit using model outputs to develop competing models. Distilling from an API without checking the terms can be a contract violation. Open-weight models have their own licences too.

Variations

  • Feature (hint) distillation: match the teacher's hidden activations, not just its outputs (FitNets, 2014; DistilBERT used a cosine loss on hidden states).
  • Self-distillation: a model teaches a fresh copy of itself, which surprisingly often improves it.
  • On-policy distillation: the student generates text and the teacher scores or corrects the student's own outputs, avoiding a mismatch between what the student sees in training and what it produces later.
  • Quantization and pruning shrink a model directly instead of training a new one, and are often combined with distillation: Quantization.
  • Mixture of experts offers another route to cheaper inference: Mixture of Experts.
  • Running the results on your own hardware: Running Models Locally.

A bit of history

Cristian Bucilă, Rich Caruana and Alexandru Niculescu-Mizil showed in 2006 that a large ensemble's knowledge could be compressed into a single small network by training it on the ensemble's predictions ("model compression"). Jimmy Ba and Rich Caruana asked in 2014 whether deep nets really need to be deep, training shallow students on deep teachers' logits. Geoffrey Hinton, Oriol Vinyals and Jeff Dean's 2015 paper "Distilling the Knowledge in a Neural Network" introduced the temperature, the term distillation and the idea of dark knowledge.

For language, Yoon Kim and Alexander Rush introduced sequence-level distillation for translation in 2016, and Hugging Face's DistilBERT (2019) and Huawei's TinyBERT made distilled encoders standard. From 2023 the open-source community distilled chat behaviour from proprietary models into open ones, and by 2024–2025 major labs routinely distilled their own frontier models into small, fast versions.

Try it

  1. Work out the teacher's probabilities for logits (4,2,1)(4, 2, 1) at T=10T = 10. What happens as TT grows very large?
  2. In the code, try T=1 and T=10, and alpha=0.0 and alpha=1.0. Which setting helps the student most? What does alpha=0.0 reduce to?
  3. Give the student only the first 100 labels but distil on all 1,200 inputs (the teacher's soft targets don't need labels). How does it compare with training on the 100 labels alone?

Hint for 2: with alpha=0.0 the teacher is never used.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A teacher image model outputs cat 84%, dog 11%, car 4%. Why is training a student on these numbers better than on the label "cat" alone?

  2. What does raising the distillation temperature T from 1 to 4 do to the teacher's probabilities?

  3. You only have API access to a large model, not its probabilities. Which kind of distillation can you still do?

  4. A colleague raises the temperature but forgets the T² factor in the loss. What happens?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face LLM Course

Hugging Face · Intermediate · Free

Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.

Article

Lil'Log

Lilian Weng · Advanced · Free

Deep, carefully referenced survey posts on diffusion, agents, RL, hallucination, attention and more.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/distillation.md