Skip to content

Distillation with forward and reverse KL

ModuleL12.4 · optional build · Python · Pass 10 · 2 to 3 h
You buildtinyllm/post/distill.py: forward and reverse KL objectives
Contractdistill.pyi
Testscourse/tests/L12.4/ (why: hand distributions, divergence direction, and on-policy samples)
NeedsM11.1 entropy and KL
Used byC2 alternative training recipe
MilestoneMS-C2
Optional depthOn-policy sequence-level distillation
  • Forward KL penalizes teacher-supported modes the student misses.
  • Reverse KL emphasizes modes the student already selects.
  • Temperature changes both target entropy and gradient scale.
  • On-policy distillation evaluates the teacher on student-generated prefixes.
Terminal window
ol start L12.4
ol tests L12.4
ol check L12.4

The agent deployment can use a smaller student if it preserves useful behavior from a larger teacher. Token-level distillation gives a measurable alternative to preference-based training.

For teacher distribution p and student distribution q, forward KL is D_KL(p||q)=Σ p_i log(p_i/q_i). Reverse KL is D_KL(q||p)=Σ q_i log(q_i/p_i). Both are nonnegative and zero when the distributions agree. At temperature T, softmax uses logits divided by T; the common T² multiplier compensates for gradient scaling when training.

SymbolMeaning
pteacher probabilities
qstudent probabilities
Tdistillation temperature

For p=[0.8,0.2] and q=[0.5,0.5], forward KL is 0.8 log(1.6)+0.2 log(0.4) ≈ 0.193. Reverse KL is 0.5 log(0.625)+0.5 log(2.5) ≈ 0.223. Tests fix these values and verify both directions become zero for equal distributions.

Implement stable log-softmax based KL and temperature handling. test_hand_forward_kl checks the worked distributions, test_reverse_kl_modes distinguishes divergence direction, and test_on_policy_sampling exercises extreme logits.

TestWhy it existsExpected result
test_hand_forward_klPins forward KL arithmeticMatches the worked distribution value
test_reverse_kl_modesMakes divergence direction explicitReverse KL differs from forward KL on the fixture
test_on_policy_samplingChecks teacher queries on student prefixesTeacher logits align to sampled prefixes
PitfallCaught by
Swap teacher and student in forward KLtest_hand_forward_kl; mutant s01
Use the student distribution as reverse-KL weightstest_reverse_kl_modes; mutant s02
DirectionModuleHow it uses this
BackM11.1Defines the forward and reverse KL measures.
ForwardC2May use distillation instead of DPO or GRPO, evaluates on the same held-out suite, and records teacher identity.
Your pieceProduction equivalentWhat it addsWhere to look
token-level KLon-policy sequence distillationTransfers behavior on student-generated prefixesHugging Face TRL distillation recipes
temperature scalingteacher/student calibrationChanges target entropy and gradient magnitudeHinton et al., Distilling the Knowledge in a Neural Network