Lensa ML

How KL Divergence Works

Step 1 of 6: Two Distributions

Compare P and Q visually

A40%25%B30%25%C20%25%D10%25%P (true)Q (approx)
P distribution
A40%
B30%
C20%
D10%
Q distribution
A25%
B25%
C25%
D25%
Entropy of P, H(P)
1.846 bits
Entropy of Q, H(Q)
2.000 bits

Both P and Q are nearly uniform, so both sit close to the 2-bit maximum.

Drag the eight sliders to shape P (blue) and Q (orange), and click an entropy card for its term-by-term sum. The slider values are weights, normalized so each distribution sums to 100%. With the defaults, P = 40/30/20/10 has an entropy of 1.846 bits and the uniform Q has 2 bits, the maximum for four outcomes. In ML, P is usually the data distribution and Q the model. Entropy scores each distribution on its own, so it cannot say how well Q models P. That takes an outcome-by-outcome comparison, which KL divergence provides.

Step 2 of 6: The KL Formula

Information gap, term by term

KL(P‖Q) = Σ P(x) · ln( P(x)/Q(x) )
0.347A0.000B-0.077C-0.092DPer-class KL contribution: P(x)·ln(P(x)/Q(x))
P distribution
A50%
B25%
C15%
D10%
Q distribution
A25%
B25%
C25%
D25%
KL(P‖Q) = sum of terms
0.1783 nats
Term A
0.347
+ Term B
0.000
+ Term C
-0.077
+ Term D
-0.092

There is a moderate gap between P and Q. The largest bar shows where most of it comes from.

