← Tensor by Tensor
§ Math Fundamentals for AI
Tensor by Tensor · Complete Guide

KL divergence

Fourteen lessons that connect high-school mathematics to AI. Start with the plain-language explanation and a small example. Then read the full formulas, derivations, and Python code at your own pace.

How to study a lesson

Read the opening example. Try the question before revealing its answer. Then work through the detailed notes below it. You do not need to understand every proof on the first reading.

Symbols: a subscript such as xi identifies one entry. Σ means add a collection of terms. ∈ means “belongs to”. The symbol ≈ means “approximately equal”, not exactly equal. A parameter is an adjustable number in a model.

01.12 · KL Divergence

Introduction

Suppose the true distribution gives two outcomes equal weight, but a model predicts 90 percent and 10 percent. KL divergence measures the extra mismatch, and reversing the two distributions changes the answer.

Learning goal

Calculate KL divergence for small distributions, explain its asymmetry, and relate it to entropy and cross-entropy.

Before you start

Discrete probability distributions, logarithms, entropy, cross-entropy, and summing weighted terms over possible outcomes.

Lesson plan

  1. Compare two small distributions and calculate their weighted log ratios.
  2. Test non-negativity and asymmetry directly by reversing the two distribution arguments.
  3. Connect KL to cross-entropy and examine forward, reverse, and machine-learning uses.

Fix the direction. D_KL(p||q) asks how costly it is to use model distribution q when data follows p. Reversing the arguments asks a different question and can produce a different number.

Distance between distributions

The Kullback-Leibler (KL) divergence measures how one probability distribution differs from another. It's not a true distance (it's asymmetric), but it's the fundamental measure of dissimilarity in information theory.

Definition · KL divergence

For discrete distributions $p$ and $q$:

$$D_{KL}(p \| q) = \sum_i p_i \log \frac{p_i}{q_i} = \mathbb{E}_p\!\left[\log \frac{p_i}{q_i}\right]$$

For continuous distributions: $D_{KL}(p \| q) = \int p(x) \log \frac{p(x)}{q(x)}\,dx$.

Properties

  • $D_{KL}(p \| q) \geq 0$ (Gibbs' inequality), with equality iff $p = q$
  • $D_{KL}(p \| q) \neq D_{KL}(q \| p)$ in general (asymmetric)
  • Does not satisfy the triangle inequality (not a metric)

Relationship to entropy and cross-entropy

KL divergence decomposes neatly:

$$D_{KL}(p \| q) = H(p, q) - H(p)$$

It's the extra bits needed when using $q$ to encode data from $p$, beyond the optimal code length $H(p)$.

Example

Let $p = (0.5, 0.5)$ and $q = (0.9, 0.1)$:

$$D_{KL}(p \| q) = 0.5\ln\frac{0.5}{0.9} + 0.5\ln\frac{0.5}{0.1} \approx 0.5(-0.588) + 0.5(1.609) \approx 0.511 \text{ nats}$$

Reversing: $D_{KL}(q \| p) = 0.9\ln\frac{0.9}{0.5} + 0.1\ln\frac{0.1}{0.5} \approx 0.368$ nats. The order changes the result. Natural logarithms give nats; base-2 logarithms give bits.

Forward vs. reverse KL

The asymmetry matters in practice:

  • Forward KL $D_{KL}(p \| q)$: $q$ must cover all modes of $p$ (zero-avoiding). Used in maximum likelihood.
  • Reverse KL $D_{KL}(q \| p)$: $q$ can focus on one mode of $p$ (zero-forcing). Used in variational inference.

Applications in ML

Variational inference (VAEs)

In a VAE, we minimise $D_{KL}(q_\phi(z|x) \| p(z))$ to regularise the encoder's posterior toward the prior.

Knowledge distillation

Distill a large teacher model into a small student by minimising $D_{KL}(p_{\text{teacher}} \| p_{\text{student}})$ on soft predictions.

Policy gradient (RL)

Trust-region methods (TRPO, PPO) constrain $D_{KL}(\pi_{\text{old}} \| \pi_{\text{new}})$ to prevent destructive policy updates.

Numerical stability

KL divergence is infinite when $q_i = 0$ but $p_i > 0$. For positive model probabilities, stable log-probability calculations help avoid numerical underflow. Adding a small constant changes the distribution and needs renormalization; it is an approximation, not a way to make a genuinely infinite divergence finite without changing the problem.