Distillation is the most reliable way to turn an expensive, high-quality model into a cheap one you can actually deploy. The recipe is conceptually simple — train a small student model to reproduce the behavior of a large teacher — but the details decide whether you get a 7B model that captures 95 percent of a 70B model's usefulness or an expensive failure that captures half of it. The big levers are which data you distill on, how you weight soft targets against hard labels, and how you measure quality honestly afterward.
This lesson covers the teacher–student objective and its temperature-scaled loss, how to build the synthetic training corpus, the interaction between distillation and quantization, structured pruning as a complementary compression tool, and an evaluation approach that catches the failure modes people miss.
What distillation actually transfers
A large teacher does not just emit the right answer; its output distribution over the vocabulary encodes relationships between tokens — that "Paris" and "Lyon" are closer than "Paris" and "photosynthesis", that a hedge is safer than an absolute claim. Cross-entropy training against one-hot labels discards all of that structure. Distillation preserves it by training the student to match the teacher's full soft distribution, scaled by a temperature parameter that softens the distribution and makes dark knowledge visible.
The loss combines two terms: a KL divergence between teacher and student distributions at temperature T, and ordinary cross-entropy against the ground-truth label. The temperature-squared multiplier keeps gradient magnitudes stable as T rises. Alpha sets the blend; starting around 0.5 with T between 2 and 5 is a sensible default, then tune against your eval.
import torch
import torch.nn as nn
import torch.nn.functional as F
class DistillationLoss(nn.Module):
def __init__(self, temperature: float = 3.0, alpha: float = 0.5):
super().__init__()
self.temperature = temperature
self.alpha = alpha
def forward(self, student_logits: torch.Tensor,
teacher_logits: torch.Tensor,
labels: torch.Tensor) -> torch.Tensor:
t = self.temperature
soft = F.kl_div(
F.log_softmax(student_logits / t, dim=-1),
F.softmax(teacher_logits / t, dim=-1),
reduction="batchmean",
) * (t * t)
hard = F.cross_entropy(student_logits, labels)
return self.alpha * soft + (1.0 - self.alpha) * hard
class DistillationTrainer:
def __init__(self, teacher: nn.Module, student: nn.Module,
optimizer: torch.optim.Optimizer,
temperature: float = 3.0, alpha: float = 0.5):
self.teacher = teacher.eval()
self.student = student
self.optimizer = optimizer
self.criterion = DistillationLoss(temperature, alpha)
def step(self, batch) -> float:
self.student.train()
with torch.no_grad():
teacher_logits = self.teacher(batch["input_ids"])
student_logits = self.student(batch["input_ids"])
loss = self.criterion(student_logits, teacher_logits, batch["labels"])
self.optimizer.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(self.student.parameters(), 1.0)
self.optimizer.step()
return loss.item()
Two implementation details trip people up. Freeze the teacher completely and keep it in eval mode, or dropout noise leaks into your targets. And remember that the teacher's logits must be computed at the same sequence positions and with the same tokenizer as the student; mixing tokenizers turns the KL term into noise.
Temperature and alpha: the two knobs that matter
Temperature controls how much of the teacher's distribution structure the student is asked to learn. At T = 1 the loss focuses on the teacher's confident choices; as T rises, the distribution flattens and the student receives gradient signal about the relative ranking of unlikely tokens — the dark knowledge that distinguishes a fluent model from a pattern matcher. In practice T between 2 and 5 works well for language tasks, with higher temperatures helping more when the student is much smaller than the teacher and needs every bit of structural signal it can get.
Alpha balances that soft signal against hard-label cross-entropy. Push alpha toward 1.0 and the student learns the teacher's style thoroughly but inherits its mistakes with no corrective anchor; push it toward 0.0 and you are back to ordinary supervised fine-tuning, ignoring the teacher's distribution entirely. A common schedule starts near 0.5, then reduces alpha late in training so the student finishes grounded in ground truth rather than in the teacher's quirks. Neither knob is universal: sweep both against your task suite on a small run before committing a full training budget, because the optimal pair depends on the teacher–student size gap and how noisy your hard labels are.
Beyond token matching: preference and multi-step distillation
Classic distillation transfers per-token distributions, but some behaviors are properties of whole trajectories rather than single tokens. Reasoning chains, tool-use sequences, and style preferences can all be transferred with the same teacher–student machinery by distilling on structured outputs instead of plain logits: feed the teacher's chain-of-thought or tool-call trace as the training target, or train the student directly on preference pairs the teacher produced. This is how smaller models inherit instruction-following and refusal behavior that pure next-token supervision would never teach them.
Choosing the distillation corpus
Distillation quality is dominated by data, more than by loss hyperparameters. Three sources get combined in practice. First, the original task data — real prompts and labels — which anchors the student to ground truth. Second, teacher-generated responses on unlabeled prompts, sometimes called self-distillation or expediting, which is where most of the volume comes from. Third, targeted synthetic data aimed at the teacher's strengths the student is currently worst at, generated after an initial evaluation round.
import json
import hashlib
from dataclasses import dataclass, field
from typing import Dict, List
@dataclass
class DistillExample:
prompt: str
teacher_response: str
hard_label: str = ""
source: str = "teacher"
verified: bool = False
class DistillCorpus:
def __init__(self, teacher_call, verifier=None):
self.teacher = teacher_call
self.verifier = verifier
self.examples: List[DistillExample] = []
self._seen = set()
def add(self, prompt: str, hard_label: str = "") -> bool:
key = hashlib.sha256(prompt.encode("utf-8")).hexdigest()
if key in self._seen:
return False
self._seen.add(key)
response = self.teacher(prompt)
verified = self.verifier(prompt, response) if self.verifier else False
self.examples.append(DistillExample(
prompt=prompt, teacher_response=response,
hard_label=hard_label, verified=verified,
))
return True
def focus_set(self, failures: List[str], n: int = 500) -> None:
for prompt in failures[:n]:
self.add(prompt)
def stats(self) -> Dict[str, int]:
by_source: Dict[str, int] = {}
for ex in self.examples:
by_source[ex.source] = by_source.get(ex.source, 0) + 1
return {"total": len(self.examples), "by_source": by_source,
"verified": sum(e.verified for e in self.examples)}
def export_jsonl(self, path: str) -> None:
with open(path, "w", encoding="utf-8") as fh:
for ex in self.examples:
fh.write(json.dumps(ex.__dict__, ensure_ascii=False) + "\n")
Two warnings. Teacher outputs must be filtered — a teacher hallucinating on five percent of prompts teaches the student to hallucinate on those prompts too, now at a tenth of the serving cost. And deduplicate prompts aggressively, because near-duplicate synthetic data is a well-documented cause of memorization and overconfidence in the student.
Quantization and pruning as companions
Distillation rarely travels alone. The student itself is usually quantized after training — INT8 for general serving, INT4 for edge — and quantization-aware training can be folded directly into the distillation loop so the student learns to be robust to its own quantization error. Structured pruning, especially removing entire attention heads or MLP blocks, complements distillation by reducing the architecture itself, which yields real latency gains rather than just memory savings.
| Technique | Size reduction | Latency impact | Quality loss | Retraining needed |
|---|---|---|---|---|
| Post-training INT8 | 4× | 2–3× faster | Under 1% typical | No |
| Post-training INT4 | 8× | 3–4× faster | 1–3% | No |
| Quantization-aware training | 4× | 2–3× faster | Under 0.5% | Yes |
| Knowledge distillation | 5–15× | 5–10× faster | 2–8% | Yes |
| Structured pruning (30%) | 1.4× params | Moderate gain | 1–4% | Yes |
| Distill + quantize combined | 20–40× | 8–12× faster | 3–10% | Yes |
The combined row is where most production deployments land: a 7B student distilled from a 70B teacher, then quantized to INT4 for the inference fleet. Budget a full evaluation cycle for each stage separately, because a combined pipeline makes it hard to attribute quality loss to the right cause.
Evaluating the student honestly
General-purpose benchmarks are necessary but insufficient. Small students frequently match teachers on aggregate scores while failing on the specific long-tail behaviors your product depends on — multi-step reasoning, refusal consistency, format adherence, domain jargon. Build an eval suite with three layers: an automated regression set of at least a few hundred labeled cases with per-category scoring, a side-by-side preference comparison where humans judge teacher versus student responses blind, and a canary set of known-hard prompts that the student must not regress on.
Track perplexity ratio against the teacher as a coarse health signal, but make pass@1 on your task suite the gating metric. A perplexity ratio near 1.2 with task accuracy within two points of the teacher is usually a strong result; a student that matches perplexity but collapses on tool-calling format is not deployable no matter how elegant the loss was.
Common Mistakes
Distilling on random web prompts instead of the task distribution
Fix: Generate synthetic data from the same prompt distribution production traffic actually uses.
Skipping verification of teacher outputs
Fix: Filter synthetic responses with a verifier or rubric; distillation scales teacher mistakes just as efficiently as teacher strengths.
Changing tokenizer or sequence length mid-distillation
Fix: Keep tokenizer, chat template, and position handling identical between teacher and student logits.
Judging a student only on aggregate benchmarks
Fix: Gate deploys on your own task suite and blind preference tests, not public leaderboards.
Stacking distillation, pruning, and quantization without intermediate evals
Fix: Measure after each stage so quality loss is attributable and reversible.
Best Practices
- Start distillation from an already instruction-tuned teacher; distilling from a raw base model wastes the alignment work you paid for.
- Mix hard labels in via the alpha term — pure soft-target training drifts on tasks where the teacher is confidently wrong.
- Deduplicate synthetic prompts before generation; repetition is the fastest path to a memorizing student.
- Reserve 1–5 percent of your compute for the evaluation suite that gates every distillation release.
- Publish a model card documenting teacher, data mix, loss settings, and measured quality deltas for every student you ship.
Key Takeaways
- Distillation transfers the teacher's full output distribution via temperature-scaled KL divergence, not just its top prediction.
- Data selection dominates outcomes: task-anchored, teacher-generated, and targeted synthetic prompts combined, all deduplicated and verified.
- The alpha blend between soft distillation loss and hard cross-entropy keeps the student grounded when the teacher is wrong.
- Distillation pairs naturally with INT8 or INT4 quantization and structured pruning for 20–40× compression overall.
- Gate releases on your own task suite and blind preference tests; aggregate benchmarks miss the long-tail behaviors that matter.