Knowledge distillation
Train a small student to imitate a large teacher, via its probabilities or its generated text, keeping most of the quality on your task at a fraction of the cost and latency.
Analogy: An apprentice shadowing a master: not just copying final answers, but noticing when the master hesitates between two options. That hesitation is the extra signal soft labels carry.
How it works
- Logit distillation matches the teacher's softened probabilities, far richer than hard labels, but needs an open teacher.
- Sequence-level distillation runs plain SFT on the teacher's generated answers; it works through any API.
- On-policy distillation (GKD) has the teacher score the student's own outputs, so it learns from its mistakes.
- It copies a task distribution, not general intelligence: the student degrades off what you distilled.
- Send low-confidence inputs back to the teacher, and re-distill when the task changes.
Check yourself
Answer to mark it learned; your answers aren't scored.
To move fast, your team had the teacher invent 50k synthetic support tickets, labeled them with the teacher, and fine-tuned a 1.5B student. On a held-out split of that set the student matches the teacher 96% of the time. On real production tickets it is far worse. Most likely cause?
Go deeper
Full explanation
Knowledge distillation trains a small student model to imitate a large teacher, so you keep most of the teacher's quality on your task at a fraction of the cost and latency.
Three flavours:
- Logit (soft-label) distillation (Hinton et al., 2015): the student matches the teacher's full probability distribution, softened by a temperature. "Cat 0.7, lynx 0.2, dog 0.1" carries far more signal than the hard label "cat". It needs the teacher's logits and, for LLMs, a shared tokenizer, so in practice an open teacher. Gemma 2 (2B, 9B) and Llama 3.2 (1B, 3B) were trained on larger models' token-level outputs.
- Sequence-level distillation: the teacher generates answers and the student is trained on them with plain Supervised fine-tuning (SFT). It works through any API and is what most companies do. DeepSeek fine-tuned Qwen and Llama models on ~800k samples curated with R1 (~600k of them reasoning traces) and got strong small reasoners.
- On-policy distillation (GKD): the student generates and the teacher scores its tokens, so the student learns from its own mistakes, not only from perfect teacher outputs.
Distillation copies a task distribution, not general intelligence: the student matches the teacher on what you distilled and degrades off it.
Code Sequence-level distillation: API teacher, open student
from datasets import Dataset
from openai import OpenAI
from trl import SFTConfig, SFTTrainer
TEACHER = "gpt-4.1" # any strong model whose terms allow this
STUDENT = "Qwen/Qwen2.5-1.5B-Instruct" # small open model you will serve
client = OpenAI()
def teach(prompt: str) -> str:
# The teacher gets the long instructions and few-shots...
r = client.chat.completions.create(
model=TEACHER, temperature=0.3,
messages=[{"role": "system", "content": LONG_SYSTEM_PROMPT},
{"role": "user", "content": prompt}])
return r.choices[0].message.content
rows = []
for p in sample_production_prompts(n=20_000): # real distribution, PII scrubbed
answer = teach(p)
if passes_checks(p, answer): # schema, verifier or judge
# ...the student sees only the bare prompt and learns them implicitly
rows.append({"messages": [{"role": "user", "content": p},
{"role": "assistant", "content": answer}]})
trainer = SFTTrainer(
model=STUDENT,
train_dataset=Dataset.from_list(rows),
args=SFTConfig(output_dir="student", num_train_epochs=2, learning_rate=2e-5),
)
trainer.train()
# Gate the switch: student vs teacher on a held-out slice, per segmentReal example
A SaaS company routes 3M support tickets a month with a frontier model and a 2,500-token prompt of rules and examples: ~1.2 s per ticket and a five-figure monthly bill. The teacher labels 60k historical tickets; they keep the 52k where two teacher runs agree and fine-tune a 1.5B student on bare ticket text. On a held-out set the student matches the teacher's label 95% of the time at ~80 ms on one GPU. Tickets with student confidence below 0.7 (~6%) still go to the teacher, and they re-distill quarterly as categories change.
Trade-offs +4 · −4
+ You gain
- Large cost and latency cuts at volume: a 1–8B student serves where a frontier model can't pay off.
- Teacher labels arrive in hours, not weeks of human annotation.
- Bakes long prompts and few-shots into the weights, removing those tokens from every call.
- You own the student: self-host it, pin the version, run it offline or on-device.
− You pay
- The student inherits the teacher's errors and biases and is capped near its quality on the task.
- Narrow: quality drops off the distilled distribution, and a changed task means re-distilling.
- Provider terms may forbid training competing models on outputs; logit distillation needs an open teacher.
- Another pipeline to own: generation, filtering, eval and a retraining cadence.
Use it when
A large model already does a narrow, stable task well, but volume makes its cost or latency unacceptable, or you must run on-device or air-gapped. Try prompting a smaller model first.
Avoid it when
Low volume (the API bill is cheaper than the pipeline), broad open-ended tasks, tasks that change weekly, or when the teacher itself isn't good enough yet.
Numbers to know 4
- DistilBERT: ~40% smaller (66M vs 110M parameters), ~60% faster, keeps ~97% of BERT's GLUE performance.
- DeepSeek-R1-Distill-Qwen-32B: 72.6% AIME 2024 pass@1 vs o1-mini's 63.6%, from SFT alone on ~800k R1-curated samples.
- Same paper: distilling R1 into Qwen-32B beat running large-scale RL on it directly (72.6% vs ~47% on AIME).
- Hinton's soft targets use a temperature T > 1 and scale the soft loss by T² to keep gradients comparable.
Common pitfalls 4
- Distilling unfiltered teacher output: the student learns the hallucinations too. Verify, or keep only examples where several teacher samples agree.
- Synthetic prompts that don't match production: the student shines in eval and fails on real traffic. Distill on logged prompts.
- Ignoring terms of service: some providers forbid using outputs to build competing models. Check before you ship, not after.
- Reporting one average: the student can match on easy cases and collapse on the hard tail. Evaluate by segment and keep a fallback to the teacher.
Interview questions 2
Answer out loud first, then reveal.
When would you distill instead of labeling with humans or just prompting a smaller model?Show answer
When a big model already does the task well and the problem is cost or latency at volume. I first try prompting a smaller model; if the gap is real, distillation is the cheapest way to close it, because the teacher produces labels in hours instead of weeks of annotation. It fits narrow, stable tasks: classification, extraction, routing, fixed-format generation. The trade-off is that I freeze a snapshot: when the task or the teacher changes I must re-run the pipeline, so I budget for that and keep the teacher as a fallback for low-confidence cases.
Logit distillation or training on teacher outputs?Show answer
Logits carry the teacher's full distribution, including what it almost said, so each example teaches more and the student needs less data. But I need the logits and a compatible tokenizer, which in practice means an open teacher I host, for example a 70B distilled into an 8B of the same family. Through a closed API I only get text, so I do sequence-level distillation: more examples and heavy filtering. If the student stumbles on its own outputs at inference, on-policy distillation (GKD) helps: the student generates and the teacher grades its tokens.