Distillation and synthetic data¶
Most small models worth using in 2026 were taught by bigger ones, and most post-training data is now written by models rather than people. Distillation and synthetic data are one idea seen from two sides: a strong model's outputs carry far more information per example than a human label, and a weaker model can learn from them — provided you know which outputs to trust, which divergence to minimise, and whose samples to train on.
10,000 ft
Pre-training a model is expensive; being taught by one is cheap. Knowledge distillation (Hinton, Vinyals and Dean, 2015) trains a small "student" to match a large "teacher"'s output distribution, and it is how compact models are made: Gemma 2's 2B and 9B models were trained by distillation instead of plain next-token prediction, NVIDIA's Minitron models were pruned and then distilled, and DeepSeek-R1's reasoning was distilled into Qwen and Llama models that beat what RL achieved directly at the same size. Synthetic data is the generalisation: use a model to write training data — instructions, answers, textbooks, reasoning traces, preference labels — then filter it. Nemotron-4 340B's alignment data was more than 98% synthetic. This page connects the two to instruction tuning (synthetic SFT data), constitutional AI (synthetic preference labels) and RL with verifiable rewards (on-policy distillation is RL with a teacher as the reward), and it confronts the risk everybody worries about: model collapse.
2,000 ft
What the student learns from defines the method. From richest signal to cheapest:
- Logit distillation — minimise the KL divergence between teacher and student next-token distributions on a corpus. Needs the teacher's logits and a shared tokenizer.
- Sequence distillation — sample complete answers from the teacher and fine-tune on them with ordinary SFT. Works through any API; loses the teacher's uncertainty.
- Synthetic-data pipelines — generate prompts and responses at scale, then filter with verifiers, tests and judges; this is sequence distillation plus quality control.
- On-policy distillation — let the student generate, and have the teacher score each token the student wrote. Fixes the train/test mismatch of 1–3 at a fraction of RL's cost.
Ground level¶
Dark knowledge: why a teacher's wrong answers teach¶
A classifier trained with one-hot labels learns, as a side effect, a full probability distribution over classes. Hinton, Vinyals and Dean's observation was that the wrong answers in that distribution carry most of the information: "An image of a BMW, for example, may only have a very small chance of being mistaken for a garbage truck, but that mistake is still many times more probable than mistaking it for a carrot." Which 2s look like 3s and which look like 7s is a similarity structure over the data that no hard label contains. They called it dark knowledge, and proposed passing it to a smaller model by training on the teacher's probabilities — "soft targets" — instead of (or alongside) the labels.
The obstacle is that a confident teacher's wrong-answer probabilities are tiny (\(10^{-6}\), \(10^{-9}\)) and contribute almost nothing to a cross-entropy loss. The fix is a temperature \(T\) in the softmax,
applied to both teacher and student during distillation. Raising \(T\) flattens the distribution and lifts the small probabilities into a range where they produce gradients. Take a teacher's logits for an image of a 2 that looks a little like a 3 and a 7:
| Temperature | \(p(2)\) | \(p(3)\) | \(p(7)\) | Entropy |
|---|---|---|---|---|
| \(T = 1\) | 0.9981 | 0.0015 | 0.0003 | 0.02 bits |
| \(T = 4\) | 0.6128 | 0.1207 | 0.0829 | 2.06 bits |
| \(T = 20\) | 0.1638 | 0.1184 | 0.1098 | 3.28 bits |
At \(T = 1\) the target is essentially the hard label. At \(T = 4\) the student is told, in effect, "this is a 2, it looks somewhat like a 3, a bit like a 7, and not at all like a 6". Too high and the target becomes nearly uniform; the useful range in the paper's MNIST experiments depended on the student's size.
The paper's numbers are still the clearest evidence that this works:
- MNIST. A large regularised net made 67 test errors; a smaller net trained on hard labels made 146; the same small net trained to match the large net's soft targets at \(T = 20\) made 74.
- The missing digit. With every 3 removed from the transfer set, the distilled student had never seen a 3, yet after one bias correction it classified 98.6% of the test 3s correctly — it had learned what a 3 is from how the teacher described other digits.
- Speech. Ten acoustic models trained from different initialisations formed an ensemble (frame accuracy 61.1% vs 58.9% for one model); a single distilled model of the same size reached 60.8%, capturing more than 80% of the ensemble's gain.
- Soft targets as a regulariser. Trained on 3% of the speech data with hard labels, the baseline overfit badly (44.5% test accuracy); trained on the same 3% with soft targets from the full model, it reached 57.0% — almost as good as training on all the data.
The standard loss mixes the two targets, with the soft term multiplied by \(T^2\) so that changing \(T\) does not change its weight (see the maths):
Distillation for language models¶
A language model is a classifier over the vocabulary at every position, so the same idea applies token by token: run teacher and student over the same text and minimise the KL between their next-token distributions at every position. Every token then carries the teacher's whole distribution, tens of thousands of numbers, instead of a single correct id.
- DistilBERT (Sanh et al., 2019) distilled BERT during pre-training: 40% smaller, 60% faster, keeping 97% of its language-understanding performance.
- Gemma 2 (Gemma Team, 2024) trained its 2B and 9B models "with knowledge distillation instead of next token prediction" from a larger model, and reported them competitive with models two to three times their size.
- Minitron (Muralidharan et al., 2024) pruned a trained 15B model's width and depth and recovered quality by distillation, deriving 8B and 4B models with "up to 40× fewer training tokens per model" than training from scratch.
Token-level distillation has two practical constraints. You need the teacher's logits, so it is a white-box method: impossible through most commercial APIs, which return text (and at most a few top log-probabilities). And teacher and student must share a tokenizer, or the distributions are over different vocabularies; cross-tokenizer distillation is an active research area, not a solved one.
Sequence-level distillation: SFT on teacher outputs¶
Kim and Rush (2016) asked a different question for machine translation: instead of matching the teacher at every position of a human-written sentence, why not train the student on the teacher's own translations? Sequence-level distillation generates the teacher's (beam-searched) output for each source sentence and fine-tunes the student on it as if it were the reference. Their best student ran 10× faster than its teacher with little loss, and, surprisingly, no longer needed beam search: the teacher's outputs are easier to imitate than human references because they sit near the teacher's mode.
This is the method behind almost every open model of 2023: take a strong model behind an API, generate answers, fine-tune on them. It needs only text. It loses the teacher's uncertainty — each example shows one sample, not the distribution — and it inherits whatever the teacher gets wrong. Its biggest modern success is reasoning:
| Model (DeepSeek-R1 paper) | Training | AIME 2024 pass@1 | MATH-500 |
|---|---|---|---|
| DeepSeek-R1-Distill-Qwen-1.5B | SFT on R1's traces | 28.9 | 83.9 |
| DeepSeek-R1-Distill-Qwen-7B | SFT on R1's traces | 55.5 | 92.8 |
| DeepSeek-R1-Distill-Qwen-32B | SFT on R1's traces | 72.6 | 94.3 |
| DeepSeek-R1-Zero-Qwen-32B | Large-scale RL, no teacher | 47.0 | 91.6 |
DeepSeek generated about 800K samples (roughly 600K reasoning, 200K general) with R1 and fine-tuned six open models on them, with no RL at all. The same 32B base trained by RL from scratch fell far short of the distilled version. Their conclusion: "distilling more powerful models into smaller ones yields excellent results", while small models trained by large-scale RL "require enormous computational power and may not even achieve the performance of distillation" (DeepSeek-AI, 2025). Reasoning, it turns out, transfers through text unusually well, and very little text is needed when the student is strong: s1 fine-tuned Qwen2.5-32B-Instruct on just 1,000 curated traces (Muennighoff et al., 2025), and LIMO reported 63.3% on AIME24 from 817 (Ye et al., 2025).
Forward or reverse KL: what should a small student copy?¶
A student smaller than its teacher cannot match it everywhere. Which mistakes it makes depends on the direction of the KL divergence it minimises (see information theory):
- Forward KL, \(\operatorname{KL}(p_{\text{teacher}} \,\|\, q_{\text{student}})\) — the classic distillation loss and, in expectation, what SFT on teacher samples minimises. It heavily penalises the student for putting low probability where the teacher puts mass, so the student spreads out to cover every mode, including the gaps between them. Mode-covering.
- Reverse KL, \(\operatorname{KL}(q_{\text{student}} \,\|\, p_{\text{teacher}})\) — penalises the student for putting mass where the teacher puts little, so the student picks one mode and fits it well. Mode-seeking.
For text generation, mass "between the modes" is a sentence no good writer would produce: a blend of two valid answers that is itself invalid. That is the argument of MiniLLM (Gu et al., 2023): replace forward with reverse KL "to prevent the student model from overestimating the low-probability regions of the teacher distribution", and optimise it with on-policy methods. The cost is diversity — a mode-seeking student is more precise and less varied.
Exposure bias, and on-policy distillation¶
Methods 1–3 share a hidden flaw. The student is trained on prefixes written by the teacher (or by humans) and then, at test time, has to continue its own prefixes. One early mistake puts it in a state no training example covered, where it is more likely to err again. Ross, Gordon and Bagnell's DAgger analysis formalised this for imitation learning: a policy that errs with probability \(\epsilon\) on the expert's states can make \(O(T^2 \epsilon)\) mistakes over a horizon of \(T\), because errors compound; training on the learner's own state distribution brings this down to \(O(T\epsilon)\). Long chains of thought make \(T\) large.
On-policy distillation applies the fix to language models: sample from the student, then ask the teacher how it would have scored each token. Generalised Knowledge Distillation (GKD) (Agarwal et al., 2023) trains the student "on its self-generated output sequences by leveraging feedback from the teacher on such sequences", and MiniLLM reaches the same place via reverse KL. In the simplest modern form the per-token reward is the negative reverse KL on the sampled token,
fed into the same policy-gradient machinery as RLVR, with no discounting: each step only has to get its own token right.
It sits between SFT and RL. Like RL it trains on the student's own samples, so it fixes exposure bias. Like SFT it gets a dense signal — a judgement on every token rather than one bit per episode — so it needs far fewer samples. The evidence from 2025:
- In the Qwen3 report, starting from the same off-policy-distilled Qwen3-8B, RL reached 67.6% on AIME'24 in 17,920 GPU hours; on-policy distillation from a larger Qwen3 teacher reached 74.4% in 1,800 (Qwen Team, 2025, Table 21).
- Thinking Machines (Lu et al., 2025) took a student SFT-distilled to 60% on AIME'24 and pushed it to 70% with about 150 steps of on-policy distillation, estimating a 9–30× cost saving over continuing SFT to the same score. They also used it to restore behaviour: a model fine-tuned on internal documents had lost instruction-following (IF-eval 85% → 79% with a mixed data recipe); on-policy distillation from the original model brought it back to 83% while keeping most of the new knowledge.
The limitation is the one you would expect: you need a teacher whose log-probabilities you can compute on arbitrary text, on the student's tokenizer.
Synthetic data: the teacher writes the curriculum¶
Distillation copies a model's answers to existing prompts. Synthetic data generation asks the model to write the prompts too, and anything else you need. A tour of the ideas that stuck:
| Method | Year | What the model generates | What it showed |
|---|---|---|---|
| Self-Instruct | 2022 | Instructions, inputs and outputs, bootstrapped from 175 seed tasks, filtered for validity and novelty | Vanilla GPT-3 tuned on its own generations gained 33 points absolute on Super-NaturalInstructions, on par with InstructGPT-001 |
| Alpaca | 2023 | 52K instruction–response pairs from text-davinci-003 |
A 7B LLaMA instruction model for under USD 600 in total (data under 500, training under 100) |
| Evol-Instruct | 2023 | Rewrites of instructions into harder and more varied ones | Difficulty and diversity can be manufactured, not just sampled |
| Orca | 2023 | Step-by-step explanation traces from GPT-4 | Imitating reasoning transfers more than imitating answers |
| phi-1 | 2023 | "Textbooks" and exercises (1B tokens, GPT-3.5) plus 6B filtered web tokens | A 1.3B code model scoring 50.6% on HumanEval: data quality can substitute for scale |
| Cosmopedia | 2024 | Over 30M textbooks, stories and articles, 25B tokens, from Mixtral-8x7B-Instruct | Open synthetic pre-training data at scale |
| Nemotron-4 340B | 2024 | Prompts, responses and preference judgements | "Over 98% of data used in our model alignment process is synthetically generated" |
| STaR, ReST-EM | 2022–23 | The model's own solutions, kept only if the answer is correct | Self-training with a verifier beats training on human solutions alone |
| DeepSeek-R1 distills, s1, LIMO | 2025 | Long reasoning traces from a reasoning model | Reasoning transfers through a few hundred to a few hundred thousand traces |
The last-but-one row deserves emphasis because it removes the teacher. STaR and ReST-EM sample many solutions from the current model, keep those a verifier accepts, fine-tune, and repeat — rejection-sampling fine-tuning. That is expectation–maximisation over the latent reasoning, and it is the bridge to RL with verifiable rewards: ReST-EM is RLVR with a 0/1 reward and an SFT update instead of a policy-gradient step.
In a mature pipeline the generation step is the easy part. The value is in the other boxes: seeds that force diversity (topics, personas, real user prompts, so that a thousand generations are not a thousand paraphrases), filters that check correctness wherever a check exists (execute the code, compare the maths answer, validate the JSON) and an LLM judge where it does not, and decontamination so that benchmark questions do not leak into training through the teacher's memory (see contamination and eval hygiene).
The false promise, and what imitation does not transfer¶
In 2023 a wave of open models fine-tuned on ChatGPT outputs were rated by crowd workers as close to ChatGPT. Gudibande et al. tested this carefully, imitating ChatGPT with base models from 1.5B to 13B and 0.3M to 150M tokens of imitation data. The imitation models "close little to none of the gap from the base LM to ChatGPT on tasks that are not heavily supported in the imitation data", while being "adept at mimicking ChatGPT's style but not its factuality" — which is exactly why raters were fooled.
This is the most important limitation in this whole subject. Imitation transfers format, style and behaviour cheaply, and transfers skills in proportion to how much of the skill's data you imitate. It does not transfer knowledge the student's base model does not have. The DeepSeek and s1 results are not a contradiction: their students were strong base models that already knew the mathematics; the traces taught them how to use it at length. The best predictor of a distilled model's quality remains the quality of its base.
Model collapse¶
If models train on model-written text, and the web fills with model-written text, does each generation get worse? Shumailov et al. (published in Nature, 2024) showed that recursively training generative models on their predecessors' output causes "irreversible defects in the resulting models, where tails of the original content distribution disappear". The mechanism is simple enough to simulate in a few lines (see Build it): every fit underestimates the spread of its data a little, sampling loses rare events, and the losses compound.
Gerstgrasser et al. (2024) found the crucial qualifier. Collapse happens when synthetic data replaces real data each generation. When the generations accumulate — real data kept, synthetic data added alongside — test error stays bounded, in language models, diffusion models and VAEs alike, and they prove the bound in a linear model. The practical rule every lab follows: synthetic data supplements real data; it never replaces it. Filtering helps for the same reason: a verifier that rejects wrong answers injects information the generator did not have.
History¶
Compressing a large model into a small one by training on its outputs predates the name: Buciluă, Caruana and Niculescu-Mizil's 2006 "Model compression" used an ensemble to label synthetic inputs for a single network, and Ba and Caruana (2014) trained shallow nets to match deep nets' logits. Hinton, Vinyals and Dean's 2015 paper gave the method its name, the temperature, and the "dark knowledge" framing; it appeared at the NIPS 2014 Deep Learning Workshop, not the main conference, and became one of the most cited papers in deep learning.
Sequence-level distillation (Kim and Rush, 2016) carried the idea to generation, and DistilBERT, TinyBERT and MiniLM (2019–2020) made distilled encoders the default for production NLP. The modern era began in March 2023: Stanford's Alpaca showed that 52K answers from an OpenAI model could turn LLaMA 7B into a passable assistant for a few hundred dollars, and within weeks Vicuna, Koala, GPT4All and dozens more followed. Gudibande et al.'s "false promise" paper (May 2023) was the correction; phi-1 ("Textbooks Are All You Need", June 2023) the counter-correction, showing that designed synthetic data could do more than imitation. 2024 made synthetic data industrial — Nemotron-4's open generation pipeline, Llama 3's synthetic code and maths data, Cosmopedia — and the model-collapse debate moved from alarm to the replace-versus-accumulate nuance. In 2025 DeepSeek-R1's distilled models and the Qwen3 report's on-policy distillation made "train the big model with RL, then distil it into the small ones" the standard recipe for reasoning model families.
First principles¶
Why a soft target is worth more than a hard one¶
A hard label from \(K\) classes carries at most \(\log_2 K\) bits and usually far fewer, since the label is predictable. A soft target carries a whole distribution: in the table above, the \(T = 4\) target has 2.06 bits of entropy, and its shape — which wrong answers are plausible — is information the label never had. Hinton et al. noted a second benefit: high-entropy targets give "much less variance in the gradient between training cases", so the student can use a higher learning rate and less data. Their 3%-of-the-data experiment is this principle measured.
There is also a statistical view. The teacher's distribution is an estimate of \(p(y \mid x)\) that has already averaged over everything it saw; training on it is like training on the expected label instead of a single noisy draw. That is why an ensemble — a better estimate of \(p(y\mid x)\) than any member — is such a good teacher, and why distillation and label smoothing are cousins: both stop the student from chasing one-hot targets to infinite logits.
Why the student's own samples matter¶
Every supervised method trains on a fixed distribution of prefixes and tests on the student's induced distribution. The gap grows with sequence length and with how different student and teacher are. On-policy training removes it by construction; the price is that you must run the teacher on every student sample. Reverse KL arises naturally here: the expectation is over the student's samples, so the objective is \(\mathbb E_{y \sim \pi_\theta}[\log \pi_\theta - \log \pi_T]\), which is the reverse KL. Mode-seeking is not an extra assumption; it is what learning from your own samples means.
Why recursion destroys tails¶
A model fitted to finite data underestimates the probability of rare events, because rare events are often absent from the sample. Sample from that model and rare events become rarer still. No step adds the missing tail back, so the losses compound geometrically — unless fresh real data (which contains the tails) or an external verifier (which knows something the generator does not) re-enters the loop.
The maths¶
The temperature gradient and the \(T^2\) factor¶
Let the student's logits be \(z\) and the teacher's \(v\), with softened probabilities \(q_i = \operatorname{softmax}(z/T)_i\) and \(p_i = \operatorname{softmax}(v/T)_i\). The soft cross-entropy \(C = -\sum_i p_i \log q_i\) has gradient
the familiar softmax-cross-entropy gradient with a chain-rule factor of \(1/T\).
Derivation: high temperature turns distillation into logit matching
For \(T\) large compared with the logits, \(e^{z_i/T} \approx 1 + z_i/T\), so with \(N\) classes
If both sets of logits are zero-mean (\(\sum_j z_j = \sum_j v_j = 0\)) the denominators are both \(N\), and
This is the gradient of \(\frac{1}{2NT^2}\sum_i (z_i - v_i)^2\): in the high-temperature limit, distillation is the logit-matching regression of Ba and Caruana. Two consequences follow. The gradient shrinks as \(1/T^2\), so the soft loss must be multiplied by \(T^2\) to keep its weight against the hard-label term when you change \(T\). And at lower temperatures, very negative logits (which the teacher's training barely constrained, and which may be noise) are matched less closely — "potentially advantageous", in the paper's words, and the reason intermediate temperatures work best for small students.
The first script in Build it checks this numerically: the cosine between the exact gradient and the logit-matching gradient rises from 0.855 at \(T=1\) to 0.999 at \(T=50\), and \(T^2 \lVert\nabla\rVert\) approaches \(\lVert z - v\rVert / N = 1.257\).
Forward KL is cross-entropy; reverse KL is a policy gradient¶
Forward KL decomposes as
so minimising it is ordinary cross-entropy against the teacher's distribution. For sequences, \(\mathbb E_{y\sim p}[-\log q_\theta(y)]\) is exactly what SFT on teacher samples estimates — which is why sequence-level distillation is a Monte Carlo approximation of forward KL, with one sample per prompt.
Reverse KL over sequences is
The expectation is over the student's own samples, so its gradient needs the score-function trick, exactly as in policy gradients: it is REINFORCE with reward \(\sum_t (\log \pi_T - \log \pi_\theta)\). Thinking Machines' implementation uses the per-token term as the advantage with discount zero — each token is credited only with its own log-ratio, a lower-variance estimator that is still minimised at \(\pi_\theta = \pi_T\).
Collapse of a recursively fitted Gaussian¶
Fit a Gaussian by maximum likelihood to \(n\) samples of \(\mathcal N(\mu, \sigma^2)\). The MLE variance \(\hat\sigma^2 = \frac1n\sum (x_i - \bar x)^2\) is biased:
If each generation samples from the previous fit and refits ("replace"), the expectations chain, \(\mathbb E[\hat\sigma_g^2] = \big(\frac{n-1}{n}\big)^g \sigma^2 \to 0\). With \(n = 50\) that is 0.817 after 10 generations, 0.133 after 100 and about \(10^{-9}\) after 1,000. The typical run collapses faster than this expectation suggests: the variance is multiplied each generation by an independent random factor \(\chi^2_{n-1}/n\), so \(\log \hat\sigma^2\) performs a random walk with a negative drift, and the mean is propped up by rare lucky runs. Debiasing (\(\frac{1}{n-1}\)) removes the drift of the mean but not the random walk, which still drifts to zero almost surely. With "accumulate", generation \(g\) fits on \(n(g+1)\) points of which the original \(n\) real ones never leave, and the estimate stays anchored.
Build it¶
Three NumPy scripts: temperature and the logit-matching limit; forward versus reverse KL; and model collapse with replace versus accumulate.
import numpy as np
def softmax(z, T=1.0):
e = np.exp((z - z.max()) / T); return e / e.sum()
# A teacher's logits for an image of a "2" (classes 0-9). The ranking of the wrong answers is the dark knowledge.
v = np.array([1.0, 2.0, 14.0, 7.5, 0.5, 1.5, 0.0, 6.0, 3.0, 1.0])
for T in [1, 4, 20]:
p = softmax(v, T)
H = -(p * np.log2(p)).sum()
print(f"T={T:>2}: p(2)={p[2]:.4f} p(3)={p[3]:.4f} p(7)={p[7]:.4f} entropy={H:.2f} bits")
# Gradient of the soft-target cross-entropy w.r.t. student logits z is (q - p)/T.
# At high T it approaches (z - v)/(N T^2) for zero-mean logits: distillation -> logit matching.
rng = np.random.default_rng(0)
z = rng.normal(0, 2, 10); z -= z.mean(); vz = v - v.mean(); N = 10
for T in [1, 5, 50]:
grad = (softmax(z, T) - softmax(vz, T)) / T
approx = (z - vz) / (N * T**2)
cos = grad @ approx / np.linalg.norm(grad) / np.linalg.norm(approx)
print(f"T={T:>2}: |grad|={np.linalg.norm(grad):.2e} T^2*|grad|={T*T*np.linalg.norm(grad):.3f} "
f"cos(grad, logit-matching grad)={cos:.3f}")
T= 1: p(2)=0.9981 p(3)=0.0015 p(7)=0.0003 entropy=0.02 bits
T= 4: p(2)=0.6128 p(3)=0.1207 p(7)=0.0829 entropy=2.06 bits
T=20: p(2)=0.1638 p(3)=0.1184 p(7)=0.1098 entropy=3.28 bits
T= 1: |grad|=1.02e+00 T^2*|grad|=1.018 cos(grad, logit-matching grad)=0.855
T= 5: |grad|=8.23e-02 T^2*|grad|=2.057 cos(grad, logit-matching grad)=0.925
T=50: |grad|=5.34e-04 T^2*|grad|=1.335 cos(grad, logit-matching grad)=0.999
The raw gradient collapses by three orders of magnitude between \(T=1\) and \(T=50\); multiplied by \(T^2\) it stays order one. Without that factor, raising the temperature would silently switch the soft loss off.
import numpy as np
# Fit one Gaussian student q to a bimodal teacher p on a grid, by forward KL(p||q) and reverse KL(q||p).
x = np.linspace(-8, 8, 4001); dx = x[1] - x[0]
gauss = lambda m, s: np.exp(-0.5 * ((x - m) / s) ** 2) / (s * np.sqrt(2 * np.pi))
p = 0.5 * gauss(-3, 0.8) + 0.5 * gauss(3, 0.8) # teacher: two modes
def kl(a, b): return np.sum(a * (np.log(a + 1e-300) - np.log(b + 1e-300))) * dx
best = {}
for name, f in [("forward KL(p||q)", lambda q: kl(p, q)), ("reverse KL(q||p)", lambda q: kl(q, p))]:
grid = [(f(gauss(m, s)), m, s) for m in np.arange(-4, 4.01, 0.1) for s in np.arange(0.3, 5, 0.05)]
val, m, s = min(grid); best[name] = (m, s)
q = gauss(m, s)
print(f"{name}: mean={m:+.1f} std={s:.2f} KL={val:.3f} student mass between modes |x|<1: "
f"{np.sum(q[np.abs(x) < 1]) * dx:.3f} (teacher {np.sum(p[np.abs(x) < 1]) * dx:.3f})")
forward KL(p||q): mean=+0.0 std=3.10 KL=0.663 student mass between modes |x|<1: 0.252 (teacher 0.006)
reverse KL(q||p): mean=+3.0 std=0.80 KL=0.693 student mass between modes |x|<1: 0.006 (teacher 0.006)
Forward KL lands on moment matching (mean 0, standard deviation \(\sqrt{0.8^2 + 3^2} = 3.10\)) and puts a quarter of its mass where the teacher has almost none. Reverse KL sits exactly on one mode; its KL of \(0.693 = \ln 2\) is precisely the cost of ignoring half the teacher.
import numpy as np
# Model collapse in one dimension: each generation fits a Gaussian (MLE) to data, then the
# next generation trains on samples from that fit. "replace" discards older data;
# "accumulate" keeps all real and synthetic data seen so far (Gerstgrasser et al., 2024).
rng = np.random.default_rng(0)
n, gens, runs = 50, 1000, 200
checkpoints = [1, 10, 100, 1000]
for mode in ["replace", "accumulate"]:
stds = {g: [] for g in checkpoints}
for _ in range(runs):
data = rng.normal(0.0, 1.0, n) # generation 0: real data, sigma = 1
pool = data.copy()
for g in range(1, gens + 1):
fit_on = data if mode == "replace" else pool
mu, sd = fit_on.mean(), fit_on.std() # MLE fit (divides by N)
data = rng.normal(mu, sd, n) # the next generation's training data
pool = np.concatenate([pool, data])
if g in checkpoints: stds[g].append(sd)
row = " ".join(f"g={g}: {np.median(stds[g]):.3f}" for g in checkpoints)
print(f"{mode:>10} median fitted std {row}")
print("theory, replace: E[var] after g gens = ((n-1)/n)^g ->",
" ".join(f"{((n-1)/n)**g:.3g}" for g in checkpoints))
replace median fitted std g=1: 0.979 g=10: 0.797 g=100: 0.114 g=1000: 0.000
accumulate median fitted std g=1: 0.991 g=10: 0.967 g=100: 0.971 g=1000: 0.974
theory, replace: E[var] after g gens = ((n-1)/n)^g -> 0.98 0.817 0.133 1.68e-09
With replacement, the fitted distribution has lost almost nine-tenths of its spread by generation 100 and is a spike by 1,000; with accumulation it holds near the true value of 1 indefinitely. (The script takes about 8 seconds.)
Things to try
- In the first script, find the temperature at which \(p(3)\) is largest. Why does it peak and then fall?
- In the second, give the teacher three modes with unequal weights. Which mode does reverse KL choose, and does the answer depend on where you start the search?
- In the collapse script, keep only the real data plus the latest generation (a sliding window). Does it collapse? What about real data plus a verifier that rejects samples with \(|x| > 2\)?
- Add a "student" with a smaller capacity (fit a Gaussian with fixed standard deviation 0.5) to the forward/reverse comparison. Which divergence degrades more gracefully?
- Read the on-policy distillation post's loss in code and write the NumPy version of one step for a toy three-token vocabulary.
In practice¶
- Pick the method by what you can access. Teacher logits and same tokenizer: logit distillation for pre-training-scale transfer, on-policy distillation for post-training. Only text: sequence distillation plus filtering. Only a verifier: rejection sampling or RLVR.
- Sample the teacher well. For reasoning traces, generate several samples per prompt and keep the ones that verify; prefer the shortest correct trace when length matters.
- Distil from the right teacher. A much larger teacher is not always better for a small student: the capacity gap can make its distribution impossible to fit. Intermediate "teacher assistants" and on-policy methods help.
- Engineer diversity. Vary seeds, personas, topics and difficulty explicitly, and deduplicate (n-gram and embedding) before training. Mode-collapsed synthetic data trains a mode-collapsed model.
- Decontaminate. Strong teachers have often memorised benchmark questions; check synthetic prompts against every eval you report.
- Keep real data in the mix, especially for pre-training-scale synthetic corpora, and keep measuring on human-written evaluation sets.
- Read the licence. Model licences and API terms of use often restrict using outputs to train other models; check before you build a product on distilled weights.
Common misconceptions¶
“A distilled model is as good as its teacher”
It is as good as its teacher on the data it imitated, and its base model elsewhere. Imitation models fool human raters with style while closing little of the knowledge gap.
“Synthetic data inevitably causes model collapse”
Collapse is a property of replacing real data with synthetic data in a closed loop. Accumulating real and synthetic data, and filtering synthetic data with verifiers, avoids it in theory and in practice — which is how 98%-synthetic alignment sets work.
“SFT on teacher samples is the same as knowledge distillation”
It is a one-sample Monte Carlo estimate of the forward-KL distillation loss. It discards the teacher's uncertainty, and like all off-policy methods it trains on prefixes the student would not have written.
Check yourself¶
Why does distillation use a temperature, and why multiply the soft loss by \(T^2\)?
At \(T = 1\) a confident teacher's wrong-answer probabilities are tiny and barely affect the loss, so the dark knowledge is invisible. Raising \(T\) flattens both distributions so those probabilities produce gradients. The gradient with respect to the student's logits is \((q - p)/T\), which shrinks as \(1/T^2\) at high temperature, so multiplying by \(T^2\) keeps the soft term's weight constant as you tune \(T\).
The distilled MNIST student never saw a 3, yet classified 98.6% of 3s correctly after a bias fix. Where did its knowledge of 3s come from?
From the soft targets on other digits. Every 2, 5, 8 or 7 that "looks a bit like a 3" carries a small teacher probability on class 3, so the student learned which input features raise the class-3 logit without ever seeing a labelled 3. Only the class's prior was missing, which is what the bias correction supplied.
Which KL direction does SFT on teacher samples minimise, and what failure does that produce in a small student?
Forward KL, \(\operatorname{KL}(p_{\text{teacher}}\|q_{\text{student}})\), estimated with one sample per prompt. It is mode-covering: a student too small to represent every mode spreads mass across them, including low-quality regions between them — in text, blended or generic answers the teacher would not produce.
Why is on-policy distillation cheaper than RL for the same student and the same final score?
RL gets roughly one scalar per episode (the reward or advantage), so it needs many episodes to assign credit. On-policy distillation gets a teacher judgement on every token, a dense signal, while still training on the student's own samples. In the Qwen3 report it beat RL on AIME'24 (74.4% vs 67.6%) with about a tenth of the GPU hours.
Alpaca-style imitation models looked close to ChatGPT to crowd workers. What did targeted evaluation find, and why were the raters fooled?
Gudibande et al. found the imitation models closed little to none of the capability gap on tasks not heavily covered by the imitation data. They had learned ChatGPT's style — confident, well-formatted, fluent — but not its factual knowledge, and style is what raters notice quickly.
Under what condition does training on synthetic data cause model collapse, and what two things prevent it?
When each generation's synthetic data replaces the real data, so errors (especially lost tails) compound across generations. Accumulating real data alongside synthetic data keeps error bounded (Gerstgrasser et al.), and filtering with a verifier or other external signal injects information the generator lacked.
Hard: for the recursive Gaussian with \(n = 50\), the expected variance after 100 generations is 0.133, but the median fitted standard deviation is 0.114 (variance about 0.013). Explain the gap.
The variance is multiplied each generation by an independent random factor with mean \((n-1)/n\). The expectation of a product of independent factors is the product of their means, but the product itself is log-normal-like: \(\log\hat\sigma^2\) is a sum of independent terms with mean \(\mathbb E[\log(\chi^2_{n-1}/n)] < \log((n-1)/n)\) (Jensen). So the typical (median) run decays faster than the mean, which is dominated by rare runs that happened to drift upwards.
Hard: DeepSeek found distilling R1 into Qwen-32B beat running large-scale RL on Qwen-32B itself. Does this contradict the claim that RL discovers things SFT cannot?
No. The teacher was produced by RL on a much larger model; distillation transfers what that RL discovered, cheaply, into a smaller model that could not discover it as efficiently on its own. RL is how the capability is found; distillation is how it is spread. DeepSeek note that pushing the frontier beyond the teacher "may still require more powerful base models and larger-scale reinforcement learning".
Go deeper¶
Papers
- Distilling the Knowledge in a Neural Network — Hinton, Vinyals, Dean, 2015. Short and still the best introduction; read sections 2–3 and 6.
- Sequence-Level Knowledge Distillation — Kim and Rush, 2016. Why training on teacher outputs works for generation.
- On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes (GKD) — Agarwal et al., 2023. The general framework: any divergence, any mix of on- and off-policy data.
- MiniLLM: On-Policy Distillation of Large Language Models — Gu et al., 2023. The case for reverse KL in generative distillation.
- DeepSeek-R1 — DeepSeek-AI, 2025. Section 4.1, distillation versus RL on the same base.
- The False Promise of Imitating Proprietary LLMs — Gudibande et al., 2023. What imitation does not transfer.
- Self-Instruct — Wang et al., 2022. The bootstrap that started synthetic instruction data.
- Textbooks Are All You Need (phi-1) — Gunasekar et al., 2023. Designed synthetic data as a substitute for scale.
- Beyond Human Data: Scaling Self-Training for Problem-Solving (ReST-EM) — Singh et al., 2023. Rejection-sampling self-training as EM.
- AI models collapse when trained on recursively generated data — Shumailov et al., Nature, 2024. The collapse result and its mechanism.
- Is Model Collapse Inevitable? — Gerstgrasser et al., 2024. Accumulate, don't replace.
- Qwen3 Technical Report — Qwen Team, 2025. Section 4.5: strong-to-weak distillation for a whole model family.
Articles and blog posts
- On-Policy Distillation — Kevin Lu and Thinking Machines, 2025. The clearest modern treatment, with code-level detail and cost accounting.
- Alpaca: A Strong, Replicable Instruction-Following Model — Stanford CRFM, 2023. The post that started the 2023 imitation wave.
- Cosmopedia: how to create large-scale synthetic data for pre-training — Hugging Face, 2024. The practical problems of diversity at 25B tokens.
- RLHF Book: Synthetic Data & Distillation — Nathan Lambert. How synthetic data is used across the post-training stack.
Videos and lectures
- EfficientML.ai Lecture 9: Knowledge Distillation — Song Han, MIT 6.5940. KD from logits to features, with the compression context.
- On-Policy Distillation & Using Synthetic Data in Post-Training — Nathan Lambert, Post-Training Course lecture 7. The current practice in one lecture.
Code
- huggingface/trl — SFT, GKD and on-policy distillation trainers; see the GKD trainer docs.
Where this leads¶
- RL with verifiable rewards — how the teachers of reasoning models are made, and why on-policy distillation is RL with a dense reward.
- Constitutional AI and RLAIF — synthetic preference data: a model as the labeller rather than the teacher.
- Parameter-efficient fine-tuning: LoRA and QLoRA — the cheap way to train a student on distilled data.
- Model merging and continual learning — on-policy distillation as a tool for recovering forgotten behaviour.
- Quality filtering and deduplication — the filtering half of every synthetic-data pipeline.