AI Grimoire
Sheet
statuscommon
difficultyintermediate
timeO(n·V)
described2015
revisedtoday

Knowledge Distillation

A one-hot label says the answer is "cat". A teacher’s distribution says it is a cat, that lynx was close, and that lorry was never in contention. The second is a far denser signal, and it is free.

Standing

Commonly usedEstablished and frequently the right choice, but competing with live alternatives rather than having settled the question.

How most small models are actually made. The classroom variant is well understood; the sequence-level variants that matter for language models are still being sorted out.

judged as of 2026-09 · what the labels mean

Theory

A hard label carries log2V\log_2 V bits and says nothing about the alternatives. A trained model’s output distribution says which alternatives were plausible and by how much — Hinton’s dark knowledge, the structure the teacher has discovered about how the classes relate.

L=(1α)LCE(y,pS)  +  αT2KL ⁣(pT(T)pS(T))\mathcal{L} = (1-\alpha)\,\mathcal{L}_{\text{CE}}(y, p_S) \;+\; \alpha\, T^2 \cdot \mathrm{KL}\!\left(p_T^{(T)} \,\big\|\, p_S^{(T)}\right)
eq. 1 — match the distribution, not the label

with p(T)=softmax(z/T)p^{(T)} = \mathrm{softmax}(z/T). Temperature flattens both distributions so the small probabilities — the informative ones — are not lost under the argmax. The T2T^2 is compensation: softening divides the logit gradient by TT twice over, and without the factor the soft term vanishes exactly as it becomes useful.

Sequence level, which is where language models live

Token-level matching has a problem specific to generation: it is off-policy. The student is scored on the teacher’s outputs, from prefixes drawn from the teacher’s distribution, and then deployed on its own — the exposure bias of teacher forcing, with a second model’s worth of distribution shift stacked on top.

Three responses, in increasing order of cost and quality:

Hard distillation. Generate with the teacher, train the student on the text as if it were data. Trivial to implement, requires no logits, and is what most “distilled” open models actually are. The student learns the teacher’s modes and not its uncertainty.

Token-level KD. Match the full distribution at every position of teacher- generated text. Denser, and needs the teacher’s logits — a [B,T,V][B, T, V] tensor that is usually the largest thing in the training step.

On-policy distillation. Sample from the student, score those sequences with the teacher, and match. The distributions are compared exactly where the student will operate, which removes the shift. It costs a teacher forward pass per student sample and it is the variant that works best.

KL(pTpS)   mass-coveringKL(pSpT)   mode-seeking\mathrm{KL}(p_T \| p_S) \;\text{ mass-covering} \qquad \mathrm{KL}(p_S \| p_T) \;\text{ mode-seeking}
eq. 2 — the direction the divergence is taken in

A small student cannot represent everything a large teacher can, so the choice is which failure to take. Forward KL spreads the student thin across modes it cannot all fit and produces hedged, incoherent output. Reverse KL picks one mode and commits, which for generation is what you want. GKD interpolates and finds the optimum is usually nearer the reverse end.

Implementation

python · torch
import torch
from torch import Tensor
from torch.nn import functional as F


def distillation_loss(
    student: Tensor, teacher: Tensor, labels: Tensor, t: float = 2.0, alpha: float = 0.9
) -> Tensor:
    """student, teacher: [B, T, V] logits. Hinton et al., eq. 1."""
    soft = F.kl_div(
        F.log_softmax(student / t, dim=-1),
        F.log_softmax(teacher / t, dim=-1),
        reduction="batchmean",
        log_target=True,                     # both in log space: no underflow
    ) * (t * t)                              # restores the gradient scale

    hard = F.cross_entropy(student.flatten(0, 1), labels.flatten())
    return alpha * soft + (1 - alpha) * hard

log_target=True matters at a 128k vocabulary. Passing probabilities means exponentiating the teacher’s logits first, and the tail entries — the ones carrying the dark knowledge — underflow to zero in bf16 before the divergence is taken.

Where it sits now

Almost every small production model is distilled. The pattern is a large model trained once, then a family of small ones distilled from it, because a 7B student of a 400B teacher beats a 7B model trained from scratch on the same budget by a wide margin.

The economics also run the other way. Speculative decoding needs a draft model that agrees with the target, and distillation is how you get one — there the student is not a deployment artefact but a component of the teacher’s own inference path.

Hard label
log₂ V bits
Teacher distribution
the full V
Extra cost
one teacher pass
Signal per token

Related

References

[1]Hinton et al. — Distilling the Knowledge in a Neural Network (2015)arXiv:1503.02531
[2]Kim & Rush — Sequence-Level Knowledge Distillation (2016)arXiv:1606.07947
[3]Agarwal et al. — On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes (2023)arXiv:2306.13649