On this page
A 70B reasoning model solves 94% of your technical QA benchmarks, but takes 180 milliseconds per response and blows through your serving budget. A 7B model answers in 42 milliseconds at less than half the cost, yet fine-tuning it on ground-truth answer strings alone leaves a sharp accuracy gap on tricky edge cases.
Knowledge distillation closes that gap by training a compact student directly from the behavior of a stronger teacher. With white-box access, the student matches softened next-token probabilities or intermediate hidden states. With black-box text-only access, it fine-tunes on verified teacher answers and reasoning traces.
Soft labels and dark knowledge
Hinton et al. showed that a teacher's full probability distribution carries far more supervision than a one-hot target.[1] Consider a four-token vocabulary for a cache-retention prompt: 7d, 3d, 30d, and never. A hard label puts 1.00 on 7d and 0.00 everywhere else, telling the student which token wins while erasing how close the runners-up were.
The teacher's non-target probabilities preserve that similarity structure. Giving 3d far more mass than 30d or never teaches the student that shorter TTL windows lie much closer to 7d than disabling caching altogether. Hinton et al. called this relative structure dark knowledge.
![Three aligned probability distributions compare a hard one-hot target with teacher softmax probabilities at T=1 and T=4 from logits [4.0, 2.0, 1.0, 0.7] over 7d, 3d, 30d, and never. Raising temperature to T=4 preserves the exact ranking while narrowing the top gap (7d minus 3d) from 1.000 to 0.708 to 0.156 and lifting informative probability mass onto secondary candidates.](https://assets.leetllm.com/v1/f3d21b149c4e/training/knowledge-distillation-llms/illustrations/_generated/soft_labels_dark_knowledge_dark.png)
Dividing raw logits by a temperature before softmax lifts those runner-up probabilities without altering rank order. When ground-truth labels are also present, training blends soft distillation loss with standard task cross-entropy:
At scale, next-token distillation pays off sharply. In the Gemma 2 technical report, a 2B student trained for 500B tokens via logit distillation from a 7B teacher reached 67.7 on their three-benchmark average, compared with 60.3 trained from scratch on the same token budget.[2]
Logit distillation and temperature scaling
In white-box causal language models, logit distillation minimizes KL divergence between the frozen teacher's and student's softened next-token distributions at every supervised prefix position:
Why multiply by ? Differentiating the unscaled soft cross-entropy with respect to student logit yields . Because large also shrinks roughly as , the unscaled gradient decays like , drowning out the distillation term relative to the hard loss.[1] Multiplying by restores the gradient to , which converges to centered-logit MSE matching as .
Verify both temperature softening and gradient preservation directly in PyTorch:
import torch
import torch.nn.functional as F
teacher = torch.tensor([4.0, 2.0, 1.0, 0.7], dtype=torch.float64)
base_student = torch.tensor([1.0, 0.4, 0.1, -0.2], dtype=torch.float64)
high_temp_limit = ((base_student - base_student.mean()) - (teacher - teacher.mean())) / len(teacher)
for T in (1.0, 4.0, 40.0, 400.0):
student = base_student.clone().requires_grad_()
q_log = F.log_softmax(teacher / T, dim=0)
p_log = F.log_softmax(student / T, dim=0)
loss = F.kl_div(p_log, q_log, log_target=True, reduction="sum")
(raw_grad,) = torch.autograd.grad(loss, student)
scaled_grad = (T ** 2) * raw_grad
gap = (scaled_grad - high_temp_limit).norm()
top_gap = float(q_log.exp()[0] - q_log.exp()[1])
print(f"T={T:5g} | top_gap={top_gap:.3f} | raw_norm={raw_grad.norm():.6f} | scaled_norm={scaled_grad.norm():.6f} | dist_to_limit={gap:.6f}")T= 1 | top_gap=0.708 | raw_norm=0.434065 | scaled_norm=0.434065 | dist_to_limit=0.156800
T= 4 | top_gap=0.156 | raw_norm=0.030553 | scaled_norm=0.488844 | dist_to_limit=0.080567
T= 40 | top_gap=0.013 | raw_norm=0.000272 | scaled_norm=0.435812 | dist_to_limit=0.008958
T= 400 | top_gap=0.001 | raw_norm=0.000003 | scaled_norm=0.429383 | dist_to_limit=0.000901Causal alignment and vocabulary identity
Two silent alignment bugs ruin autoregressive logit distillation:
- One-step label shift: Logits at prefix position predict the hard token at . Shift hard labels left (
labels[1:]), while keeping teacher and student logits aligned at the same position (logits[:-1]). - Exact token-to-ID mapping: Equal
vocab_sizeis insufficient. If token ID17meansreturnin the teacher and<pad>in the student, KL training runs without errors while driving the student toward gibberish.
![Four prefix positions t0 through t3 align teacher and student 4-logit vectors vertically for KL distillation over shared token IDs (0=7d, 1=3d, 2=30d, 3=never). Below, original labels [0, 0, 1, -100] shift left by one step to pair t0 with 0 (7d), t1 with 1 (3d), and t2 with -100 (masked out of both KL and cross-entropy loss), while t3 has no next label.](https://assets.leetllm.com/v1/1d3a2a654257/training/knowledge-distillation-llms/illustrations/_generated/causal_logit_alignment_dark.png)
Forward versus reverse KL
Because KL divergence is asymmetric, choosing which distribution sits on the left dictates how a capacity-limited student allocates probability mass:
- Forward KL (mode-covering): Putting anywhere drives the penalty to . A smaller student stretches mass across all teacher modes, sometimes spilling probability into low-quality valleys between them.
- Reverse KL (mode-seeking): Putting where blows up the loss, whereas dropping an entire teacher mode pays only a finite cost (covering one of two equal
0.5modes gives ). The student concentrates sharply on high-probability teacher modes, boosting precision at the cost of diversity.
Neither direction wins everywhere. MiniLLM optimizes sequence-level reverse KL via policy gradients with teacher-mixed sampling and length normalization to prevent repetition collapse.[3] Generalized Knowledge Distillation (GKD) decouples divergence from sampling and finds generalized Jensen-Shannon divergence beats both KL directions on smaller translation students, while forward KL wins its headline GSM8K run.[4]
By the chain rule of KL divergence, a full-sequence KL decomposes into next-token KL terms weighted by prefixes drawn from the left distribution. Watch both the chain-rule identity and the asymmetry on tail leaks:

import math
def kl(left: list[float], right: list[float]) -> float:
total = 0.0
for p, q in zip(left, right):
if p == 0.0:
continue
if q == 0.0:
return math.inf
total += p * math.log(p / q)
return total
# 1. Tail leak asymmetry on (7d, 3d, never)
teacher = [0.58, 0.40, 0.02]
for name, student in [("mild_leak", [0.54, 0.36, 0.10]), ("heavy_leak", [0.40, 0.35, 0.25])]:
print(f"{name:10s} | forward KL={kl(teacher, student):.3f} | reverse KL={kl(student, teacher):.3f}")
print(f"drop mode | forward KL={kl([0.5, 0.5], [1.0, 0.0])} | reverse KL={kl([1.0, 0.0], [0.5, 0.5]):.3f}")
# 2. Sequence KL chain rule weights prefixes by the left distribution
t1, s1 = [0.8, 0.2], [0.5, 0.5]
t2, s2 = [[0.9, 0.1], [0.2, 0.8]], [[0.5, 0.5], [0.4, 0.6]]
t_joint = [t1[i] * t2[i][j] for i in range(2) for j in range(2)]
s_joint = [s1[i] * s2[i][j] for i in range(2) for j in range(2)]
fwd_chain = kl(t1, s1) + sum(t1[i] * kl(t2[i], s2[i]) for i in range(2))
rev_chain = kl(s1, t1) + sum(s1[i] * kl(s2[i], t2[i]) for i in range(2))
print(f"seq forward: joint={kl(t_joint, s_joint):.6f} == teacher-weighted={fwd_chain:.6f}")
print(f"seq reverse: joint={kl(s_joint, t_joint):.6f} == student-weighted={rev_chain:.6f}")mild_leak | forward KL=0.051 | reverse KL=0.084
heavy_leak | forward KL=0.218 | reverse KL=0.436
drop mode | forward KL=inf | reverse KL=0.693
seq forward: joint=0.505499 == teacher-weighted=0.505499
seq reverse: joint=0.530881 == student-weighted=0.530881Response distillation and synthetic reasoning traces
When the teacher is behind an API or uses a different tokenizer, response distillation (sequence-level KD) fine-tunes the student on verified (prompt, response) completions generated by the teacher. It decouples teacher inference from student GPU memory, works across model families, and transfers multi-step reasoning traces that far outpace short final-answer labels.
| Recipe | Teacher signal | Key takeaway |
|---|---|---|
| Alpaca 7B[5] | 52K Self-Instruct pairs | Popularized synthetic SFT distillation (non-commercial license) |
| Orca 13B[6] | Step-by-step explanation traces | Rich rationales outperform terse answer imitation |
| phi-1.5[7] | Synthetic textbook prose + filtered code | High-signal synthetic corpora rival much larger web datasets |
| Distilling Step-by-Step[8] | Rationales + task labels | Multi-task supervision cuts labeled data requirements |
| DeepSeek-R1-Distill[9] | ~800K curated reasoning + general traces | Fine-tuned Qwen/Llama students (32B Qwen hit 72.6% AIME 2024 pass@1 and 94.3% MATH-500) |
Standard SFT treats every teacher token as ground truth, so unfiltered errors become training targets. Use a Seed-Expand-Filter pipeline: author 100 to 500 seed prompts, split seed families before expansion so paraphrases never cross train/eval boundaries, deduplicate prompts before paying for teacher generation, and filter outputs with programmatic verifiers (unit tests, math checkers, schema checks):
def normalize(text: str) -> str:
return " ".join(text.lower().replace("?", "").split())
held_out_eval = {
normalize("Explain how FlashAttention tiles SRAM"),
normalize("Derive the softmax Jacobian"),
}
candidates = [
("What is 17 * 24?", "408", "408"),
(" what is 17 * 24? ", "408", "408"),
("What is 2**10 - 24?", "1024", "1000"),
("Explain how FlashAttention tiles SRAM?", "Tiles Q, K, V...", "Tiles Q, K, V..."),
]
seen, kept, dropped = set(), [], []
for prompt, teacher_out, expected in candidates: key = normalize(prompt)
if key in seen:
dropped.append((prompt.strip(), "duplicate"))
elif key in held_out_eval:
dropped.append((prompt.strip(), "eval_contamination"))
elif teacher_out != expected:
dropped.append((prompt.strip(), "wrong_teacher_output"))
else:
seen.add(key)
kept.append({"prompt": prompt.strip(), "response": teacher_out})
print("kept training rows:", kept)
print("filtered out: ", dropped)kept training rows: [{'prompt': 'What is 17 * 24?', 'response': '408'}]
filtered out: [('what is 17 * 24?', 'duplicate'), ('What is 2**10 - 24?', 'wrong_teacher_output'), ('Explain how FlashAttention tiles SRAM?', 'eval_contamination')]Feature alignment and student-sampled supervision
Feature distillation
With white-box access, feature distillation aligns selected student hidden states to corresponding detached teacher layers using a learned linear projection that bridges hidden-dimension differences:
Here pairs student layer with a teacher layer (depths need not match), and padding tokens are masked before averaging. Because layer pairing and activation storage add real complexity, benchmark feature matching against plain logit KD on held-out tasks before adopting it.
Closing exposure bias with student-generated prefixes
Training strictly on fixed teacher completions suffers from exposure bias: at inference time the student conditions on its own earlier tokens, so a single off-track token shifts it into prefixes absent from the offline dataset.
On-policy distillation (OPD) fixes this by sampling live completions from the student and scoring those exact student-generated prefixes with the teacher. In GKD, a mixing fraction blends fixed teacher prefixes with live student generations, and either forward KL, reverse KL, or generalized Jensen-Shannon divergence applies on top.[4] Gemma 2's post-training similarly combines synthetic teacher responses with distillation on the student's own distribution.[2] Remember that the sampling source (fixed dataset vs live student samples) is orthogonal to the divergence (forward vs reverse KL).

| Method | Teacher signal | Main advantage | Main constraint |
|---|---|---|---|
| Response KD | Verified text traces | Tokenizer-independent; works with API teachers | Unfiltered teacher errors become SFT targets |
| Logit KD | Softened token probabilities | Transfers full runner-up ranking | Requires identical token-to-ID vocabulary |
| Feature KD | Intermediate hidden states | Supervises internal representations | Extra layer mapping, projections, and memory |
| Student-sampled KD (OPD) | Teacher logits on student prefixes | Closes exposure bias directly | Requires online student sampling + teacher scoring |
Production trainers such as Hugging Face TRL's DistillationTrainer and experimental GKDTrainer implement live student sampling and chunked full-vocabulary generalized Jensen-Shannon losses to avoid materializing giant [batch, seq, vocab] tensors (note that chunked trainers reading lm_head.weight directly need modules_to_save=["lm_head"] rather than LoRA on lm_head).[10][11]
Practical PyTorch training loop and logit caching
A bug-free PyTorch logit KD loop requires three invariants:
- Freeze the teacher: Set
teacher.requires_grad_(False)andteacher.eval(), and run teacher forward passes undertorch.no_grad(). - Mask prompt and padding tokens explicitly:
F.cross_entropysupportsignore_index=-100, whereasF.kl_divdoes not.[12][13] Index both branches withvalid = shifted_labels != -100. - Flatten valid tokens before
batchmean:F.kl_div(..., reduction="batchmean")divides by the leading dimension only.[13] Flattening to[num_valid_tokens, vocab]yields a true per-token mean; leaving[batch, seq, vocab]sums across sequence length instead.
import torch
from torch import nn
import torch.nn.functional as F
class TinyLM(nn.Module):
def __init__(self, vocab_size: int, hidden_size: int):
super().__init__()
self.embed = nn.Embedding(vocab_size, hidden_size)
self.lm_head = nn.Linear(hidden_size, vocab_size)
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.lm_head(self.embed(input_ids))
def kd_loss(student_logits, teacher_logits, labels, vocab_s, vocab_t, temperature=3.0, alpha=0.7):
if vocab_s != vocab_t:
raise ValueError("Logit KD requires identical token-to-ID mappings.")
shifted_labels = labels[:, 1:]
valid = shifted_labels != -100
if not valid.any():
raise ValueError("No supervised next-token positions; skip this batch.")
s_flat = student_logits[:, :-1, :][valid].float()
t_flat = teacher_logits[:, :-1, :].detach()[valid].float()
y_flat = shifted_labels[valid]
soft = F.kl_div(
F.log_softmax(s_flat / temperature, dim=-1),
F.log_softmax(t_flat / temperature, dim=-1),
log_target=True,
reduction="batchmean",
) * (temperature ** 2)
hard = F.cross_entropy(s_flat, y_flat)
return alpha * soft + (1.0 - alpha) * hard
torch.manual_seed(0)
torch.set_num_threads(1)
vocab = tuple(f"t{i}" for i in range(12))
teacher = TinyLM(12, 16).eval()
teacher.requires_grad_(False)
student = TinyLM(12, 6).train()
optimizer = torch.optim.AdamW(student.parameters(), lr=0.05)
input_ids = torch.tensor([[1, 2, 3, 4, 5], [1, 3, 5, 7, 9]])
labels = input_ids.clone()
labels[:, :2] = -100 # mask prompt tokens
labels[1, -1] = -100 # mask trailing padding token
with torch.no_grad():
teacher_logits = teacher(input_ids)
teacher_before = teacher.lm_head.weight.clone()
loss_before = kd_loss(student(input_ids), teacher_logits, labels, vocab, vocab)
optimizer.zero_grad()
loss_before.backward()
optimizer.step()
loss_after = kd_loss(student(input_ids), teacher_logits, labels, vocab, vocab)
perturbed = teacher_logits.clone()
perturbed[:, :-1, :][labels[:, 1:] == -100] = 1000.0
loss_perturbed = kd_loss(student(input_ids), perturbed, labels, vocab, vocab)
print(f"loss before -> after : {float(loss_before):.4f} -> {float(loss_after):.4f}")
print(f"teacher frozen : {bool(torch.equal(teacher.lm_head.weight, teacher_before))}")
print(f"ignored-mask delta : {abs(float(loss_after - loss_perturbed)):.6f}")loss before -> after : 1.1329 -> 0.9520
teacher frozen : True
ignored-mask delta : 0.000000Offline top-k logit caching and the tail illusion
Caching dense bf16 teacher logits over 50M tokens and a 32K vocabulary consumes 2,980.2 GiB, whereas caching top-k (k=64) values plus int32 token IDs takes 17.9 GiB (166.7x smaller). Never renormalize only the top- tokens to sum to 1, however: if the teacher puts [0.60, 0.30, 0.10] and the student puts [0.30, 0.15, 0.55], both renormalized top-2 distributions become [2/3, 1/3], reporting 0.000 KL while hiding a 0.453 full-vocabulary error where the student dumps 55% mass onto tail junk! Keep an explicit residual tail bucket (1 - sum(top_k)) whenever caching top- logits.
| Quantity | Formula | Value |
|---|---|---|
| Dense bf16 logit cache (50M tok, 32K vocab) | 2,980.2 GiB | |
Top-64 cache (bf16 value + int32 ID) | 17.9 GiB (166.7x smaller) | |
| Full-vocabulary forward KL | on [0.60, 0.30, 0.10] vs. [0.30, 0.15, 0.55] | 0.453 |
| Renormalized top-2 KL (no tail bucket) | Both rescale to [2/3, 1/3] | 0.000 (hides 55% tail error) |
Capacity limits, evaluation, and failure modes
Distillation cannot bypass student parameter capacity, shorter context windows, or missing prompt coverage. Benchmark four checkpoints under identical decoding budgets: the base student, hard-label SFT, the distilled student, and the teacher. Check licensing as well, since teacher API terms and open weights often restrict commercial distillation.[5]
Ship a distilled student only when it clears every target threshold simultaneously: accuracy, critical error rate, latency, and serving cost.

| Symptom | Likely cause | Fix |
|---|---|---|
| Higher stops helping held-out scores | Over-softening blurs informative peaks | Tune and on held-out tasks, not training KL |
| Student predicts current token | Missing one-token shift on hard labels | Pair logits at with hard labels at |
| KL drops cleanly, outputs are gibberish | Teacher/student token-to-ID mismatch | Verify exact vocabulary equality or use response KD |
| Student repeats teacher hallucinations | Unfiltered SFT errors or excessive | Filter traces with verifiers and lower |
| Small student fails hard reasoning slices | Capacity gap or exposure bias | Increase student size, narrow scope, or add OPD |