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
- Builds on
- 33 concepts →
- Quiz
- 4 questions ↓
Read first
Pretraining Large Language ModelsThis leads to
—The full path from zero — 33 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- Pretraining Large Language Models
- 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.
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 , one per class (or, for a language model, one per vocabulary token). The softmax turns them into probabilities. Distillation adds a distillation temperature :
With this is the ordinary softmax. A higher 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 .
- At : , , , total 64.7. Probabilities .
- At : divide the logits by 4 to get . Then , , , total 5.651. Probabilities .
The ordering never changes, but at 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- distribution match the teacher's . 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 :
- (between 0 and 1) balances imitating the teacher against fitting the labels.
- The factor keeps the soft term's gradients at a sensible size: dividing logits by shrinks gradients by about , so we multiply back (as recommended in Hinton, Vinyals and Dean, 2015).
- At inference the student uses 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:
- 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.
- Better data, much of it filtered or rewritten by larger models.
- Distillation from strong teachers, by logits or by generated data.
- 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 . 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
- Work out the teacher's probabilities for logits at . What happens as grows very large?
- In the code, try
T=1andT=10, andalpha=0.0andalpha=1.0. Which setting helps the student most? What doesalpha=0.0reduce to?- 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.0the teacher is never used.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Distilling the Knowledge in a Neural Network
Training small models on the soft outputs of big ones.
DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter
Distils BERT into a model 40% smaller and 60% faster that keeps about 97% of its language-understanding performance.
Gemma 2: Improving Open Language Models at a Practical Size
Trains the smaller Gemma 2 models by distillation from a larger teacher's next-token distributions instead of plain next-token prediction.
DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via RL
Open reasoning model trained largely with reinforcement learning on verifiable rewards.
Hugging Face LLM Course
Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.
Lil'Log
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