← notes Training systems

Multi-teacher on-policy distillation

How one student model learns from several specialist teachers on its own samples: why on-policy, the per-token loss and its estimators, what changes with more than one teacher, and how to keep the teacher GPUs busy.

12 min read 3 interactive

Read more M3OPD-Reasoner (arXiv) ↗

One deployment, several specialists

Suppose you have a base model and you want it to be good at several things: maths, charts, code, long video. For each skill you can make a specialist, usually by supervised fine-tuning (SFT) and/or reinforcement learning (RL) on that domain. Now you have several models and one deployment slot. The task of MOPD is to fold the specialists into one student.

There are four common ways to do it.

  • Mixed SFT, or off-policy distillation. Fine-tune the student on the union of the teachers’ outputs. It is simple and cheap. The student sees the teachers’ text, not its own, so it learns to copy outputs and not behaviour.
  • Mixed-domain RL. Run RL on all domains at once. It is one run, but the domains can pull the weights in different directions, and each answer gives one sparse reward.
  • Weight merging. Average or combine the specialists’ weight changes. There is no training, but it works best when the teachers share an origin, and the result can lose what each did well.
  • On-policy distillation. The student samples an answer, and a teacher scores each token of that answer. The student moves towards what the teacher would have said at the states the student reached.

The rest of the note is about the last option with more than one teacher. The first two are the usual baselines to compare it with.

Why on-policy

An SFT student is trained on prefixes that the teacher wrote. At test time it must continue from prefixes that it wrote itself. A small error puts it in a state that the training data never showed, the next error is more likely, and errors compound. This is the exposure-bias problem.

On-policy distillation changes the data source. The student writes the prefix, so the training states are the states it will meet at test time. The teacher then says what it would do at each of those states. The student gets feedback on its own mistakes, not on a teacher’s fluent text that it would never write.

The second property is density. In RL a whole answer gets one reward. In on-policy distillation every token gets a signal from the teacher. This is much more information per sample, which is one reason the method is sample-efficient. The cost is that the teacher must score every sample.

The objective

Write pp for the student and qq for the teacher, both as next-token distributions. For a student sample yy the per-token loss on the student’s own prefixes is the reverse KL

KL(p ∥ q)  =  Ey∼p[log⁡p(y)−log⁡q(y)].\mathrm{KL}(p\,\|\,q)\;=\;\mathbb{E}_{y\sim p}\big[\log p(y)-\log q(y)\big].

Its gradient is a policy gradient with a dense per-token reward

rt  =  log⁡q(yt∣st)  −  log⁡p(yt∣st),r_t \;=\; \log q(y_t\mid s_t)\;-\;\log p(y_t\mid s_t),

where sts_t is the prefix and yty_t is the token the student sampled. The reward is high when the teacher finds the token more likely than the student does. The mean of rtr_t over the student’s samples is −KL(p ∥ q)-\mathrm{KL}(p\,\|\,q). So you can implement the method as a policy-gradient step in which the advantage at each token is rtr_t, with no value function and no outcome reward. (The exact gradient sums the rewards of the later tokens too; most implementations use only the reward of the token itself.)

The direction of the KL matters. Forward KL, KL(q ∥ p)\mathrm{KL}(q\,\|\,p), is mode-covering: the student must put mass wherever the teacher does, so a one-mode student spreads over several modes. Reverse KL is mode-seeking: the student is punished for mass where the teacher has none, so it commits to a mode. For a language model this is usually what you want. The student should write one good answer, not an average of several.

playground

Forward versus reverse KL

Move the separation slider, switch the objective, and switch the side the student starts on.

Objective
Student starts near
teacher q (two modes) student p (one Gaussian)
student mean
student std
student mass on the teacher's modes

Toy example: a teacher with two equal modes and a student with one Gaussian, fitted by a local search. Reverse KL picks one mode (the start side decides which); forward KL spreads over both and covers the gap. With a small separation the two agree.

A note on names. The sequence-level reverse KL splits into one reverse KL per position, taken on prefixes that the student wrote. Inside one position you may still compute the loss in either direction, or over only part of the vocabulary. The next section shows the variants. The words “on-policy” refer to where the prefixes come from, and “forward” or “reverse” refer to the direction of the KL at one position.

Estimators and their cost

At one position the teacher must return something. There are three common choices.

Full vocabulary. The teacher returns its whole distribution qq. The loss is exact and has no sampling noise. It costs one vector of vocabulary size for every token of every sample, which is heavy in memory and in network bandwidth.

Top-k with a tail correction. The teacher returns its kk most likely tokens and their log-probabilities. The student’s loss over that set is

∑i∈top-k  qi (log⁡qi−log⁡pi)  −  qi  +  pi.\sum_{i\in \text{top-}k}\; q_i\,(\log q_i-\log p_i)\;-\;q_i\;+\;p_i .

The first part is the log-gap, weighted by how much the teacher cares about the token. The terms −qi+pi-q_i+p_i are the tail correction. The top-kk set holds nearly all of the teacher’s mass but not all of it. These terms keep the loss tied to how much mass the student puts inside the set. Over the full vocabulary they cancel, because both pp and qq sum to 1. Note that the weight on each term is qq, so inside one position this is KL(q ∥ p)\mathrm{KL}(q\,\|\,p) restricted to the top-kk tokens. It is the same on-policy idea with a different direction inside the position, and it is a design choice. Clamping the loss per token keeps rare large gaps from dominating a batch.