Drag the sliders and click any Term card to see its arithmetic. With the default P of 50/25/15/10 against a uniform Q, term A is 0.5 × ln 2 ≈ 0.347, term B is exactly 0 because P(B) = Q(B), and terms C and D are negative. Single terms can drop below zero, but the total never does (Gibbs' inequality); here it is 0.178 nats. Using log₂ in place of ln gives bits. If Q(x) = 0 anywhere that P(x) > 0, the divergence is infinite, which is one reason count-based models use smoothing.

Step 3 of 6: Asymmetry

KL(P‖Q) ≠ KL(Q‖P)

ABCDP (reference)Q (approx)
P distribution (reference)
A60%
B20%
C15%
D5%
Q distribution (approx)
A20%
B30%
C30%
D20%
KL(P‖Q)
0.4048
KL(Q‖P)
0.3871
|Diff|
0.0177

The two directions are nearly equal here, but that is a coincidence of these settings.

Press the swap button to switch between KL(P‖Q) and KL(Q‖P). With the defaults, P = 60/20/15/5 and Q = 20/30/30/20, the two directions come out at 0.405 and 0.387 nats. KL also fails the triangle inequality, so it is called a divergence rather than a distance. For a symmetric score, the Jensen-Shannon divergence averages the KL of each distribution to their midpoint (P + Q)/2. It is always finite, and its square root is a true metric. The original GAN objective is tied to it: with an optimal discriminator, the generator minimizes a JS divergence.

Step 4 of 6: KL = Cross-Entropy − Entropy

Breaking down the divergence

H(P,Q) = H(P) + KL(P‖Q)
cross-entropy = entropy + divergence
H(P)1.235H(P)+KLKL=0.151H(P,Q)1.386
P distribution
A45%
B30%
C15%
D10%
Q distribution
A25%
B25%
C25%
D25%
H(P)
1.235 nats
KL(P‖Q)
0.151 nats
H(P,Q)
1.386 nats

Cross-entropy is always ≥ entropy. The extra cost is exactly the KL divergence: the price of using Q in place of P.

Drag the sliders and compare the three bars, all in nats. With the default P of 45/30/15/10 and a uniform Q, H(P) = 1.235, KL = 0.151, and H(P, Q) = 1.386. That last value is ln 4, the cross-entropy of any P against a uniform Q over four outcomes. In training, P is the data distribution and stays fixed, so H(P) is a constant. Minimizing cross-entropy and minimizing KL(P‖Q) therefore give the same model. Frameworks compute cross-entropy because it needs only the model's log-probabilities on observed samples, while H(P) is unknown for real data.

Step 5 of 6: Mode-Seeking vs Mode-Covering

How the direction changes fitting behavior

Mode 1Mode 2missedmissedP (bimodal)Q (you set it)
Q center
Q spread
KL(P‖Q)
1.836 nats
Modes hit
0/2

Mode-covering: KL(P‖Q) penalizes Q for missing anywhere P has mass. Increase the spread to cover both peaks.

Drag Q center and Q spread, then press the toggle to switch direction. P is a mix of two Gaussians at −2 and +2, each with σ = 0.7, and Q is a single Gaussian, so no setting of Q matches P exactly. The direction you minimize decides the compromise. Maximum likelihood minimizes the forward KL(P‖Q), which is why likelihood-trained models tend to spread probability broadly. Variational inference minimizes the reverse KL(Q‖P), because that only needs expectations under Q. This is why variational posteriors often underestimate uncertainty.

Step 6 of 6: Cross-Entropy Loss

How classifiers learn from KL

Loss = −log(P(true class)) = −log(0.188) = 1.669
cross-entropy loss = how surprised the model is by the correct answer
118.8%Cat ✓071.5%Dog09.7%BirdTrue labelModel prediction
True class
Model confidence (logits)
Cat18.8%
Dog71.5%
Bird9.7%
Cross-entropy loss
1.669
P(Cat)
18.8%

The model gives Cat less than 40%, so other classes hold most of the probability. The loss is high and the gradient update would be strong.

Click Cat, Dog or Bird to set the true class, then drag the logit sliders. The logits pass through a softmax (divided by 15 here), and the target is a one-hot vector. A one-hot P has zero entropy, so cross-entropy, KL(P‖Q) and −ln Q(true class) are the same number. With the defaults and Cat as the true class, Q(Cat) is about 18.8% and the loss is 1.669 nats. Label smoothing uses a target such as 0.9 / 0.05 / 0.05, so H(P) is no longer 0 and logits are discouraged from growing without limit.

What is KL divergence?

KL divergence (Kullback-Leibler divergence) measures how much a probability distribution Q differs from a reference distribution P. It is defined as KL(P‖Q) = Σ P(x) log(P(x)/Q(x)), the expected extra information needed to encode samples from P with a code built for Q. It is zero exactly when P and Q are identical and positive otherwise, and it is not symmetric.

KL divergence appears all over machine learning. Training a classifier with cross-entropy loss minimizes the KL divergence from the label distribution to the model's predictions. VAEs add a KL term that keeps the encoder's latent distribution close to a prior, knowledge distillation trains a small model to match a large model's output distribution, and RLHF penalizes a fine-tuned language model for drifting too far, in KL, from its reference model.

Key ideas

  • KL(P‖Q) = Σ P(x) log(P(x)/Q(x)) is the expected log ratio of P to Q under P.
  • KL divergence is never negative, and it is zero only when P = Q.
  • KL(P‖Q) and KL(Q‖P) usually differ, so KL is not a distance metric.
  • Cross-entropy equals entropy plus KL divergence: H(P, Q) = H(P) + KL(P‖Q).
  • Forward KL(P‖Q) is mode-covering, and reverse KL(Q‖P) is mode-seeking.
  • With one-hot labels, cross-entropy loss and KL divergence are the same number.

Common questions

Who introduced KL divergence?

Solomon Kullback and Richard Leibler defined it in their 1951 paper "On Information and Sufficiency", building on Shannon's information theory. They called it the mean information for discrimination between two hypotheses. In statistics it is also known as relative entropy.

What is the KL divergence between two Gaussians?

For one-dimensional normals it has a closed form: KL(N(μ₁, σ₁²) ‖ N(μ₂, σ₂²)) = ln(σ₂/σ₁) + (σ₁² + (μ₁ − μ₂)²) / (2σ₂²) − 1/2. It grows with the squared distance between the means and with any mismatch in spread. Multivariate Gaussians have a similar formula involving the covariance matrices.

How is KL divergence used in a VAE?

The VAE loss is a reconstruction term plus KL(q(z|x) ‖ p(z)), where q is the encoder's Gaussian over latent codes and p(z) is a standard normal prior. For a standard normal prior the KL term reduces to 1/2 (μ² + σ² − 1 − ln σ²) per latent dimension. It keeps the latent space smooth, so sampling z from the prior produces sensible outputs.

Why does RLHF use a KL penalty?

During RLHF, the policy is rewarded by a learned reward model, which it can exploit by producing odd text that scores well. Subtracting β × KL(policy ‖ reference model) from the reward keeps the fine-tuned model close to the original. The coefficient β trades reward against staying close.

Related explainers

References

  1. Kullback & Leibler (1951), "On Information and Sufficiency", Annals of Mathematical Statistics
  2. Kingma & Welling (2013), "Auto-Encoding Variational Bayes"
  3. Ouyang et al. (2022), "Training language models to follow instructions with human feedback"
  4. Szegedy et al. (2016), "Rethinking the Inception Architecture for Computer Vision" (label smoothing)
  5. Bishop (2006), "Pattern Recognition and Machine Learning", sections 1.6 and 10.1

Last updated