Kullback-Leibler divergence, also called KL divergence or relative entropy, is a measure of how much a probability distribution Q differs from a reference distribution P, expressed as the expected extra information needed to encode samples from P with a code optimized for Q. In probabilistic models and across artificial intelligence, it is the standard way to quantify the gap between a model and the truth or between an approximation and an exact posterior.
Introduced by Solomon Kullback and Richard Leibler in 1951, the quantity sits at the center of maximum likelihood estimation, variational inference, information theory and the training of many generative models. It is always non-negative and equals zero only when the two distributions are identical, but it is not symmetric and therefore not a true distance.
How KL divergence is defined and computed
For discrete distributions, KL divergence is KL(P || Q) = sum over x of P(x) log(P(x) / Q(x)). For continuous densities, the sum becomes an integral. The expression is the expectation under P of the log-ratio between the two distributions, so outcomes that P considers likely dominate the result.
The value also equals cross-entropy minus entropy: KL(P || Q) = H(P, Q) - H(P). This identity explains its role in training. Because the entropy of the data distribution is fixed, minimizing cross-entropy loss in a classifier or language model is equivalent to minimizing KL divergence from the data to the model.
The following table summarizes the core properties that practitioners rely on.
| Property | Statement | Practical consequence |
|---|---|---|
| Non-negativity | KL is always at least zero | Follows from Gibbs inequality |
| Identity | Zero only if P equals Q almost everywhere | Useful as a convergence target |
| Asymmetry | KL(P || Q) differs from KL(Q || P) | Direction must be chosen deliberately |
| Unboundedness | Infinite if Q is zero where P is positive | Requires support coverage or smoothing |
| Units | Bits with log base 2, nats with natural log | Report the base with every value |
| Chain rule | Decomposes over joint distributions | Simplifies factorized models |
Forward and reverse KL in model fitting
The direction of KL divergence changes what an approximation learns. Forward KL, KL(P || Q), penalizes Q heavily wherever P has mass that Q misses, so it produces mass-covering approximations that spread out to include every mode. Reverse KL, KL(Q || P), penalizes Q for placing mass where P has little, so it produces mode-seeking approximations that lock onto one peak.
| Aspect | Forward KL (P || Q) | Reverse KL (Q || P) |
|---|---|---|
| Behavior on multimodal targets | Covers all modes, may blur them | Selects one mode, ignores others |
| Variance of fitted Q | Tends to overestimate | Tends to underestimate |
| Requires samples from | The target P | The approximation Q |
| Typical method | Maximum likelihood, expectation propagation | Variational inference |
| Main risk | Mass in implausible regions | Overconfident uncertainty |
Maximum likelihood estimation minimizes forward KL from the empirical data distribution to the model. Variational inference minimizes reverse KL from the approximate posterior to the true posterior, because expectations under the tractable Q are easy to estimate. This choice is why mean-field variational posteriors are known to underestimate posterior variance.
Where KL divergence appears in machine learning
KL divergence is a building block in many objectives, often hidden inside a larger formula. Recognizing it clarifies what a method is actually optimizing.
| Method | Role of KL divergence | Effect |
|---|---|---|
| Evidence lower bound | Gap between ELBO and log evidence | Maximizing ELBO tightens the posterior fit |
| Variational autoencoder | Regularizer between encoder and prior | Keeps the latent space smooth |
| Knowledge distillation | Matches student to teacher outputs | Transfers soft predictions |
| RLHF fine-tuning | Penalty against the reference model | Limits drift and reward hacking |
| Trust region policy optimization | Constraint on policy updates | Stabilizes reinforcement learning |
| t-SNE | Objective between neighbor distributions | Preserves local structure in embeddings |
In the evidence lower bound, log evidence equals the ELBO plus KL(q(z) || p(z | x)). Since the KL term is non-negative, the ELBO is a lower bound, and raising the ELBO directly reduces the divergence from the true posterior. In language model alignment, a KL penalty coefficient typically between 0.01 and 0.2 keeps the fine-tuned policy close to its starting point, although the best value depends on the reward scale.
Comparison with related divergences
KL divergence belongs to the broader family of f-divergences and is one of several ways to compare distributions. Alternatives are chosen when asymmetry, infinite values or non-overlapping supports cause problems.
| Measure | Symmetric | Bounded | Handles disjoint supports |
|---|---|---|---|
| KL divergence | No | No | No, becomes infinite |
| Jensen-Shannon divergence | Yes | Yes, at most log 2 | Yes, but gradients vanish |
| Total variation distance | Yes | Yes, at most 1 | Yes |
| Wasserstein distance | Yes | Depends on space | Yes, with useful gradients |
| Hellinger distance | Yes | Yes, at most 1 | Yes |
Estimation pitfalls and common mistakes
Closed forms exist for pairs such as two Gaussians, but most practical cases require Monte Carlo estimation from samples, which brings variance and bias. Several mistakes recur in applied work.
- Treating KL as a distance. Without symmetry or the triangle inequality, KL values cannot be compared like geometric distances.
- Ignoring zero probabilities. A single outcome with Q equal to zero makes the divergence infinite, so histograms and counts need smoothing or a small epsilon.
- Mixing log bases. Values in nats are about 0.693 times the value in bits, and unreported units make results incomparable.
- Swapping arguments in code. Library functions differ in argument order, and a silent swap changes the optimized behavior.
- Over-trusting high-dimensional estimates. Nearest-neighbor and density-based estimators become unreliable in high dimensions without large samples.
In everyday language
KL divergence measures how surprised you will be when you expect one pattern but reality follows another. Imagine you pack for a trip expecting sunshine. If it rains every day, your guess was far off. KL divergence puts a number on that mismatch.
A value of zero means your guess matched reality exactly. Larger numbers mean a worse match. The measure is one-sided. Being wrong about the real weather costs more than being wrong about weather that rarely happens.
Seen in the real world
A team training a language model to follow instructions uses reinforcement learning from human feedback. A reward model scores answers, and the policy is updated to earn higher scores. Without a limit, the policy soon exploits weaknesses in the reward model, producing long, repetitive answers that score well but read poorly.
The team adds a KL penalty against the original model, starting at a coefficient of 0.05, and logs the average divergence per token during training. When the measured KL rises above roughly 10 nats per response, reviewers see quality drop, so the team raises the coefficient.
The final model gains on the reward score while staying close to the original writing style. Monitoring KL divergence gave the team a single, interpretable drift signal that warned of reward hacking before human evaluation did.