Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 12 of 13
Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
A teacher network with 72,196 numbers teaches a student with 676 through soft labels. On synthetic data over five seeds the student scores 73.8% against the teacher's 76.1%, and 1.2 points above a student that learned alone.
What you will learn
- Explain soft labels and why a temperature softens them
- Write a distillation loss in PyTorch with softmax, log_softmax and kl_div
- Compare a distilled student fairly against a student that learned alone, over several seeds
- Say what distillation can give you (size, speed) and what it can't
Before you start
- The Same Network in PyTorch
- The Forward Pass and Activation Functions
Think of a junior doctor learning from a senior one. The textbook gives one answer: this patient has a cold. The senior says more: mostly a cold, a small chance of flu, almost surely not an allergy. That shading is what the junior picks up.
That's distillation. The senior is the teacher model, big and accurate. The junior is the student, small and fast. And the shaded answer is called a soft label. In this article we squeeze a big network into one about 100 times smaller, test it on rows neither model has seen, and look honestly at what it gives you and what it doesn't. Everything runs on synthetic data on a CPU.
The result first
The data comes from scikit-learn's make_classification: 4,000 rows, 20 features, 4 classes, with 10% of the labels assigned at random to add noise. Half is for training (2,000 rows) and half is held out (2,000 rows).
import copy
import time
import torch
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from torch import nn
EPOCHS = 150
TEMP = 3.0
def make_data(seed):
X, y = make_classification(
n_samples=4000, n_features=20, n_informative=12,
n_classes=4, flip_y=0.1, random_state=seed,
)
parts = train_test_split(
X, y, test_size=0.5, random_state=seed
)
Xa, Xb, ya, yb = parts
return (
torch.tensor(Xa, dtype=torch.float32),
torch.tensor(Xb, dtype=torch.float32),
torch.tensor(ya), torch.tensor(yb),
)
def make_net(hidden):
return nn.Sequential(
nn.Linear(20, hidden), nn.ReLU(),
nn.Linear(hidden, hidden), nn.ReLU(),
nn.Linear(hidden, 4),
)
The teacher is make_net(256) and the student is make_net(16). Same shape, very different width:
teacher numbers: 72196
student numbers: 676
Over five seeds, the teacher averaged 76.1% on the held-out rows and the student 73.8%. About 100 times smaller and about two points lower. That's the trade.
What a soft label looks like
Before training the student, let's ask the teacher what it actually says. For seed 0:
training row, plain label: 0
training row, teacher soft: [1.0, 0.0, 0.0, 0.0]
new row, teacher soft: [0.01, 0.01, 0.02, 0.96]
how sure, seen rows: 0.93
how sure, new rows: 0.85
On a training row the plain label is class 0, and the teacher's soft answer is [1.0, 0.0, 0.0, 0.0]. The same thing. On a new row it's [0.01, 0.01, 0.02, 0.96]: mostly sure, with a small spread. On average its top guess gets 0.93 on rows it trained on and 0.85 on new rows.
So this teacher is quite sure of itself. That leaves less shading to pass on, and it may be part of why the gain you're about to see is small.
The lesson in code: train_soft
Here's how the student learns from the teacher, in distill.py:
def train_soft(net, teacher, X):
"""Learn from the teacher's soft answers."""
with torch.no_grad():
soft = (teacher(X) / TEMP).softmax(dim=1)
opt = torch.optim.Adam(net.parameters(), lr=0.01)
for _ in range(EPOCHS):
guess = (net(X) / TEMP).log_softmax(dim=1)
loss = nn.functional.kl_div(
guess, soft, reduction="batchmean"
)
opt.zero_grad()
loss.backward()
opt.step()
return net
- The teacher answers every training row. Its raw scores are divided by a temperature of 3 before softmax. A bigger temperature flattens the probabilities, so the small chances (the "maybe flu") become visible. This runs under
torch.no_grad()because the teacher isn't learning. - The student guesses, softened the same way.
log_softmaxhere, becausekl_divexpects log-probabilities for its first argument. - The loss measures how far the student is from the teacher.
kl_divis the KL divergence between the two distributions. Notice that there are no plain labels in this function at all. Theycolumn never appears. - Then the usual three lines,
zero_grad,backward,step, 150 times.
kl_div pulls the student's guess towards the teacher's soft labels. Only the student is updated.A fair comparison needs a third model
If you only compare the student with the teacher, you can't tell whether the teacher helped. Maybe a small network learning from the plain labels would do just as well. So run_one trains three models:
def run_one(seed):
torch.manual_seed(seed)
Xa, Xb, ya, yb = make_data(seed)
teacher = train_hard(make_net(256), Xa, ya)
start = make_net(16)
alone = train_hard(copy.deepcopy(start), Xa, ya)
pupil = train_soft(copy.deepcopy(start), teacher, Xa)
...
alone and pupil start from the same weights (copy.deepcopy(start)). The only difference is what they learn from: plain labels with train_hard, or the teacher with train_soft. All three are scored on the same 2,000 held-out rows, and compare.py repeats it for five seeds:
synthetic data, held-out accuracy
seed teacher alone student copied
0 0.765 0.738 0.752 0.54
1 0.762 0.728 0.728 0.60
2 0.763 0.724 0.728 0.57
3 0.749 0.707 0.724 0.54
4 0.767 0.733 0.760 0.49
mean 0.761 0.726 0.738 0.55
The student alone averaged 72.6%. The student with a teacher averaged 73.8%. So the teacher added 1.2 points. And it isn't the same every time: seed 4 gained nearly three points (0.733 to 0.760), while seed 1 gained nothing (0.728 both ways).
The honest reading: on this data, most of what the student knows it could learn alone, and the teacher helps a little.
What distillation can and can't give you
It copies mistakes too
The copied column looks only at held-out rows the teacher got wrong, and asks how often the student gave that same wrong answer. On average, 55% of the time. The student learns the teacher's opinions, good and bad.
It stays below the teacher
In every seed the student scored below the teacher. A student learns what the teacher knows, not more.
What it gives: size and speed
teacher ms per 1000 rows: 8.67
student ms per 1000 rows: 0.80
In this run the teacher took about 8.7 ms per 1,000 rows and the student about 0.8 ms. Treat those timings loosely: they moved around a lot between runs on the same machine, so don't read a fixed speed-up ratio into them. The size gap, 72,196 numbers against 676, doesn't move.
So reach for distillation when you need a model that is small and fast, you can accept a small drop in accuracy, and you've got a good teacher to learn from. For the memory side of model size, see Model Size and Memory.
Common mistakes
- Comparing the student only with the teacher. Always train a same-size student on the plain labels too, from the same starting weights. Otherwise you can't see what the teacher added.
- Judging on one seed. Here one seed showed +2.7 points and another +0. Five seeds told the real story: +1.2.
- Scoring on training rows. The teacher is near certain on rows it has seen (0.93). Only held-out rows tell you how good either model is.
- Passing probabilities where
kl_divwants log-probabilities. The student side useslog_softmax, the teacher sidesoftmax. - Expecting the student to beat the teacher. It copies the teacher, including about half of its mistakes.
Quick recap
| Idea | In this run |
|---|---|
| Soft label | The teacher's softened probabilities, e.g. [0.01, 0.01, 0.02, 0.96] |
| Temperature | TEMP = 3.0, scores divided by 3 before softmax |
| Loss | kl_div(log_softmax(student), softmax(teacher)), no plain labels |
| Size | 72,196 numbers down to 676 |
| Accuracy (5 seeds) | teacher 0.761, student alone 0.726, student with teacher 0.738 |
| Downside | Copied the teacher's wrong answer 55% of the time |
Try it yourself
In run_one, change the student from make_net(16) to make_net(64). How close does it get to the teacher now, and does the teacher still add anything over the student that learned alone?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
Next →Serving Open Models: Continuous Batching, vLLM and Cold Starts
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.