Knowledge Distillation
This post documents knowledge distillation methods roughly in the order they were developed: soft labels, sequence-level distillation, representation matching, relational distillation, and on-policy distillation. The final sections describe an idea based on Gromov-Wasserstein distance, and the post distinguishes throughout between established work and conjecture.
The setup
You have a big model that is good and a small model that is cheap. Distillation is any procedure that transfers behavior from the first into the second. Each method below is a different answer to two questions: what data is used for training, and what signal is taken from the teacher?
Soft labels
The original recipe is from Hinton, Vinyals and Dean (2015). A hard label says “cat”. The teacher’s output distribution says “cat, somewhat lynx-like, definitely not a truck”, and that extra structure is what the student learns from. To expose it you soften the teacher’s logits with a temperature $\tau$:
\[p_i^{\tau} = \frac{\exp(z_i/\tau)}{\sum_j \exp(z_j/\tau)}\]and train the student on a mix of the usual cross-entropy and a KL term against the teacher:
\[\mathcal{L} = (1-\alpha)\,\mathrm{CE}(y, p^S) + \alpha\,\tau^2\,\mathrm{KL}\!\left(p_T^{\tau} \,\|\, p_S^{\tau}\right).\]The factor $\tau^2$ keeps gradient magnitudes comparable across temperatures.
Distilling language models
For an autoregressive model the same idea runs per token. Take a prefix from a fixed dataset, and push the student’s next-token distribution toward the teacher’s:
\[\mathcal{L}_{\text{KD}} = \mathbb{E}_{(x,y)\sim \mathcal{D}} \sum_t \mathrm{KL}\!\left(\pi_T(\cdot \mid x, y_{<t}) \,\|\, \pi_\theta(\cdot \mid x, y_{<t})\right).\]This requires access to the teacher’s logits. When only API access is available, an alternative is sequence-level distillation (Kim and Rush, 2016): sample complete outputs from the teacher and run ordinary supervised fine-tuning on them. Many current recipes that fine-tune a small model on a larger model’s reasoning traces follow this approach.
Matching representations instead of outputs
Everything so far matches outputs. An older line of work matches intermediate computation instead. FitNets (Romero et al., 2015) matched intermediate features, attention transfer (Zagoruyko and Komodakis, 2017) matched attention maps, and TinyBERT and MiniLM (2020) matched hidden states and attention in transformers. The argument is that how the teacher computes may be as informative as what it outputs.
The standard version is point to point. For each position, the student’s hidden state should resemble the teacher’s:
loss = (1 - F.cosine_similarity(proj(h_student), h_teacher.detach(), dim=-1)).mean()
This formulation has two limitations.
First, if the widths differ, a learned projection is required, and the projection may account for much of the matching. A sufficiently flexible map can align with the teacher’s features without the student’s own representation becoming similar to the teacher’s.
Second, it assumes that the two spaces share coordinates in a meaningful way. There is no reason for a 896-dimensional space and a 1536-dimensional space from separate training runs to align axis by axis. What is plausibly shared is the structure: which examples are near each other and which are far apart.
One practical note, which is well documented: LLM hidden states often contain a few massive-activation dimensions that dominate any raw MSE or dot-product loss. Center and normalize before comparing.
Relational knowledge distillation
Relational knowledge distillation (RKD; Park, Kim, Lu and Cho, CVPR 2019) addresses both limitations by matching relations between examples instead of the embeddings themselves. For a batch of examples with teacher embeddings $t_i$ and student embeddings $s_i$, it defines two losses.
The distance-wise loss compares pairwise distances, normalized by their mean $\mu$ so that scale does not matter:
\[\psi_D(t_i, t_j) = \frac{1}{\mu}\,\lVert t_i - t_j \rVert_2, \qquad \mathcal{L}_{\text{RKD-D}} = \sum_{i,j} \ell_\delta\!\left(\psi_D(s_i, s_j),\, \psi_D(t_i, t_j)\right),\]where $\ell_\delta$ is the Huber loss. The angle-wise loss does the same for the angle formed by each triplet of examples, which captures structure that pairwise distances miss:
\[\psi_A(t_i, t_j, t_k) = \cos \angle\, t_i t_j t_k = \langle e^{ij}, e^{kj} \rangle, \qquad e^{ij} = \frac{t_i - t_j}{\lVert t_i - t_j \rVert_2}.\]Because only relations are compared, the two embedding spaces can have different dimensions and no projection layer is needed. A closely related method, similarity-preserving KD (Tung and Mori, 2019), matches batch similarity matrices.
RKD was developed for image models, where the “examples” are different images in a batch. The same idea transfers to language models if the examples are token positions within a sequence. A sketch of the distance-wise term in that setting:
def relational_loss(hs, ht, mask):
# hs: [B, T, Ds], ht: [B, T, Dt]; mask: [B, T] bool
hs = F.normalize(hs - hs.mean(dim=1, keepdim=True), dim=-1)
ht = F.normalize(ht - ht.mean(dim=1, keepdim=True), dim=-1)
Cs = 1 - hs @ hs.transpose(1, 2)
Ct = 1 - ht @ ht.transpose(1, 2)
m = mask[:, :, None] & mask[:, None, :]
return ((Cs - Ct) ** 2 * m).sum() / m.sum()
This uses cosine distance on centered features instead of RKD’s mean-normalized Euclidean distance, and squared error instead of Huber, which are design choices rather than settled ones. Combined with the on-policy sampling described below, it gives “OPD plus a relational loss”, a straightforward combination of two existing methods.
Limitations of off-policy distillation
In all of the methods above, the student is trained on inputs the teacher would produce or that come from a fixed dataset, but at test time it generates its own text. Once it emits a slightly unusual token, it is conditioned on a prefix that never appeared in training, and nothing in its training teaches it to recover. Errors accumulate over the length of the generation.
This is known as exposure bias, and it is equivalent to covariate shift in behavior cloning. Imitation learning addressed it with DAgger (Ross et al., 2011): the learner acts, and the expert labels the states the learner actually reaches.
On-policy distillation
On-policy distillation (OPD) is that fix applied to language models. It appears in the GKD paper (Agarwal et al., 2024) and was described more recently by Thinking Machines Lab. The loop is short:
- Sample a response from the student.
- Run the teacher over that same response and get its log-probabilities at each token.
- Penalize the student, token by token, for disagreeing with the teacher on its own prefixes.
The loss is a reverse KL under the student’s own samples:
\[\mathcal{L}_{\text{OPD}} = \mathbb{E}_{x,\; y\sim \pi_\theta} \sum_t \mathrm{KL}\!\left(\pi_\theta(\cdot \mid x, y_{<t}) \,\|\, \pi_T(\cdot \mid x, y_{<t})\right).\]On a sampled token, the per-token quantity reduces to a single number:
\[r_t = \log \pi_T(y_t \mid x, y_{<t}) - \log \pi_\theta(y_t \mid x, y_{<t}).\]OPD can be viewed as reinforcement learning with a per-token reward provided by the teacher. You can reuse a policy-gradient trainer and just swap in $r_t$. A minimal sketch:
with torch.no_grad():
y = student.generate(x) # on-policy sample
t_logp = token_logprobs(teacher, x, y) # [B, T], teacher forward pass only
s_logp = token_logprobs(student, x, y) # [B, T], with grad
reward = (t_logp - s_logp).detach() # per-token reward
loss = -(reward * s_logp).mean() # no discounting; mask padding in real code
Compared with outcome-reward RL, the feedback is dense (every token is scored, not just the end of the rollout), and the teacher requires only a forward pass, since it never generates.
The choice of reverse KL is deliberate. Forward KL is mean-seeking: the student must cover every region where the teacher places mass, which a small model often cannot afford, so its probability mass is spread thinly. Reverse KL is mode-seeking: the student is penalized for placing mass where the teacher would not. For generation this is usually preferable, although it may reduce diversity.
Using Gromov-Wasserstein distance
RKD still carries one assumption: example $i$ in the student corresponds to example $i$ in the teacher. The relations are compared pair by pair under a known matching. Gromov-Wasserstein (GW) distance removes that assumption. It compares two metric spaces by their internal distances only, and finds the correspondence as part of the comparison. Given student states ${h^S_i}$ and teacher states ${h^T_j}$, form the distance matrices $C^S_{ik} = d(h^S_i, h^S_k)$ and $C^T_{jl} = d(h^T_j, h^T_l)$. Then
\[\mathrm{GW}(C^S, C^T) = \min_{\Gamma \in \Pi(p,q)} \sum_{i,k,j,l} \left| C^S_{ik} - C^T_{jl} \right|^2 \Gamma_{ij}\Gamma_{kl},\]where $\Gamma$ is a soft correspondence between student points and teacher points. In words: if two student points are far apart, the teacher points they are matched to should be far apart too. Dimension, rotation and scale of the ambient space do not matter.
When the correspondence is known, $\Gamma$ is the identity and the objective is exactly the distance-wise RKD term. The GW formulation therefore adds nothing over RKD unless the correspondence is unknown or uncertain. Two settings fit that description, and each comes with a cheaper alternative that the GW version has to beat.
Different tokenizers
If the teacher and student use different tokenizers, their token sequences differ in length and boundaries, so per-token OPD and position-wise RKD are no longer well defined. A possible on-policy pipeline is to sample from the student, decode to a string, re-tokenize with the teacher’s tokenizer, and run the teacher forward on that string.
Both token sequences then cover the same text, and character offsets provide an approximate alignment without any GW. Pooling teacher hidden states over each student token’s character span (or pooling both models to the word level) and applying RKD is therefore the natural baseline. GW could add something where boundaries are ambiguous, such as a student token spanning parts of two teacher tokens, because a soft coupling handles that more gracefully than hard pooling.
Different layer counts
A 12-layer student and a 28-layer teacher have no obvious layer-to-layer map, and the usual practice is a fixed rule such as matching every fourth layer. A GW coupling over layers could learn the map, with each layer treated as a point and layer-to-layer dissimilarity (for example, one minus CKA) as the distance.
References
- Hinton, Vinyals, Dean. Distilling the Knowledge in a Neural Network. 2015.
- Romero et al. FitNets: Hints for Thin Deep Nets. 2015.
- Zagoruyko, Komodakis. Paying More Attention to Attention. ICLR 2017.
- Kim, Rush. Sequence-Level Knowledge Distillation. EMNLP 2016.
- Park, Kim, Lu, Cho. Relational Knowledge Distillation. CVPR 2019.
- Tung, Mori. Similarity-Preserving Knowledge Distillation. ICCV 2019.
- Ross, Gordon, Bagnell. A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning. 2011.
- Agarwal et al. On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes. ICLR 2024.
- Thinking Machines Lab. On-Policy Distillation. 2025.
- Mémoli. Gromov-Wasserstein Distances and the Metric Approach to Object Matching. 2011.
- Peyré, Cuturi, Solomon. Gromov-Wasserstein Averaging of Kernel and Distance Matrices. ICML 2016.
- Vayer et al. Optimal Transport for Structured Data with Application on Graphs. ICML 2019 (fused GW).