AI State of the Art
Math/Information Theory/12 min
Section 335

KL Divergence and Cross-Entropy

Listen as a podcast β†’

Comparing two distributions

In machine learning, we constantly compare probability distributions. The model's predictions vs the true labels. The approximate posterior vs the true posterior. The student's policy vs the teacher's. Cross-entropy and KL divergence are the mathematical tools to quantify these gaps.

Cross-entropy

Definition

The cross-entropy between a "true" distribution pp and a "predicted" distribution qq is:

H(p,q)=βˆ’βˆ‘xp(x)log⁑q(x)H(p, q) = -\sum_x p(x) \log q(x)

It measures the average number of bits needed to encode messages drawn from pp using the code optimized for qq.

H(p,q)=H(p)+DKL(pβˆ₯q)H(p, q) = H(p) + D_{KL}(p \| q)

Cross-entropy is the entropy of pp plus the KL divergence from pp to qq. If q=pq = p (perfect predictions), cross-entropy is minimal and equals exactly H(p)H(p).

The cross-entropy loss in classification

In multi-class classification, the labels are one-hot: p=(0,…,1,…,0)p = (0, \ldots, 1, \ldots, 0) with a 1 for the true class cc. The predictions are the softmax outputs: q=(y^1,…,y^K)q = (\hat{y}_1, \ldots, \hat{y}_K).

The cross-entropy simplifies to:

H(p,q)=βˆ’log⁑y^cH(p, q) = -\log \hat{y}_c

That's the loss everyone uses. The higher the probability assigned to the correct class, the lower the loss. If y^c=1\hat{y}_c = 1, the loss is 0. If y^c→0\hat{y}_c \to 0, the loss tends toward infinity.

Why not MSE for classification?

MSE βˆ‘(ykβˆ’y^k)2\sum (y_k - \hat{y}_k)^2 also works mathematically, but it has gradients that weaken when the model is very confident and wrong. Cross-entropy, on the other hand, produces strong gradients when the model assigns low probability to the correct class. It severely penalizes confident errors, which speeds up learning.

KL divergence

Definition

The Kullback-Leibler divergence measures how different qq is from pp:

DKL(pβˆ₯q)=βˆ‘xp(x)log⁑p(x)q(x)=H(p,q)βˆ’H(p)D_{KL}(p \| q) = \sum_x p(x) \log \frac{p(x)}{q(x)} = H(p, q) - H(p)

It's the "extra cost" in bits when you use the code for qq to encode messages from pp, beyond the theoretical minimum H(p)H(p).

Fundamental properties

  • Non-negativity: DKL(pβˆ₯q)β‰₯0D_{KL}(p \| q) \geq 0, with equality if and only if p=qp = q
  • Not a distance: KL divergence is not symmetric and doesn't satisfy the triangle inequality
  • Not symmetric: DKL(pβˆ₯q)β‰ DKL(qβˆ₯p)D_{KL}(p \| q) \neq D_{KL}(q \| p) in general, which has important practical consequences
Four plots. Top left, two Gaussians, p in red centred at 0 and q in blue centred at 1. Top right, the pointwise contributions to KL from p to q in red and to KL from q to p in blue, two curves with different shapes, shifted relative to one another. Bottom left, the two terms of the Jensen-Shannon divergence relative to the mixture m. Bottom right, the Jensen-Shannon divergence curve, symmetric.
Two neighbouring Gaussians (top left) are enough to expose the asymmetry. Top right, the pointwise contribution to KL from p to q (red) and the one to KL from q to p (blue) do not look alike: the two integrals give different numbers. At the bottom, the Jensen-Shannon divergence averages both directions and becomes symmetric again.Source : Lilian Weng, From GAN to WGAN (Lil Log)

Asymmetry has consequences

The non-symmetry of KL divergence is not a flaw: the two directions capture different behaviors.

DKL(pβˆ₯q)D_{KL}(p \| q) (forward KL): mode-covering

Minimizing DKL(pβˆ₯q)D_{KL}(p \| q) with respect to qq forces qq to cover the entire support of pp. Where p(x)>0p(x) > 0, we must have q(x)>0q(x) > 0 too (otherwise the log diverges). Result: qq tends to be too broad, covering areas where pp is zero.

DKL(qβˆ₯p)D_{KL}(q \| p) (reverse KL): mode-seeking

Minimizing DKL(qβˆ₯p)D_{KL}(q \| p) with respect to qq allows qq to concentrate on a single mode of pp. If pp is multimodal (multiple peaks), qq can ignore some modes and lock onto just one. This is "mode-seeking" behavior.

Illustration

Imagine that pp is a bimodal distribution (two peaks). With forward KL, qq will be a broad Gaussian covering both peaks. With reverse KL, qq will be a narrow Gaussian centered on a single peak. This difference has concrete consequences on model behavior: a VAE (reverse KL) may "choose" a single mode, while the cross-entropy loss (forward KL) forces the model to cover the entire data distribution.

