Distillation and Smaller Models
Distillation (knowledge distillation) trains a small student model to imitate a large teacher model. Instead of learning only from the right answers, the student learns from the teacher's full output: how confident it was, and which wrong answers it thought were close. The result is a model that is much smaller, faster and cheaper to run, while keeping much of the teacher's skill on the task.
Many small language models are made this way, trained on text or answers produced by larger models.
Distillation Terms
| Term | Description |
|---|---|
| Teacher | A large, accurate model whose behavior is copied |
| Student | It is used in production: a smaller model trained to match the teacher |
| Soft labels | The teacher's probabilities for every class, not just its top answer |
| Temperature | It is used to soften the probabilities so small differences between wrong answers are visible |
| Synthetic data | Examples written by a large model to train a smaller one; distillation for language models |
| Unlabeled data | Inputs without answers; the teacher provides the answers |
Example: Distilling a Digit Classifier
This program trains a teacher on the handwritten digits from "Training a Network in PyTorch", then trains three copies of a tiny student network in different ways.
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
digits = load_digits()
X = torch.tensor(digits.data / 16, dtype=torch.float32)
y = torch.tensor(digits.target)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
X_small, y_small = X_train[:200], y_train[:200] # the student only gets 200 labeled images
def accuracy(model):
with torch.no_grad():
return (model(X_test).argmax(dim=1) == y_test).float().mean().item()
def train(model, X, targets, loss_fn, epochs=60):
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
for _ in range(epochs):
for i in torch.randperm(len(X)).split(32):
optimizer.zero_grad()
loss_fn(model(X[i]), targets[i]).backward()
optimizer.step()
return model.eval()
def size(model):
return sum(p.numel() for p in model.parameters())
# The teacher: a bigger network trained on all 1,347 training images
torch.manual_seed(0)
teacher = train(nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 10)),
X_train, y_train, nn.functional.cross_entropy, epochs=20)
print(f"Teacher: {size(teacher):6,} parameters, test accuracy {accuracy(teacher):.1%}")
def student():
torch.manual_seed(1)
return nn.Sequential(nn.Linear(64, 16), nn.ReLU(), nn.Linear(16, 10))
# Student 1: learns from the 200 labels alone
s1 = train(student(), X_small, y_small, nn.functional.cross_entropy)
print(f"Student from 200 labels: {size(s1):6,} parameters, test accuracy {accuracy(s1):.1%}")
# Student 2: the same small network with all 1,347 labels
s_all = train(student(), X_train, y_train, nn.functional.cross_entropy)
print(f"Student from 1,347 labels: {size(s_all):6,} parameters, test accuracy {accuracy(s_all):.1%}")
# Student 3: distillation. It copies the teacher's soft answers on all 1,347 images, no labels needed
T = 4.0 # temperature: softer probabilities share more
with torch.no_grad():
soft = (teacher(X_train) / T).softmax(dim=1)
def distill_loss(logits, soft_targets):
return nn.functional.kl_div((logits / T).log_softmax(dim=1), soft_targets, reduction="batchmean") * T * T
s3 = train(student(), X_train, soft, distill_loss)
print(f"Student taught by teacher: {size(s3):6,} parameters, test accuracy {accuracy(s3):.1%}")
print("\nThe teacher's soft answer for one test image of a", y_test[0].item())
with torch.no_grad():
probs = (teacher(X_test[:1]) / T).softmax(dim=1)[0]
print(" ", " ".join(f"{d}:{p:.2f}" for d, p in enumerate(probs.tolist())))Teacher: 85,002 parameters, test accuracy 97.8%
Student from 200 labels: 1,210 parameters, test accuracy 91.3%
Student from 1,347 labels: 1,210 parameters, test accuracy 96.2%
Student taught by teacher: 1,210 parameters, test accuracy 96.0%
The teacher's soft answer for one test image of a 1
0:0.01 1:0.53 2:0.03 3:0.02 4:0.03 5:0.15 6:0.12 7:0.01 8:0.08 9:0.02Explanation:
| Model | Parameters | Learns from | Test accuracy |
|---|---|---|---|
| Teacher | 85,002 | 1,347 labeled images | 97.8% |
| Student | 1,210 | 200 labeled images | 91.3% |
| Student | 1,210 | 1,347 labeled images | 96.2% |
| Student, distilled | 1,210 | The teacher's soft answers on 1,347 images, no labels | 96.0% |
- The student is 70 times smaller than the teacher (1,210 parameters against 85,002), so it is far cheaper to run.
- With only 200 labels, the student reaches 91.3%. Labels are often the expensive part of a project.
- Distillation reaches 96.0% without using a single label for its 1,347 images: the teacher supplied the answers. That is almost the 96.2% the student gets from all the human labels.
- The loss compares probabilities:
kl_divmeasures how far the student's softened probabilities are from the teacher's. Multiplying byT * Tkeeps the gradients a useful size, a standard detail from the original method. - The soft answer shows what the teacher knows: for a "1" it gives 0.53 to 1 but also 0.15 to 5 and 0.12 to 6, the digits this 1 looks a bit like. A hard label would just say "1"; the soft one teaches the student which mistakes are close.
Distillation for Language Models
| Approach | How it works |
|---|---|
| Training on generated text | A large model writes answers, explanations or conversations, and a small model is fine-tuned on them |
| Matching probabilities | The student is trained to match the teacher's next-token probabilities, as with the digits |
| Reasoning distillation | A large model's step-by-step solutions teach a small model to reason through problems |
Small models made partly this way, often 1 to 10 billion parameters, can run on a laptop or phone, answer faster and cost far less per request. For one narrow task, a distilled or fine-tuned small model can match a large general model.
What Small Models Are Good At
| Small models are good at | Small models are weaker at |
|---|---|
| One narrow task, after fine-tuning or distillation | Broad knowledge and rare facts |
| Speed and low cost per request | Long, multi-step reasoning |
| Privacy: running on your own device | Following long, complicated instructions |
| Working offline | Handling very unusual inputs |
Common Mistakes
Expecting the student to beat the teacher. It usually gets close on the task it was trained for, rarely better overall.
Distilling on inputs unlike real use. The student learns the teacher's behavior only on the kinds of inputs it sees.
Copying the teacher's mistakes. A student trained on wrong answers learns them; filter the teacher's outputs.
Ignoring licenses. Using a service's outputs to train another model may break its terms.
Interview Corner
What is knowledge distillation?
Training a small student model to reproduce a large teacher model's outputs, usually its softened probabilities, so the student keeps much of the teacher's accuracy at a fraction of the size. For language models, it often means fine-tuning a small model on text generated by a large one.
Why use soft labels instead of hard labels?
Soft labels carry more information: how confident the teacher is and which wrong classes are similar. That extra signal helps the student learn faster and generalize better, especially with little data.
Practice
Exercise: temperature. Change T = 4.0 to T = 1.0 and then T = 10.0. How does the distilled student's accuracy change? Print the teacher's soft answer at each temperature to see why.
Check your understanding:
- How much smaller is the student than the teacher?
- How did the distilled student reach 96.0% without labels?
- What does the teacher's 0.15 for the digit 5 tell the student?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Teacher's soft labels | (teacher(X) / T).softmax(dim=1) |
| Distillation loss | kl_div((student(X) / T).log_softmax(dim=1), soft, reduction="batchmean") * T * T |
| Count parameters | sum(p.numel() for p in model.parameters()) |
| Turn off gradients | with torch.no_grad(): |
Was this tutorial helpful?