Math Fundamentals · lesson 12/15
KL Divergence
KL divergence measures how much extra cost you pay when you encode data from one distribution using a model of another. It is the difference between cross-entropy and entropy, it is always non-negative, and it is not symmetric — facts that explain why it shows up in VAEs, distillation, and RLHF.
The idea
For discrete distributions and :
The rewriting as a difference is the useful part for training. Since is a constant of the data, minimizing cross-entropy is exactly minimizing .
Properties to keep straight:
- Non-negative. Gibbs' inequality gives , with equality if and only if almost everywhere.
- Asymmetric. in general, so it is a divergence, not a distance. It also violates the triangle inequality.
- Support. If but , the term is infinite. A model that assigns zero probability to a possible event is penalized without bound.
- Direction matters. Minimizing is mass-covering: spreads out to avoid the infinite penalty on 's mass. Minimizing is mode-seeking: can collapse onto one mode and ignore the rest.
Worked example
Let and . In nats,
The reverse direction:
Both are positive and they differ by about nats. That gap is the asymmetry, and it is small here only because the two distributions are close. If were while kept mass on both outcomes, would diverge to infinity while stayed finite.
In code
import numpy as np
p = np.array([0.5, 0.5])
q = np.array([0.9, 0.1])
print((p * np.log(p / q)).sum()) # 0.5108 -> D_KL(p || q)
print((q * np.log(q / p)).sum()) # 0.3681 -> D_KL(q || p)Note the argument order: the second array sits inside the , so (p * log(p / q)) is . Swapping the two arrays silently optimizes the wrong objective.
Check yourself
- Why is not considered a distance?
- For which pair of distributions is the divergence zero, and what does that mean about the model?
- Explain why minimizing cross-entropy and minimizing KL divergence are the same optimization problem.
Key takeaways
- KL divergence is the extra coding cost of using when is true: .
- It is non-negative, asymmetric, and infinite when rules out an event that allows.
- Forward KL covers mass; reverse KL seeks modes; training minimizes cross-entropy, which differs from KL only by a constant.