Kullback-Leibler divergence

Also known as: KL divergence · relative entropy

On this page 7

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.

PropertyStatementPractical consequence
Non-negativityKL is always at least zeroFollows from Gibbs inequality
IdentityZero only if P equals Q almost everywhereUseful as a convergence target
AsymmetryKL(P || Q) differs from KL(Q || P)Direction must be chosen deliberately
UnboundednessInfinite if Q is zero where P is positiveRequires support coverage or smoothing
UnitsBits with log base 2, nats with natural logReport the base with every value
Chain ruleDecomposes over joint distributionsSimplifies factorized models
Key mathematical properties

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.

AspectForward KL (P || Q)Reverse KL (Q || P)
Behavior on multimodal targetsCovers all modes, may blur themSelects one mode, ignores others
Variance of fitted QTends to overestimateTends to underestimate
Requires samples fromThe target PThe approximation Q
Typical methodMaximum likelihood, expectation propagationVariational inference
Main riskMass in implausible regionsOverconfident uncertainty
Forward versus reverse KL divergence

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.

MethodRole of KL divergenceEffect
Evidence lower boundGap between ELBO and log evidenceMaximizing ELBO tightens the posterior fit
Variational autoencoderRegularizer between encoder and priorKeeps the latent space smooth
Knowledge distillationMatches student to teacher outputsTransfers soft predictions
RLHF fine-tuningPenalty against the reference modelLimits drift and reward hacking
Trust region policy optimizationConstraint on policy updatesStabilizes reinforcement learning
t-SNEObjective between neighbor distributionsPreserves local structure in embeddings
Common uses in probabilistic and deep models

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.

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.

MeasureSymmetricBoundedHandles disjoint supports
KL divergenceNoNoNo, becomes infinite
Jensen-Shannon divergenceYesYes, at most log 2Yes, but gradients vanish
Total variation distanceYesYes, at most 1Yes
Wasserstein distanceYesDepends on spaceYes, with useful gradients
Hellinger distanceYesYes, at most 1Yes
KL divergence and alternatives

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.