Two side-by-side panels. In each one, a blue target distribution with two bumps of unequal height and a green approximation. On the left, labelled mode-seeking, the green curve is narrow and sits on the single tallest peak, ignoring the other one entirely. On the right, labelled mode-covering, the green curve is broad and spreads across both peaks, including the trough between them where the target is zero.
The blue target has two peaks, the green approximation has only one bump. On the left, reverse KL picks a side: it locks onto a single peak and acts as if the other did not exist. On the right, forward KL refuses to give anything up: it spreads out to cover both peaks, even if that means putting probability in the empty trough in the middle.Source : Sander Dieleman, Generating music in the waveform domain

Applications in deep learning

The cross-entropy loss = minimizing KL

When you train a model with cross-entropy, you minimize:

H(pdata,qΞΈ)=H(pdata)+DKL(pdataβˆ₯qΞΈ)H(p_{\text{data}}, q_\theta) = H(p_{\text{data}}) + D_{KL}(p_{\text{data}} \| q_\theta)

Since H(pdata)H(p_{\text{data}}) is a constant (independent of ΞΈ\theta), minimizing cross-entropy is exactly equivalent to minimizing DKL(pdataβˆ₯qΞΈ)D_{KL}(p_{\text{data}} \| q_\theta). You're looking for parameters ΞΈ\theta such that the predictions qΞΈq_\theta are as close as possible to the true data distribution.

VAE: KL between posterior and prior

In a Variational Autoencoder, the objective (ELBO) contains a KL divergence term:

LELBO=EqΟ•(z∣x)[log⁑pΞΈ(x∣z)]βˆ’DKL(qΟ•(z∣x)βˆ₯p(z))\mathcal{L}_{\text{ELBO}} = E_{q_\phi(z|x)}[\log p_\theta(x|z)] - D_{KL}(q_\phi(z|x) \| p(z))

The first term is reconstruction. The second term forces the approximate posterior qΟ•(z∣x)q_\phi(z|x) to stay close to the prior p(z)=N(0,I)p(z) = \mathcal{N}(0, I).

For Gaussians, the KL has a closed-form analytical formula:

DKL(N(ΞΌ,Οƒ2)βˆ₯N(0,1))=12(ΞΌ2+Οƒ2βˆ’log⁑σ2βˆ’1)D_{KL}(\mathcal{N}(\mu, \sigma^2) \| \mathcal{N}(0, 1)) = \frac{1}{2}\left(\mu^2 + \sigma^2 - \log \sigma^2 - 1\right)

That's why VAEs use Gaussians: the KL is computable exactly, no approximation needed.

Knowledge distillation

Distillation transfers knowledge from a large model (teacher) to a small model (student). You minimize:

DKL(pteacherβˆ₯qstudent)D_{KL}(p_{\text{teacher}} \| q_{\text{student}})

where the distributions are softmax outputs with a high temperature. The student learns not only the correct class, but also the relationships between classes captured by the teacher's probabilities.

RLHF and PPO

In RLHF (Reinforcement Learning from Human Feedback), you adjust an LLM according to human preferences while staying close to the base model. The loss contains a term:

Rewardβˆ’Ξ²β‹…DKL(πθβˆ₯Ο€ref)\text{Reward} - \beta \cdot D_{KL}(\pi_\theta \| \pi_{\text{ref}})

The KL term prevents the aligned model πθ\pi_\theta from straying too far from the reference model Ο€ref\pi_{\text{ref}}, which avoids mode collapse and maintains language diversity.

Choice of KL direction

ApplicationKL directionReason
Standard trainingDKL(pdataβˆ₯qΞΈ)D_{KL}(p_{\text{data}} \| q_\theta)Forward KL via cross-entropy
Variational inference (VAE)DKL(qΟ•βˆ₯p)D_{KL}(q_\phi \| p)Reverse KL, tractable
DistillationDKL(pteacherβˆ₯qstudent)D_{KL}(p_{\text{teacher}} \| q_{\text{student}})Forward KL, cover the teacher
RLHFDKL(πθβˆ₯Ο€ref)D_{KL}(\pi_\theta \| \pi_{\text{ref}})Penalize deviations from the base model

Other divergences and distances

Jensen-Shannon divergence

The JS divergence is the symmetric version of KL:

DJS(pβˆ₯q)=12DKL(pβˆ₯m)+12DKL(qβˆ₯m),m=p+q2D_{JS}(p \| q) = \frac{1}{2} D_{KL}(p \| m) + \frac{1}{2} D_{KL}(q \| m), \quad m = \frac{p + q}{2}

It's symmetric, bounded between 0 and log⁑2\log 2, and its square root is a true distance. It's the divergence used in the original GAN objective.

Wasserstein distance

Also called the Earth Mover's Distance, it measures the "transportation cost" to transform pp into qq. Used in Wasserstein GANs (WGAN) to solve the training problems of classic GANs.

Key takeaways

  • Cross-entropy H(p,q)=βˆ’βˆ‘plog⁑qH(p, q) = -\sum p \log q is the standard classification loss
  • KL divergence measures the "extra cost" of using qq instead of pp for encoding
  • KL is not symmetric: forward KL covers everything, reverse KL concentrates
  • Training with cross-entropy = minimizing the forward KL between data and predictions
  • KL appears in VAEs, distillation, and RLHF with different roles
  • For Gaussians, KL has an analytical form, which simplifies calculations

Where this is used. The KL penalty is the guardrail that keeps a model from drifting during alignment: see RLHF in practice.