Skip to main content

Distillation: Learning from a Teacher

Distillation Is a Source of Supervision

Let \(q\) denote a teacher and \(p_\theta\) a student. Distillation transfers information exposed by the teacher that is not contained in a single hard label:

  • uncertainty across classes or tokens
  • similarities between alternatives
  • intermediate representations
  • generated solutions or trajectories
  • behavior on states selected by either teacher or student

The defining property is not one particular formula. It is that the training target comes from another model. A distilled student may be discriminative, generative, representational, or policy-like.

Three choices define a distillation objective:

  1. What is matched? Outputs, logits, features, relations, sequences, or behavior.
  2. Where is it matched? Data inputs, teacher-generated inputs, or student-generated/on-policy states.
  3. How is it matched? Forward KL, reverse KL, MSE, cosine distance, sequence NLL, or an RL-style objective.

Output Distillation: Soft Targets

For class or token logits \(z^T\) and \(z^S\), temperature \(\tau\) defines

\[ q_\tau(i\mid x) = \operatorname{softmax}\left(\frac{z_i^T}{\tau}\right), \qquad p_{\theta,\tau}(i\mid x) = \operatorname{softmax}\left(\frac{z_i^S}{\tau}\right). \]

Classical output distillation minimizes forward KL:

\[ \mathcal L_{\mathrm{KD}} = \tau^2 \operatorname{KL} \left(q_\tau(\cdot\mid x)\|p_{\theta,\tau}(\cdot\mid x)\right). \]

The teacher supplies the expectation, so missing a teacher-supported class is costly. The entropy of \(q_\tau\) is constant with respect to the student; therefore this is equivalent to soft-label cross-entropy up to a constant.

NoteOne-hot targets: CE = forward KL = NLL

If the target is one-hot at the observed class \(y\), then \(q(i\mid x)=\mathbf{1}[i=y]\) and its entropy is zero: \(H(q)=0\). Thus the losses are exactly equal:

\[ \operatorname{CE}(q,p_\theta) = \operatorname{KL}(q\|p_\theta) + H(q) = \operatorname{KL}(q\|p_\theta) = -\log p_\theta(y\mid x) = \operatorname{NLL}(y,p_\theta). \]

This equality uses forward KL, from target to student, with the same predicted distribution and loss scaling. For soft targets, CE and forward KL differ by the target entropy, but still have the same student gradients when the target is fixed.

To see why, expand the identity for a soft target:

\[ \underbrace{-\sum_i q_i\log p_{\theta,i}}_{\operatorname{CE}(q,p_\theta)} = \underbrace{\sum_i q_i\log\frac{q_i}{p_{\theta,i}}}_{\operatorname{KL}(q\|p_\theta)} + \underbrace{\left(-\sum_i q_i\log q_i\right)}_{H(q)}. \]

When the teacher target \(q\) is fixed, \(H(q)\) does not depend on the student parameters \(\theta\), so its gradient is zero:

\[ \nabla_\theta\operatorname{CE}(q,p_\theta) = \nabla_\theta\operatorname{KL}(q\|p_\theta). \]

The loss values differ, but they produce the same student updates under the same scaling and optimizer. For example, if \(q=(0.5,0.5)\), then \(H(q)=\log 2\approx0.693\) (using natural logarithms). CE is always KL plus \(0.693\), regardless of the student prediction. When \(p_\theta=q\), KL is zero while CE is \(0.693\). For a one-hot target, \(H(q)=0\), so even the loss values are identical.

Larger \(\tau\) reveals relative preferences among non-maximum classes. Dividing logits by \(\tau\) also shrinks their gradients, so the conventional \(\tau^2\) factor approximately preserves gradient scale when comparing temperatures.

A common supervised mixture is

\[ \mathcal L = (1-\lambda)\operatorname{CE}(y,p_{\theta,1}) + \lambda\tau^2 \operatorname{KL}(q_\tau\|p_{\theta,\tau}). \]

The hard label anchors the student to observed outcomes; the soft target transfers the teacher’s richer geometry. A teacher can also be wrong, biased, or miscalibrated, so the mixture is not automatically better than either term.

Minimal implementation

import torch
import torch.nn.functional as F


