Reasoning Distillation
Copying a teacher's text and matching its distribution are different things. Why distillation is cheap, and why it is capped by the teacher.
Jump to a section
What R1's distilled models showed
When DeepSeek released R1, it also released six smaller Qwen and Llama models, from 1.5B to 70B parameters, that got no reinforcement learning of their own. Each was fine-tuned with plain supervised learning on about 800k samples curated with R1. The 32B Qwen model trained this way scored 72.6% pass@1 on AIME 2024.
The paper then ran the obvious comparison. It trained the same Qwen 32B base with large-scale RL for more than 10,000 steps, and that model only reached the level of QwQ-32B-Preview. The distilled 32B model was better across the reported benchmarks. For a model that size, learning from a stronger model's written reasoning beat discovering reasoning through RL.
That is reasoning distillation: train a smaller student on a stronger teacher's reasoning. No reward, verifier or RL loop runs during training. The limit runs the other way: distillation is cheap when a strong teacher exists, and RL is how you get past the teacher.
Hard targets: train on what the teacher wrote
The simplest form, and the one R1 used, is sequence-level or hard distillation. Generate solutions with the teacher, keep the good ones, and fine-tune the student on the text with ordinary next-token cross-entropy.
The filter is where verifiers come back in. R1's reasoning data came from sampling several responses per prompt and keeping only the correct ones, after also discarding traces with mixed languages, long paragraphs or code blocks. Training on unchecked teacher output teaches the student the teacher's mistakes as faithfully as its reasoning.
The loss is the negative log-likelihood of teacher outputs given prompts :
It is computed only on response tokens, with the prompt masked out. The aim is to model responses given prompts, not to spend capacity predicting the prompt. Hard targets need nothing from the teacher but text, so they work with teachers that are only available through an API.
Soft targets: match what the teacher considered
A sampled token discards most of what the teacher computed. At each position the teacher has a full distribution over the vocabulary, and the runner-up tokens say which alternatives it found plausible. Soft distillation, from Hinton et al., trains the student to match that distribution.
Both models' logits are softened by a temperature : and . The loss is
Match the teacher’s whole distribution
Raise the temperature to reveal the teacher’s relative preferences beyond its top answer, then watch the student move toward them.
The visual loads as you reach this section.
Temperature is what exposes the alternatives. With teacher logits , the runner-up gets 4.7% of the probability at and 23% at . The gradient of the loss with respect to the student's logits is . Without the factor it would be , and since itself shrinks as grows, gradient magnitudes would fall roughly as . The factor keeps them comparable across temperatures and against any hard-label term mixed in.
1from math import exp, log
2
3
4def softmax(z, T=1.0):
5 m = max(z)
6 e = [exp((v - m) / T) for v in z]
7 s = sum(e)
8 return [v / s for v in e]
9
10
11def soft_loss(teacher_logits, student_logits, T):
12 q, p = softmax(teacher_logits, T), softmax(student_logits, T)
13 return T * T * sum(qi * log(qi / pi) for qi, pi in zip(q, p))
14
15
16teacher = [6.0, 3.0, 2.0, 0.0]
17assert softmax(teacher, 1.0)[1] < 0.05 # runner-up nearly invisible at T = 1
18assert softmax(teacher, 4.0)[1] > 0.2 # its relative preference shows at T = 4
19
20# The gradient of T^2 KL(q || p) with respect to the student's logits is T (p - q).
21student, T, h = [1.0, 1.0, 1.0, 1.0], 4.0, 1e-5
22q, p = softmax(teacher, T), softmax(student, T)
23for i in range(4):
24 up, down = student[:], student[:]
25 up[i] += h
26 down[i] -= h
27 numeric = (soft_loss(teacher, up, T) - soft_loss(teacher, down, T)) / (2 * h)
28 assert abs(numeric - T * (p[i] - q[i])) < 1e-6Soft targets have practical requirements. You need the teacher's logits, not just its text, and the two models must share a vocabulary or be aligned token by token. Storage adds up quickly: with Llama 3's 128,256-token vocabulary in bf16, one position's distribution is about 256 KB, so a single 10,000-token trace needs about 2.6 GB. The alternatives are to keep only the top few teacher probabilities per position or to recompute the teacher's logits during training.
The student's own mistakes
Both forms above are usually off-policy. The student trains on prefixes the teacher wrote, but at test time it conditions on its own earlier tokens. One early slip puts it in a state the training data never contained, and errors compound from there. This is exposure bias.
On-policy distillation, studied by Agarwal et al., samples sequences from the student and asks the teacher to score or correct them token by token. The student learns what to do in the states it actually reaches, including after its own mistakes. The cost is running the teacher inside the training loop instead of once ahead of time.
The three options trade what you need from the teacher against what the student learns from. Hard off-policy distillation needs only text and is generated once. Soft off-policy distillation needs logits and a shared vocabulary, stored or recomputed. On-policy distillation needs the teacher available during training, scoring states the student produced.
In code
Hard distillation is ordinary supervised fine-tuning with the prompt masked. Labels are the input shifted by one.
1import torch
2import torch.nn.functional as F
3
4def distill_loss(logits, input_ids, prompt_len):
5 # logits: [B, L, V]; input_ids: [B, L] = prompt + teacher response
6 pred = logits[:, :-1] # position t predicts token t+1
7 target = input_ids[:, 1:].clone()
8 target[:, : prompt_len - 1] = -100 # ignore prompt tokens
9 return F.cross_entropy(pred.reshape(-1, pred.size(-1)),
10 target.reshape(-1), ignore_index=-100)
11
12B, L, V = 2, 12, 100
13loss = distill_loss(torch.randn(B, L, V), torch.randint(0, V, (B, L)), prompt_len=5)With a padded batch, use a per-example prompt length and mask padding tokens as well.
Where it goes wrong
Unfiltered traces. Wrong teacher solutions are imitated as faithfully as right ones. Filter with a verifier where answers can be checked, and spot-check the rest.
Evaluation leakage. If the teacher's prompts overlap the benchmark, the student can score well by recall. Evaluate on a split the teacher's solutions did not come from.
The teacher is the ceiling. Imitation can approach the teacher but has no signal for going past it. The R1 paper itself notes that pushing beyond current capability may still need stronger base models and larger-scale RL.
Format without substance. Cross-entropy on a long trace is dominated by the many tokens of reasoning prose, not the few tokens of the final answer. A falling loss can mean the student has learned to sound like the teacher. Measure final-answer accuracy, not trace length or style.
Soft targets across tokenizers. Matching distributions position by position is meaningless if the teacher and student split text differently. Use hard targets or an explicit alignment step.
Sources and further reading
- Hinton et al., Distilling the Knowledge in a Neural Network: soft targets and temperature.
- DeepSeek-AI, DeepSeek-R1: SFT-only distillation of R1 reasoning into Qwen and Llama models, compared with RL on the smaller model.
- Agarwal et al., On-Policy Distillation of Language Models: training on student-generated sequences with teacher feedback.
- Raschka, Building Reasoning Models from the Ground Up: distills DeepSeek-R1 answers on MATH into a small Qwen3 model.