Model Distillation

Distillation trains a small student to reproduce the behaviour of a large teacher . Here we revise it for language models: what the loss is, which divergence to use, where the training text should come from, what you can do with only API access, and why the whole thing works. The note follows a tutoring session (2026-11-13, 2026-11-14); the derivations are the ones done there, and the last section lists the slips made on the way.

The thing to remember: almost every design choice reduces to three questions.

  • Which divergence? Forward or reverse KL.
  • Whose text? Teacher-written, student-written, or a mix.
  • What does the teacher expose? Text, probabilities, or internals.

The basic loss

Gradient of cross-entropy with respect to the logits

Student logits , , target distribution , loss .

Since , the Jacobian of the log-softmax is

The probability that appears belongs to the logit you differentiate with respect to (), not to the token in the numerator (). Then

The one formula to keep

The gradient on every logit is the student's probability minus the target's probability. Everything else in this note is a consequence. See Softmax Function.

Hard label versus soft target

Take , hard label on token 1, teacher .

TargetGradient Token 2Token 3
Hard pushed downpushed down
Soft pushed uppushed down

With a hard label every wrong logit is pushed down in proportion to the student's own : the signal contains nothing the student did not already believe. The soft target changes the sign of the update on token 2. That is the precise meaning of "dark knowledge".

Temperature

A confident teacher, e.g. , gives a soft target that is nearly one-hot, so the information about wrong tokens is numerically invisible. Divide the logits by before the softmax to flatten the distribution:

  • Apply to both sides. If only the teacher is softened, the student at learns a flattened distribution and is underconfident at inference.
  • Matching at implies matching at . , so softening is a renormalised -th root. If for all , raising to the power gives , and two normalised distributions that are proportional are equal. only changes which errors the loss emphasises during training.

The factor

With , the chain rule gives , hence

The difference shrinks too. For large , use on numerator and denominator ( tokens, mean logit ):

So and the gradient scales as .

Why the loss is multiplied by

Higher temperature makes the gradient smaller, by about . Multiplying the distillation term by keeps its size constant as changes. At high distillation is approximately matching mean-centred logits.

The mixed objective

Both terms are cross-entropies; they differ in target and temperature. Forgetting at makes the distillation term about 16 times weaker than intended, and the student behaves almost like one trained on hard labels only. Introduced in Hinton's Distilling the Knowledge in a Neural Network.

Choice of divergence

Forward versus reverse KL

Forward Reverse
Formula
Weighted by (teacher) (student)
Forbids where (term blows up) where (term blows up)
Does not seemass placed where (term weighted by )modes dropped by the student (term weighted by )
Small studentone wide peak over all modes, mass in the gapscommits to one mode, stays out of the gaps
Sampled textvaried, drifts into incoherencecoherent, low variety
Namemass-covering, mean-seekingmode-seeking, zero-forcing
  • Soft-target cross-entropy is forward KL: and does not depend on the student.
  • Concrete forward failure: teacher has on three plausible tokens, the student manages . Over 200 sampled tokens the student emits about 20 implausible ones against about 2 for the teacher.
  • Concrete reverse failure: teacher has on three plausible tokens; a student with all mass on the first pays only . Dropping plausible options is cheap, so about half of the teacher's variety at that position disappears.
When is reverse KL the wrong choice?

When the spread itself is the point: mixed strategies (a penalty taker who always shoots left is exploitable, see Nash Equilibrium), creative generation, synthetic data, calibrated probabilities. Reverse KL only loses something at positions where the teacher has two or more plausible options.

Which KL can you compute?

Over whole sequences:

SettingWhat you can do with Easy divergence
Variational Inferenceevaluate up to a constant, cannot samplereverse
Distillationcan sample (the teacher is a model you run)forward
  • Forward needs only teacher text. has no student parameters, so it drops out; what is left is on teacher samples, i.e. ordinary hard-label training. A dataset generated once stays valid because the teacher is frozen.
  • Reverse needs fresh samples from the current student at every step (a stored set is stale after one update) and the teacher's log-probabilities on them. It is an on-policy method.

Token level versus sequence level

Same mean, different variance

On a teacher-written prefix you can train with (a) the token the teacher sampled, one-hot, or (b) the teacher's full next-token distribution.

  • (a) gradient with ; (b) gradient .
  • , so the two gradients are equal in expectation. (a) is a single-sample estimate of (b).

Coordinate of is a Bernoulli variable with parameter (note , so ):

  • Zero exactly when the teacher is certain ( one-hot): hard labels lose nothing there.
  • Largest for uniform : .
  • Across a dataset both methods share the variance from which prefixes were drawn; (a) adds on top. That is the entire gap.
The advantage of soft targets is data efficiency