def forward_kl_distillation(student_logits, teacher_logits, temperature=2.0):
    """Teacher-to-student KL, averaged over the batch."""
    log_p_student = F.log_softmax(student_logits / temperature, dim=-1)
    p_teacher = F.softmax(teacher_logits / temperature, dim=-1)
    return (
        F.kl_div(
            log_p_student,
            p_teacher,
            reduction="batchmean",
        )
        * temperature**2
    )


torch.manual_seed(0)
teacher_logits = torch.randn(8, 10)
close_student = teacher_logits + 0.01 * torch.randn_like(teacher_logits)
far_student = torch.randn_like(teacher_logits)
assert forward_kl_distillation(
    close_student, teacher_logits
) < forward_kl_distillation(far_student, teacher_logits)

Detach teacher outputs unless the teacher is intentionally co-trained. Otherwise the objective may change the target while the student chases it.

KL Direction and State Distribution Are Independent

Two design axes are often conflated.

Divergence direction

Forward KL uses teacher probability as its local weighting:

\[ \operatorname{KL}(q\|p_\theta) = \mathbb E_{a\sim q} \left[\log q(a)-\log p_\theta(a)\right]. \]

It encourages the student to cover alternatives supported by the teacher. Reverse KL uses student probability as its local weighting:

\[ \operatorname{KL}(p_\theta\|q) = \mathbb E_{a\sim p_\theta} \left[\log p_\theta(a)-\log q(a)\right]. \]

It strongly discourages choices the student makes that the teacher considers unlikely, but can be mode-seeking. These are tendencies; capacity, support, temperature, and optimization also matter.

State or input distribution

The context \(h\) at which the distributions are compared can come from:

State source What it teaches Main risk
observed/data inputs behavior near the training distribution misses student-induced errors
teacher trajectories states a strong policy visits student may not reach them
student trajectories recovery on deployment-like states teacher may be unreliable off distribution
mixture or replay broader coverage weighting becomes another design choice

One can use forward or reverse KL under any of these state distributions. “Use reverse KL” does not by itself make an objective on-policy.

On-Policy Distillation for Autoregressive Models

Teacher forcing trains on data prefixes, whereas generation visits prefixes created by the student. On-policy distillation lets the student generate a prefix \(h_t\) and asks the teacher to evaluate that encountered state.

A common local objective is

\[ \mathcal L_{\mathrm{OPD}}(h_t) = \operatorname{KL} \left( p_\theta(\cdot\mid h_t) \middle\| q(\cdot\mid h_t) \right). \]

For a sampled action \(a_t\sim p_\theta(\cdot\mid h_t)\),

\[ r_t = \log q(a_t\mid h_t) - \log p_\theta(a_t\mid h_t) \]

can act as a dense token-level reward. Full-vocabulary KL is available when teacher logits can be queried; sampled implementations require care because the sampling distribution itself depends on \(\theta\).

On-policy training addresses state-distribution mismatch. Reverse KL chooses the local discrepancy geometry. They solve different problems.

Potential failures include:

  • the student reaches prefixes outside the teacher’s reliable region
  • reverse KL removes useful diversity
  • teacher querying dominates training cost
  • sampled gradient estimates have high variance
  • locally imitating next-token probabilities does not preserve sequence-level behavior

On-Policy Distillation develops the state- distribution view. MiniLLM studies reverse-KL distillation for generative language models. More recent trust-region methods such as TrOPD restrict unreliable updates and can mix forward-KL guidance into uncertain regions.

For a production case, Composer 2.5 constructs a local teacher by inserting textual corrective feedback at a problematic turn, then adds an on-policy KL loss while retaining the trajectory-level RL objective. See Cursor’s Continual Training Loop.

Sequence Distillation

When teacher logits are unavailable or expensive to store, generate teacher outputs \(\widetilde y\sim q(\cdot\mid x)\) and train by ordinary NLL:

\[ \mathcal L_{\mathrm{seq}} = -\log p_\theta(\widetilde y\mid x). \]

This converts the teacher into a data generator. It is simple and works across different APIs or vocabularies, but a sampled sequence exposes far less information than the full teacher distribution. Decoding also changes the target: greedy outputs reduce diversity, while sampled outputs introduce variance and possible errors.

