13.4 Knowledge Distillation
A support team wants a smaller classifier to route messages to billing or returns. Its teacher replies “billing.” A second teacher supplies both class probabilities. The two answers pick the same queue, but only the second tells the student how close the decision was. Knowledge distillation trains a student model on signals from a teacher. Choosing an objective begins with what you can observe.
1. What can the teacher provide?
For the same input, let and be the teacher and student logits over the same classes. At temperature , their distributions are and . Hinton et al. used softened output probabilities as targets. Increasing above 1 makes the distribution flatter, exposing differences among low-probability classes. A commonly scaled loss is [1]
Here indexes classes and the natural logarithm measures forward KL in nats before the scaling. If the teacher gives only its top label, the student cannot reconstruct the full distribution for that input.
Match the objective to the available signal
| Teacher signal | What the student can train on |
|---|---|
| An answer or a generated explanation | Collect the text and train the student to predict its tokens. Hsieh et al. used generated rationales as an additional text target. An explanation is observable text. Whether it faithfully describes the computation that produced the answer is a separate question. [2] |
| Full logits or probabilities | Match distributions when both models refer to the same outcomes. For next-token KL, check the token IDs, ordering and conditioning prefix. A few returned top tokens leave the remaining probability allocation unknown. [1] |
| Intermediate features | Capture activations at chosen layers and positions. FitNets, first posted in December 2014, trained a projection from student features to teacher features. This requires access to the relevant tensors. [6] |
Text, probabilities and features can provide complementary supervision. To see exactly what the third option adds, change the hidden coordinates and the output layer independently.
2. Distribution Calibration for Generative Models: Forward KL vs Reverse KL
In knowledge distillation for autoregressive models that generate tokens sequentially, one of the most critical mathematical decisions is the direction of the Divergence function. Traditional knowledge distillation minimizes the Forward KL Divergence between the teacher distribution and the student distribution .
- Forward KL (Mean-seeking): This is the classic choice. It encourages the student to cover the support of the teacher distribution. That can be helpful when broad coverage matters, but it can also spread probability mass too widely when the student is much smaller than the teacher.
- Reverse KL (Mode-seeking): Work such as MiniLLM argues that for autoregressive generation, Reverse KL Divergence can be a better fit in some settings [3]. It encourages the student to commit more strongly to modes the teacher itself prefers, which can improve fluency and reduce diffuse, low-confidence generations.
The key lesson is not that one direction is universally superior. It is that the divergence choice changes the student’s behavior, and generative KD often benefits from treating this as a design decision rather than a default.
3. On-Policy Distillation: Learning from Student’s Mistakes
Fixed teacher trajectories and student-generated trajectories can differ in distribution. Teacher outputs can also contain errors, and one different student token does not necessarily cause failure. Evaluate errors in actual student states and design the training distribution to cover them.
One response is On-Policy Distillation. Instead of training only on teacher-generated trajectories, methods such as Generalized Knowledge Distillation (GKD) ask the teacher to score sequences that the student itself produced [4]. That way, the teacher is not only showing the “ideal path.” It is also correcting the student in the situations the student is likely to create at inference time.
This matters operationally because deployed models do not fail on pristine examples. They fail after a slightly wrong turn, when the next token must be chosen from a bad local state.
4. Bridging Architectural Heterogeneity
Two models can agree on the next token while using different hidden dimensions or different coordinates within those dimensions. To train on intermediate features, choose a layer and token positions in each model. A learned projection maps the student’s state into the space in which the teacher target is defined. FitNets used this idea to train a thinner student from a wider teacher. [6]
PyTorch Implementation: Feature-Based KD
This example combines the next-token cross-entropy, forward KL between softened output distributions, and MSE between the projected student state and its teacher target.
Educational loss example. Assumes aligned teacher/student outputs with identical tokenizers, vocabulary ordering and chat templates. Run the pinned teacher checkpoint in
eval()andinference_mode(). Replace the synthetic mask with tokenizer-native assistant-span masks. Avoid duplicate BOS/EOS, match EOS inclusion, truncation and padding, and block cross-sample attention when packing. Full-model training, cross-tokenizer probability mapping and distributed normalization by global token count are omitted.
import torch
import torch.nn as nn
import torch.nn.functional as F
class ModernKDLoss(nn.Module):
def __init__(self, student_dim, teacher_dim, temp=2.0, alpha=0.5, beta=0.1):
super().__init__()
if temp <= 0 or not 0 <= alpha <= 1 or beta < 0:
raise ValueError("invalid loss settings")
self.temp, self.alpha, self.beta = temp, alpha, beta
self.feature_projector = nn.Linear(student_dim, teacher_dim, bias=False)
def forward(self, student_logits, teacher_logits, student_hidden,
teacher_hidden, labels, assistant_mask):
# Same tokenizer, vocabulary ordering and [B,S,V] positions required.
if student_logits.shape != teacher_logits.shape or student_logits.ndim != 3:
raise ValueError("teacher/student logit alignment mismatch")
if labels.shape != student_logits.shape[:2] or assistant_mask.shape != labels.shape:
raise ValueError("label/mask shape mismatch")
if labels.shape[1] < 2:
raise ValueError("at least one next-token target required")
# Position t predicts token t+1; padding uses -100, prompts use mask=False.
valid = assistant_mask[:, 1:].bool() & labels[:, 1:].ne(-100)
if not valid.any():
raise ValueError("no supervised assistant tokens")
s = student_logits[:, :-1].float()[valid]
t = teacher_logits[:, :-1].detach().float()[valid]
targets = labels[:, 1:][valid]
ce = F.cross_entropy(s, targets)
log_s = F.log_softmax(s / self.temp, dim=-1)
log_t = F.log_softmax(t / self.temp, dim=-1)
kd = F.kl_div(log_s, log_t, log_target=True, reduction="none").sum(-1).mean()
# Align the predictive hidden states at the same selected positions.
projected = self.feature_projector(student_hidden[:, :-1][valid])
target_hidden = teacher_hidden[:, :-1].detach()[valid].float()
feature = F.mse_loss(projected.float(), target_hidden)
return (1-self.alpha)*ce + self.alpha*self.temp**2*kd + self.beta*feature
# Small CPU smoke example. Teacher outputs are frozen and already aligned.
torch.manual_seed(0)
B, S, V, Ds, Dt = 2, 6, 32, 8, 12
s_logits = torch.randn(B, S, V, requires_grad=True)
t_logits = torch.randn(B, S, V)
s_hidden = torch.randn(B, S, Ds, requires_grad=True)
t_hidden = torch.randn(B, S, Dt)
labels = torch.randint(V, (B, S))
labels[1, -2:] = -100
assistant_mask = torch.zeros(B, S, dtype=torch.bool)
assistant_mask[:, 3:] = True # template-derived in a real pipeline
criterion = ModernKDLoss(Ds, Dt)
loss = criterion(s_logits, t_logits, s_hidden, t_hidden, labels, assistant_mask)
loss.backward()
print("KD loss:", loss.item())
5. A Practical Distillation Playbook
If you are designing a distillation pipeline for a real product, the main questions are usually not philosophical. They are operational:
- What behavior matters most? Accuracy, latency, format adherence, tool use, or safety all imply different teacher signals.
- Is the teacher the right teacher? For specialized tasks, domain fit can matter more than raw parameter count.
- What failure modes do you evaluate? A student that looks good on clean benchmarks may still drift in length, calibration, or refusal behavior.
- Where is the budget spent? Teacher inference for rationale generation or on-policy scoring can dominate the total cost of the distillation pipeline.
This is why production distillation is rarely “train a small model on teacher outputs and stop.” It usually includes dataset curation, teacher quality checks, student-trajectory evaluation, and post-training release gates.
6. The geometric constraint of feature alignment
Take one hidden state . The output layer has rows for class A and for class B. Its logits are . The teacher assigns probability 0.993307 to B at . Both student switches start in the teacher’s configuration. Swap the student’s hidden coordinates, predict what will happen, then swap the two columns of its output layer as well.
Original order
- Hidden state
- [1, 3]
- Readout rows
- [2, -1], [1, 1]
- Logits (A, B)
- [-1, 4]
- Probability of B
- 99.33%
- Forward KL (nats)
- 0.000000
- Hidden MSE
- 0
Only hidden coordinates swapped
- Hidden state
- [3, 1]
- Readout rows
- [2, -1], [1, 1]
- Logits (A, B)
- [5, 4]
- Probability of B
- 26.89%
- Forward KL (nats)
- 1.266389
- Hidden MSE
- 4
Only readout columns swapped
- Hidden state
- [1, 3]
- Readout rows
- [-1, 2], [1, 1]
- Logits (A, B)
- [5, 4]
- Probability of B
- 26.89%
- Forward KL (nats)
- 1.266389
- Hidden MSE
- 0
Both pairs swapped
- Hidden state
- [3, 1]
- Readout rows
- [-1, 2], [1, 1]
- Logits (A, B)
- [-1, 4]
- Probability of B
- 99.33%
- Forward KL (nats)
- 0.000000
- Hidden MSE
- 4
Swapping the hidden coordinates alone changes the logits to . B falls to 0.268941 and forward KL rises to 1.266389 nats. With both switches on, the logits return to and KL to zero. In both cases the raw hidden-state mean squared error (MSE) is .
This holds for every hidden state when the output layer undoes the same permutation. With permutation matrix , and give because . A feature projection also maps this student’s coordinates back to the teacher’s, bringing the projected feature MSE to zero. The identity explains the example without any model training.
Check it in standard Python. Each row prints the student’s probability of B, forward KL in nats and raw hidden MSE. The order is unchanged, readout only, hidden only, then both.
from math import exp, log
h = [1, 3]
W = [[2, -1], [1, 1]]
def probabilities(state, rows):
logits = [sum(a * b for a, b in zip(row, state)) for row in rows]
terms = [exp(z - max(logits)) for z in logits]
return [v / sum(terms) for v in terms]
p = probabilities(h, W)
for state in (h, h[::-1]):
for rows in (W, [row[::-1] for row in W]):
q = probabilities(state, rows)
kl = sum(a * log(a / b) for a, b in zip(p, q))
mse = sum((a - b)**2 for a, b in zip(h, state)) / len(h)
print(f"{q[1]:.6f} {kl:.6f} {mse:.0f}")
7. Summary and Next Steps
Choose the supervision you can collect, then test the behavior you intend to serve. In the support example, held-out routing accuracy tells you whether customers reach the right team. Agreement on an explanation, a logit vector or an intermediate state answers a different question.
Section 13.5 returns to deployment and asks which tensors a low-precision format actually compresses.
SteerDistill: learn from locally corrected behavior
As of 2026-11-15 — emerging research. SteerDistill restores an agent environment near a behavioral divergence and uses teacher guidance to elicit the quantized student’s own correction. Locally verified revisions are distilled without the steering prompt: forward KL at corrected turns, reverse KL to the full-precision teacher elsewhere. The study covers three models and five agent benchmarks. Successful teacher references, restorable state and reliable local verification are required; a locally valid correction does not guarantee task success. [5]
Track verifier errors and final task outcomes separately. Preserve teacher/student versions, masks and environment snapshots, and quarantine evaluation tasks and their variants.
Distillation run contract
Record provenance, permissions, filters, deduplication, evaluation quarantine and teacher/student/tokenizer/template hashes in the input manifest. Supervise valid next-token assistant positions; pin teacher checkpoint, decoding and response-length policy, projection parameters and loss weights together. The example is CPU FP32 tensor arithmetic. A real budget adds both models’ weights, student gradients/optimizer/activations, teacher inference buffers, stored logits, collectives and evaluation.
Observe token-normalized CE/KL and domain-slice validation, nonfinite/overflow counts and norms, throughput/MFU, data wait/collectives and reconstructable batch IDs. Abort on nonfinite values, mask mismatches or critical-slice regression. Checkpoints include student/projection, optimizer/scheduler/precision state, step/tokens, RNG, sampler, exact data cursor and hashes. Promote only after isolated domain, base-capability retention, safety, format/tool, latency, cost and error-rate gates with paired uncertainty, plus rehearsal of restoring the last known-good bundle.
Quizzes
Quiz 1: Can one top label determine the forward KL for a multiclass output?
No. Different teacher distributions can share a top label. Full-distribution KL requires the probability of each aligned class, including the alternatives.
Quiz 2: Why can Reverse KL be appealing for autoregressive distillation compared with always using Forward KL?
Forward KL encourages broad coverage of the teacher distribution, which can be useful but may spread probability mass too widely for a smaller student. Reverse KL is more mode-seeking, so it can encourage the student to commit more strongly to the teacher’s preferred continuations. That can improve fluency in some generative settings, though it is not automatically the right choice for every task.
Quiz 3: What problem is On-Policy Distillation trying to solve?
It addresses the mismatch between clean teacher trajectories seen during training and the imperfect trajectories the student generates at inference time. By letting the teacher score sequences produced by the student itself, on-policy methods teach the student how to recover after its own mistakes instead of only showing ideal examples.
Quiz 4: If the student swaps the two hidden coordinates and both readout columns, what can an output-only loss detect?
The logits stay identical for every hidden state. Forward KL is zero, even though raw hidden MSE is 4 for the worked input. A feature projection can undo the permutation before comparing coordinates.
Quiz 5: In a real distillation pipeline, why can teacher choice matter more than raw teacher size?
Because the student only learns from the signal the teacher provides. A domain-aligned teacher often produces cleaner outputs, more relevant rationales, and more useful hidden-state structure for the target task than a much larger but more general model. Bigger is not automatically better if the teacher’s behavior is mismatched to the deployment goal.
References
- Hinton, G., Vinyals, O., & Dean, J. (2015). Distilling the Knowledge in a Neural Network. arXiv:1503.02531.
- Hsieh, C. Y., et al. (2023). Distilling Step-by-Step! Outperforming Larger Language Models with Less Training Data and Smaller Model Sizes. arXiv:2305.02301.
- Gu, Y., Dong, L., Wei, F., & Huang, M. (2024). MiniLLM: On-Policy Distillation of Large Language Models. arXiv:2306.08543.
- Agarwal, R., et al. (2024). On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes. arXiv:2306.13649.
- Research preprint (2026). SteerDistill: Quantizing LLM Agents via Closed-Loop Teacher Steering. Version pinned; accessed 2026-11-15.
- Romero, A., et al. (2014/2015). FitNets: Hints for Thin Deep Nets. arXiv:1412.6550v4.