Same objective (forward KL), same expected gradient, lower variance. With unlimited data both converge to the same student. Soft targets help most where the teacher is uncertain, which is where its distribution carries the most information.

Why hard labels still work

Each long prefix occurs once, so "50k samples per prefix" would make sequence-level distillation impossible. It is not: the weights are shared, the gradient is averaged over all positions, and what is learned at one prefix transfers to similar ones. Sequence-level distillation from teacher text (Kim and Rush's Sequence-Level Knowledge Distillation) is the most common form in practice.

Exposure bias and on-policy distillation

Compounding errors

Training prefixes come from the teacher or from data; inference prefixes come from the student. If each token leaves the training distribution with probability and never returns, a generation of tokens survives with probability . For , : . A student that is 99% reliable per token almost never finishes on-distribution.

  • The argument appears for compositional tasks in Dziri's Faith and Fate; the rigorous imitation-learning version is Ross and Bagnell's.
  • The assumption "once off, always off" is often false: a model can recover if it has been trained on what to do after a mistake.

On-policy distillation

The student writes the training sequences; the teacher supplies its next-token distribution at every position of them.

  • At position after a bad token at , the teacher's distribution is conditioned on the flawed prefix, so it describes the best continuation from that bad state. The student gets recovery targets for exactly the mistakes it makes.
  • Training is still one parallel pass: average the per-position cross-entropy over the student-written sequence.
  • This is DAgger applied to language models. See Agarwal's On-Policy Distillation of Language Models (GKD).
  • Injected or templated errors are a weaker substitute: you have to guess what the student's mistakes look like.

Mixing teacher and student prefixes

Pure on-policy training from a weak student fails: its text is garbage the teacher has never seen, so the teacher's distributions on it are unreliable.

MethodPrefix sourceNote
Supervised KDfixed teacher or data texttrain/inference mismatch
On-policy (GKD)studentunreliable teacher targets early; sensitive to student initialisation
Teacher-mixed sampling (MiniLLM)blend of both next-token distributions at each stepreverse-KL objective; mixing stops the student gaming the teacher with degenerate text
Interleaved sampling (SKD)student proposes, teacher replaces tokens outside its top-behaves like supervised KD early, like on-policy later, with no hand-tuned schedule
Practical schedule

Start from a pretrained student, begin with mostly teacher-written prefixes and shift to student-written ones. The acceptance rate of student tokens under the teacher is a signal that sets the mix automatically.

Black-box distillation

What each level of access allows

Teacher exposesAvailableRuled out
Text onlysequence-level (forward KL, hard labels)soft targets, reverse KL, on-policy scoring, internals
Text + reasoningsequence-level on rationale + answersame as above
Log-probabilitiestoken-level soft targets, on-policy, reverse KLinternals
Weightseverything, including hidden states and attentionnothing
  • Hiding reasoning text blocks sequence-level distillation of the reasoning. Withholding log-probabilities blocks token-level and on-policy methods. They are different protections.
  • Visible reasoning does not enable on-policy distillation: the teacher wrote that text.

Rationales

Training on reasoning followed by answer supervises many more tokens per example and makes the answer easier to predict from what precedes it. Hsieh's Distilling Step-by-Step shows small models need far fewer examples when rationales are an extra target. The cost: outputs are much longer, so by a small student has more chances to derail before the answer.

Protecting against distillation

  • Providers hide raw chains of thought partly for this reason (competitive advantage is on OpenAI's own list of reasons).
  • Savani's Antidistillation Sampling keeps traces visible but perturbs sampling to poison them: in their MMLU example a 72% teacher yields a 52% student from ordinary traces and about 40% from poisoned ones.
  • Hiding is not airtight; 2026 reports describe raw traces recovered through provider APIs.

Building a dataset without prompts

  • Write a few seed prompts, have the teacher generate more, then have it answer them.
  • Generated prompts are narrower than real ones: every call samples from the same high-probability region.
  • Counters: higher temperature, a different random subset of seeds per call, conditioning on a sampled topic or style, removing near-duplicates. Detection: compare token statistics with a sample of real prompts.

One sample or many per prompt?

  • Default: more distinct prompts. Ten answers to one prompt overlap; ten prompts cover ten contexts that shared weights can pool.
  • Extra samples are informative only where the teacher's answers vary ( large): open-ended tasks, several valid solutions, genuine uncertainty.
  • Agreement among samples is an empirical confidence estimate without log-probabilities; use it to filter or down-weight.

Intermediate representations

Hidden-state matching

Student state , teacher state , learned projection :

  • Project the student up, not the teacher down. with and the student both free has the trivial solution , . Projecting up has a fixed, input-dependent target, so one constant vector cannot fit it.
  • Used as an auxiliary loss next to output distillation, not alone.

What the loss constrains

  • Basis-free. If student B has states for an invertible , it reaches the same loss with . No individual neuron means anything to the loss.
  • Linear recoverability. The loss is small iff the teacher's state can be reconstructed from the student's by a linear map. Information present only in a nonlinear encoding counts as lost.
  • PCA floor. varies in at most dimensions. With (centred) teacher variances along principal directions, the best case captures the top directions and the loss cannot go below .
Weakness of hidden-state matching

It rewards reproducing the teacher's highest-variance directions, which need not be the ones that matter for predicting the next token.

Layer mapping

Residual view: . With a 24-layer teacher and a 6-layer student, the uniform rule pairs student layer with teacher layer , so one student block must approximate a composition of four teacher blocks.

MappingAssumption
Uniform (TinyBERT)the small network computes things in the same order and proportion
Last layer only (MiniLM)one termnone on intermediate layers; they organise freely
Softtarget , learnedthe student chooses which teacher layers to track

Attention matching

One head: , with , , and .

  • are weights and depend on the width. The map is whatever and are; row is a distribution over positions.
  • So no projection is needed: compare maps directly, by row-wise cross-entropy or by squared error.
  • Remaining mismatch: head count. Heads have no natural order, so pairing head with head is arbitrary. MiniLMv2 concatenates queries and keys across heads and re-splits them into the same number of groups on both sides.

A complete white-box loss

Practical issues

The capacity gap

A much stronger teacher can give a worse student. Its distributions depend on distinctions the student cannot represent; under forward KL the student averages over them and smears mass onto tokens that are wrong in each specific context, and those positions seed compounding errors. A weaker teacher's distributions can be fitted without smearing.

Remedies:

  • Reverse KL on student-written text: the student commits to the modes it can represent.
  • Simplify the target: filter or truncate the teacher's distribution.
  • Teacher assistant (Mirzadeh's Improved Knowledge Distillation via Teacher Assistant): distil 70B into 7B, then 7B into 1B. Each gap is smaller, but the copy errors chain.

Toy model of the trade-off (invented numbers): a step across ratio keeps of performance; equal steps keep .

ratio per stepkept overall
1700.800.80
28.40.930.86
42.90.970.89
81.70.980.85

Interior optimum: a few intermediate models. Each one also costs a full distillation run.

A two-teacher variant

Idea from the session: train the 1B student on 70B-written text with soft targets from a 7B model that was not itself distilled from the 70B one. This is the mixed objective with two teachers: hard labels from the 70B model (unbiased, noisy, the only route for its knowledge) and soft targets from the 7B model (low variance, biased towards what the 7B model already believes). Where the teachers disagree the two terms conflict, and those are the positions where the 70B model knows more. Open question whether it beats the chain; not checked against the multi-teacher literature.

Tokenizer mismatch

Anything that passes through plain text survives; anything defined per token or per position breaks.

MethodDifferent tokenizers?Why
Token-level soft targetsbreaksdistributions over different vocabularies
Sequence-level on teacher textworksre-tokenise the teacher's string with the student's tokenizer
On-policy, per-token scoringbreakspositions and vocabularies do not line up
On-policy, whole-string worksthe teacher scores the string with its own tokenizer; one sparse number per sequence
Hidden statesbreaksposition covers different text; needs alignment (e.g. pooling over words)
Attention mapsbreaks with different

Dense signal without matching vocabularies: Minixhofer's Universal Cross-Tokenizer Distillation via Approximate Likelihood Matching compares the likelihood of chunks of text that both tokenizations delimit identically. See Tokenization.

Why distillation works

Targets as estimators of the true distribution

Let be the true next-token distribution. Both the human token and the teacher's distribution estimate it.

TargetBiasVarianceError for
Human token 00.62
Label smoothing , squared norm 0.00050.50
Teacher small0.015
  • The teacher saw the same single token at this prefix. Its low variance comes from pooling many similar contexts through shared weights; averaging samples divides variance by .
  • The price is bias, from treating similar contexts alike and from the teacher's own errors. It is visible as the teacher's excess loss on held-out text: .
  • Label smoothing also reduces variance, but with a context-independent vector: it adds no information. The gain of distillation is context-specific information, not smoothing. See Bias Variance Trade-off, Entropy.

Three reasons, then: information about unsampled tokens, lower-variance targets, and both bought with a bias.

Connections

  • Variational Inference: same two divergences, opposite one is tractable, because there you cannot sample from .
  • Imitation learning: exposure bias is behaviour cloning's compounding error; on-policy distillation is DAgger. See Inverse Reinforcement Learning.
  • Quantal Response Equilibrium: the temperature softmax is the logit response function; plays the role of the inverse rationality parameter.
  • Ensemble Methods: the original motivation was compressing an ensemble into one network.
  • Low-Rank Adaptation: both are rank arguments. LoRA limits the rank of a weight update; the projection limits the rank of the reconstruction of the teacher's activations.
  • LLM-to-LLM alignment in social simulation: fitting one model's action distribution to another's is distillation of a policy. The divergence decides whether mixed strategies survive (forward) or collapse to a pure one (reverse).

Personal pitfalls

Slips made during the session, with the correction. Review these first.

SlipCorrection
Wrote in the gradient; later gave hard-label gradients : the index of the logit, so the sum is
"Higher temperature gives bigger gradients"Gradient scales as ; hence the factor
Left out twice; wrote as the loss is the gradient. Loss:
Attached "mean" to reverse KL (twice)Forward is mean-seeking; reverse is mode-seeking
"Soft targets minimise reverse KL"The sum is weighted by : forward KL plus
"Forward KL is hard to compute"True in VI only. In distillation you can sample the teacher, so forward is the easy one
"A stored dataset suits reverse KL"Reverse needs samples from the current student; stored ones are stale after one step
ABAB teacher, all-A reverse-KL studentThat student has infinite reverse KL; reverse only loses where is multi-modal at one position
"Visible reasoning enables on-policy distillation"Teacher wrote the text; on-policy needs teacher log-probs on student text
Fix for exposure bias: inject template errorsThe student should write the prefixes; its own mistakes are the relevant ones
"Sequence-level is the average of token-level"It is the single-sample version, equal in expectation
"Averaging many samples makes the estimate unbiased"Averaging reduces variance by ; bias is separate
Compared only bias of label smoothing with the teacher's errorTotal error is bias + variance
"Extra samples help where the teacher always answers the same"Variance is 0 there; they help where answers vary
Trivial solution assigned to "project student up"It is "project teacher down": ,
Attention map is , depends on widthWeights depend on width; the map is
Tokenizer mismatch: sequence-level breaks, hidden and attention surviveThe reverse: text survives, per-position quantities break
" of a string is not defined across tokenizers"The teacher tokenises the string itself; it is defined, just sparse
Uniform total variance ; layer step 3 for 24 vs 6; step 4

References

Checked during the session:

  • Agarwal et al., On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes, ICLR 2024.
  • Gu, Dong, Wei, Huang, MiniLLM: Knowledge Distillation of Large Language Models, ICLR 2024.
  • Xu et al., Speculative Knowledge Distillation: Bridging the Teacher-Student Gap Through Interleaved Sampling, ICLR 2025.
  • Hsieh et al., Distilling Step-by-Step!, Findings of ACL 2023.
  • Minixhofer, Vulić, Ponti, Universal Cross-Tokenizer Distillation via Approximate Likelihood Matching, NeurIPS 2025.
  • Savani et al. (Kolter group), Antidistillation Sampling, arXiv 2504.13146. Venue not checked.

Cited from memory, venue not re-checked:

  • Hinton, Vinyals, Dean, Distilling the Knowledge in a Neural Network, 2015.
  • Kim and Rush, Sequence-Level Knowledge Distillation, EMNLP 2016.
  • Ross, Gordon, Bagnell, A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning (DAgger), AISTATS 2011.
  • Dziri et al., Faith and Fate: Limits of Transformers on Compositionality, NeurIPS 2023.
  • Jiao et al., TinyBERT, Findings of EMNLP 2020.
  • Wang et al., MiniLM, NeurIPS 2020; MiniLMv2, Findings of ACL 2021.
  • Mirzadeh et al., Improved Knowledge Distillation via Teacher Assistant, AAAI 2020.

Flagged, not peer-reviewed (used only for the claims about hidden reasoning):

  • Simon Willison, notes on OpenAI o1, quoting OpenAI's stated reasons (2024).
  • eWeek on o3-mini chain-of-thought summaries (2025).
  • Xint blog on leaked reasoning traces; Cloud Security Alliance research note (2026).

Review checklist

  • Derive without the index slip.
  • Hard vs soft gradient on the example: which logit changes sign.
  • Why goes on both sides, and why matching at implies matching at .
  • High- expansion of the softmax and the gradient scaling.
  • Forward vs reverse KL: what each forbids, what each ignores, what the text looks like.
  • Which KL is tractable in VI and which in distillation, and why.
  • Hard-label gradient variance ; when it is zero and when maximal.
  • and what on-policy distillation changes.
  • Why pure on-policy from a weak student fails; how SKD and teacher-mixed sampling fix it.
  • Access table: text, reasoning, log-probs, weights.
  • Hidden-state loss: projection direction, basis invariance, PCA floor.
  • Attention map shape and why no projection is needed.
  • Capacity gap mechanism and the teacher-assistant trade-off.
  • Tokenizer mismatch: what survives and what breaks.
  • Bias-variance comparison of human token, label smoothing, teacher target.