For reasoning models, a teacher can supply final answers, rationales, tool-use traces, or verified trajectories. These are different supervisory objects. Imitating a rationale’s tokens does not prove that the student has learned the same internal algorithm, and incorrect rationales can transfer persuasive failure modes.

Feature and Relational Distillation

Output matching is not the only transfer channel.

Feature matching

Given teacher and student representations \(h^T(x)\) and \(h^S(x)\),

\[ \mathcal L_{\mathrm{feature}} = \left\|P_\phi(h^S(x))-h^T(x)\right\|_2^2, \]

where \(P_\phi\) aligns dimensions. Cosine distance or attention-map matching may be used instead. Layer alignment is an architectural hypothesis, not a neutral implementation detail: a smaller student may organize computation differently.

Relational matching

Rather than matching coordinates, match relations within a batch:

\[ \mathcal L_{\mathrm{relation}} = \sum_{i,j} \left( \operatorname{sim}(h_i^S,h_j^S) - \operatorname{sim}(h_i^T,h_j^T) \right)^2. \]

This preserves teacher geometry while allowing rotations or different feature bases. It connects distillation to Representation Learning.

Self-distillation methods such as BYOL- and DINO-style training use a momentum or stop-gradient teacher to create a stable target. Their main challenge is not compression but preventing representational collapse.

Learning from an Unreliable Teacher

The strongest practical evidence here supports checking teacher-generated supervision against external feedback, rather than assuming that confidence or agreement makes a target correct. The following are documented practices and findings, not a universal recipe for arbitrary teacher noise.

  • Filter generated solutions using correctness signals. DeepSeek-R1 samples multiple reasoning responses, retains those judged correct, and applies readability filters. Its smaller Qwen/Llama students receive SFT on the resulting curated dataset. Some judgments use a model supplied with ground truth, so the pipeline is not entirely rule-verified. See DeepSeek-R1 (2025), §§2.3.3–2.4.
  • For coding, execute the proposed solution and validate tool use. Qwen3-Coder-Next filters unsuccessful trajectories and malformed tool calls, and verifies SFT responses using compiler, runtime, and environment feedback. This is a concrete alternative to trusting the generator’s self-assessment. See Qwen3-Coder-Next (2026), §§3.1.2 and 4.1.
  • Do not equate confidence with correctness. Guo et al. show that modern networks can be miscalibrated and study temperature scaling on held-out data. Calibration can improve probability estimates; a positive scalar temperature preserves class ranking and cannot fix a wrong top prediction. See On Calibration of Modern Neural Networks (ICML 2017). For fitting methods and calibration-oriented training, see Model Calibration: From CTR/CVR to Calibrated Decisions.
  • Select by student task performance, not teacher imitation alone. Stanton et al. find that closer teacher matching does not always improve generalization. This supports evaluating downstream quality separately from distillation loss. See Does Knowledge Distillation Really Work? (NeurIPS 2021).

A practical synthesis is to retain trusted supervision, filter teacher outputs where meaningful verification is available, and compare against a student trained without distillation on held-out tasks. Tune the teacher contribution on validation data; use a separate test set for the final comparison. These are evaluation recommendations drawn from the evidence above, not an established optimal weighting rule. Passing tests does not prove every reasoning step correct, and shared teacher errors can survive consensus.

Multi-Teacher Distillation and MoE

Multiple teachers can provide complementary supervision: for example, one specializes in repository repair, another in web development, and another in single-turn code questions. There are distinct ways to combine them.

Combining distributions or selecting a teacher

For teachers \(q_1,\ldots,q_K\) over the same output space, a generic probability mixture is

\[ \bar q(\cdot\mid x)=\sum_{k=1}^K a_k(x)q_k(\cdot\mid x), \qquad a_k(x)\geq0,\quad\sum_k a_k(x)=1. \]

At a fixed input and temperature, with fixed weights and teachers,

\[ \sum_k a_k\operatorname{KL}(q_k\|p_\theta) =\operatorname{KL}(\bar q\|p_\theta) +\sum_k a_k\operatorname{KL}(q_k\|\bar q). \]

