On-Policy Distillation Explained: Loss Functions, Vocabulary Sampling, and Memory
This article explains on-policy distillation (OPD) for post-training large language models, focusing on three practical issues: choosing the correct KL direction in the loss function, matching distributions over the vocabulary space, and estimating the memory and communication costs of that matching. It also compares Sampled-Token, Top-k, and Full-Vocab strategies, discusses multi-teacher distillation, and provides formulas and checklists for capacity planning and debugging.
Introduction
The mainstream approach to post-training large models is changing. More teams are moving away from mixing SFT and RL in a single large-scale training run. Instead, they first train several expert models and then distill their capabilities into a unified model. On-Policy Distillation (OPD) is a key part of this pipeline. Its effectiveness depends on three things: whether the KL direction in the loss function is correct, whether the vocabulary-space matching method is appropriate, and whether memory and communication can support that matching. This article covers these three areas and provides formulas and checklists that can be used directly for estimation and troubleshooting.
1. The Essence of OPD: Loss Functions and KL Direction
First, define the notation. Let the teacher’s next-token distribution over a given prefix be pT, the student’s distribution be p_S, x be the prompt, and y<t be the generated prefix. OPD data comes from sequences generated by the student’s current policy, which is the same as in RL. The loss matches the divergence between two distributions over the vocabulary, which is similar to SFT. Therefore, OPD can be described as RL in terms of data source and distribution matching in terms of loss computation.
In practice, both KL directions appear.
Forward KL: KL(p_T ‖ p_S) = Σ_v p_T(v) · log(p_T(v) / p_S(v)). The expectation is weighted by the teacher distribution. If the teacher assigns high probability to a token but the student assigns low probability, the loss becomes large, so the student must cover all high-probability regions of the teacher. This property is called mean-seeking, and the student may produce an averaged distribution between two modes.
Reverse KL: KL(p_S ‖ p_T) = Σ_v p_S(v) · log(p_S(v) / p_T(v)). The expectation is weighted by the student distribution. If the student assigns probability to tokens that the teacher considers very unlikely, it is heavily penalized, so the student shrinks toward the teacher’s high-probability regions. This property is called mode-seeking. Its benefit is that it suppresses sampling of absurd tokens and makes outputs more conservative; its risk is that the student may lose secondary modes of the teacher and produce less diverse outputs. In contexts where the teacher itself is uncertain, Reverse KL may also make the student overly confident.
One confusing formulation is worth noting. Some materials write the loss as -Σ p_T(y) · log(p_S(y) / p_T(y)), which is actually equal to Σ p_T(y) · log(p_T(y) / p_S(y)), i.e., Forward KL. If an article writes this formula and calls it mode-seeking, the two descriptions contradict each other. In implementation, first decide which KL to use, then derive the gradient accordingly; do not rely only on the appearance of the formula.
A common Reverse KL implementation computes the sum above at each time step on sequences sampled by the student, and backpropagates gradients only through p_S. Teacher parameters are frozen and do not require gradients.
2. Differences from Earlier Distillation Methods and Multi-Teacher Distillation
Around 2023, GKD and MiniLLM had already explored distillation based on student-generated sequences. GKD mixed student-generated sequences with standard data during training and used a generalized JSD divergence. MiniLLM adopted reverse KL and optimized a sequence-level objective with policy gradients. Their common idea was to make the training distribution closer to the student’s inference-time distribution, thereby reducing exposure bias.
The change in modern OPD is mainly one of engineering organization. A common approach is to train expert models by domain, such as math, code, tool calling, and instruction following, with each expert undergoing SFT and RL. Then, in the distillation stage, these experts are used as teachers to train a unified student. This avoids gradient conflicts in multi-domain mixed RL and makes it easier to evaluate each expert separately.
There are three main ways to implement multi-teacher distillation.
- Routing-based: Each prompt corresponds to only one domain teacher, and the KL for that teacher is computed. This is simple to implement and suitable for data with clear domain boundaries.
- Weighted-sum: For each sample, compute the KL for multiple teachers and add them with weights. The weights can be fixed or adjusted dynamically based on validation performance in each domain.
- Conflict-handling: When different teachers give clearly different distributions for the same context, normalize or clip first to prevent one teacher’s large loss from dominating the overall gradient.
Regarding efficiency, some technical reports mention that OPD can achieve gains close to large-scale RL with less compute. However, such numbers depend on model size, task composition, training steps, and comparison methodology. This article does not cite unverified values; readers should check the settings in the original reports when evaluating such claims.
3. Vocabulary Sampling Strategies: Sampled-Token, Top-k, and Full-Vocab
How to match distributions over the vocabulary space is a key decision in OPD implementation. The table below compares three strategies.
| Strategy | Computation scope | Memory and communication | Dark knowledge retention | Suitable scenarios | Main risks |
|---|---|---|---|---|---|
| Sampled-Token | Only tokens sampled by the student | Lowest | Very little | Prototyping, resource-constrained settings | High gradient variance, sparse learning signal |
| Top-k | The k tokens with highest probability | Grows with k, far below full vocabulary | Medium | Trade-off between cost and distribution information | Whether to renormalize after truncation changes the distribution; tail information is lost |
| Full-Vocab | Entire vocabulary | Highest, requires full logits | High, best long-tail alignment | Training that requires precise distribution matching | High peak memory, usually requires vocabulary parallelism |
The Sampled-Token method computes loss only on tokens sampled by the student. It does not require a full-vocabulary softmax, so memory access and communication pressure are low. However, it discards the teacher’s information about rejecting other candidate tokens, often called dark knowledge. When student sampling noise is high, gradient variance also increases.
The Top-k method keeps the k tokens with the highest teacher probability. It retains more distribution information, and computation grows linearly with k. During implementation, it is important to specify whether the truncated distribution is renormalized. If it is not normalized, the two distributions have different total mass, and the KL value loses strict meaning. Tail-token information is still lost, so the choice of k needs to be confirmed experimentally.
The Full-Vocab method computes both distributions over the entire vocabulary and aligns them with KL. It has the highest cost but preserves the teacher’s judgments about long-tail tokens. When different experts have subtle differences in distribution for the same context, Full-Vocab can pass those differences fully to the student. Note that vocabulary sizes in common models are roughly in the range of tens of thousands to over one hundred thousand, depending on the model.
4. Memory Estimation and Optimization
The main cost of Full-Vocab comes from logits. The logits activation size for a single model can be estimated as:
logits bytes ≈ batch_size × seq_len × vocab_size × bytes per element
For example, with batch_size = 4, seq_len = 8192, vocab_size = 150000, and bf16 (2 bytes per element):
4 × 8192 × 150000 × 2 ≈ 9.8 × 10⁹ bytes, about 9.8 GB.
With fp32, this is about 19.7 GB. Teacher and student each produce one set of logits, totaling about 19.7 GB in bf16. Softmax intermediates and backpropagation gradients also take extra space, so the actual peak is usually higher than this number.
With tensor parallelism, the vocabulary dimension is split across TP ranks. Taking TP = 8, the logits per GPU are about 9.8 / 8 ≈ 1.23 GB (bf16, single model). This shows that vocabulary splitting can effectively reduce per-GPU peak memory, but the all-reduce required for softmax normalization introduces communication overhead; the longer the sequence, the larger the communication volume.
In addition to logits, peak memory also includes the following parts.
- Model weights: teacher and student parameters. The teacher is frozen but still occupies memory.
- Student optimizer states: under mixed precision, fp32 master weights plus Adam first- and second-order moments are typically estimated at about 12 bytes per parameter.
- KV Cache: the KV cache size for each model is approximately 2 × layers × KV heads × head dim × seq_len × batch_size × bytes per element. The two models compute their own caches separately; one does not replace the other.
- Activations: intermediate-layer activations. Gradient checkpointing can trade memory for recomputation time.
On KV cache sharing. There is a claim that teacher and student process the same input, so they can share a KV cache. This premise usually does not hold. The two models have different weights, so the K and V tensors at each layer are generally different. Only when the architecture, tokenizer, and sequence positions are identical, and the corresponding layers match exactly, might this condition hold; in most practical OPD setups, teacher and student KV caches cannot be shared.
