Chapter 14
Distillation, KL Divergence, and Model Sizing
On this page
- Define the transfer contract
- Cross entropy and KL
- Temperature
- Engineer the teacher data path
- Why combine soft and hard targets
- Sequence and feature distillation
- Draft-model distillation
- Model-size tradeoff
- Evaluate transfer, not resemblance alone
- Anti-distillation and extraction resistance
- Design Exercises
Distillation trains a student from teacher probabilities, generated sequences, or intermediate representations. The target determines the loss, storage cost, and information the student receives.
The teacher supplies soft targets. The diagram uses a for the mixing weight alpha in the code; CE uses hard labels and KL compares teacher with student at temperature T.
Define the transfer contract¶
Distillation can transfer several different objects: token probabilities, selected sequences, rankings, hidden representations, tool trajectories, or verified outcomes. These targets are not interchangeable. Token probabilities preserve local uncertainty but are expensive to store. Generated sequences are compact but collapse the teacher distribution to sampled paths. Feature targets require compatible internal shapes and introduce a layer-mapping problem.
Fix the teacher checkpoint and decoding policy, the prompts it labels, and the student's capacity limit. Decide whether targets are stored or recomputed; dense teacher logits can dominate the data pipeline.
A student should not be optimized to imitate teacher behavior that the product does not want. Verified labels, safety policy, and human adjudication can override the teacher where it is unreliable.
Cross entropy and KL¶
Let teacher distribution be p(y|x) and student distribution be q(y|x). Cross entropy from teacher to student is:
Teacher cross entropy weights student error by probability under the teacher.
It decomposes as H(p) + KL(p || q). The teacher entropy does not depend on student parameters, so minimizing teacher cross entropy is equivalent to minimizing forward KL.
Forward KL penalizes missing probability mass where the teacher assigns support.
Forward KL heavily penalizes the student for assigning too little probability where the teacher has mass. It is often described as mode covering. Reverse KL, KL(q || p), weights regions under the student and tends to concentrate on one teacher mode when representing all modes is expensive.
These slogans are helpful but incomplete. Token distributions are conditional, the student is parameterized, the support is finite after softmax, and sequence-level behavior compounds local choices. Always connect the divergence to the actual objective and sampling process.
Temperature¶
With temperature T, logits z become:
Temperature reveals or suppresses probability structure among non-argmax tokens.
Higher temperature softens the distribution and exposes relationships among non-argmax tokens. Lower temperature sharpens it. In classic distillation, multiplying the KL term by T^2 compensates for the approximate inverse-square gradient scaling in the high-temperature regime. It does not make the objective or all finite-temperature gradients invariant to temperature.
Example status: Optional PyTorch example; standalone function, tested in the tensor environment.
from torch.nn.functional import softmax, log_softmax, kl_div, cross_entropy
def distillation_loss(student_logits, teacher_logits, labels, T=2.0, alpha=0.7):
# Inputs are already shifted and masked to [N,V] and [N].
if T <= 0 or not 0 <= alpha <= 1 or student_logits.shape[0] == 0:
raise ValueError("invalid temperature, mixing weight, or target count")
teacher = softmax(teacher_logits.detach() / T, dim=-1)
student_logp = log_softmax(student_logits / T, dim=-1)
soft = kl_div(student_logp, teacher, reduction="batchmean") * (T * T)
hard = cross_entropy(student_logits, labels)
return alpha * soft + (1.0 - alpha) * hard
The excerpt assumes next-token alignment and masking have already selected valid tokens. With [N,V] logits, batchmean divides the KL sum by the same valid-token count used by hard cross entropy. Applying it directly to [B,S,V] would divide by B instead and change the loss balance with sequence length; see PyTorch's KL reduction contract. A production version also handles sharded vocabulary, controls teacher precision, and avoids storing full teacher logits when bandwidth dominates.
Engineer the teacher data path¶
Full-vocabulary logits can exceed the storage cost of the original training examples by orders of magnitude. A data path must choose among online teacher inference, offline dense logits, top-k logits plus residual mass, quantized scores, or sampled sequences.
Online inference avoids a static logit corpus and can follow student-relevant prompts, but it couples training throughput to teacher capacity and version availability. Offline targets make runs reproducible but can become stale and create heavy object-store traffic. Top-k storage is effective when most useful probability mass is concentrated, provided the omitted tail is represented consistently rather than silently renormalized into a different target.
Preserving the tail's total mass still discards its internal distribution. For teacher probabilities [0.6,0.3,0.1] and student probabilities [0.6,0.1,0.3], full forward KL is 0.2*log(3), about 0.220 nats. If only the first token is stored and the remaining tokens become one tail event, both distributions are [0.6,0.4] and the coarsened KL is zero. That objective cannot see how probability is divided inside the tail. Specify whether a sparse target is a coarsened loss, a reconstructed approximation, or a sampled estimator of the full loss; they are different training signals.
Version every teacher artifact with teacher checkpoint, tokenizer, prompt template, decoding or temperature configuration, precision, and generation code. If the student and teacher tokenize differently, sequence alignment and probability transfer require an explicit mapping; matching strings does not imply matching token events.
Why combine soft and hard targets¶
Soft targets transfer relative preference among tokens. Hard labels preserve ground truth or verified behavior when the teacher is wrong. The balance depends on teacher reliability, student capacity, domain shift, and whether labels represent a unique answer.
For generated sequence data, a hard next-token label from a teacher sample discards uncertainty. Offline logits preserve more information but are enormous. Alternatives include top-k logit storage, quantized logits, on-policy teacher queries, sequence-level ranking, hidden-state targets, or verifier-selected trajectories.
Sequence and feature distillation¶
Sequence distillation trains on teacher-generated outputs. It can simplify the target distribution and transfer style or reasoning patterns, but it inherits teacher errors and may reduce diversity. Feature distillation aligns hidden representations or attention maps, which can help when architectures are compatible. Layer mapping, scale, and representational non-identifiability complicate it.
Online distillation queries the teacher on student-relevant states, reducing mismatch between a fixed corpus and the student's current failure modes. It costs teacher inference and creates a moving data distribution.
Draft-model distillation¶
A speculative draft is evaluated jointly with the target. The most relevant objectives are acceptance rate, average accepted prefix, draft latency, target verification cost, memory footprint, and final exactness.
Train on real product prompts and target continuations. Include high-entropy positions, domain slices, long-context states, and student failure cases. Match tokenizer and vocabulary unless the system explicitly supports a mapping; otherwise verification and KV reuse become much harder.
An effective loss can combine hard target tokens, forward KL on target logits, and emphasis on positions that control rejection. Evaluate under the actual sampling policy. A draft that agrees under greedy decoding may disagree at production temperature.
Model-size tradeoff¶
A larger draft costs more per proposed token but can raise acceptance. A smaller draft is cheap but may create verification waste. Let:
C_draft(m, gamma)be draft time for model sizemandgammaproposed tokens;C_verify(gamma)be target verification time for those proposals;A(m, gamma)be expected committed output tokens per cycle, including any correction or bonus token;C_basebe one ordinary target decode step.
A simple speed model is:
The useful numerator is committed target-equivalent progress; the denominator includes draft and verification time.
The model omits queueing and overlap but identifies the decision. Benchmark a grid of draft size and proposal length using production shapes. Watch memory capacity: loading a larger draft can reduce target batch size and erase its acceptance benefit.
Evaluate transfer, not resemblance alone¶
Lower distillation loss does not prove that the student is more useful. Evaluate four layers:
- distribution agreement: KL, calibration, rank correlation, or acceptance under the relevant prompts;
- capability transfer: task success, critical slices, robustness, and failures inherited from the teacher;
- systems outcome: latency, memory, throughput, energy, and target batch capacity;
- independent evidence: verified labels or human judgment that can disagree with the teacher.
Compare against a student trained on hard labels with the same tokens and compute. Otherwise, gains attributed to soft targets may come from additional teacher-generated data or a different curriculum.
Anti-distillation and extraction resistance¶
"Anti-distillation" covers techniques that make model extraction less effective: rate limits, query anomaly detection, output perturbation, watermarking, restricted logit access, policy controls, and legal or contractual measures. There is no free defense. Perturbing outputs can harm users and may not stop a determined extractor. Detection must distinguish legitimate high-volume customers from imitation workflows.
A rigorous framing is a threat model: attacker access, budget, query adaptivity, target fidelity, and acceptable product degradation. Treat claims of protection as measured risk reduction, not impossibility.
Design Exercises¶
- Explain forward versus reverse KL using behavior and gradients, not only slogans.
- Why multiply a temperature-scaled KL term by
T^2? - Design a draft-model training corpus and evaluation.
- When can a 3B draft outperform a 1B draft end to end?
- What defenses against extraction preserve normal user quality?