The last term is independent of the student, so weighted forward KL to individual teachers has the same student gradient as forward KL to their probability mixture. This is an algebraic identity, not a claim about the implementation of the reports below. It does not extend unchanged to reverse KL or averaging raw logits.

Alternatively, select a specialist \(k=d(x)\) for each task, or collect and verify generated solutions from several teachers for sequence-level SFT. Direct token-distribution matching requires compatible token spaces or an explicit alignment; text-based distillation can cross tokenizer boundaries.

Recent coding and agentic model examples

Qwen3-Coder-Next (2026). The report describes specialists for Web Development, User Experience, Single-turn RL, and Software Engineering, trained from a shared starting model and distilled back into the SFT model. The deployed model is an MoE with 80B total and 3B active parameters. Section 4.2.5 documents consolidation but does not specify the distillation loss, teacher weights, or whether rollouts are on-policy; those details should not be inferred. See the technical report, §§1 and 4.2.5.

MiMo-V2-Flash (2026). This 309B-total/15B-active MoE uses Multi-Teacher On-Policy Distillation (MOPD). A teacher is selected by prompt domain; the student generates the trajectories. Its token-level signal is based on

\[ \log q_{d(x)}(y_t\mid h_t)-\log p_\theta(y_t\mid h_t), \]

corresponding to reverse-KL distillation. The training surrogate combines this signal with outcome-reward advantages and corrects training/inference policy mismatch. Thus MOPD here means domain-specialist supervision on student rollouts, not averaging every teacher on every token. See the technical report, §4.4.

How this combines with MoE

Concept What is selected or transferred? Where it operates
Multi-teacher supervision A full teacher model or a mixture of teacher targets Training supervision
Sparse MoE routing Internal expert subnetworks for each token Forward passes during training and inference
Distillation into one deployed model Behaviors from teachers transferred into student parameters Removes the need to serve the teacher ensemble

A domain teacher is a complete model; it is not necessarily one internal MoE expert. Distilling several teachers into an MoE student does not imply a one-to-one mapping between teachers and expert subnetworks. The student can retain internal MoE routing while deployment uses only that single model.

MoE also introduces a concrete on-policy training concern: MiMo reports replaying the expert routes recorded during rollout to reduce routing mismatch between inference and training. See MiMo-V2-Flash, §4.6.1. Conversely, an MoE teacher can supervise a dense student: DeepSeek-R1 distills into dense Qwen and Llama models through curated outputs, without copying its internal routing. See DeepSeek-R1, §2.4.

For an experiment, compare each single teacher with the multi-teacher setup under a matched student-training budget, and report results by domain as well as in aggregate. This is a suggested evaluation design: the reports establish working systems, not that every additional teacher or MoE architecture improves distillation.

Choosing the Distillation Objective

Constraint or goal Natural starting point
same label/token space and teacher logits available temperature-scaled forward KL
generation errors compound on student prefixes on-policy state collection
only teacher API outputs available sequence distillation
output vocabularies differ sequence-, feature-, or representation-level transfer
internal geometry matters feature or relational matching
teacher has multiple useful modes prefer covering objectives and audit diversity
deployment behavior matters more than token agreement trajectory or policy distillation

Common Failure Modes

Failure First-principles diagnosis
student copies teacher errors the teacher was treated as ground truth
no gain over hard labels temperature or teacher distribution exposes little extra information
capacity gap the student cannot represent the teacher target
mode loss divergence, decoding, or synthetic data collapses alternatives
exposure bias matching occurs only on data/teacher states
unstable on-policy learning student visits states where teacher guidance or estimation is unreliable
feature conflict forced layer correspondence is inappropriate
hidden cost teacher inference or stored logits erase the intended efficiency gain

Interview Questions

  • Why is distillation a supervision mechanism rather than one loss formula?
  • Derive why forward KL and soft-label cross-entropy have the same student gradient.
  • Why is the \(\tau^2\) factor commonly used in logit distillation?
  • Separate KL direction from the distribution over prefixes or inputs.
  • Why might reverse KL improve generation while reducing diversity?
  • Compare logit, sequence, feature, relational, and policy distillation.
  • When can sequence distillation work across different tokenizers?
  • How can a self-distillation teacher avoid becoming a moving, collapsing target?

Exercises

Primary References