Sampled-token k1. The student samples a token yy and the teacher returns only log⁡q(y)\log q(y). The signal is log⁡q(y)−log⁡p(y)\log q(y)-\log p(y), used as an advantage in a policy-gradient step, usually with an importance mask for off-policy lag. Its mean over the student’s samples is −KL(p ∥ q)-\mathrm{KL}(p\,\|\,q), the reverse direction. It needs one number per token, so it is the cheapest in bandwidth. It is also the noisiest: each position gives one sample of the log-ratio.

The tradeoff is variance against memory and bandwidth. In all three cases the teacher does the same compute: one forward pass over the sequence, called a prefill. It reads the student’s tokens and returns log-probabilities at every position, so it does no decoding.

playground

Dense versus sampled signal at one position

Raise the student noise. Move top-k from 1 to 20. Watch how the three loss values and the k1 spread change.

teacher q student p
teacher mass in top-k
top-k loss (with −q + p)
top-k, without −q + p
full sum over all tokens
k1 signal: mean of 64 samples
k1 signal: spread of one sample

Toy numbers: 20 tokens, a fixed teacher, a random student. At k = 20 the −q + p terms cancel and the top-k loss equals the full sum. At small k the loss sees only the head of the teacher. The k1 signal needs only one token, but one sample is noisy and its mean needs many.

What changes with several teachers

With one teacher the recipe is a loss and a sampler. With several, a few new things appear.

Routing. Each prompt carries a domain label, and the student’s answer is scored by the teacher of that domain. The student sees a mixed batch. Each token gets a signal from one teacher.

A shared tokenizer. Every teacher must use the same tokenizer and, for multimodal models, the same processor as the student. A teacher from another family would score token ids that mean something else to it, and the log-ratio would be meaningless. In practice the teachers and the student start from the same base model.

Loss scale per domain. Teachers differ in entropy. A sharp teacher gives large log-ratios, and a diffuse one gives small ones. A single loss weight then lets the sharp domain dominate the update. A per-domain scale, for example from the measured spread of the log-ratio, is one fix.

Interference or specialisation. Distilling from several teachers can reduce the interference that mixed RL has, because each token is pulled towards one teacher. It can also fail the other way: when two teachers disagree on a shared skill, the student may take a poor compromise. Check this per domain, not only on average.

The ceiling. Under pure imitation the student is capped by its teachers. The loss is minimised when the student equals the teacher, so it cannot pass it. Two common options are to add a task-reward term next to the distillation term, and to use a one-sided gate that applies the teacher signal only where it helps and lets the student go beyond the teacher elsewhere.

Teachers off their own distribution. The teacher was trained on its own data and samples. The student’s prefixes are different: they may contain odd phrasing or early mistakes. The teacher’s log-probabilities on those states can be poorly calibrated. This is a quiet source of noise, and it is larger when the student is far from the teacher.

Systems: keeping the teachers busy

A step has three parts: rollout (the student writes answers), teacher scoring, and the training update. Scoring is a prefill, and it can start as soon as a sequence ends. So the teacher servers run next to the rollout, and the scores stream in while the other sequences are still being written. After the last score the trainer takes the batch.

This layout can leave teacher GPUs idle. Four causes are common:

  1. The rollout pauses while the trainer runs, so no new work reaches the teachers.
  2. The last long sequences of a step keep only a few teacher replicas busy.
  3. The GPUs are split between teachers in a fixed way, and the token load per domain differs.
  4. A prefill is cheaper than decoding, so a teacher pool sized to the rollout can be under-loaded overall.

The cheapest fix for the third cause is to measure the token load of each domain and assign teacher GPUs in proportion. The widget below shows the effect.

animation

Eight teacher GPUs in one step

Change the split, then the video share. Press Play to sweep the step.

Teacher GPU split (math / charts / video)
math charts video
step time (toy units)
idle: math GPUs
idle: charts GPUs
idle: video GPUs
idle: all 8 teacher GPUs

Toy simulation: 96 sequences, 16 decode replicas, made-up lengths per domain. Only the shape matters: a fixed split that does not match the load keeps one domain busy while the others wait. Try “by load”.

Other options are to let the rollout run one step ahead of the trainer, which removes cause 1 at the price of slightly stale samples, to host several teachers on every teacher GPU if memory allows, and to colocate teachers with the rollout GPUs at the price of serial phases. Measure first: the busy share of each teacher, the queue wait, and the rollout tail time.

Pitfalls

  • Tokenizer or template mismatch. The teacher must see the exact token ids and the same chat template as the student. A different template changes the log-probabilities without any error message.
  • Truncated responses. A sequence cut at the length limit has no real end. Scoring the cut end as if it were an answer teaches the student to stop in the wrong place. Mask them or handle them on purpose.
  • Teacher off-distribution. See above. Compare teacher scores on its own samples and on the student’s samples. A large drop is a warning.
  • KL is not reward. A falling KL means the student looks more like the teacher. It does not mean the student answers better. Track task metrics too.
  • Loss clamping. A per-token clamp stops outliers but hides them. Log how often it triggers.

Further reading