KL Divergence: From Definition to LLM Training
Machine LearningModel answerLast updated
Define KL divergence, explain its asymmetry and support requirements, and walk through how it appears in language model training and alignment.
KL Divergence in Language Model Training
Information-theoretic quantities show up throughout modern ML, and KL divergence is one of the most frequently misunderstood. This question tests whether you can move from the mathematical definition all the way to practical consequences in large language model (LLM) training pipelines.
Your Task
Answer the following, in order:
-
Definition — Write out the formula for KL divergence between two distributions P and Q over the same discrete random variable. State what the quantity measures, when it equals zero, and whether it can be negative.
-
Asymmetry — KL(P ∥ Q) ≠ KL(Q ∥ P) in general. Give an intuitive explanation of the difference, and describe what each direction penalizes in practice.
-
Support mismatch — What happens when Q assigns zero probability to an event that P considers possible? What about the reverse? How does this affect which distribution you choose as the reference?
-
Token-level vs. sequence-level — In practice, KL is computed token-by-token rather than over entire sequences. Explain why, and describe any gap this introduces relative to the true objective.
-
LLM use cases — Describe at least two concrete places where KL divergence appears during LLM training or post-training fine-tuning (for example, alignment or distillation), including what the two distributions are in each case and what the KL term is meant to accomplish.
Constraints and Framing
- Both distributions are over the same vocabulary of tokens.
- KL divergence is not symmetric and is not a distance metric.
- When discussing estimation, assume the expectation is approximated with samples rather than computed exactly.
- Be precise about which distribution is the reference and which is being optimized.
Hints
Hint 1
Start from the raw formula: KL(P ∥ Q) = Σ P(x) log(P(x)/Q(x)). Ask yourself: whose expectation is this taken under, and what does that mean when Q is nearly zero somewhere?
Hint 2
For asymmetry, think about what 'mean-seeking' versus 'mode-seeking' behavior looks like when you fit a unimodal Q to a multimodal P, and vice versa. One direction forces Q to cover everything P puts mass on; the other lets Q ignore some modes.
Hint 3
In RLHF and related alignment methods, the policy being trained is one distribution and the original frozen model is another. Think about which one you want as the reference and why — then consider what would go wrong if you swapped them.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Definition and Basic Properties
KL divergence from Q to P — written KL(P ∥ Q) — measures how much extra information you need, on average, if you encode samples drawn from P using a code optimized for Q instead of P:
KL(P ∥ Q) = Σ_x P(x) log( P(x) / Q(x) )
Three facts follow directly from the definition:
- Non-negativity (Gibbs' inequality): KL(P ∥ Q) ≥ 0 for all P, Q.
- Zero condition: KL(P ∥ Q) = 0 if and only if P = Q everywhere.
- Not a metric: it is not symmetric and does not satisfy the triangle inequality.
Asymmetry and What Each Direction Penalizes
Because the expectation is taken under P, KL(P ∥ Q) heavily weights regions where P has high probability. This leads to two qualitatively different behaviors:
Forward KL — KL(P ∥ Q), minimized over Q: Q is penalized whenever P(x) > 0 and Q(x) is small. To avoid infinite loss Q must spread mass across every mode of P. The result is mean-seeking or mass-covering behavior: Q ends up broad and may assign probability to regions between modes even if P does not.
Reverse KL — KL(Q ∥ P), minimized over Q: Now the expectation is under Q. Q is penalized only where it puts mass but P does not. Q can safely ignore modes of P that it never samples — leading to mode-seeking behavior. The fitted Q latches onto one mode and ignores the rest.
This distinction matters in variational inference and distillation, where the choice of direction determines whether the approximation is conservative or selective.
Support Mismatch
If Q(x) = 0 for some x where P(x) > 0, then log(P(x)/Q(x)) = +∞ and KL(P ∥ Q) diverges. In practice this forces Q to have full support over anything P considers possible — or you must add smoothing.
The reverse is softer: if P(x) = 0, that term contributes 0 to KL(P ∥ Q) regardless of Q(x), because the weight P(x) = 0 kills it. This is why, when you are optimizing Q and you want to avoid hard constraints, placing Q in the reference position (reverse KL) is numerically safer.
Practical rule of thumb: use the distribution you control as Q, put the fixed or target distribution as P in the forward direction only when you are confident Q will have full support, otherwise use the reverse direction.
Token-Level Estimation vs. Sequence-Level Objective
The true objective in language modeling would be KL divergence over entire sequences — joint distributions over token strings of arbitrary length. That is intractable: even for a vocabulary of 50,000 and sequences of length 512, the support is astronomically large.
In practice the KL is factored autoregressively and summed token by token:
KL(P_seq ∥ Q_seq) ≈ Σ_t KL( P(·| x_{<t}) ∥ Q(·| x_{<t}) )
This is exact under the chain rule when both models share the same context. The gap arises during training with sampled contexts: if the contexts x_{<t} are drawn from the reference model's distribution rather than the policy's own rollouts, the estimate is biased. Exposure bias accumulates — the policy is never corrected for errors it makes at earlier tokens. Methods like DPO and online RLHF mitigate this by sampling from the current policy.
Where KL Divergence Appears in LLM Pipelines
1. RLHF policy regularization
During reinforcement learning from human feedback, the reward model score alone would push the policy toward degenerate outputs (reward hacking). A KL penalty is added to the objective:
maximize E[ r(x) ] − β · KL( π_θ ∥ π_ref )
Here π_θ is the current policy and π_ref is the frozen supervised fine-tuned model. The reverse KL direction keeps the policy from drifting into territory where the reference assigns near-zero probability. β controls the trade-off: too small and the model hacks the reward; too large and it barely moves from the baseline.
2. Knowledge distillation
When distilling a large teacher T into a smaller student S, the student minimizes:
KL( T(·| x) ∥ S(·| x) )
The forward KL forces the student to cover all modes of the teacher's soft distribution, transferring uncertainty rather than just argmax predictions. Temperature scaling on the teacher's logits flattens the distribution and makes the signal richer.
3. Variational fine-tuning and monitoring
Some methods treat the language model as a variational approximation to a Bayesian posterior over text. KL to a prior distribution is added as a regularizer. Separately, KL between consecutive checkpoints is used as a monitoring signal — a sudden spike often flags training instability or a distribution shift in the data.
Common Mistakes
- Swapping P and Q carelessly. The direction determines which failure mode you get. Always name which distribution is the reference before writing the formula.
- Assuming KL is a distance. It is not symmetric and cannot be used directly in nearest-neighbor or clustering algorithms without modification (e.g., Jensen-Shannon divergence, which is symmetric).
- Ignoring support mismatch in practice. Log probabilities near −∞ cause numerical instability. Always check that the reference model assigns nonzero probability to the tokens the policy generates, especially after vocabulary changes.
- Conflating token-level and sequence-level KL. Reporting per-token KL during evaluation is convenient but does not directly bound sequence-level divergence, especially for long generations.